From 5dbf1809c6e3e905b94b8764e99491e608122261 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Verschelde?= Date: Sun, 5 Mar 2017 16:44:50 +0100 Subject: 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 --- core/allocators.h | 144 +- core/array.cpp | 119 +- core/array.h | 40 +- core/bind/core_bind.cpp | 1513 ++-- core/bind/core_bind.h | 305 +- core/class_db.cpp | 820 +- core/class_db.h | 282 +- core/color.cpp | 291 +- core/color.h | 87 +- core/command_queue_mt.cpp | 36 +- core/command_queue_mt.h | 914 +-- core/compressed_translation.cpp | 564 +- core/compressed_translation.h | 23 +- core/core_string_names.cpp | 26 +- core/core_string_names.h | 16 +- core/dictionary.cpp | 132 +- core/dictionary.h | 36 +- core/dvector.cpp | 38 +- core/dvector.h | 367 +- core/engine.cpp | 44 +- core/engine.h | 8 +- core/error_list.h | 23 +- core/error_macros.cpp | 40 +- core/error_macros.h | 209 +- core/event_queue.cpp | 147 +- core/event_queue.h | 11 +- core/func_ref.cpp | 37 +- core/func_ref.h | 11 +- core/global_config.cpp | 610 +- core/global_config.h | 88 +- core/global_constants.cpp | 990 ++- core/global_constants.h | 2 - core/hash_map.h | 342 +- core/hashfuncs.h | 61 +- core/helper/math_fieldwise.cpp | 15 +- core/helper/math_fieldwise.h | 2 +- core/helper/value_evaluator.h | 3 +- core/image.cpp | 2032 +++-- core/image.h | 85 +- core/input_map.cpp | 225 +- core/input_map.h | 35 +- core/int_types.h | 30 +- core/io/compression.cpp | 90 +- core/io/compression.h | 13 +- core/io/config_file.cpp | 128 +- core/io/config_file.h | 27 +- core/io/file_access_buffered.cpp | 10 +- core/io/file_access_buffered.h | 10 +- core/io/file_access_buffered_fa.h | 26 +- core/io/file_access_compressed.cpp | 320 +- core/io/file_access_compressed.h | 19 +- core/io/file_access_encrypted.cpp | 204 +- core/io/file_access_encrypted.h | 23 +- core/io/file_access_memory.cpp | 28 +- core/io/file_access_memory.h | 19 +- core/io/file_access_network.cpp | 324 +- core/io/file_access_network.h | 34 +- core/io/file_access_pack.cpp | 237 +- core/io/file_access_pack.h | 83 +- core/io/file_access_zip.cpp | 94 +- core/io/file_access_zip.h | 36 +- core/io/http_client.cpp | 637 +- core/io/http_client.h | 26 +- core/io/image_loader.cpp | 44 +- core/io/image_loader.h | 29 +- core/io/ip.cpp | 154 +- core/io/ip.h | 38 +- core/io/ip_address.cpp | 74 +- core/io/ip_address.h | 23 +- core/io/json.cpp | 299 +- core/io/json.h | 17 +- core/io/marshalls.cpp | 1117 ++- core/io/marshalls.h | 80 +- core/io/networked_multiplayer_peer.cpp | 46 +- core/io/networked_multiplayer_peer.h | 32 +- core/io/packet_peer.cpp | 141 +- core/io/packet_peer.h | 37 +- core/io/packet_peer_udp.cpp | 32 +- core/io/packet_peer_udp.h | 26 +- core/io/pck_packer.cpp | 26 +- core/io/pck_packer.h | 7 +- core/io/resource_format_binary.cpp | 1256 ++- core/io/resource_format_binary.h | 76 +- core/io/resource_import.cpp | 153 +- core/io/resource_import.h | 59 +- core/io/resource_loader.cpp | 198 +- core/io/resource_loader.h | 96 +- core/io/resource_saver.cpp | 71 +- core/io/resource_saver.h | 45 +- core/io/stream_peer.cpp | 406 +- core/io/stream_peer.h | 44 +- core/io/stream_peer_ssl.cpp | 37 +- core/io/stream_peer_ssl.h | 26 +- core/io/stream_peer_tcp.cpp | 39 +- core/io/stream_peer_tcp.h | 29 +- core/io/tcp_server.cpp | 18 +- core/io/tcp_server.h | 20 +- core/io/translation_loader_po.cpp | 125 +- core/io/translation_loader_po.h | 10 +- core/io/xml_parser.cpp | 333 +- core/io/xml_parser.h | 27 +- core/io/zip_io.h | 72 +- core/list.h | 407 +- core/map.h | 507 +- core/math/a_star.cpp | 308 +- core/math/a_star.h | 41 +- core/math/audio_frame.cpp | 1 - core/math/audio_frame.h | 77 +- core/math/bsp_tree.cpp | 418 +- core/math/bsp_tree.h | 105 +- core/math/camera_matrix.cpp | 593 +- core/math/camera_matrix.h | 40 +- core/math/face3.cpp | 426 +- core/math/face3.h | 247 +- core/math/geometry.cpp | 836 +- core/math/geometry.h | 758 +- core/math/math_2d.cpp | 364 +- core/math/math_2d.h | 706 +- core/math/math_defs.h | 8 +- core/math/math_funcs.cpp | 76 +- core/math/math_funcs.h | 249 +- core/math/matrix3.cpp | 379 +- core/math/matrix3.h | 217 +- core/math/octree.h | 987 ++- core/math/plane.cpp | 81 +- core/math/plane.h | 84 +- core/math/quat.cpp | 102 +- core/math/quat.h | 167 +- core/math/quick_hull.cpp | 299 +- core/math/quick_hull.h | 42 +- core/math/rect3.cpp | 355 +- core/math/rect3.h | 333 +- core/math/transform.cpp | 96 +- core/math/transform.h | 239 +- core/math/triangle_mesh.cpp | 416 +- core/math/triangle_mesh.h | 22 +- core/math/triangulate.cpp | 194 +- core/math/triangulate.h | 21 +- core/math/vector3.cpp | 79 +- core/math/vector3.h | 274 +- core/message_queue.cpp | 261 +- core/message_queue.h | 20 +- core/method_bind.cpp | 73 +- core/method_bind.h | 241 +- core/method_ptrcall.h | 484 +- core/object.cpp | 1175 ++- core/object.h | 658 +- core/os/copymem.h | 2 +- core/os/dir_access.cpp | 151 +- core/os/dir_access.h | 70 +- core/os/file_access.cpp | 284 +- core/os/file_access.h | 111 +- core/os/input.cpp | 90 +- core/os/input.h | 100 +- core/os/input_event.cpp | 181 +- core/os/input_event.h | 136 +- core/os/keyboard.cpp | 297 +- core/os/keyboard.h | 514 +- core/os/main_loop.cpp | 64 +- core/os/main_loop.h | 14 +- core/os/memory.cpp | 112 +- core/os/memory.h | 102 +- core/os/mutex.cpp | 12 +- core/os/mutex.h | 25 +- core/os/os.cpp | 202 +- core/os/os.h | 165 +- core/os/power.h | 15 +- core/os/rw_lock.cpp | 9 +- core/os/rw_lock.h | 42 +- core/os/semaphore.cpp | 6 +- core/os/semaphore.h | 12 +- core/os/shell.cpp | 13 +- core/os/shell.h | 8 +- core/os/thread.cpp | 25 +- core/os/thread.h | 26 +- core/os/thread_dummy.cpp | 10 +- core/os/thread_dummy.h | 14 +- core/os/thread_safe.cpp | 2 +- core/os/thread_safe.h | 22 +- core/packed_data_container.cpp | 301 +- core/packed_data_container.h | 54 +- core/pair.h | 12 +- core/path_db.cpp | 238 +- core/path_db.h | 25 +- core/path_remap.cpp | 1 - core/pool_allocator.cpp | 370 +- core/pool_allocator.h | 53 +- core/print_string.cpp | 34 +- core/print_string.h | 13 +- core/ref_ptr.cpp | 37 +- core/ref_ptr.h | 11 +- core/reference.cpp | 31 +- core/reference.h | 197 +- core/register_core_types.cpp | 148 +- core/resource.cpp | 221 +- core/resource.h | 69 +- core/rid.cpp | 4 - core/rid.h | 109 +- core/ring_buffer.h | 52 +- core/safe_refcount.cpp | 56 +- core/safe_refcount.h | 29 +- core/script_debugger_local.cpp | 206 +- core/script_debugger_local.h | 13 +- core/script_debugger_remote.cpp | 687 +- core/script_debugger_remote.h | 42 +- core/script_language.cpp | 196 +- core/script_language.h | 297 +- core/self_list.h | 53 +- core/set.h | 478 +- core/simple_type.h | 86 +- core/sort.h | 197 +- core/string_db.cpp | 239 +- core/string_db.h | 63 +- core/translation.cpp | 1697 ++--- core/translation.h | 39 +- core/typedefs.h | 67 +- core/ucaps.h | 2697 ++++--- core/undo_redo.cpp | 358 +- core/undo_redo.h | 48 +- core/ustring.cpp | 2786 ++++--- core/ustring.h | 175 +- core/variant.cpp | 1833 +++-- core/variant.h | 280 +- core/variant_call.cpp | 2259 +++--- core/variant_construct_string.cpp | 286 +- core/variant_op.cpp | 3781 ++++----- core/variant_parser.cpp | 1654 ++-- core/variant_parser.h | 66 +- core/vector.h | 279 +- core/vmap.h | 102 +- core/vset.h | 63 +- drivers/alsa/audio_driver_alsa.cpp | 100 +- drivers/alsa/audio_driver_alsa.h | 17 +- drivers/convex_decomp/b2d_decompose.cpp | 195 +- drivers/convex_decomp/b2d_decompose.h | 2 +- drivers/gl_context/context_gl.cpp | 19 +- drivers/gl_context/context_gl.h | 24 +- drivers/gles2/rasterizer_gles2.cpp | 8039 +++++++++----------- drivers/gles2/rasterizer_gles2.h | 894 ++- drivers/gles2/rasterizer_instance_gles2.cpp | 3 +- drivers/gles2/rasterizer_instance_gles2.h | 1 - drivers/gles2/shader_compiler_gles2.cpp | 1032 ++- drivers/gles2/shader_compiler_gles2.h | 20 +- drivers/gles2/shader_gles2.cpp | 621 +- drivers/gles2/shader_gles2.h | 306 +- drivers/gles3/rasterizer_canvas_gles3.cpp | 1084 ++- drivers/gles3/rasterizer_canvas_gles3.h | 28 +- drivers/gles3/rasterizer_gles3.cpp | 249 +- drivers/gles3/rasterizer_gles3.h | 11 +- drivers/gles3/rasterizer_scene_gles3.cpp | 3797 +++++---- drivers/gles3/rasterizer_scene_gles3.h | 338 +- drivers/gles3/rasterizer_storage_gles3.cpp | 4914 ++++++------ drivers/gles3/rasterizer_storage_gles3.h | 557 +- drivers/gles3/shader_compiler_gles3.cpp | 623 +- drivers/gles3/shader_compiler_gles3.h | 29 +- drivers/gles3/shader_gles3.cpp | 628 +- drivers/gles3/shader_gles3.h | 317 +- drivers/png/image_loader_png.cpp | 212 +- drivers/png/image_loader_png.h | 14 +- drivers/png/resource_saver_png.cpp | 106 +- drivers/png/resource_saver_png.h | 10 +- drivers/pulseaudio/audio_driver_pulseaudio.cpp | 41 +- drivers/pulseaudio/audio_driver_pulseaudio.h | 28 +- drivers/register_driver_types.cpp | 18 +- drivers/rtaudio/audio_driver_rtaudio.cpp | 95 +- drivers/rtaudio/audio_driver_rtaudio.h | 13 +- drivers/unix/dir_access_unix.cpp | 144 +- drivers/unix/dir_access_unix.h | 34 +- drivers/unix/file_access_unix.cpp | 144 +- drivers/unix/file_access_unix.h | 39 +- drivers/unix/ip_unix.cpp | 113 +- drivers/unix/ip_unix.h | 6 +- drivers/unix/mutex_posix.cpp | 15 +- drivers/unix/mutex_posix.h | 17 +- drivers/unix/os_unix.cpp | 251 +- drivers/unix/os_unix.h | 53 +- drivers/unix/packet_peer_udp_posix.cpp | 118 +- drivers/unix/packet_peer_udp_posix.h | 14 +- drivers/unix/rw_lock_posix.cpp | 25 +- drivers/unix/rw_lock_posix.h | 6 +- drivers/unix/semaphore_posix.cpp | 22 +- drivers/unix/semaphore_posix.h | 8 +- drivers/unix/socket_helpers.h | 48 +- drivers/unix/stream_peer_tcp_posix.cpp | 61 +- drivers/unix/stream_peer_tcp_posix.h | 18 +- drivers/unix/tcp_server_posix.cpp | 34 +- drivers/unix/tcp_server_posix.h | 6 +- drivers/unix/thread_posix.cpp | 67 +- drivers/unix/thread_posix.h | 29 +- drivers/windows/dir_access_windows.cpp | 160 +- drivers/windows/dir_access_windows.h | 9 +- drivers/windows/file_access_windows.cpp | 132 +- drivers/windows/file_access_windows.h | 10 +- drivers/windows/mutex_windows.cpp | 46 +- drivers/windows/mutex_windows.h | 19 +- drivers/windows/rw_lock_windows.cpp | 18 +- drivers/windows/rw_lock_windows.h | 6 +- drivers/windows/semaphore_windows.cpp | 37 +- drivers/windows/semaphore_windows.h | 10 +- drivers/windows/shell_windows.cpp | 9 +- drivers/windows/shell_windows.h | 4 +- drivers/windows/thread_windows.cpp | 61 +- drivers/windows/thread_windows.h | 29 +- drivers/xaudio2/audio_driver_xaudio2.cpp | 29 +- drivers/xaudio2/audio_driver_xaudio2.h | 41 +- editor/animation_editor.cpp | 3270 ++++---- editor/animation_editor.h | 64 +- editor/array_property_edit.cpp | 220 +- editor/array_property_edit.h | 16 +- editor/asset_library_editor_plugin.cpp | 994 ++- editor/asset_library_editor_plugin.h | 111 +- editor/call_dialog.cpp | 2 +- editor/call_dialog.h | 6 +- editor/code_editor.cpp | 602 +- editor/code_editor.h | 63 +- editor/collada/collada.cpp | 1935 +++-- editor/collada/collada.h | 375 +- editor/connections_dialog.cpp | 484 +- editor/connections_dialog.h | 34 +- editor/create_dialog.cpp | 507 +- editor/create_dialog.h | 47 +- editor/dependency_editor.cpp | 456 +- editor/dependency_editor.h | 52 +- editor/doc/doc_data.cpp | 886 +-- editor/doc/doc_data.h | 36 +- editor/doc/doc_dump.cpp | 269 +- editor/doc/doc_dump.h | 4 +- editor/doc_code_font.h | 8 +- editor/doc_font.h | 8 +- editor/doc_title_font.h | 8 +- editor/editor_asset_installer.cpp | 236 +- editor/editor_asset_installer.h | 13 +- editor/editor_audio_buses.cpp | 830 +- editor/editor_audio_buses.h | 80 +- editor/editor_autoload_settings.cpp | 77 +- editor/editor_autoload_settings.h | 18 +- editor/editor_data.cpp | 499 +- editor/editor_data.h | 87 +- editor/editor_dir_dialog.cpp | 150 +- editor/editor_dir_dialog.h | 13 +- editor/editor_export.cpp | 560 +- editor/editor_export.h | 150 +- editor/editor_file_dialog.cpp | 1018 ++- editor/editor_file_dialog.h | 51 +- editor/editor_file_system.cpp | 1038 ++- editor/editor_file_system.h | 73 +- editor/editor_fonts.cpp | 106 +- editor/editor_help.cpp | 1002 ++- editor/editor_help.h | 97 +- editor/editor_initialize_ssl.cpp | 13 +- editor/editor_log.cpp | 103 +- editor/editor_log.h | 17 +- editor/editor_name_dialog.cpp | 21 +- editor/editor_name_dialog.h | 8 +- editor/editor_node.cpp | 3353 ++++---- editor/editor_node.h | 312 +- editor/editor_path.cpp | 119 +- editor/editor_path.h | 12 +- editor/editor_plugin.cpp | 232 +- editor/editor_plugin.h | 89 +- editor/editor_plugin_settings.cpp | 152 +- editor/editor_plugin_settings.h | 14 +- editor/editor_profiler.cpp | 563 +- editor/editor_profiler.h | 36 +- editor/editor_resource_preview.cpp | 227 +- editor/editor_resource_preview.h | 42 +- editor/editor_run.cpp | 104 +- editor/editor_run.h | 10 +- editor/editor_run_native.cpp | 34 +- editor/editor_run_native.h | 9 +- editor/editor_run_script.cpp | 32 +- editor/editor_run_script.h | 7 +- editor/editor_scale.cpp | 2 +- editor/editor_settings.cpp | 651 +- editor/editor_settings.h | 74 +- editor/editor_sub_scene.cpp | 122 +- editor/editor_sub_scene.h | 19 +- editor/editor_themes.cpp | 40 +- editor/file_type_cache.cpp | 37 +- editor/file_type_cache.h | 17 +- editor/fileserver/editor_file_server.cpp | 266 +- editor/fileserver/editor_file_server.h | 20 +- editor/filesystem_dock.cpp | 1026 ++- editor/filesystem_dock.h | 72 +- editor/groups_editor.cpp | 90 +- editor/groups_editor.h | 16 +- editor/import/editor_import_collada.cpp | 1450 ++-- editor/import/editor_import_collada.h | 12 +- .../import/resource_importer_csv_translation.cpp | 60 +- editor/import/resource_importer_csv_translation.h | 9 +- editor/import/resource_importer_obj.cpp | 162 +- editor/import/resource_importer_obj.h | 10 +- editor/import/resource_importer_scene.cpp | 764 +- editor/import/resource_importer_scene.h | 69 +- editor/import/resource_importer_texture.cpp | 232 +- editor/import/resource_importer_texture.h | 30 +- editor/import/resource_importer_wav.cpp | 434 +- editor/import/resource_importer_wav.h | 12 +- editor/import_dock.cpp | 177 +- editor/import_dock.h | 15 +- editor/inspector_dock.h | 3 +- editor/io_plugins/editor_atlas.cpp | 92 +- editor/io_plugins/editor_atlas.h | 5 +- editor/io_plugins/editor_bitmask_import_plugin.cpp | 8 +- editor/io_plugins/editor_export_scene.cpp | 4 +- editor/io_plugins/editor_font_import_plugin.cpp | 6 +- editor/io_plugins/editor_mesh_import_plugin.cpp | 4 +- editor/io_plugins/editor_sample_import_plugin.cpp | 6 +- editor/io_plugins/editor_scene_import_plugin.cpp | 25 +- editor/io_plugins/editor_scene_import_plugin.h | 16 +- .../io_plugins/editor_scene_importer_fbxconv.cpp | 2 +- editor/io_plugins/editor_texture_import_plugin.cpp | 12 +- editor/io_plugins/editor_texture_import_plugin.h | 15 +- .../editor_translation_import_plugin.cpp | 6 +- editor/multi_node_edit.cpp | 90 +- editor/multi_node_edit.h | 19 +- editor/node_dock.cpp | 40 +- editor/node_dock.h | 8 +- editor/output_strings.cpp | 139 +- editor/output_strings.h | 20 +- editor/pane_drag.cpp | 34 +- editor/pane_drag.h | 7 +- editor/plugins/animation_player_editor_plugin.cpp | 790 +- editor/plugins/animation_player_editor_plugin.h | 50 +- editor/plugins/animation_tree_editor_plugin.cpp | 1166 ++- editor/plugins/animation_tree_editor_plugin.h | 49 +- editor/plugins/baked_light_baker.cpp | 6 +- editor/plugins/baked_light_baker.h | 2 +- editor/plugins/baked_light_baker_cmpxchg.cpp | 58 +- editor/plugins/baked_light_editor_plugin.cpp | 7 +- editor/plugins/baked_light_editor_plugin.h | 5 +- editor/plugins/camera_editor_plugin.cpp | 50 +- editor/plugins/camera_editor_plugin.h | 13 +- editor/plugins/canvas_item_editor_plugin.cpp | 2381 +++--- editor/plugins/canvas_item_editor_plugin.h | 138 +- .../plugins/collision_polygon_2d_editor_plugin.cpp | 301 +- .../plugins/collision_polygon_2d_editor_plugin.h | 18 +- editor/plugins/collision_polygon_editor_plugin.cpp | 6 +- editor/plugins/collision_polygon_editor_plugin.h | 4 +- .../plugins/collision_shape_2d_editor_plugin.cpp | 222 +- editor/plugins/collision_shape_2d_editor_plugin.h | 32 +- editor/plugins/color_ramp_editor_plugin.cpp | 44 +- editor/plugins/color_ramp_editor_plugin.h | 7 +- editor/plugins/cube_grid_theme_editor_plugin.cpp | 8 +- editor/plugins/cube_grid_theme_editor_plugin.h | 3 +- editor/plugins/editor_preview_plugins.cpp | 38 +- editor/plugins/gi_probe_editor_plugin.cpp | 22 +- editor/plugins/gi_probe_editor_plugin.h | 13 +- editor/plugins/item_list_editor_plugin.cpp | 189 +- editor/plugins/item_list_editor_plugin.h | 96 +- editor/plugins/light_occluder_2d_editor_plugin.cpp | 334 +- editor/plugins/light_occluder_2d_editor_plugin.h | 20 +- editor/plugins/line_2d_editor_plugin.cpp | 88 +- editor/plugins/line_2d_editor_plugin.h | 20 +- editor/plugins/material_editor_plugin.cpp | 52 +- editor/plugins/material_editor_plugin.h | 6 +- editor/plugins/mesh_editor_plugin.h | 6 +- editor/plugins/mesh_instance_editor_plugin.cpp | 141 +- editor/plugins/mesh_instance_editor_plugin.h | 15 +- editor/plugins/multimesh_editor_plugin.cpp | 208 +- editor/plugins/multimesh_editor_plugin.h | 16 +- .../plugins/navigation_polygon_editor_plugin.cpp | 396 +- editor/plugins/navigation_polygon_editor_plugin.h | 20 +- editor/plugins/particles_2d_editor_plugin.cpp | 110 +- editor/plugins/particles_2d_editor_plugin.h | 13 +- editor/plugins/particles_editor_plugin.cpp | 3 +- editor/plugins/particles_editor_plugin.h | 2 +- editor/plugins/path_2d_editor_plugin.cpp | 306 +- editor/plugins/path_2d_editor_plugin.h | 20 +- editor/plugins/path_editor_plugin.cpp | 4 +- editor/plugins/path_editor_plugin.h | 3 +- editor/plugins/polygon_2d_editor_plugin.cpp | 741 +- editor/plugins/polygon_2d_editor_plugin.h | 19 +- .../plugins/resource_preloader_editor_plugin.cpp | 296 +- editor/plugins/resource_preloader_editor_plugin.h | 31 +- editor/plugins/rich_text_editor_plugin.cpp | 62 +- editor/plugins/rich_text_editor_plugin.h | 18 +- editor/plugins/sample_editor_plugin.cpp | 4 +- editor/plugins/sample_editor_plugin.h | 2 +- editor/plugins/sample_library_editor_plugin.cpp | 6 +- editor/plugins/sample_library_editor_plugin.h | 9 +- editor/plugins/sample_player_editor_plugin.cpp | 2 - editor/plugins/sample_player_editor_plugin.h | 4 +- editor/plugins/script_editor_plugin.cpp | 1171 ++- editor/plugins/script_editor_plugin.h | 145 +- editor/plugins/script_text_editor.cpp | 644 +- editor/plugins/script_text_editor.h | 50 +- editor/plugins/shader_editor_plugin.cpp | 250 +- editor/plugins/shader_editor_plugin.h | 32 +- editor/plugins/shader_graph_editor_plugin.cpp | 6 +- editor/plugins/shader_graph_editor_plugin.h | 9 +- editor/plugins/spatial_editor_plugin.cpp | 2678 +++---- editor/plugins/spatial_editor_plugin.h | 166 +- editor/plugins/sprite_frames_editor_plugin.cpp | 611 +- editor/plugins/sprite_frames_editor_plugin.h | 35 +- editor/plugins/stream_editor_plugin.h | 2 +- editor/plugins/style_box_editor_plugin.cpp | 44 +- editor/plugins/style_box_editor_plugin.h | 22 +- editor/plugins/texture_editor_plugin.cpp | 84 +- editor/plugins/texture_editor_plugin.h | 13 +- editor/plugins/texture_region_editor_plugin.cpp | 755 +- editor/plugins/texture_region_editor_plugin.h | 23 +- editor/plugins/theme_editor_plugin.cpp | 610 +- editor/plugins/theme_editor_plugin.h | 34 +- editor/plugins/tile_map_editor_plugin.cpp | 781 +- editor/plugins/tile_map_editor_plugin.h | 54 +- editor/plugins/tile_set_editor_plugin.cpp | 156 +- editor/plugins/tile_set_editor_plugin.h | 27 +- editor/progress_dialog.cpp | 133 +- editor/progress_dialog.h | 43 +- editor/project_export.cpp | 453 +- editor/project_export.h | 53 +- editor/project_manager.cpp | 776 +- editor/project_manager.h | 32 +- editor/project_settings.cpp | 1070 ++- editor/project_settings.h | 48 +- editor/property_editor.cpp | 3137 ++++---- editor/property_editor.h | 164 +- editor/property_selector.cpp | 528 +- editor/property_selector.h | 32 +- editor/pvrtc_compress.cpp | 63 +- editor/pvrtc_compress.h | 1 - editor/quick_open.cpp | 82 +- editor/quick_open.h | 19 +- editor/register_exporters.h | 1 - editor/reparent_dialog.cpp | 45 +- editor/reparent_dialog.h | 16 +- editor/resources_dock.cpp | 216 +- editor/resources_dock.h | 39 +- editor/run_settings_dialog.cpp | 25 +- editor/run_settings_dialog.h | 15 +- editor/scene_tree_dock.cpp | 1172 ++- editor/scene_tree_dock.h | 80 +- editor/scene_tree_editor.cpp | 786 +- editor/scene_tree_editor.h | 83 +- editor/script_create_dialog.cpp | 235 +- editor/script_create_dialog.h | 25 +- editor/script_editor_debugger.cpp | 1189 ++- editor/script_editor_debugger.h | 70 +- editor/settings_config_dialog.cpp | 229 +- editor/settings_config_dialog.h | 19 +- editor/spatial_editor_gizmos.cpp | 2418 +++--- editor/spatial_editor_gizmos.h | 327 +- main/input_default.cpp | 347 +- main/input_default.h | 62 +- main/main.cpp | 1115 ++- main/main.h | 7 +- main/performance.cpp | 95 +- main/performance.h | 10 +- main/splash.h | 2 +- main/tests/test_containers.cpp | 16 +- main/tests/test_containers.h | 3 +- main/tests/test_gdscript.cpp | 1022 +-- main/tests/test_gdscript.h | 3 +- main/tests/test_gui.cpp | 207 +- main/tests/test_gui.h | 4 +- main/tests/test_image.cpp | 25 +- main/tests/test_image.h | 3 +- main/tests/test_io.cpp | 53 +- main/tests/test_io.h | 3 +- main/tests/test_main.cpp | 58 +- main/tests/test_main.h | 9 +- main/tests/test_math.cpp | 463 +- main/tests/test_math.h | 3 +- main/tests/test_physics.cpp | 377 +- main/tests/test_physics.h | 3 +- main/tests/test_physics_2d.cpp | 293 +- main/tests/test_physics_2d.h | 4 +- main/tests/test_render.cpp | 134 +- main/tests/test_render.h | 3 +- main/tests/test_shader_lang.cpp | 228 +- main/tests/test_shader_lang.h | 3 +- main/tests/test_sound.cpp | 6 +- main/tests/test_sound.h | 3 +- main/tests/test_string.cpp | 260 +- main/tests/test_string.h | 8 +- modules/cscript/godot_c.cpp | 1 - modules/cscript/godot_c.h | 309 +- modules/cscript/register_types.cpp | 3 - modules/dds/register_types.cpp | 2 +- modules/dds/texture_loader_dds.cpp | 345 +- modules/dds/texture_loader_dds.h | 9 +- modules/enet/networked_multiplayer_enet.cpp | 446 +- modules/enet/networked_multiplayer_enet.h | 31 +- modules/enet/register_types.cpp | 7 +- modules/etc1/image_etc.cpp | 153 +- modules/etc1/image_etc.h | 1 - modules/etc1/register_types.cpp | 2 +- modules/etc1/texture_loader_pkm.cpp | 46 +- modules/etc1/texture_loader_pkm.h | 9 +- modules/gdscript/gd_compiler.cpp | 1303 ++-- modules/gdscript/gd_compiler.h | 144 +- modules/gdscript/gd_editor.cpp | 2016 +++-- modules/gdscript/gd_function.cpp | 991 ++- modules/gdscript/gd_function.h | 84 +- modules/gdscript/gd_functions.cpp | 1044 ++- modules/gdscript/gd_functions.h | 4 +- modules/gdscript/gd_parser.cpp | 2682 ++++--- modules/gdscript/gd_parser.h | 164 +- modules/gdscript/gd_script.cpp | 1069 ++- modules/gdscript/gd_script.h | 270 +- modules/gdscript/gd_tokenizer.cpp | 1163 ++- modules/gdscript/gd_tokenizer.h | 122 +- modules/gdscript/register_types.cpp | 28 +- modules/gridmap/grid_map.cpp | 974 ++- modules/gridmap/grid_map.h | 88 +- modules/gridmap/grid_map_editor_plugin.cpp | 958 ++- modules/gridmap/grid_map_editor_plugin.h | 36 +- modules/gridmap/register_types.cpp | 4 - modules/jpg/image_loader_jpegd.cpp | 54 +- modules/jpg/image_loader_jpegd.h | 8 +- modules/jpg/register_types.cpp | 4 +- modules/openssl/stream_peer_openssl.cpp | 360 +- modules/openssl/stream_peer_openssl.h | 50 +- modules/opus/audio_stream_opus.cpp | 222 +- modules/opus/audio_stream_opus.h | 36 +- modules/opus/register_types.cpp | 4 +- modules/pbm/bitmap_loader_pbm.cpp | 154 +- modules/pbm/bitmap_loader_pbm.h | 8 +- modules/pbm/register_types.cpp | 6 +- modules/pvr/register_types.cpp | 2 +- modules/pvr/texture_loader_pvr.cpp | 447 +- modules/pvr/texture_loader_pvr.h | 12 +- modules/regex/regex.cpp | 461 +- modules/regex/regex.h | 29 +- modules/regex/register_types.cpp | 2 - modules/squish/image_compress_squish.cpp | 53 +- modules/stb_vorbis/audio_stream_ogg_vorbis.cpp | 134 +- modules/stb_vorbis/audio_stream_ogg_vorbis.h | 31 +- modules/stb_vorbis/register_types.cpp | 1 - .../stb_vorbis/resource_importer_ogg_vorbis.cpp | 31 +- modules/stb_vorbis/resource_importer_ogg_vorbis.h | 11 +- modules/theora/register_types.cpp | 6 +- modules/theora/video_stream_theora.cpp | 458 +- modules/theora/video_stream_theora.h | 56 +- modules/visual_script/register_types.cpp | 26 +- modules/visual_script/visual_script.cpp | 1841 ++--- modules/visual_script/visual_script.h | 435 +- .../visual_script/visual_script_builtin_funcs.cpp | 713 +- .../visual_script/visual_script_builtin_funcs.h | 20 +- modules/visual_script/visual_script_editor.cpp | 2441 +++--- modules/visual_script/visual_script_editor.h | 91 +- modules/visual_script/visual_script_expression.cpp | 1158 ++- modules/visual_script/visual_script_expression.h | 107 +- .../visual_script/visual_script_flow_control.cpp | 1235 ++- modules/visual_script/visual_script_flow_control.h | 138 +- modules/visual_script/visual_script_func_nodes.cpp | 1611 ++-- modules/visual_script/visual_script_func_nodes.h | 113 +- modules/visual_script/visual_script_nodes.cpp | 2142 +++--- modules/visual_script/visual_script_nodes.h | 387 +- .../visual_script/visual_script_yield_nodes.cpp | 355 +- modules/visual_script/visual_script_yield_nodes.h | 39 +- modules/vorbis/audio_stream_ogg_vorbis.cpp | 269 +- modules/vorbis/audio_stream_ogg_vorbis.h | 35 +- modules/vorbis/register_types.cpp | 4 +- modules/webm/video_stream_webm.cpp | 55 +- modules/webm/video_stream_webm.h | 2 +- modules/webp/image_loader_webp.cpp | 103 +- modules/webp/image_loader_webp.h | 8 +- modules/webp/register_types.cpp | 4 +- platform/android/audio_driver_jandroid.cpp | 127 +- platform/android/audio_driver_jandroid.h | 15 +- platform/android/audio_driver_opensl.cpp | 163 +- platform/android/audio_driver_opensl.h | 25 +- platform/android/dir_access_android.cpp | 87 +- platform/android/dir_access_android.h | 11 +- platform/android/dir_access_jandroid.cpp | 153 +- platform/android/dir_access_jandroid.h | 9 +- platform/android/export/export.cpp | 15 +- platform/android/file_access_android.cpp | 100 +- platform/android/file_access_android.h | 17 +- platform/android/file_access_jandroid.cpp | 139 +- platform/android/file_access_jandroid.h | 16 +- platform/android/globals/global_defaults.cpp | 3 +- platform/android/godot_android.cpp | 1022 ++- platform/android/java_class_wrapper.cpp | 755 +- platform/android/java_class_wrapper.h | 172 +- platform/android/java_glue.cpp | 1194 ++- platform/android/java_glue.h | 48 +- platform/android/os_android.cpp | 419 +- platform/android/os_android.h | 77 +- platform/android/power_android.cpp | 103 +- platform/android/power_android.h | 14 +- platform/android/thread_jandroid.cpp | 58 +- platform/android/thread_jandroid.h | 27 +- platform/bb10/audio_driver_bb10.cpp | 37 +- platform/bb10/audio_driver_bb10.h | 20 +- platform/bb10/export/export.cpp | 12 +- platform/bb10/godot_bb10.cpp | 7 +- platform/bb10/os_bb10.cpp | 305 +- platform/bb10/os_bb10.h | 47 +- platform/bb10/payment_service.cpp | 36 +- platform/bb10/payment_service.h | 8 +- platform/bb10/power_bb10.cpp | 15 +- platform/bb10/power_bb10.h | 1 + platform/haiku/audio_driver_media_kit.cpp | 20 +- platform/haiku/audio_driver_media_kit.h | 15 +- platform/haiku/context_gl_haiku.cpp | 4 +- platform/haiku/context_gl_haiku.h | 10 +- platform/haiku/godot_haiku.cpp | 4 +- platform/haiku/haiku_application.cpp | 4 +- platform/haiku/haiku_application.h | 7 +- platform/haiku/haiku_direct_window.cpp | 44 +- platform/haiku/haiku_direct_window.h | 41 +- platform/haiku/haiku_gl_view.cpp | 5 +- platform/haiku/haiku_gl_view.h | 5 +- platform/haiku/key_mapping_haiku.cpp | 60 +- platform/haiku/key_mapping_haiku.h | 5 +- platform/haiku/os_haiku.cpp | 31 +- platform/haiku/os_haiku.h | 59 +- platform/haiku/power_haiku.cpp | 13 +- platform/haiku/power_haiku.h | 1 + platform/iphone/app_delegate.h | 8 +- platform/iphone/audio_driver_iphone.cpp | 37 +- platform/iphone/audio_driver_iphone.h | 17 +- platform/iphone/game_center.h | 6 +- platform/iphone/gl_view.h | 25 +- platform/iphone/globals/global_defaults.cpp | 1 - platform/iphone/godot_iphone.cpp | 37 +- platform/iphone/icloud.h | 7 +- platform/iphone/in_app_store.h | 9 +- platform/iphone/ios.h | 2 - platform/iphone/os_iphone.cpp | 103 +- platform/iphone/os_iphone.h | 62 +- platform/iphone/platform_refcount.h | 8 +- platform/iphone/power_iphone.cpp | 14 +- platform/iphone/rasterizer_iphone.cpp | 1652 ++-- platform/iphone/rasterizer_iphone.h | 420 +- platform/iphone/sem_iphone.cpp | 33 +- platform/iphone/sem_iphone.h | 3 - platform/iphone/view_controller.h | 3 +- platform/javascript/audio_driver_javascript.cpp | 25 +- platform/javascript/audio_driver_javascript.h | 7 +- platform/javascript/audio_server_javascript.cpp | 2 +- platform/javascript/dom_keys.h | 26 +- platform/javascript/export/export.cpp | 14 +- platform/javascript/javascript_eval.cpp | 28 +- platform/javascript/javascript_eval.h | 5 +- platform/javascript/javascript_main.cpp | 125 +- platform/javascript/os_javascript.cpp | 404 +- platform/javascript/os_javascript.h | 64 +- platform/javascript/power_javascript.cpp | 18 +- platform/javascript/power_javascript.h | 1 - platform/osx/audio_driver_osx.cpp | 36 +- platform/osx/audio_driver_osx.h | 16 +- platform/osx/context_gl_osx.cpp | 42 +- platform/osx/context_gl_osx.h | 4 +- platform/osx/dir_access_osx.h | 13 +- platform/osx/export/export.cpp | 11 +- platform/osx/joypad_osx.cpp | 296 +- platform/osx/joypad_osx.h | 4 +- platform/osx/os_osx.h | 71 +- platform/osx/power_osx.cpp | 66 +- platform/osx/power_osx.h | 2 +- platform/osx/sem_osx.cpp | 25 +- platform/osx/sem_osx.h | 3 - platform/server/godot_server.cpp | 6 +- platform/server/os_server.cpp | 75 +- platform/server/os_server.h | 34 +- platform/uwp/app.cpp | 281 +- platform/uwp/export/export.cpp | 31 +- platform/uwp/gl_context_egl.cpp | 84 +- platform/uwp/gl_context_egl.h | 11 +- platform/uwp/joypad_uwp.cpp | 36 +- platform/uwp/joypad_uwp.h | 11 +- platform/uwp/os_uwp.cpp | 313 +- platform/uwp/os_uwp.h | 116 +- platform/uwp/thread_uwp.cpp | 15 +- platform/uwp/thread_uwp.h | 11 +- platform/windows/context_gl_win.cpp | 126 +- platform/windows/context_gl_win.h | 12 +- platform/windows/ctxgl_procaddr.cpp | 14 +- platform/windows/ctxgl_procaddr.h | 3 +- platform/windows/export/export.cpp | 3 +- platform/windows/godot_win.cpp | 202 +- platform/windows/joypad.cpp | 95 +- platform/windows/joypad.h | 38 +- platform/windows/key_mapping_win.cpp | 373 +- platform/windows/key_mapping_win.h | 9 +- platform/windows/lang_table.h | 296 +- platform/windows/os_windows.cpp | 1455 ++-- platform/windows/os_windows.h | 105 +- platform/windows/packet_peer_udp_winsock.cpp | 124 +- platform/windows/packet_peer_udp_winsock.h | 14 +- platform/windows/power_windows.cpp | 83 +- platform/windows/stream_peer_winsock.cpp | 48 +- platform/windows/stream_peer_winsock.h | 19 +- platform/windows/tcp_server_winsock.cpp | 21 +- platform/windows/tcp_server_winsock.h | 5 +- platform/x11/context_gl_x11.cpp | 117 +- platform/x11/context_gl_x11.h | 13 +- platform/x11/export/export.cpp | 9 +- platform/x11/godot_x11.cpp | 10 +- platform/x11/joypad_linux.cpp | 156 +- platform/x11/joypad_linux.h | 11 +- platform/x11/key_mapping_x11.cpp | 336 +- platform/x11/key_mapping_x11.h | 7 +- platform/x11/os_x11.cpp | 1378 ++-- platform/x11/os_x11.h | 93 +- platform/x11/power_x11.cpp | 177 +- platform/x11/power_x11.h | 11 +- scene/2d/animated_sprite.cpp | 408 +- scene/2d/animated_sprite.h | 86 +- scene/2d/area_2d.cpp | 489 +- scene/2d/area_2d.h | 45 +- scene/2d/back_buffer_copy.cpp | 50 +- scene/2d/back_buffer_copy.h | 9 +- scene/2d/camera_2d.cpp | 452 +- scene/2d/camera_2d.h | 19 +- scene/2d/canvas_item.cpp | 651 +- scene/2d/canvas_item.h | 112 +- scene/2d/canvas_modulate.cpp | 56 +- scene/2d/canvas_modulate.h | 7 +- scene/2d/collision_object_2d.cpp | 228 +- scene/2d/collision_object_2d.h | 30 +- scene/2d/collision_polygon_2d.cpp | 203 +- scene/2d/collision_polygon_2d.h | 19 +- scene/2d/collision_shape_2d.cpp | 107 +- scene/2d/collision_shape_2d.h | 7 +- scene/2d/joints_2d.cpp | 265 +- scene/2d/joints_2d.h | 31 +- scene/2d/light_2d.cpp | 363 +- scene/2d/light_2d.h | 51 +- scene/2d/light_occluder_2d.cpp | 132 +- scene/2d/light_occluder_2d.h | 19 +- scene/2d/line_2d.cpp | 105 +- scene/2d/line_2d.h | 10 +- scene/2d/line_builder.cpp | 214 +- scene/2d/line_builder.h | 6 +- scene/2d/navigation2d.cpp | 556 +- scene/2d/navigation2d.h | 79 +- scene/2d/navigation_polygon.cpp | 291 +- scene/2d/navigation_polygon.h | 34 +- scene/2d/node_2d.cpp | 289 +- scene/2d/node_2d.h | 38 +- scene/2d/parallax_background.cpp | 128 +- scene/2d/parallax_background.h | 22 +- scene/2d/parallax_layer.cpp | 89 +- scene/2d/parallax_layer.h | 12 +- scene/2d/particles_2d.cpp | 814 +- scene/2d/particles_2d.h | 54 +- scene/2d/path_2d.cpp | 230 +- scene/2d/path_2d.h | 29 +- scene/2d/path_texture.cpp | 40 +- scene/2d/path_texture.h | 10 +- scene/2d/physics_body_2d.cpp | 1030 ++- scene/2d/physics_body_2d.h | 86 +- scene/2d/polygon_2d.cpp | 300 +- scene/2d/polygon_2d.h | 23 +- scene/2d/position_2d.cpp | 13 +- scene/2d/position_2d.h | 7 +- scene/2d/ray_cast_2d.cpp | 178 +- scene/2d/ray_cast_2d.h | 18 +- scene/2d/remote_transform_2d.cpp | 32 +- scene/2d/remote_transform_2d.h | 7 +- scene/2d/screen_button.cpp | 240 +- scene/2d/screen_button.h | 25 +- scene/2d/sprite.cpp | 190 +- scene/2d/sprite.h | 17 +- scene/2d/tile_map.cpp | 923 ++- scene/2d/tile_map.h | 114 +- scene/2d/visibility_notifier_2d.cpp | 218 +- scene/2d/visibility_notifier_2d.h | 34 +- scene/2d/y_sort.cpp | 19 +- scene/2d/y_sort.h | 4 +- scene/3d/area.cpp | 488 +- scene/3d/area.h | 46 +- scene/3d/baked_light_instance.cpp | 1437 ++-- scene/3d/baked_light_instance.h | 70 +- scene/3d/body_shape.cpp | 166 +- scene/3d/body_shape.h | 10 +- scene/3d/bone_attachment.cpp | 65 +- scene/3d/bone_attachment.h | 13 +- scene/3d/camera.cpp | 448 +- scene/3d/camera.h | 46 +- scene/3d/character_camera.cpp | 1 - scene/3d/character_camera.h | 1 - scene/3d/collision_object.cpp | 232 +- scene/3d/collision_object.h | 36 +- scene/3d/collision_polygon.cpp | 134 +- scene/3d/collision_polygon.h | 18 +- scene/3d/gi_probe.cpp | 1317 ++-- scene/3d/gi_probe.h | 72 +- scene/3d/immediate_geometry.cpp | 120 +- scene/3d/immediate_geometry.h | 27 +- scene/3d/interpolated_camera.cpp | 66 +- scene/3d/interpolated_camera.h | 8 +- scene/3d/light.cpp | 366 +- scene/3d/light.h | 45 +- scene/3d/listener.cpp | 62 +- scene/3d/listener.h | 15 +- scene/3d/mesh_instance.cpp | 166 +- scene/3d/mesh_instance.h | 28 +- scene/3d/multimesh_instance.cpp | 22 +- scene/3d/multimesh_instance.h | 10 +- scene/3d/navigation.cpp | 577 +- scene/3d/navigation.h | 94 +- scene/3d/navigation_mesh.cpp | 240 +- scene/3d/navigation_mesh.h | 28 +- scene/3d/particles.cpp | 2 +- scene/3d/particles.h | 4 +- scene/3d/path.cpp | 242 +- scene/3d/path.h | 25 +- scene/3d/physics_body.cpp | 942 ++- scene/3d/physics_body.h | 89 +- scene/3d/physics_joint.cpp | 1080 ++- scene/3d/physics_joint.h | 210 +- scene/3d/portal.cpp | 158 +- scene/3d/portal.h | 17 +- scene/3d/position_3d.cpp | 4 +- scene/3d/position_3d.h | 6 +- scene/3d/proximity_group.cpp | 45 +- scene/3d/proximity_group.h | 8 +- scene/3d/quad.cpp | 153 +- scene/3d/quad.h | 13 +- scene/3d/ray_cast.cpp | 139 +- scene/3d/ray_cast.h | 16 +- scene/3d/reflection_probe.cpp | 226 +- scene/3d/reflection_probe.h | 20 +- scene/3d/remote_transform.cpp | 30 +- scene/3d/remote_transform.h | 19 +- scene/3d/room_instance.cpp | 92 +- scene/3d/room_instance.h | 25 +- scene/3d/scenario_fx.cpp | 46 +- scene/3d/scenario_fx.h | 9 +- scene/3d/skeleton.cpp | 393 +- scene/3d/skeleton.h | 50 +- scene/3d/spatial.cpp | 407 +- scene/3d/spatial.h | 81 +- scene/3d/spatial_indexer.cpp | 2 +- scene/3d/sprite_3d.cpp | 721 +- scene/3d/sprite_3d.h | 67 +- scene/3d/test_cube.cpp | 8 +- scene/3d/test_cube.h | 9 +- scene/3d/vehicle_body.cpp | 743 +- scene/3d/vehicle_body.h | 98 +- scene/3d/visibility_notifier.cpp | 176 +- scene/3d/visibility_notifier.h | 33 +- scene/3d/visual_instance.cpp | 232 +- scene/3d/visual_instance.h | 62 +- scene/animation/animation_cache.cpp | 206 +- scene/animation/animation_cache.h | 29 +- scene/animation/animation_player.cpp | 911 +-- scene/animation/animation_player.h | 162 +- scene/animation/animation_tree_player.cpp | 1485 ++-- scene/animation/animation_tree_player.h | 286 +- scene/animation/tween.cpp | 1038 ++- scene/animation/tween.h | 167 +- scene/animation/tween_interpolaters.cpp | 450 +- scene/audio/audio_player.cpp | 184 +- scene/audio/audio_player.h | 16 +- scene/gui/base_button.cpp | 299 +- scene/gui/base_button.h | 39 +- scene/gui/box_container.cpp | 181 +- scene/gui/box_container.h | 27 +- scene/gui/button.cpp | 167 +- scene/gui/button.h | 23 +- scene/gui/button_array.cpp | 472 +- scene/gui/button_array.h | 46 +- scene/gui/center_container.cpp | 33 +- scene/gui/center_container.h | 7 +- scene/gui/check_box.cpp | 45 +- scene/gui/check_box.h | 15 +- scene/gui/check_button.cpp | 27 +- scene/gui/check_button.h | 6 +- scene/gui/color_picker.cpp | 406 +- scene/gui/color_picker.h | 45 +- scene/gui/color_ramp_edit.cpp | 292 +- scene/gui/color_ramp_edit.h | 15 +- scene/gui/color_rect.cpp | 19 +- scene/gui/color_rect.h | 10 +- scene/gui/container.cpp | 65 +- scene/gui/container.h | 9 +- scene/gui/control.cpp | 1831 ++--- scene/gui/control.h | 204 +- scene/gui/dialogs.cpp | 216 +- scene/gui/dialogs.h | 56 +- scene/gui/file_dialog.cpp | 593 +- scene/gui/file_dialog.h | 46 +- scene/gui/graph_edit.cpp | 862 +-- scene/gui/graph_edit.h | 68 +- scene/gui/graph_node.cpp | 556 +- scene/gui/graph_node.h | 47 +- scene/gui/grid_container.cpp | 149 +- scene/gui/grid_container.h | 6 +- scene/gui/input_action.cpp | 70 +- scene/gui/input_action.h | 10 +- scene/gui/item_list.cpp | 1094 ++- scene/gui/item_list.h | 51 +- scene/gui/label.cpp | 565 +- scene/gui/label.h | 28 +- scene/gui/line_edit.cpp | 648 +- scene/gui/line_edit.h | 15 +- scene/gui/link_button.cpp | 73 +- scene/gui/link_button.h | 12 +- scene/gui/margin_container.cpp | 18 +- scene/gui/margin_container.h | 4 +- scene/gui/menu_button.cpp | 39 +- scene/gui/menu_button.h | 11 +- scene/gui/option_button.cpp | 212 +- scene/gui/option_button.h | 26 +- scene/gui/panel.cpp | 10 +- scene/gui/panel.h | 10 +- scene/gui/panel_container.cpp | 46 +- scene/gui/panel_container.h | 5 +- scene/gui/patch_9_rect.cpp | 88 +- scene/gui/patch_9_rect.h | 12 +- scene/gui/popup.cpp | 160 +- scene/gui/popup.h | 26 +- scene/gui/popup_menu.cpp | 812 +- scene/gui/popup_menu.h | 83 +- scene/gui/progress_bar.cpp | 38 +- scene/gui/progress_bar.h | 6 +- scene/gui/range.cpp | 162 +- scene/gui/range.h | 17 +- scene/gui/reference_rect.cpp | 7 +- scene/gui/reference_rect.h | 4 +- scene/gui/rich_text_label.cpp | 1704 ++--- scene/gui/rich_text_label.h | 127 +- scene/gui/scroll_bar.cpp | 519 +- scene/gui/scroll_bar.h | 32 +- scene/gui/scroll_container.cpp | 310 +- scene/gui/scroll_container.h | 9 +- scene/gui/separator.cpp | 29 +- scene/gui/separator.h | 15 +- scene/gui/slider.cpp | 155 +- scene/gui/slider.h | 23 +- scene/gui/spin_box.cpp | 169 +- scene/gui/spin_box.h | 20 +- scene/gui/split_container.cpp | 290 +- scene/gui/split_container.h | 32 +- scene/gui/tab_container.cpp | 75 +- scene/gui/tab_container.h | 28 +- scene/gui/tabs.cpp | 491 +- scene/gui/tabs.h | 25 +- scene/gui/text_edit.cpp | 2903 ++++--- scene/gui/text_edit.h | 154 +- scene/gui/texture_button.cpp | 141 +- scene/gui/texture_button.h | 21 +- scene/gui/texture_progress.cpp | 319 +- scene/gui/texture_progress.h | 14 +- scene/gui/texture_rect.cpp | 104 +- scene/gui/texture_rect.h | 13 +- scene/gui/tool_button.h | 3 +- scene/gui/tree.cpp | 2713 +++---- scene/gui/tree.h | 223 +- scene/gui/video_player.cpp | 168 +- scene/gui/video_player.h | 21 +- scene/gui/viewport_container.cpp | 41 +- scene/gui/viewport_container.h | 6 +- scene/io/resource_format_image.cpp | 4 +- scene/main/canvas_layer.cpp | 167 +- scene/main/canvas_layer.h | 15 +- scene/main/http_request.cpp | 377 +- scene/main/http_request.h | 21 +- scene/main/instance_placeholder.cpp | 51 +- scene/main/instance_placeholder.h | 13 +- scene/main/node.cpp | 1848 ++--- scene/main/node.h | 209 +- scene/main/resource_preloader.cpp | 101 +- scene/main/resource_preloader.h | 21 +- scene/main/scene_main_loop.cpp | 1417 ++-- scene/main/scene_main_loop.h | 246 +- scene/main/timer.cpp | 82 +- scene/main/timer.h | 7 +- scene/main/viewport.cpp | 1515 ++-- scene/main/viewport.h | 157 +- scene/register_scene_types.cpp | 271 +- scene/resources/animation.cpp | 1562 ++-- scene/resources/animation.h | 149 +- scene/resources/audio_stream_resampled.cpp | 1 - scene/resources/audio_stream_sample.cpp | 435 +- scene/resources/audio_stream_sample.h | 36 +- scene/resources/baked_light.cpp | 1 - scene/resources/baked_light.h | 2 - scene/resources/bit_mask.cpp | 145 +- scene/resources/bit_mask.h | 21 +- scene/resources/bounds.cpp | 16 +- scene/resources/bounds.h | 8 +- scene/resources/box_shape.cpp | 32 +- scene/resources/box_shape.h | 6 +- scene/resources/canvas.cpp | 4 +- scene/resources/canvas.h | 4 +- scene/resources/capsule_shape.cpp | 70 +- scene/resources/capsule_shape.h | 6 +- scene/resources/capsule_shape_2d.cpp | 50 +- scene/resources/capsule_shape_2d.h | 10 +- scene/resources/circle_shape_2d.cpp | 31 +- scene/resources/circle_shape_2d.h | 9 +- scene/resources/color_ramp.cpp | 86 +- scene/resources/color_ramp.h | 59 +- scene/resources/concave_polygon_shape.cpp | 62 +- scene/resources/concave_polygon_shape.h | 33 +- scene/resources/concave_polygon_shape_2d.cpp | 42 +- scene/resources/concave_polygon_shape_2d.h | 12 +- scene/resources/convex_polygon_shape.cpp | 37 +- scene/resources/convex_polygon_shape.h | 7 +- scene/resources/convex_polygon_shape_2d.cpp | 53 +- scene/resources/convex_polygon_shape_2d.h | 14 +- scene/resources/curve.cpp | 824 +- scene/resources/curve.h | 57 +- scene/resources/default_theme/default_theme.cpp | 1166 ++- scene/resources/default_theme/default_theme.h | 2 +- scene/resources/dynamic_font.cpp | 702 +- scene/resources/dynamic_font.h | 103 +- scene/resources/dynamic_font_stb.cpp | 334 +- scene/resources/dynamic_font_stb.h | 70 +- scene/resources/environment.cpp | 966 ++- scene/resources/environment.h | 33 +- scene/resources/font.cpp | 407 +- scene/resources/font.h | 73 +- scene/resources/material.cpp | 1110 ++- scene/resources/material.h | 106 +- scene/resources/mesh.cpp | 716 +- scene/resources/mesh.h | 133 +- scene/resources/mesh_data_tool.cpp | 485 +- scene/resources/mesh_data_tool.h | 42 +- scene/resources/mesh_library.cpp | 175 +- scene/resources/mesh_library.h | 32 +- scene/resources/multimesh.cpp | 183 +- scene/resources/multimesh.h | 24 +- scene/resources/packed_scene.cpp | 1128 ++- scene/resources/packed_scene.h | 81 +- scene/resources/plane_shape.cpp | 31 +- scene/resources/plane_shape.h | 5 +- scene/resources/polygon_path_finder.cpp | 487 +- scene/resources/polygon_path_finder.h | 38 +- scene/resources/ray_shape.cpp | 17 +- scene/resources/ray_shape.h | 5 +- scene/resources/rectangle_shape_2d.cpp | 31 +- scene/resources/rectangle_shape_2d.h | 12 +- scene/resources/room.cpp | 22 +- scene/resources/room.h | 13 +- scene/resources/scene_format_text.cpp | 873 +-- scene/resources/scene_format_text.h | 71 +- scene/resources/segment_shape_2d.cpp | 101 +- scene/resources/segment_shape_2d.h | 23 +- scene/resources/shader.cpp | 77 +- scene/resources/shader.h | 56 +- scene/resources/shader_graph.cpp | 47 +- scene/resources/shader_graph.h | 1 - scene/resources/shape.cpp | 39 +- scene/resources/shape.h | 10 +- scene/resources/shape_2d.cpp | 82 +- scene/resources/shape_2d.h | 21 +- scene/resources/shape_line_2d.cpp | 52 +- scene/resources/shape_line_2d.h | 10 +- scene/resources/sky_box.cpp | 134 +- scene/resources/sky_box.h | 19 +- scene/resources/space_2d.cpp | 18 +- scene/resources/space_2d.h | 10 +- scene/resources/sphere_shape.cpp | 40 +- scene/resources/sphere_shape.h | 6 +- scene/resources/style_box.cpp | 290 +- scene/resources/style_box.h | 55 +- scene/resources/surface_tool.cpp | 737 +- scene/resources/surface_tool.h | 87 +- scene/resources/texture.cpp | 1111 ++- scene/resources/texture.h | 237 +- scene/resources/theme.cpp | 690 +- scene/resources/theme.h | 171 +- scene/resources/tile_set.cpp | 373 +- scene/resources/tile_set.h | 51 +- scene/resources/video_stream.cpp | 6 +- scene/resources/video_stream.h | 50 +- scene/resources/world.cpp | 190 +- scene/resources/world.h | 29 +- scene/resources/world_2d.cpp | 234 +- scene/resources/world_2d.h | 28 +- scene/scene_string_names.cpp | 186 +- scene/scene_string_names.h | 22 +- servers/audio/audio_driver_dummy.cpp | 37 +- servers/audio/audio_driver_dummy.h | 14 +- servers/audio/audio_effect.cpp | 4 +- servers/audio/audio_effect.h | 13 +- servers/audio/audio_filter_sw.cpp | 244 +- servers/audio/audio_filter_sw.h | 43 +- servers/audio/audio_rb_resampler.cpp | 325 +- servers/audio/audio_rb_resampler.h | 92 +- servers/audio/audio_stream.cpp | 52 +- servers/audio/audio_stream.h | 59 +- servers/audio/effects/audio_effect_amplify.cpp | 31 +- servers/audio/effects/audio_effect_amplify.h | 18 +- servers/audio/effects/audio_effect_chorus.cpp | 370 +- servers/audio/effects/audio_effect_chorus.h | 64 +- servers/audio/effects/audio_effect_compressor.cpp | 152 +- servers/audio/effects/audio_effect_compressor.h | 28 +- servers/audio/effects/audio_effect_delay.cpp | 313 +- servers/audio/effects/audio_effect_delay.h | 25 +- servers/audio/effects/audio_effect_distortion.cpp | 148 +- servers/audio/effects/audio_effect_distortion.h | 23 +- servers/audio/effects/audio_effect_eq.cpp | 78 +- servers/audio/effects/audio_effect_eq.h | 48 +- servers/audio/effects/audio_effect_filter.cpp | 115 +- servers/audio/effects/audio_effect_filter.h | 77 +- servers/audio/effects/audio_effect_limiter.cpp | 77 +- servers/audio/effects/audio_effect_limiter.h | 21 +- servers/audio/effects/audio_effect_panner.cpp | 28 +- servers/audio/effects/audio_effect_panner.h | 18 +- servers/audio/effects/audio_effect_phaser.cpp | 128 +- servers/audio/effects/audio_effect_phaser.h | 35 +- servers/audio/effects/audio_effect_pitch_shift.cpp | 30 +- servers/audio/effects/audio_effect_pitch_shift.h | 52 +- servers/audio/effects/audio_effect_reverb.cpp | 161 +- servers/audio/effects/audio_effect_reverb.h | 19 +- .../audio/effects/audio_effect_stereo_enhance.cpp | 119 +- .../audio/effects/audio_effect_stereo_enhance.h | 20 +- servers/audio/effects/eq.cpp | 145 +- servers/audio/effects/eq.h | 43 +- servers/audio/effects/reverb.cpp | 279 +- servers/audio/effects/reverb.h | 39 +- servers/audio/reverb_sw.cpp | 520 +- servers/audio/reverb_sw.h | 16 +- servers/audio/voice_rb_sw.h | 36 +- servers/audio_server.cpp | 827 +- servers/audio_server.h | 157 +- servers/physics/area_pair_sw.cpp | 81 +- servers/physics/area_pair_sw.h | 15 +- servers/physics/area_sw.cpp | 172 +- servers/physics/area_sw.h | 93 +- servers/physics/body_pair_sw.cpp | 331 +- servers/physics/body_pair_sw.h | 22 +- servers/physics/body_sw.cpp | 394 +- servers/physics/body_sw.h | 262 +- servers/physics/broad_phase_basic.cpp | 135 +- servers/physics/broad_phase_basic.h | 34 +- servers/physics/broad_phase_octree.cpp | 76 +- servers/physics/broad_phase_octree.h | 21 +- servers/physics/broad_phase_sw.cpp | 5 +- servers/physics/broad_phase_sw.h | 33 +- servers/physics/collision_object_sw.cpp | 135 +- servers/physics/collision_object_sw.h | 66 +- servers/physics/collision_solver_sat.cpp | 1271 ++-- servers/physics/collision_solver_sat.h | 3 +- servers/physics/collision_solver_sw.cpp | 294 +- servers/physics/collision_solver_sw.h | 22 +- servers/physics/constraint_sw.h | 30 +- servers/physics/gjk_epa.cpp | 19 +- servers/physics/gjk_epa.h | 4 +- servers/physics/joints/cone_twist_joint_sw.cpp | 234 +- servers/physics/joints/cone_twist_joint_sw.h | 74 +- servers/physics/joints/generic_6dof_joint_sw.cpp | 563 +- servers/physics/joints/generic_6dof_joint_sw.h | 507 +- servers/physics/joints/hinge_joint_sw.cpp | 299 +- servers/physics/joints/hinge_joint_sw.h | 46 +- servers/physics/joints/jacobian_entry_sw.h | 123 +- servers/physics/joints/pin_joint_sw.cpp | 89 +- servers/physics/joints/pin_joint_sw.h | 29 +- servers/physics/joints/slider_joint_sw.cpp | 303 +- servers/physics/joints/slider_joint_sw.h | 87 +- servers/physics/joints_sw.h | 11 +- servers/physics/physics_server_sw.cpp | 747 +- servers/physics/physics_server_sw.h | 135 +- servers/physics/shape_sw.cpp | 1195 ++- servers/physics/shape_sw.h | 233 +- servers/physics/space_sw.cpp | 561 +- servers/physics/space_sw.h | 84 +- servers/physics/step_sw.cpp | 201 +- servers/physics/step_sw.h | 12 +- servers/physics_2d/area_2d_sw.cpp | 176 +- servers/physics_2d/area_2d_sw.h | 91 +- servers/physics_2d/area_pair_2d_sw.cpp | 83 +- servers/physics_2d/area_pair_2d_sw.h | 15 +- servers/physics_2d/body_2d_sw.cpp | 394 +- servers/physics_2d/body_2d_sw.h | 241 +- servers/physics_2d/body_pair_2d_sw.cpp | 331 +- servers/physics_2d/body_pair_2d_sw.h | 22 +- servers/physics_2d/broad_phase_2d_basic.cpp | 120 +- servers/physics_2d/broad_phase_2d_basic.h | 36 +- servers/physics_2d/broad_phase_2d_hash_grid.cpp | 479 +- servers/physics_2d/broad_phase_2d_hash_grid.h | 80 +- servers/physics_2d/broad_phase_2d_sw.cpp | 5 +- servers/physics_2d/broad_phase_2d_sw.h | 35 +- servers/physics_2d/collision_object_2d_sw.cpp | 144 +- servers/physics_2d/collision_object_2d_sw.h | 68 +- servers/physics_2d/collision_solver_2d_sat.cpp | 1171 ++- servers/physics_2d/collision_solver_2d_sat.h | 3 +- servers/physics_2d/collision_solver_2d_sw.cpp | 186 +- servers/physics_2d/collision_solver_2d_sw.h | 16 +- servers/physics_2d/constraint_2d_sw.h | 27 +- servers/physics_2d/joints_2d_sw.cpp | 260 +- servers/physics_2d/joints_2d_sw.h | 44 +- servers/physics_2d/physics_2d_server_sw.cpp | 613 +- servers/physics_2d/physics_2d_server_sw.h | 117 +- servers/physics_2d/physics_2d_server_wrap_mt.cpp | 78 +- servers/physics_2d/physics_2d_server_wrap_mt.h | 273 +- servers/physics_2d/shape_2d_sw.cpp | 878 +-- servers/physics_2d/shape_2d_sw.h | 414 +- servers/physics_2d/space_2d_sw.cpp | 926 +-- servers/physics_2d/space_2d_sw.h | 94 +- servers/physics_2d/step_2d_sw.cpp | 204 +- servers/physics_2d/step_2d_sw.h | 12 +- servers/physics_2d_server.cpp | 704 +- servers/physics_2d_server.h | 405 +- servers/physics_server.cpp | 767 +- servers/physics_server.h | 446 +- servers/register_server_types.cpp | 66 +- servers/server_wrap_mt_common.h | 1397 ++-- servers/visual/rasterizer.cpp | 11 +- servers/visual/rasterizer.h | 861 ++- servers/visual/shader_language.cpp | 3466 ++++----- servers/visual/shader_language.h | 172 +- servers/visual/shader_types.cpp | 242 +- servers/visual/shader_types.h | 14 +- servers/visual/visual_server_canvas.cpp | 902 +-- servers/visual/visual_server_canvas.h | 156 +- servers/visual/visual_server_global.cpp | 14 +- servers/visual/visual_server_global.h | 4 +- servers/visual/visual_server_light_baker.cpp | 4 +- servers/visual/visual_server_light_baker.h | 7 - servers/visual/visual_server_raster.cpp | 85 +- servers/visual/visual_server_raster.h | 770 +- servers/visual/visual_server_scene.cpp | 2230 +++--- servers/visual/visual_server_scene.h | 284 +- servers/visual/visual_server_viewport.cpp | 378 +- servers/visual/visual_server_viewport.h | 102 +- servers/visual_server.cpp | 1161 ++- servers/visual_server.h | 859 +-- 1318 files changed, 140937 insertions(+), 166890 deletions(-) mode change 100755 => 100644 platform/iphone/gl_view.h mode change 100755 => 100644 platform/iphone/globals/global_defaults.cpp 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 +template 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, 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; + 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;ihand& 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;inext; + 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 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 avs; - avs.compare.obj=p_obj; - avs.compare.func=p_function; - avs.sort(_p->array.ptr(),_p->array.size()); - + SortArray 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 _ResourceLoader::load_interactive(const String& p_path,const String& p_type_hint) { - return ResourceLoader::load_interactive(p_path,p_type_hint); +Ref _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 _ResourceLoader::get_recognized_extensions_for_type(const String& p_type) { +PoolVector _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) { List exts; - ResourceLoader::get_recognized_extensions_for_type(p_type,&exts); + ResourceLoader::get_recognized_extensions_for_type(p_type, &exts); PoolVector ret; - for(List::Element *E=exts.front();E;E=E->next()) { + for (List::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 deps; ResourceLoader::get_dependencies(p_path, &deps); PoolStringArray ret; - for(List::Element *E=deps.front();E;E=E->next()) { + for (List::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 _ResourceSaver::get_recognized_extensions(const RES& p_resource) { +PoolVector _ResourceSaver::get_recognized_extensions(const RES &p_resource) { - ERR_FAIL_COND_V(p_resource.is_null(),PoolVector()); + ERR_FAIL_COND_V(p_resource.is_null(), PoolVector()); List exts; - ResourceSaver::get_recognized_extensions(p_resource,&exts); + ResourceSaver::get_recognized_extensions(p_resource, &exts); PoolVector ret; - for(List::Element *E=exts.front();E;E=E->next()) { + for (List::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 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::Element *E=vmlist.front();E;E=E->next() ){ + for (List::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 & p_arguments, bool p_blocking, Array p_output) { +int _OS::execute(const String &p_path, const Vector &p_arguments, bool p_blocking, Array p_output) { OS::ProcessID pid; List args; - for(int i=0;iexecute(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 _OS::get_cmdline_args() { List cmdline = OS::get_singleton()->get_cmdline_args(); Vector cmdlinev; - for(List::Element *E=cmdline.front();E;E=E->next()) { + for (List::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 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(datetime[SECOND_KEY]): 0); - unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast(datetime[MINUTE_KEY]): 0); - unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast(datetime[HOUR_KEY]): 0); - unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast(datetime[DAY_KEY]): 0); - unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast(datetime[MONTH_KEY]) -1: 0); - unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast(datetime[YEAR_KEY]):0); + unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast(datetime[SECOND_KEY]) : 0); + unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast(datetime[MINUTE_KEY]) : 0); + unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast(datetime[HOUR_KEY]) : 0); + unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast(datetime[DAY_KEY]) : 0); + unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast(datetime[MONTH_KEY]) - 1 : 0); + unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast(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(imonth+1); + date.month = static_cast(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.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 > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List >::Element *E=rsrc.front();E;E=E->next()) { + for (List >::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& p_types) { +void _OS::print_resources_by_type(const Vector &p_types) { - Map type_count; + Map type_count; List > resources; ResourceCache::get_cached_resources(&resources); @@ -841,13 +815,13 @@ void _OS::print_resources_by_type(const Vector& p_types) { List > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List >::Element *E=rsrc.front();E;E=E->next()) { + for (List >::Element *E = rsrc.front(); E; E = E->next()) { Ref r = E->get(); bool found = false; - for (int i=0; iis_class(p_types[i])) found = true; } @@ -855,20 +829,18 @@ void _OS::print_resources_by_type(const Vector& 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 _Geometry::build_box_planes(const Vector3& p_extents) { +PoolVector _Geometry::build_box_planes(const Vector3 &p_extents) { return Geometry::build_box_planes(p_extents); } PoolVector _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 _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 _Geometry::get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2) { +PoolVector _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 r; r.resize(2); - r.set(0,r1); - r.set(1,r2); + r.set(0, r1); + r.set(1, r2); return r; } -PoolVector _Geometry::get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2) { +PoolVector _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 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 _Geometry::segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius) { +PoolVector _Geometry::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) { PoolVector 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 _Geometry::segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius) { +PoolVector _Geometry::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) { PoolVector 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 _Geometry::segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector& p_planes) { +PoolVector _Geometry::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector &p_planes) { PoolVector 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 _Geometry::triangulate_polygon(const Vector& p_polygon) { +Vector _Geometry::triangulate_polygon(const Vector &p_polygon) { return Geometry::triangulate_polygon(p_polygon); } -Dictionary _Geometry::make_atlas(const Vector& p_rects) { +Dictionary _Geometry::make_atlas(const Vector &p_rects) { Dictionary ret; Vector rects; - for (int i=0; i& p_rects) { Size2 r_size = size; Vector r_result; - for (int i=0; i &p_key) { - -Error _File::open_encrypted(const String& p_path, int p_mode_flags,const Vector& 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 _File::get_buffer(int p_length) const{ +PoolVector _File::get_buffer(int p_length) const { PoolVector 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::Write w = data.write(); - int len = f->get_buffer(&w[0],p_length); - ERR_FAIL_COND_V( len < 0 , PoolVector()); + int len = f->get_buffer(&w[0], p_length); + ERR_FAIL_COND_V(len < 0, PoolVector()); w = PoolVector::Write(); @@ -1563,10 +1498,8 @@ PoolVector _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 _File::get_csv_line(String delim) const { - ERR_FAIL_COND_V(!f,Vector()); + ERR_FAIL_COND_V(!f, Vector()); return f->get_csv_line(delim); } @@ -1620,79 +1546,76 @@ Vector _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& p_buffer){ +void _File::store_buffer(const PoolVector &p_buffer) { ERR_FAIL_COND(!f); int len = p_buffer.size(); - if (len==0) + if (len == 0) return; PoolVector::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 buff; buff.resize(len); PoolVector::Write w = buff.write(); - err = encode_variant(p_var,&w[0],len); - ERR_FAIL_COND( err != OK ); - w=PoolVector::Write(); + err = encode_variant(p_var, &w[0], len); + ERR_FAIL_COND(err != OK); + w = PoolVector::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 buff = get_buffer(len); ERR_FAIL_COND_V(buff.size() != len, Variant()); @@ -1761,8 +1682,8 @@ Variant _File::get_var() const { PoolVector::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 buff; buff.resize(len); PoolVector::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 b64buff; b64buff.resize(b64len); PoolVector::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::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 &p_arr) { b64buff.resize(b64len); PoolVector::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 _Marshalls::base64_to_raw(const String &p_str) { buf.resize(strlen / 4 * 3 + 1); PoolVector::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 _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::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::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 classes; @@ -2392,29 +2277,28 @@ PoolStringArray _ClassDB::get_class_list() const { PoolStringArray ret; ret.resize(classes.size()); - int idx=0; - for (List::Element *E=classes.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List::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 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::Element *E=classes.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List::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 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::Element *E=signals.front();E;E=E->next()) { + for (List::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 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::Element *E=plist.front();E;E=E->next()) { + for (List::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 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::Element *E=methods.front();E;E=E->next()) { + for (List::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 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::Element *E=constants.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List::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 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 get_recognized_extensions_for_type(const String& p_type); + Ref 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 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 get_recognized_extensions(const RES& p_resource); - + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags); + PoolVector 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 & p_arguments,bool p_blocking,Array p_output=Array()); + int execute(const String &p_path, const Vector &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 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& p_types); + void print_resources_by_type(const Vector &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 build_box_planes(const Vector3& p_extents); - PoolVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - PoolVector 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 get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2); - PoolVector 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 segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius); - PoolVector segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius); - PoolVector segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector& 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 triangulate_polygon(const Vector& p_polygon); - - Dictionary make_atlas(const Vector& p_rects); + PoolVector build_box_planes(const Vector3 &p_extents); + PoolVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + PoolVector 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 get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2); + PoolVector 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 segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius); + PoolVector segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius); + PoolVector segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector &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 triangulate_polygon(const Vector &p_polygon); + + Dictionary make_atlas(const Vector &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& 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 &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 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 get_csv_line(String delim=",") const; + Vector get_csv_line(String delim = ",") const; + void store_buffer(const PoolVector &p_buffer); ///< store an array of bytes - void store_buffer(const PoolVector& 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& p_arr); - PoolVector base64_to_raw(const String& p_str); + String raw_to_base64(const PoolVector &p_arr); + PoolVector 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 ClassDB::classes; -HashMap ClassDB::resource_base_extensions; -HashMap ClassDB::compat_classes; +HashMap ClassDB::classes; +HashMap ClassDB::resource_base_extensions; +HashMap 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 *p_classes) { +void ClassDB::get_class_list(List *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 *p_classes) { p_classes->sort(); } - -void ClassDB::get_inheriters_from_class( const StringName& p_class,List *p_classes) { +void ClassDB::get_inheriters_from_class(const StringName &p_class, List *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 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(); - for (List::Element *E=names.front();E;E=E->next()) { + for (List::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 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(); - for (List::Element *F=snames.front();F;F=F->next()) { + for (List::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;iget_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;iget_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 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(); - for (List::Element *F=snames.front();F;F=F->next()) { + for (List::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 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(); - for (List::Element *F=snames.front();F;F=F->next()) { + for (List::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;iget().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 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(); - for (List::Element *F=snames.front();F;F=F->next()) { + for (List::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::Element *F=t->property_list.front();F;F=F->next()) { + for (List::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 *p_methods,bool p_no_inheritance) { - +void ClassDB::get_method_list(StringName p_class, List *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::Element *E=type->virtual_methods.front();E;E=E->next()) { + for (List::Element *E = type->virtual_methods.front(); E; E = E->next()) { p_methods->push_back(E->get()); } - for( List::Element *E=type->method_order.front();E;E=E->next()) { + for (List::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;iget_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 *p_constants, bool p_no_inheritance) { +void ClassDB::get_integer_constant_list(const StringName &p_class, List *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::Element *E=type->constant_order.front();E;E=E->next()) + for (List::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 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 *p_signals,bool p_no_inheritance) { +void ClassDB::get_signal_list(StringName p_class, List *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 *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 *p_list, bool p_no_inheritance,const Object *p_validator) { +void ClassDB::get_property_list(StringName p_class, List *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::Element *E=check->property_list.front();E;E=E->next()) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { + for (List::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 *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 defvals; defvals.resize(p_defcount); - for(int i=0;iset_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 * p_methods , bool p_no_inheritance) { +void ClassDB::get_virtual_methods(const StringName &p_class, List *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::Element *E=check->virtual_methods.front();E;E=E->next()) { + for (List::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 *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 *p_extensions) { +void ClassDB::get_extensions_for_type(const StringName &p_class, List *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 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 method_map; - HashMap constant_map; - HashMap signal_map; + HashMap method_map; + HashMap constant_map; + HashMap signal_map; List property_list; #ifdef DEBUG_METHODS_ENABLED List constant_order; @@ -143,44 +141,42 @@ public: List virtual_methods; StringName category; #endif - HashMap property_setget; - + HashMap property_setget; StringName inherits; StringName name; bool disabled; - Object* (*creation_func)(); + Object *(*creation_func)(); ClassInfo(); ~ClassInfo(); }; - template + template static Object *creator() { - return memnew( T ); + return memnew(T); } static RWLock *lock; - static HashMap classes; - static HashMap resource_base_extensions; - static HashMap compat_classes; + static HashMap classes; + static HashMap resource_base_extensions; + static HashMap 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 + template 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 + template 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->creation_func = &creator; T::register_custom_data_to_otdb(); } - template + template static void register_virtual_class() { GLOBAL_LOCK_FUNCTION; @@ -223,29 +219,29 @@ public: //nothing } - template - static Object* _create_ptr_func() { + template + static Object *_create_ptr_func() { return T::create(); } - template + template 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->creation_func = &_create_ptr_func; T::register_custom_data_to_otdb(); } - static void get_class_list( List *p_classes); - static void get_inheriters_from_class( const StringName& p_class,List *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 *p_classes); + static void get_inheriters_from_class(const StringName &p_class, List *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 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 - static MethodBind* bind_method(N p_method_name, M p_method) { + template + 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 - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1) { + template + 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 - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2) { + template + 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 - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3) { + template + 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 - 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 + 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 - 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 + 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 - 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 + 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 - static MethodBind* bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method,const MethodInfo& p_info=MethodInfo(),const Vector& p_default_args=Vector()) { + template + static MethodBind *bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method, const MethodInfo &p_info = MethodInfo(), const Vector &p_default_args = Vector()) { 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 *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 *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 *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 *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 *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 *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 * 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 *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 *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 *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 *p_extensions); - static void get_extensions_for_type(const StringName& p_class,List *p_extensions); + static void get_extensions_for_type(const StringName &p_class, List *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::Element* color = _named_colors.find(name); - if(color) { + + const Map::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 */ @@ -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 (adelay_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 */ @@ -48,69 +48,69 @@ class CommandQueueMT { struct CommandBase { - virtual void call()=0; - virtual ~CommandBase() {}; + virtual void call() = 0; + virtual ~CommandBase(){}; }; - template + template struct Command0 : public CommandBase { - T*instance; + T *instance; M method; virtual void call() { (instance->*method)(); } }; - template + template struct Command1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; virtual void call() { (instance->*method)(p1); } }; - template + template struct Command2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; - virtual void call() { (instance->*method)(p1,p2); } + virtual void call() { (instance->*method)(p1, p2); } }; - template + template struct Command3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; - virtual void call() { (instance->*method)(p1,p2,p3); } + virtual void call() { (instance->*method)(p1, p2, p3); } }; - template + template struct Command4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::type_t p4; - virtual void call() { (instance->*method)(p1,p2,p3,p4); } + virtual void call() { (instance->*method)(p1, p2, p3, p4); } }; - template + template struct Command5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -118,13 +118,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::type_t p5; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5); } }; - template + template struct Command6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -133,13 +133,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::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 + template struct Command7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -149,13 +149,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::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 + template struct Command8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -166,96 +166,120 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p7; typename GetSimpleTypeT::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 + template 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 + template struct CommandRet1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::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 + template struct CommandRet2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandRet3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::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 + template struct CommandRet4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::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 + template struct CommandRet5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::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 + template struct CommandRet6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -263,16 +287,20 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::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 + template struct CommandRet7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -281,16 +309,20 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::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 + template struct CommandRet8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -300,56 +332,72 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::type_t p7; typename GetSimpleTypeT::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 + template 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 + template struct CommandSync1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::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 + template struct CommandSync2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 + template struct CommandSync8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::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 - T* allocate() { + template + 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 - T* allocate_and_lock() { + template + T *allocate_and_lock() { lock(); - T* ret; + T *ret; - while ( (ret=allocate())==NULL ) { + while ((ret = allocate()) == 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( &command_mem[read_ptr] ); + CommandBase *cmd = reinterpret_cast(&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 - void push( T * p_instance, M p_method ) { + template + void push(T *p_instance, M p_method) { - Command0 * cmd = allocate_and_lock< Command0 >(); + Command0 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; + cmd->instance = p_instance; + cmd->method = p_method; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1 ) { + template + void push(T *p_instance, M p_method, P1 p1) { - Command1 * cmd = allocate_and_lock< Command1 >(); + Command1 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2) { - Command2 * cmd = allocate_and_lock< Command2 >(); + Command2 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - Command3 * cmd = allocate_and_lock< Command3 >(); + Command3 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - Command4 * cmd = allocate_and_lock< Command4 >(); + Command4 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - Command5 * cmd = allocate_and_lock< Command5 >(); + Command5 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - Command6 * cmd = allocate_and_lock< Command6 >(); + Command6 *cmd = allocate_and_lock >(); - 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 - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { - Command7 * cmd = allocate_and_lock< Command7 >(); + Command7 *cmd = allocate_and_lock >(); - 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 - 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 + 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 * cmd = allocate_and_lock< Command8 >(); + Command8 *cmd = allocate_and_lock >(); - 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 + void push_and_ret(T *p_instance, M p_method, R *r_ret) { - template - void push_and_ret( T * p_instance, M p_method, R* r_ret) { - - CommandRet0 * cmd = allocate_and_lock< CommandRet0 >(); + CommandRet0 *cmd = allocate_and_lock >(); - 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 - void push_and_ret( T * p_instance, M p_method, P1 p1, R* r_ret) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, R *r_ret) { - CommandRet1 * cmd = allocate_and_lock< CommandRet1 >(); + CommandRet1 *cmd = allocate_and_lock >(); - 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 - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, R* r_ret) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, R *r_ret) { - CommandRet2 * cmd = allocate_and_lock< CommandRet2 >(); + CommandRet2 *cmd = allocate_and_lock >(); - 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 - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, R *r_ret) { - CommandRet3 * cmd = allocate_and_lock< CommandRet3 >(); + CommandRet3 *cmd = allocate_and_lock >(); - 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 - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R *r_ret) { - CommandRet4 * cmd = allocate_and_lock< CommandRet4 >(); + CommandRet4 *cmd = allocate_and_lock >(); - 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 - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R *r_ret) { - CommandRet5 * cmd = allocate_and_lock< CommandRet5 >(); + CommandRet5 *cmd = allocate_and_lock >(); - 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 - 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 + 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 * cmd = allocate_and_lock< CommandRet6 >(); + CommandRet6 *cmd = allocate_and_lock >(); - 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 - 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 + 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 * cmd = allocate_and_lock< CommandRet7 >(); + CommandRet7 *cmd = allocate_and_lock >(); - 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 - 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 * cmd = allocate_and_lock< CommandRet8 >(); - - 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 + 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 *cmd = allocate_and_lock >(); + + 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 + void push_and_sync(T *p_instance, M p_method) { - template - void push_and_sync( T * p_instance, M p_method) { + CommandSync0 *cmd = allocate_and_lock >(); - CommandSync0 * cmd = allocate_and_lock< CommandSync0 >(); + 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 - void push_and_sync( T * p_instance, M p_method, P1 p1) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1) { - CommandSync1 * cmd = allocate_and_lock< CommandSync1 >(); + CommandSync1 *cmd = allocate_and_lock >(); - 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 - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2) { - CommandSync2 * cmd = allocate_and_lock< CommandSync2 >(); + CommandSync2 *cmd = allocate_and_lock >(); - 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 - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - CommandSync3 * cmd = allocate_and_lock< CommandSync3 >(); + CommandSync3 *cmd = allocate_and_lock >(); - 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 - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - CommandSync4 * cmd = allocate_and_lock< CommandSync4 >(); + CommandSync4 *cmd = allocate_and_lock >(); - 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 - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - CommandSync5 * cmd = allocate_and_lock< CommandSync5 >(); + CommandSync5 *cmd = allocate_and_lock >(); - 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 - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - CommandSync6 * cmd = allocate_and_lock< CommandSync6 >(); + CommandSync6 *cmd = allocate_and_lock >(); - 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 - 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 + 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 * cmd = allocate_and_lock< CommandSync7 >(); + CommandSync7 *cmd = allocate_and_lock >(); - 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 - 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 + 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 * cmd = allocate_and_lock< CommandSync8 >(); + CommandSync8 *cmd = allocate_and_lock >(); - 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<\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<\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", "", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad", + " we", "ly", "ee", " n", "id", " cl", "ac", "il", " 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 &p_from) { List 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 > > buckets; - Vector< Map< uint32_t, int > > table; - Vector< uint32_t > hfunc_table; - Vector< _PHashTranslationCmp > compressed; + print_line("compressing keys: " + itos(keys.size())); + Vector > > buckets; + Vector > table; + Vector 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::Element *E=keys.front();E;E=E->next()) { + for (List::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 p; - p.first=idx; - p.second=cs; + uint32_t h = hash(0, cs.get_data()); + Pair 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 > &b = buckets[i]; - Map< uint32_t, int > &t=table[i]; + Vector > &b = buckets[i]; + Map &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 &p_from) { PoolVector::Write htwb = hash_table.write(); PoolVector::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 &t=table[i]; - if (t.size()==0) { - htw[i]=0xFFFFFFFF; //nothing + Map &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::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::Write cw = strings.write(); - for(int i=0;iget_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::Read htr = hash_table.read(); - const uint32_t *htptr = (const uint32_t*)&htr[0]; - PoolVector::Read btr = bucket_table.read(); - const uint32_t *btptr = (const uint32_t*)&btr[0]; + PoolVector::Read htr = hash_table.read(); + const uint32_t *htptr = (const uint32_t *)&htr[0]; + PoolVector::Read btr = bucket_table.read(); + const uint32_t *btptr = (const uint32_t *)&btr[0]; PoolVector::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 *p_list) const { -void PHashTranslation::_get_property_list( List *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 bucket_table; PoolVector 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 *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 *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 &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_map; + HashMap variant_map; int counter; - }; struct DictionaryPrivateSort { - bool operator()(const HashMap::Pair *A,const HashMap::Pair *B) const { + bool operator()(const HashMap::Pair *A, const HashMap::Pair *B) const { return A->data.order < B->data.order; } }; -void Dictionary::get_key_list( List *p_keys) const { +void Dictionary::get_key_list(List *p_keys) const { if (_p->variant_map.empty()) return; int count = _p->variant_map.size(); - const HashMap::Pair **pairs = (const HashMap::Pair**)alloca( count * sizeof(HashMap::Pair *) ); + const HashMap::Pair **pairs = (const HashMap::Pair **)alloca(count * sizeof(HashMap::Pair *)); _p->variant_map.get_key_value_ptr_array(pairs); - SortArray::Pair*,DictionaryPrivateSort> sort; - sort.sort(pairs,count); + SortArray::Pair *, DictionaryPrivateSort> sort; + sort.sort(pairs, count); - for(int i=0;ipush_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;ivariant_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 keys; get_key_list(&keys); - for (List::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::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::Pair **pairs = (const HashMap::Pair**)alloca( count * sizeof(HashMap::Pair *) ); + const HashMap::Pair **pairs = (const HashMap::Pair **)alloca(count * sizeof(HashMap::Pair *)); _p->variant_map.get_key_value_ptr_array(pairs); - SortArray::Pair*,DictionaryPrivateSort> sort; - sort.sort(pairs,count); + SortArray::Pair *, DictionaryPrivateSort> sort; + sort.sort(pairs, count); - for(int i=0;idata.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 keys; get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { - n[E->get()]=operator[](E->get()); + for (List::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 *p_keys) const; +public: + void get_key_list(List *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;i0); - + 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 */ - -template +template 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;isize / 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;isize / 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;ilock(); - 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 - void fill_with(const MC& p_mc) { - + template + 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& 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 &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 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& aux=*((PoolVector*)0); // nullreturn - ERR_FAIL_COND_V(p_from<0 || p_from>=size(),aux) + if (p_from < 0 || p_from >= size()) { + PoolVector &aux = *((PoolVector *)0); // nullreturn + ERR_FAIL_COND_V(p_from < 0 || p_from >= size(), aux) } - if (p_to<0 || p_to>=size()) { - PoolVector& aux=*((PoolVector*)0); // nullreturn - ERR_FAIL_COND_V(p_to<0 || p_to>=size(),aux) + if (p_to < 0 || p_to >= size()) { + PoolVector &aux = *((PoolVector *)0); // nullreturn + ERR_FAIL_COND_V(p_to < 0 || p_to >= size(), aux) } PoolVector 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; ip_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;ilock>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 +template int PoolVector::size() const { - return alloc ? alloc->size/sizeof(T) : 0; + return alloc ? alloc->size / sizeof(T) : 0; } -template +template T PoolVector::get(int p_index) const { return operator[](p_index); } -template -void PoolVector::set(int p_index, const T& p_val) { +template +void PoolVector::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 -void PoolVector::push_back(const T& p_val) { +template +void PoolVector::push_back(const T &p_val) { - resize( size() + 1 ); - set( size() -1, p_val ); + resize(size() + 1); + set(size() - 1, p_val); } -template +template const T PoolVector::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::operator[](int p_index) const { return r[p_index]; } - -template +template Error PoolVector::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::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::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::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::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 +template void PoolVector::invert() { T temp; Write w = write(); int s = size(); - int half_s = s/2; + int half_s = s / 2; - for(int i=0;i0? 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;iargs;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 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 ps = s.substr(0,sl).split("."); - String prop=s.substr(sl,s.length()-sl); - for(int i=1;i 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_list) const { @@ -195,66 +187,63 @@ void GlobalConfig::_get_property_list(List *p_list) const { Set<_VCSort> vclist; - for(Map::Element *E=props.front();E;E=E->next()) { + for (Map::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(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;iget_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 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 > &props,const CustomMap& p_custom) { - +Error GlobalConfig::_save_settings_binary(const String &p_file, const Map > &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 >::Element *E=props.front();E;E=E->next()) { + for (Map >::Element *E = props.front(); E; E = E->next()) { - for(List::Element *F=E->get().front();F;F=F->next()) { + for (List::Element *F = E->get().front(); F; F = F->next()) { count++; } @@ -535,17 +501,16 @@ Error GlobalConfig::_save_settings_binary(const String& p_file,const Mapstore_32(count); //store how many properties are saved + for (Map >::Element *E = props.front(); E; E = E->next()) { - for(Map >::Element *E=props.front();E;E=E->next()) { - - for(List::Element *F=E->get().front();F;F=F->next()) { + for (List::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 Mapstore_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 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 > &props,const CustomMap& p_custom) { +Error GlobalConfig::_save_settings_text(const String &p_file, const Map > &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 >::Element *E = props.front(); E; E = E->next()) { - for(Map >::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::Element *F=E->get().front();F;F=F->next()) { + if (E->key() != "") + file->store_string("[" + E->key() + "]\n\n"); + for (List::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& p_ignore_masks) { +Error GlobalConfig::save_custom(const String &p_path, const CustomMap &p_custom, const Set &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::Element *G=props.front();G;G=G->next()) { + for (Map::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::Element *E=p_ignore_masks.front();E;E=E->next()) { + for (const Set::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::Element *E=p_custom.front();E;E=E->next()) { - + for (const Map::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 > props; + Map > 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::Element *E=singleton_ptrs.find(p_name); + const Map::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 *p_singletons) { - for(List::Element *E=singletons.front();E;E=E->next()) + for (List::Element *E = singletons.front(); E; E = E->next()) p_singletons->push_back(E->get()); } @@ -800,20 +753,19 @@ Vector GlobalConfig::get_optimizer_presets() const { GlobalConfig::get_singleton()->get_property_list(&pi); Vector names; - for (List::Element *E=pi.front();E;E=E->next()) { + for (List::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 */ - class GlobalConfig : public Object { - GDCLASS( GlobalConfig, Object ); + GDCLASS(GlobalConfig, Object); _THREAD_SAFE_CLASS_ public: - - typedef Map CustomMap; + typedef Map 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 props; + Map props; String resource_path; - Map custom_prop_info; + Map custom_prop_info; bool disable_platform_override; bool using_datapack; List 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 *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 > &props,const CustomMap& p_custom=CustomMap()); - Error _save_settings_binary(const String& p_file,const Map > &props,const CustomMap& p_custom=CustomMap()); + Error _save_settings_text(const String &p_file, const Map > &props, const CustomMap &p_custom = CustomMap()); + Error _save_settings_binary(const String &p_file, const Map > &props, const CustomMap &p_custom = CustomMap()); List singletons; - Map singleton_ptrs; + Map 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& p_ignore_masks=Set()); + Error save_custom(const String &p_path = "", const CustomMap &p_custom = CustomMap(), const Set &p_ignore_masks = Set()); 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 *p_singletons); - bool has_singleton(const String& p_name) const; + bool has_singleton(const String &p_name) const; Vector get_optimizer_presets() const; List 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 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, uint8_t MIN_HASH_TABLE_POWER=3,uint8_t RELATIONSHIP=8> +template , 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< ( (1< ((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< ((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<next; - int new_pos = se->hash & ((1<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 == 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<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<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( get_entry(p_pair.key) ); + e = const_cast(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(get_entry(p_key )); + Entry *e = const_cast(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(get_entry(p_key )); + const Entry *e = const_cast(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 - _FORCE_INLINE_ TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) { + template + _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 == 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 - _FORCE_INLINE_ const TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) const { + template + _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 == 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 == 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( get_entry(p_key) ); + e = const_cast(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<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 & ((1 << hash_table_power) - 1); index++; - for (int i=index;i<(1<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<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<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 *p_keys) const { if (!hash_table) return; - for(int i=0;i<(1<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> 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 +template 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 +template 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 - -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>=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 -static void _convert( int p_width,int p_height,const uint8_t* p_src,uint8_t* p_dst ){ - - +template +static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) { - for(int y=0;y=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::Read(); w = PoolVector::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 -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 +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 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 -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 +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; - - 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> 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>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 +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 -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;iMAX_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::Read r = data.read(); - const unsigned char*r_ptr=r.ptr(); + const unsigned char *r_ptr = r.ptr(); PoolVector::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::Read(); w = PoolVector::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::Read r = data.read(); PoolVector::Write w = dst.data.write(); - for (int y=0;y=width || y>=height)) { - for(uint32_t i=0;i= 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::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::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>=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 -static void _generate_po2_mipmap(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_width, uint32_t p_height) { +template +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>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 dest; - dest.resize(width*2*height*2*4); + dest.resize(width * 2 * height * 2 * 4); { PoolVector::Read r = data.read(); PoolVector::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::Write w=new_img.write(); - PoolVector::Read r=data.read(); + PoolVector::Write w = new_img.write(); + PoolVector::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 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::Write w=new_img.write(); - PoolVector::Read r=data.read(); + PoolVector::Write w = new_img.write(); + PoolVector::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::Write wp=data.write(); + PoolVector::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(&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(&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 Image::get_data() const { @@ -1126,53 +1071,48 @@ PoolVector 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::Write w= data.write(); - zeromem(w.ptr(),size); + PoolVector::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& p_data) { +void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector &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 colormap; + HashMap colormap; int colormap_size; uint32_t pixel_size; PoolVector::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='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;x0) {\ - \ - 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::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::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 newdata; newdata.resize(size); @@ -1507,358 +1426,339 @@ Error Image::_decompress_bc() { PoolVector::Write w = newdata.write(); PoolVector::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>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>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>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;ja_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::Write(); - r=PoolVector::Read(); + w = PoolVector::Write(); + r = PoolVector::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& 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 &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::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;j2; + 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 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::Write wp = data.write(); - uint8_t *dst_data_ptr=wp.ptr(); + uint8_t *dst_data_ptr = wp.ptr(); PoolVector::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 (*Image::lossy_packer)(const Image& ,float )=NULL; -Image (*Image::lossy_unpacker)(const PoolVector& )=NULL; -PoolVector (*Image::lossless_packer)(const Image& )=NULL; -Image (*Image::lossless_unpacker)(const PoolVector& )=NULL; +PoolVector (*Image::lossy_packer)(const Image &, float) = NULL; +Image (*Image::lossy_unpacker)(const PoolVector &) = NULL; +PoolVector (*Image::lossless_packer)(const Image &) = NULL; +Image (*Image::lossless_unpacker)(const PoolVector &) = 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::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::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>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 dcopy = data; PoolVector::Read rp = dcopy.read(); - const uint8_t *srcptr=rp.ptr(); + const uint8_t *srcptr = rp.ptr(); PoolVector::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=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] @@ -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 (*lossy_packer)(const Image& p_image,float p_quality); - static Image (*lossy_unpacker)(const PoolVector& p_buffer); - static PoolVector (*lossless_packer)(const Image& p_image); - static Image (*lossless_unpacker)(const PoolVector& p_buffer); -private: + static PoolVector (*lossy_packer)(const Image &p_image, float p_quality); + static Image (*lossy_unpacker)(const PoolVector &p_buffer); + static PoolVector (*lossless_packer)(const Image &p_image); + static Image (*lossless_unpacker)(const PoolVector &p_buffer); +private: Format format; PoolVector 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& p_data); + void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector &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 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& p_data); + Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector &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 actions = get_actions(); - if(actions.empty()) + if (actions.empty()) return ret; - for(const List::Element *E=actions.front();E;E=E->next()) { + for (const List::Element *E = actions.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -96,55 +91,55 @@ Array InputMap::_get_actions() { List InputMap::get_actions() const { List actions = List(); - if(input_map.empty()){ + if (input_map.empty()) { return actions; } - for (Map::Element *E=input_map.front();E;E=E->next()) { + for (Map::Element *E = input_map.front(); E; E = E->next()) { actions.push_back(E->key()); } return actions; } -List::Element *InputMap::_find_event(List &p_list,const InputEvent& p_event, bool p_action_test) const { +List::Element *InputMap::_find_event(List &p_list, const InputEvent &p_event, bool p_action_test) const { - for (List::Element *E=p_list.front();E;E=E->next()) { + for (List::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::Element *InputMap::_find_event(List &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::Element *E=_find_event(input_map[p_action].inputs,p_event); + List::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 *al = get_action_list(p_action); if (al) { - for(const List::Element *E=al->front();E;E=E->next()) { + for (const List::Element *E = al->front(); E; E = E->next()) { ret.push_back(E->get()); } } return ret; - } -const List *InputMap::get_action_list(const StringName& p_action) { +const List *InputMap::get_action_list(const StringName &p_action) { - const Map::Element *E=input_map.find(p_action); + const Map::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::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::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& InputMap::get_action_map() const { +const Map &InputMap::get_action_map() const { return input_map; } @@ -250,94 +237,88 @@ void InputMap::load_from_globals() { List pinfo; GlobalConfig::get_singleton()->get_property_list(&pinfo); - for(List::Element *E=pinfo.front();E;E=E->next()) { - const PropertyInfo &pi=E->get(); + for (List::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 inputs; }; + private: static InputMap *singleton; mutable Map input_map; - mutable Map input_id_map; + mutable Map input_id_map; - List::Element *_find_event(List &p_list,const InputEvent& p_event, bool p_action_test=false) const; + List::Element *_find_event(List &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 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 *get_action_list(const StringName& p_action); - bool event_is_action(const InputEvent& p_event, const StringName& p_action) const; + const List *get_action_list(const StringName &p_action); + bool event_is_action(const InputEvent &p_event, const StringName &p_action) const; - const Map& get_action_map() const; + const Map &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 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::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List::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 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::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List::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(); + values[p_section] = Map(); } - 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 *r_sections) const{ +void ConfigFile::get_sections(List *r_sections) const { - for(const Map< String, Map >::Element *E=values.front();E;E=E->next()) { + for (const Map >::Element *E = values.front(); E; E = E->next()) { r_sections->push_back(E->key()); } } -void ConfigFile::get_section_keys(const String& p_section,List *r_keys) const{ +void ConfigFile::get_section_keys(const String &p_section, List *r_keys) const { ERR_FAIL_COND(!values.has(p_section)); - for(const Map ::Element *E=values[p_section].front();E;E=E->next()) { + for (const Map::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 >::Element *E = values.front(); E; E = E->next()) { - for(Map< String, Map >::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::Element *F=E->get().front();F;F=F->next()) { + for (Map::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 > values; + Map > 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 *r_sections) const; - void get_section_keys(const String& p_section,List *r_keys) const; + void get_section_keys(const String &p_section, List *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::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 +template 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() ); + return memnew(FileAccessBufferedFA()); }; 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;iget_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;istore_32(0); //compressed sizes, will update later } - Vector block_sizes; - for(int i=0;i 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;istore_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_blockget_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=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_blockget_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 (iget_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 read_blocks; int read_total; - - - String magic; mutable Vector 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 -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector& p_key,Mode p_mode) { +Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector &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 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 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;istore_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 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 &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& 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 >* files = NULL; +static Map > *files = NULL; void FileAccessMemory::register_file(String p_name, Vector 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 >::Element* E = files->find(name); + Map >::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 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 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::create_ref() ); - sem=Semaphore::create(); - lockcount=0; + quit = false; + singleton = this; + last_id = 0; + client = Ref(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& p_block) { +void FileAccessNetwork::_set_block(size_t p_offset, const Vector &p_block) { - - int page = p_offset/page_size; - ERR_FAIL_INDEX(page,pages.size()); - if (pagelock(); - 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;ilock(); if (pages[page].buffer.empty()) { //fuck - waiting_on_page=page; - for(int j=0;junlock(); 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;junlock(); } - 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 accesses; + Map accesses; Ref 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 buffer; - Page() { activity=0; queued=false; } + Page() { + activity = 0; + queued = false; + } }; - mutable Vector< Page > pages; + mutable Vector 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& p_block); + void _respond(size_t p_len, Error p_status); + void _set_block(size_t p_offset, const Vector &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; itry_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 ds=p.get_base_dir().split("/"); + Vector ds = p.get_base_dir().split("/"); - for(int j=0;jsubdirs.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::Element *E=p_dir->subdirs.front();E;E=E->next()) + for (Map::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { - for(int i=0;iget_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;iget_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::Element *E=current->subdirs.front();E;E=E->next()) { + for (Map::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } - for (Set::Element *E=current->files.front();E;E=E->next()) { + for (Set::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 paths = nd.split("/"); @@ -425,18 +413,18 @@ Error DirAccessPack::change_dir(String p_dir) { else pd = current; - for(int i=0;iparent) { - 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 subdirs; + Map subdirs; Set 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 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 files; + Map files; - Vector sources; + Vector sources; PackedDir *root; //Map 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::Element *E=files.find(pmd5); + Map::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 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;iadd_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)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 #include "core/io/file_access_pack.h" -#include "unzip.h" #include "map.h" +#include "unzip.h" +#include class ZipArchive : public PackSource { public: - struct File { int package; @@ -50,23 +49,20 @@ public: }; }; - private: - struct Package { String filename; unzFile zfile; }; Vector packages; - Map files; + Map 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& p_connection){ +void HTTPClient::set_connection(const Ref &p_connection) { close(); - connection=p_connection; - status=STATUS_CONNECTED; - + connection = p_connection; + status = STATUS_CONNECTED; } Ref HTTPClient::get_connection() const { @@ -82,14 +77,13 @@ Ref HTTPClient::get_connection() const { return connection; } -Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector& p_headers,const PoolVector& 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 &p_headers, const PoolVector &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 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 data; //Maybe this goes faster somehow? - for(int i=0;i::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& p_headers,const String& p_body) { +Error HTTPClient::request(Method p_method, const String &p_url, const Vector &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 Vector0; - for(int i=0;i 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 *r_response) { if (!response_headers.size()) return ERR_INVALID_PARAMETER; - for(int i=0;ipush_back(response_headers[i]); } @@ -223,71 +218,67 @@ Error HTTPClient::get_response_headers(List *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 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 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 rh; get_response_headers(&rh); Dictionary ret; - for(const List::Element *E=rh.front();E;E=E->next()) { + for (const List::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::Element *E=rh.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (const List::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='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& p_connection); + void set_connection(const Ref &p_connection); Ref get_connection() const; - Error request_raw( Method p_method, const String& p_url, const Vector& p_headers,const PoolVector& p_body); - Error request( Method p_method, const String& p_url, const Vector& 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 &p_headers, const PoolVector &p_body); + Error request(Method p_method, const String &p_url, const Vector &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 extensions; get_recognized_extensions(&extensions); - for (List::Element *E=extensions.front();E;E=E->next()) { + for (List::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;irecognize(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 *p_extensions) { - for (int i=0;iget_recognized_extensions(p_extensions); - } } -bool ImageLoader::recognize(const String& p_extension) { +bool ImageLoader::recognize(const String &p_extension) { - for (int i=0;irecognize(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 */ - /** * @class ImageScanLineLoader * @author Juan Linietsky @@ -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 *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 *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 *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 *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;iresolve_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 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_addresses; get_local_addresses(&ip_addresses); - for(List::Element *E=ip_addresses.front();E;E=E->next()) { + for (List::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 *r_addresses) const=0; + virtual void get_local_addresses(List *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 #include +#include 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_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> 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;i0) - 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 keys; d.get_key_list(&keys); - for (List::Element *E=keys.front();E;E=E->next()) { + for (List::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 +#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 data; data.resize(datalen); PoolVector::Write wr = data.write(); - copymem(&wr[0],&buf[20],datalen); + copymem(&wr[0], &buf[20], datalen); wr = PoolVector::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 names; Vector 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;ilen,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 (ilen,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;ilen,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA); PoolVector data; if (count) { data.resize(count); PoolVector::Write w = data.write(); - for(int i=0;i::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 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::Write w = data.write(); - for(int i=0;i::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 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::Write w = data.write(); - for(int i=0;i::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 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 varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector::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 varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector::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 carray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { carray.resize(count); PoolVector::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 data=image.get_data(); + PoolVector 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::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 keys; d.get_key_list(&keys); - - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::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 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::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 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::Read r = data.read(); - for(int i=0;i 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::Read r = data.read(); - for(int i=0;i 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 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 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 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>=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 &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::Write w = r_buffer.write(); - for(int i=0;i &p_buffer) { int len = p_buffer.size(); - if (len==0) + if (len == 0) return OK; PoolVector::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 &p_buffer) { +Error PacketPeer::_put_packet(const PoolVector &p_buffer) { return put_packet_buffer(p_buffer); } PoolVector PacketPeer::_get_packet() const { PoolVector 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;iput_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 &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< &p_buffer); PoolVector _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 &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 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& p_peer); + void set_stream_peer(const Ref &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::create_ref() { @@ -72,14 +70,12 @@ Ref PacketPeerUDP::create_ref() { return Ref(_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 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; istore_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; istore_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 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 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;iget_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 imgdata; imgdata.resize(datalen); PoolVector::Write w = imgdata.write(); - f->get_buffer(w.ptr(),datalen); + f->get_buffer(w.ptr(), datalen); _advance_padding(datalen); - w=PoolVector::Write(); + w = PoolVector::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 data; data.resize(f->get_32()); PoolVector::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); w = PoolVector::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;iget_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;iget_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 array; array.resize(len); PoolVector::Write w = array.write(); - f->get_buffer(w.ptr(),len); + f->get_buffer(w.ptr(), len); _advance_padding(len); - w=PoolVector::Write(); - r_v=array; + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_INT_ARRAY: { @@ -504,19 +488,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::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::Write(); - r_v=array; + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_REAL_ARRAY: { @@ -525,20 +509,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::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::Write(); - r_v=array; + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_STRING_ARRAY: { @@ -546,11 +530,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::Write w = array.write(); - for(uint32_t i=0;i::Write(); - r_v=array; - + for (uint32_t i = 0; i < len; i++) + w[i] = get_unicode_string(); + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_VECTOR2_ARRAY: { @@ -560,16 +543,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::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::Write(); - r_v=array; + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_VECTOR3_ARRAY: { @@ -588,14 +571,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::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::Write(); - r_v=array; + w = PoolVector::Write(); + r_v = array; } break; case VARIANT_COLOR_ARRAY: { @@ -616,16 +599,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector array; array.resize(len); PoolVector::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::Write(); - r_v=array; + w = PoolVector::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 ResourceInteractiveLoaderBinary::get_resource(){ - +Ref ResourceInteractiveLoaderBinary::get_resource() { return resource; } -Error ResourceInteractiveLoaderBinary::poll(){ +Error ResourceInteractiveLoaderBinary::poll() { - if (error!=OK) + if (error != OK) return error; - int s = stage; - 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(); 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;iset(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 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 *p_dependencies,bool p_add_types) { +void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List *p_dependencies, bool p_add_types) { open(p_f); if (error) return; - for(int i=0;ipush_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;iget_32(); - for(uint32_t i=0;iget_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;iget_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 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()); + ERR_FAIL_COND_V(err != OK, Ref()); } - Ref ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref 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 *p_extensions) const { +void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List extensions; - ClassDB::get_extensions_for_type(p_type,&extensions); + ClassDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::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 *p_extensions) const{ +void ResourceFormatLoaderBinary::get_recognized_extensions(List *p_extensions) const { List extensions; ClassDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::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 *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List *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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref 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& p_map) { - +Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map &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_formatremove(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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - ria->remaps=p_map; + Ref 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;iget_32(); + uint32_t ext_resources_size = f->get_32(); fw->store_32(ext_resources_size); - for(uint32_t i=0;iget_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;iget_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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref 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;istore_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::Read r = val.get_data().read(); - f->store_buffer(r.ptr(),dlen); + f->store_buffer(r.ptr(), dlen); _pad_buffer(dlen); } else { PoolVector 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::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;istore_32(get_string_index(np.get_name(i))); - for(int i=0;istore_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 keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::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;istore_32(VARIANT_RAW_ARRAY); PoolVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::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 arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_32(r[i]); } break; @@ -1717,10 +1642,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_REAL_ARRAY); PoolVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_real(r[i]); } @@ -1729,10 +1654,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_STRING_ARRAY); PoolVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_32(VARIANT_VECTOR3_ARRAY); PoolVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_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 arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_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 arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector::Read r = arr.read(); - for(int i=0;istore_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::Element *E=property_list.front();E;E=E->next()) { + for (List::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 keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::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;istore_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 resources; - { - - for(List::Element *E=saved_resources.front();E;E=E->next()) { - + for (List::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 property_list; - E->get()->get_property_list( &property_list ); + E->get()->get_property_list(&property_list); - for(List::Element *F=property_list.front();F;F=F->next()) { + for (List::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 save_order; save_order.resize(external_resources.size()); - for(Map::Element *E=external_resources.front();E;E=E->next()) { - save_order[E->get()]=E->key(); + for (Map::Element *E = external_resources.front(); E; E = E->next()) { + save_order[E->get()] = E->key(); } - for(int i=0;iget_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 ofs_pos; Set used_indices; - for(List::Element *E=saved_resources.front();E;E=E->next()) { + for (List::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::Element *E=saved_resources.front();E;E=E->next()) { - + for (List::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::Element *E=resources.front();E;E=E->next()) { + for (List::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::Element *F=rd.properties.front();F;F=F->next()) { + for (List::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;iseek(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 *p_extensions) const { +void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List *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 remaps; + Map 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 get_resource(); virtual Error poll(); virtual int get_stage() const; virtual int get_stage_count() const; - void set_remaps(const Map& p_remaps) { remaps=p_remaps; } + void set_remaps(const Map &p_remaps) { remaps = p_remaps; } void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List *p_dependencies, bool p_add_types); - ResourceInteractiveLoaderBinary(); ~ResourceInteractiveLoaderBinary(); - }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { public: - - virtual Ref load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const; + virtual Ref load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const; virtual void get_recognized_extensions(List *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 *p_dependencies, bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map& p_map); - - - + virtual void get_dependencies(const String &p_path, List *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map &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 resource_set; - Map string_map; + Map string_map; Vector strings; - - Map external_resources; + Map external_resources; List saved_resources; - struct Property { int name_idx; Variant value; PropertyInfo pi; - }; struct ResourceData { @@ -155,36 +138,25 @@ class ResourceFormatSaverBinaryInstance { List 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 *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 *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 *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions(List *p_extensions) const { Set found; - for (Set< Ref >::Element *E=importers.front();E;E=E->next()) { + for (Set >::Element *E = importers.front(); E; E = E->next()) { List local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List::Element *F=local_exts.front();F;F=F->next()) { + for (List::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 *p_extension } } -void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const { - if (p_type=="") { + if (p_type == "") { return get_recognized_extensions(p_extensions); } Set found; - for (Set< Ref >::Element *E=importers.front();E;E=E->next()) { + for (Set >::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 local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List::Element *F=local_exts.front();F;F=F->next()) { + for (List::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 >::Element *E=importers.front();E;E=E->next()) { + for (Set >::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 *p_dependencies,bool p_add_types){ +void ResourceFormatImporter::get_dependencies(const String &p_path, List *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 ResourceFormatImporter::get_importer_by_name(const String& p_name) { +Ref ResourceFormatImporter::get_importer_by_name(const String &p_name) { - for (Set< Ref >::Element *E=importers.front();E;E=E->next()) { - if (E->get()->get_importer_name()==p_name) { + for (Set >::Element *E = importers.front(); E; E = E->next()) { + if (E->get()->get_importer_name() == p_name) { return E->get(); } } @@ -241,34 +232,32 @@ Ref ResourceFormatImporter::get_importer_by_name(const String& return Ref(); } +void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List > *r_importers) { -void ResourceFormatImporter::get_importers_for_extension(const String& p_extension,List > *r_importers) { - - for (Set< Ref >::Element *E=importers.front();E;E=E->next()) { + for (Set >::Element *E = importers.front(); E; E = E->next()) { List local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List::Element *F=local_exts.front();F;F=F->next()) { - if (p_extension.to_lower()==F->get()) { + for (List::Element *F = local_exts.front(); F; F = F->next()) { + if (p_extension.to_lower() == F->get()) { r_importers->push_back(E->get()); } } } } -Ref ResourceFormatImporter::get_importer_by_extension(const String& p_extension) { - +Ref ResourceFormatImporter::get_importer_by_extension(const String &p_extension) { Ref importer; - float priority=0; + float priority = 0; - for (Set< Ref >::Element *E=importers.front();E;E=E->next()) { + for (Set >::Element *E = importers.front(); E; E = E->next()) { List local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List::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::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 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 > importers; -public: + Set > 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 *p_extensions) const; - virtual void get_recognized_extensions_for_type(const String& p_type,List *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 *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 *p_dependencies,bool p_add_types=false); + virtual void get_dependencies(const String &p_path, List *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& p_importer) { importers.insert(p_importer); } - Ref get_importer_by_name(const String& p_name); - Ref get_importer_by_extension(const String& p_extension); - void get_importers_for_extension(const String& p_extension,List > *r_importers); + void add_importer(const Ref &p_importer) { importers.insert(p_importer); } + Ref get_importer_by_name(const String &p_name); + Ref get_importer_by_extension(const String &p_extension); + void get_importers_for_extension(const String &p_extension, List > *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 *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 *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 *r_options,int p_preset=0) const=0; - virtual bool get_option_visibility(const String& p_option,const Map& p_options) const=0; - - - virtual Error import(const String& p_source_file,const String& p_save_path,const Map& p_options,List* r_platform_variants,List* r_gen_files=NULL)=0; + virtual void get_import_options(List *r_options, int p_preset = 0) const = 0; + virtual bool get_option_visibility(const String &p_option, const Map &p_options) const = 0; + virtual Error import(const String &p_source_file, const String &p_save_path, const Map &p_options, List *r_platform_variants, List *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 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::Element *E=extensions.front();E;E=E->next()) { - + for (List::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 *p_extensions) const { -void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List *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 *p_extensions) { +void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) { - for (int i=0;iget_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; - 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 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 ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) { //either this - Ref res = load(p_path,p_path,r_error); + Ref res = load(p_path, p_path, r_error); if (res.is_null()) return Ref(); - Ref ril = Ref( memnew( ResourceInteractiveLoaderDefault )); - ril->resource=res; + Ref ril = Ref(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 ril = load_interactive(p_path,r_error); + Ref 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 *p_dependencies, bool p_add_types) { +void ResourceFormatLoader::get_dependencies(const String &p_path, List *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;irecognize_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 ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) { - +Ref 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()); - - + ERR_FAIL_COND_V(local_path == "", Ref()); 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 res_cached = ResourceCache::get(local_path); Ref ril = Ref(memnew(ResourceInteractiveLoaderDefault)); @@ -259,14 +241,14 @@ Ref 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;irecognize_path(local_path,p_type_hint)) + if (!loader[i]->recognize_path(local_path, p_type_hint)) continue; - found=true; - Ref ril = loader[i]->load_interactive(local_path,r_error); + found = true; + Ref ril = loader[i]->load_interactive(local_path, r_error); if (ril.is_null()) continue; if (!p_no_cache) @@ -276,39 +258,37 @@ Ref 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()); return Ref(); - } 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 *p_dependencies, bool p_add_types) { - +void ResourceLoader::get_dependencies(const String &p_path, List *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;irecognize_path(local_path)) continue; @@ -317,22 +297,19 @@ void ResourceLoader::get_dependencies(const String& p_path, List *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& p_map) { - +Error ResourceLoader::rename_dependencies(const String &p_path, const Map &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;irecognize_path(local_path)) continue; @@ -341,41 +318,34 @@ Error ResourceLoader::rename_dependencies(const String &p_path,const Maprename_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;iget_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 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 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 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 *p_extensions) const=0; - virtual void get_recognized_extensions_for_type(const String& p_type,List *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 *p_dependencies,bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map& p_map) { return OK; } + virtual Ref 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 *p_extensions) const = 0; + virtual void get_recognized_extensions_for_type(const String &p_type, List *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 *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map &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 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 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 *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 *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 *p_dependencies,bool p_add_types=false); - static Error rename_dependencies(const String &p_path,const Map& 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 *p_dependencies, bool p_add_types = false); + static Error rename_dependencies(const String &p_path, const Map &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;irecognize(p_resource)) continue; List 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::Element *E=extensions.front();E;E=E->next()) { + for (List::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 *p_extensions) { -void ResourceSaver::get_recognized_extensions(const RES& p_resource,List *p_extensions) { - - - for (int i=0;iget_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 */ - - - - - 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 *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 *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 *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 *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& p_data) { +Error StreamPeer::_put_data(const PoolVector &p_data) { int len = p_data.size(); - if (len==0) + if (len == 0) return OK; PoolVector::Read r = p_data.read(); - return put_data(&r[0],len); + return put_data(&r[0], len); } -Array StreamPeer::_put_partial_data(const PoolVector& p_data) { +Array StreamPeer::_put_partial_data(const PoolVector &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& p_data) { PoolVector::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 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()); @@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) { } PoolVector::Write w = data.write(); - Error err = get_data(&w[0],p_bytes); + Error err = get_data(&w[0], p_bytes); w = PoolVector::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 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()); @@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) { PoolVector::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::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 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 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 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 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::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::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 & p_data){ +void StreamPeerBuffer::set_data_array(const PoolVector &p_data) { - data=p_data; - pointer=0; + data = p_data; + pointer = 0; } -PoolVector StreamPeerBuffer::get_data_array() const{ +PoolVector StreamPeerBuffer::get_data_array() const { return data; } - void StreamPeerBuffer::clear() { data.resize(0); - pointer=0; + pointer = 0; } - Ref StreamPeerBuffer::duplicate() const { Ref 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& p_data); - Array _put_partial_data(const PoolVector& p_data); + Error _put_data(const PoolVector &p_data); + Array _put_partial_data(const PoolVector &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 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 & p_data); + void set_data_array(const PoolVector &p_data); PoolVector 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 p_base)=0; - virtual Error connect_to_stream(Ref 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 p_base) = 0; + virtual Error connect_to_stream(Ref 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::create_ref() { @@ -68,7 +67,7 @@ Ref StreamPeerTCP::create_ref() { return Ref(_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 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::create_ref() { @@ -37,7 +37,7 @@ Ref TCP_Server::create_ref() { return Ref(_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 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 take_connection() = 0; - virtual void stop()=0; //stop listening + virtual void stop() = 0; //stop listening static Ref 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 = Ref( memnew( Translation )); + Ref translation = Ref(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;iclose(); 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 configs = config.split("\n"); - for(int i=0;iset_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 *p_extensions) const{ +void TranslationLoaderPO::get_recognized_extensions(List *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 *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 '' && - (*(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& p_buffer) { +Error XMLParser::open_buffer(const Vector &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("&"); 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 special_characters; String node_name; bool node_empty; @@ -81,8 +81,8 @@ private: Vector 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& p_buffer); + Error open(const String &p_path); + Error open_buffer(const Vector &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 +template class List { struct _Data; -public: - +public: class Element { private: - friend class List; + friend class List; 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( const_cast(p_I) ); + memdelete_allocator(const_cast(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 - Element* find(const T_v& p_val) { + template + 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;ivalue, 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 >(); + sort_custom >(); } - template + template 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 + template 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 + template 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 > 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 > 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;ilast = 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 A=DefaultAllocator> +template , class A = DefaultAllocator> class Map { enum Color { @@ -45,26 +45,25 @@ class Map { BLACK }; struct _Data; -public: +public: class Element { private: - friend class Map; + friend class Map; //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(_root); - _root=NULL; + memdelete_allocator(_root); + _root = NULL; } } @@ -147,7 +144,7 @@ private: _free_root(); #ifdef GLOBALNIL_DISABLED - memdelete_allocator(_nil); + memdelete_allocator(_nil); #endif //memdelete_allocator(_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(p_node); + memdelete_allocator(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( p_element ); + memdelete_allocator(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;ineighbours.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::Element *E=points.front();E;E=E->next()) { + for (const Map::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::Element *E=points.front();E;E=E->next()) { + for (const Map::Element *E = points.front(); E; E = E->next()) { real_t d = p_point.distance_squared_to(E->get()->pos); - if (closest_id<0 || dkey(); + 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::Element *E = segments.front(); E; E = E->next()) { - for (const Set::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::List open_list; - bool found_route=false; - + bool found_route = false; - for(int i=0;ineighbours.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 *least_cost_point=NULL; - real_t least_cost=1e30; + SelfList *least_cost_point = NULL; + real_t least_cost = 1e30; //this could be faster (cache previous results) - for (SelfList *E=open_list.first();E;E=E->next()) { + for (SelfList *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 (costself(); + Point *p = least_cost_point->self(); //open the neighbours for search int es = p->neighbours.size(); - for(int i=0;ineighbours[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 AStar::get_point_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector()); - ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector()); - + ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector()); + ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector()); 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 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(); //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 path; @@ -335,54 +312,49 @@ PoolVector AStar::get_point_path(int p_from_id, int p_to_id) { { PoolVector::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 AStar::get_id_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector()); - ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector()); - + ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector()); + ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector()); 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 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(); //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 path; @@ -391,15 +363,14 @@ PoolVector AStar::get_id_path(int p_from_id, int p_to_id) { { PoolVector::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 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 */ -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 neighbours; + Vector neighbours; //used for pathfinding Point *prev_point; real_t distance; - Point() : list(this) {} + Point() + : list(this) {} }; - Map points; + Map 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_to) { - SWAP(p_from,p_to); + SWAP(p_from, p_to); } - from=p_from; - to=p_to; + from = p_from; + to = p_to; } }; - Set 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 get_point_path(int p_from_id, int p_to_id); PoolVector 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::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;i0) { - 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=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=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& p_indices,real_t p_tolerance) { +static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector &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;ip_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& 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& 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 &p_indices, Vector &p_planes, Vector &p_nodes, real_t p_tolerance) { -static int _bsp_create_node(const Face3 *p_faces,const Vector& p_indices,Vector &p_planes, Vector &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 faces_over; Vector 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;ip_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& 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 plane_values; - plane_values.resize(planes.size()*4); + plane_values.resize(planes.size() * 4); - for(int i=0;i dst_nodes; - dst_nodes.resize(nodes.size()*3); + dst_nodes.resize(nodes.size() * 3); - for(int i=0;i 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 src_planes=d["planes"]; - int plane_count=src_planes.size(); - ERR_FAIL_COND(plane_count%4); - planes.resize(plane_count/4); + PoolVector 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::Read r = src_planes.read(); - for(int i=0;i::Read r = src_nodes.read(); - for(int i=0;i& p_faces,real_t p_error_radius) { +BSP_Tree::BSP_Tree(const PoolVector &p_faces, real_t p_error_radius) { // compute aabb - int face_count=p_faces.size(); - PoolVector::Read faces_r=p_faces.read(); + int face_count = p_faces.size(); + PoolVector::Read faces_r = p_faces.read(); const Face3 *facesptr = faces_r.ptr(); - - bool first=true; + bool first = true; Vector indices; - for (int i=0;i& 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 &p_nodes, const Vector &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 &p_nodes, const Vector &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 */ 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 - bool _test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const; + template + 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 get_nodes() const; Vector 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 - 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 + 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& p_faces,real_t p_error_radius=0); - BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const Rect3& p_aabb,real_t p_error_radius=0); + BSP_Tree(const Variant &p_variant); + BSP_Tree(const PoolVector &p_faces, real_t p_error_radius = 0); + BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const Rect3 &p_aabb, real_t p_error_radius = 0); ~BSP_Tree(); - }; -template -bool BSP_Tree::_test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const { +template +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 -bool BSP_Tree::convex_is_inside(const T& p_convex) const { +template +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 { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast(p_ptr) ) ); + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast(p_ptr))); return s; } - _FORCE_INLINE_ static void encode(BSP_Tree p_val,void* p_ptr) { - Dictionary *d = reinterpret_cast(p_ptr); - *d=Variant(p_val); + _FORCE_INLINE_ static void encode(BSP_Tree p_val, void *p_ptr) { + Dictionary *d = reinterpret_cast(p_ptr); + *d = Variant(p_val); } }; -template<> -struct PtrToArg { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast(p_ptr) ) ); +template <> +struct PtrToArg { + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast(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 CameraMatrix::get_projection_planes(const Transform& p_transform) const { +Vector CameraMatrix::get_projection_planes(const Transform &p_transform) const { /** Fast Plane Extraction from combined modelview/projection matrices. * References: @@ -284,88 +273,79 @@ Vector CameraMatrix::get_projection_planes(const Transform& p_transform) Vector 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 */ - - 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 get_projection_planes(const Transform& p_transform) const; + Vector 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 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 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 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 vtx_remap; + Map vtx_remap; - for(int i=0;i new_vertices; new_vertices.resize(vtx_remap.size()); - for(int i=0;i > (*Geometry::_decompose_func)(const Vector& p_polygon)=NULL; +Vector > (*Geometry::_decompose_func)(const Vector &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=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 > Geometry::separate_objects(PoolVector p_array) { -PoolVector< PoolVector< Face3 > > Geometry::separate_objects( PoolVector< Face3 > p_array ) { - - PoolVector< PoolVector< Face3 > > objects; + PoolVector > objects; int len = p_array.size(); - PoolVector::Read r=p_array.read(); + PoolVector::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 >() ); // invalid geometry + ERR_FAIL_COND_V(error, PoolVector >()); // invalid geometry } /* group connected faces in separate objects */ - int group=0; - for (int i=0;i=0) { + if (group >= 0) { objects.resize(group); - PoolVector< PoolVector >::Write obw=objects.write(); - PoolVector< Face3 > *group_faces = obw.ptr(); + PoolVector >::Write obw = objects.write(); + PoolVector *group_faces = obw.ptr(); - for (int i=0;i=0 && _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=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& 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 &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 Geometry::wrap_geometry(PoolVector p_array, real_t *p_error) { #define _MIN_SIZE 1.0 #define _MAX_LENGTH 20 - int face_count=p_array.size(); - PoolVector::Read facesr=p_array.read(); + int face_count = p_array.size(); + PoolVector::Read facesr = p_array.read(); const Face3 *faces = facesr.ptr(); Rect3 global_aabb; - for(int i=0;i 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 Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t PoolVector wrapped_faces; - for (int i=0;i Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t // transform face vertices to global coords - int wrapped_faces_count=wrapped_faces.size(); - PoolVector::Write wrapped_facesw=wrapped_faces.write(); - Face3* wrapped_faces_ptr=wrapped_facesw.ptr(); + int wrapped_faces_count = wrapped_faces.size(); + PoolVector::Write wrapped_facesw = wrapped_faces.write(); + Face3 *wrapped_faces_ptr = wrapped_facesw.ptr(); - for(int i=0;i &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;i0.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 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 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 &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 Geometry::build_box_planes(const Vector3& p_extents) { +PoolVector Geometry::build_box_planes(const Vector3 &p_extents) { PoolVector 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 Geometry::build_cylinder_planes(real_t p_radius, real_t p_heig PoolVector planes; - for (int i=0;i Geometry::build_sphere_planes(real_t p_radius, int p_lats,int p_lons, Vector3::Axis p_axis) { - +PoolVector Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) { PoolVector 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 Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) { PoolVector 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_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& p_rects,Vector& r_result, Size2i& r_size) { +void Geometry::make_atlas(const Vector &p_rects, Vector &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& p_rects,Vector& 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 results; - for(int i=0;i<=12;i++) { + for (int i = 0; i <= 12; i++) { - int w = 1< hmax; hmax.resize(w); - for(int j=0;j w) { + if (ofs + wrects[j].s.width > w) { - ofs=0; + ofs = 0; } - int from_y=0; - for(int k=0;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 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;iw ? 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 */ 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=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=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 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_l0) { + if (den > 0) { //backwards facing plane - if (distmin) { - 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= 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()= 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 clip_polygon(const Vector& polygon,const Plane& p_plane) { + static inline Vector clip_polygon(const Vector &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 triangulate_polygon(const Vector& p_polygon) { + static Vector triangulate_polygon(const Vector &p_polygon) { Vector triangles; - if (!Triangulate::triangulate(p_polygon,triangles)) + if (!Triangulate::triangulate(p_polygon, triangles)) return Vector(); //fail return triangles; } - static Vector< Vector > (*_decompose_func)(const Vector& p_polygon); - static Vector< Vector > decompose_polygon(const Vector& p_polygon) { + static Vector > (*_decompose_func)(const Vector &p_polygon); + static Vector > decompose_polygon(const Vector &p_polygon) { if (_decompose_func) return _decompose_func(p_polygon); - return Vector< Vector >(); - + return Vector >(); } + static PoolVector > separate_objects(PoolVector 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 wrap_geometry(PoolVector 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 edges; - Vector< Vector3 > vertices; + Vector 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<>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 convex_hull_2d(Vector P) - { + static Vector convex_hull_2d(Vector P) { int n = P.size(), k = 0; Vector 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 &p_planes); - static PoolVector build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis=Vector3::AXIS_Z); - static PoolVector build_box_planes(const Vector3& p_extents); - static PoolVector build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - static PoolVector 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& p_rects,Vector& r_result, Size2i& r_size); - + static PoolVector build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z); + static PoolVector build_box_planes(const Vector3 &p_extents); + static PoolVector build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + static PoolVector 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 &p_rects, Vector &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 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_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.xend.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(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.xend.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].ypos.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 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=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 #include - +#include + #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 @@ -45,18 +45,17 @@ typedef uint32_t OctreeElementID; #define OCTREE_ELEMENT_INVALID_ID 0 #define OCTREE_SIZE_LIMIT 1e15 -template +template 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 pairable_elements; - List elements; + List pairable_elements; + List 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 pair_list; + List pair_list; struct OctantOwner { Octant *octant; - typename List::Element *E; + typename List::Element *E; }; // an element can be in max 8 octants - List 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 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::Element *eA,*eB; + typename List::Element *eA, *eB; }; typedef Map, 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::Element *E=p_element->pair_list.front(); - while(E) { + typename List::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( root ); + memdelete_allocator(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(p_octant); + memdelete_allocator(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& 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 &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 -T *Octree::get(OctreeElementID p_id) const { +template +T *Octree::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 -bool Octree::is_pairable(OctreeElementID p_id) const { +template +bool Octree::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 -int Octree::get_subindex(OctreeElementID p_id) const { +template +int Octree::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 -void Octree::_insert_element(Element *p_element,Octant *p_octant) { +template +void Octree::_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::_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 *E=p_octant->pairable_elements.front(); + typename List::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 -void Octree::_ensure_valid_root(const Rect3& p_aabb) { +template +void Octree::_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 -bool Octree::_remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit) { +template +bool Octree::_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 *E=p_octant->pairable_elements.front(); - while(E) { - _pair_unreference( p_element,E->get() ); - E=E->next(); + typename List::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(p_octant); + memdelete_allocator(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 -void Octree::_unpair_element(Element *p_element,Octant *p_octant) { - +template +void Octree::_unpair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List::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 *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 -void Octree::_pair_element(Element *p_element,Octant *p_octant) { +template +void Octree::_pair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List::Element *E=p_octant->pairable_elements.front(); + typename List::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 -void Octree::_remove_element(Element *p_element) { +template +void Octree::_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::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 -OctreeElementID Octree::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 +OctreeElementID Octree::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 -void Octree::move(OctreeElementID p_id, const Rect3& p_aabb) { +template +void Octree::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::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::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 owners = e.octant_owners; // save the octant owners - Octant *common_parent=e.common_parent; + List 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::Element *E=owners.front();E;) { + for (typename List::Element *E = owners.front(); E;) { - Octant *o=E->get().octant; - typename List::Element *N=E->next(); + Octant *o = E->get().octant; + typename List::Element *N = E->next(); /* if (!use_pairs) @@ -980,77 +947,70 @@ void Octree::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::Element *E=owners.front();E;E=E->next()) { + for (typename List::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 -void Octree::set_pairable(OctreeElementID p_id,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) { +template +void Octree::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 -void Octree::erase(OctreeElementID p_id) { +template +void Octree::erase(OctreeElementID p_id) { typename ElementMap::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); @@ -1066,28 +1026,28 @@ void Octree::erase(OctreeElementID p_id) { _optimize(); } -template -void Octree::_cull_convex(Octant *p_octant,_CullConvexData *p_cull) { +template +void Octree::_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 *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_idxresult_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::_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 *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_idxresult_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::_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 +void Octree::_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 -void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1171,19 +1130,19 @@ void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1197,36 +1156,35 @@ void Octree::_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 -void Octree::_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 +void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1243,20 +1201,20 @@ void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1272,37 +1230,35 @@ void Octree::_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 +void Octree::_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 -void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1319,20 +1275,20 @@ void Octree::_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 *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_idxuserdata; if (p_subindex_array) @@ -1348,120 +1304,103 @@ void Octree::_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 -int Octree::cull_convex(const Vector& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask) { +template +int Octree::cull_convex(const Vector &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 -int Octree::cull_AABB(const Rect3& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { - +template +int Octree::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 -int Octree::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 +int Octree::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 -int Octree::cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { +template +int Octree::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 +void Octree::set_pair_callback(PairCallback p_callback, void *p_userdata) { -template -void Octree::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 -void Octree::set_unpair_callback( UnpairCallback p_callback, void *p_userdata ) { - - unpair_callback=p_callback; - unpair_callback_userdata=p_userdata; +template +void Octree::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) { + unpair_callback = p_callback; + unpair_callback_userdata = p_userdata; } +template +Octree::Octree(real_t p_unit_size) { -template -Octree::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 */ -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& p_points, Geometry::MeshData &r_mesh) { +uint32_t QuickHull::debug_stop_after = 0xFFFFFFFF; +Error QuickHull::build(const Vector &p_points, Geometry::MeshData &r_mesh) { static const real_t over_tolerance = 0.0001; /* CREATE AABB VOLUME */ Rect3 aabb; - for(int i=0;i valid_points; valid_points.resize(p_points.size()); Set valid_cache; - for(int i=0;i& p_points, Geometry::MeshData &r_me int simplex[4]; { - real_t max,min; + real_t max, min; - for(int i=0;i 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;imaxd) { + if (i == 0 || d > maxd) { - maxd=d; - simplex[2]=i; + maxd = d; + simplex[2] = i; } } } @@ -128,102 +121,92 @@ Error QuickHull::build(const Vector& 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;imaxd) { + 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 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::Element *E=faces.front();E;E=E->next()) { + for (List::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& 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 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::Element* > lit_faces; //lit face is a death sentence + List::Element *> lit_faces; //lit face is a death sentence - Map lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot + Map lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot - for(List::Element *E=faces.front();E;E=E->next()) { + for (List::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::Element *F=lit_edges.find(e); + Map::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::Element* > new_faces; //new faces + List::Element *> new_faces; //new faces - for(Map::Element *E=lit_edges.front();E;E=E->next()) { + for (Map::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& 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::Element* >::Element *F=lit_faces.front();F;F=F->next()) { + for (List::Element *>::Element *F = lit_faces.front(); F; F = F->next()) { Face &lf = F->get()->get(); - for(int i=0;i::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List::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& p_points, Geometry::MeshData &r_me //put faces that contain no points on the front - for (List< List::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List::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 ret_edges; + Map ret_edges; List ret_faces; - - for(List::Element *E=faces.front();E;E=E->next()) { + for (List::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::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::Element *G=ret_edges.find(e); + Map::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::Element *E=ret_faces.front();E;E=E->next()) { + for (List::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;iget().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::Element *F=ret_edges.find(e); + Map::Element *F = ret_edges.find(e); ERR_CONTINUE(!F); List::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;jget().indices[j]==a) { + if (O->get().indices[j] == a) { //append the rest - for(int k=0;kget().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::Element *F2=ret_edges.find(e2); + Map::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& 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::Element *E=ret_faces.front();E;E=E->next()) { - r_mesh.faces[idx++]=E->get(); - - + int idx = 0; + for (List::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::Element *E=ret_edges.front();E;E=E->next()) { + idx = 0; + for (Map::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 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::Element *left,*right; - FaceConnect() { left=NULL; right=NULL; } + List::Element *left, *right; + FaceConnect() { + left = NULL; + right = NULL; + } }; struct RetFaceConnect { - List::Element *left,*right; - RetFaceConnect() { left=NULL; right=NULL; } + List::Element *left, *right; + RetFaceConnect() { + left = NULL; + right = NULL; + } }; public: - static uint32_t debug_stop_after; - static Error build(const Vector& p_points,Geometry::MeshData& r_mesh); - + static Error build(const Vector &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.xend_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;i0) ? -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;ipos.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.xend.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;iaabb; + 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 sort_x; - sort_x.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray 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 sort_y; - sort_y.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray 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 sort_z; - sort_z.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray 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 &p_faces) { -void TriangleMesh::create(const PoolVector& 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::Write bw = bvh.write(); { @@ -114,148 +106,143 @@ void TriangleMesh::create(const PoolVector& p_faces) { PoolVector::Read r = p_faces.read(); PoolVector::Write w = triangles.write(); - Map db; + Map db; - for(int i=0;i::Element *E=db.find(vs); + int vidx = -1; + Vector3 vs = v[j].snapped(0.0001); + Map::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::Write vw = vertices.write(); - for (Map::Element *E=db.front();E;E=E->next()) { - vw[E->get()]=E->key(); + for (Map::Element *E = db.front(); E; E = E->next()) { + vw[E->get()] = E->key(); } - } - PoolVector bwptrs; + PoolVector bwptrs; bwptrs.resize(fc); - PoolVector::Write bwp = bwptrs.write(); - for(int i=0;i::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::Write(); //clearup + bw = PoolVector::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<::Read trianglesr = triangles.read(); - PoolVector::Read verticesr=vertices.read(); - PoolVector::Read bvhr=bvh.read(); + PoolVector::Read verticesr = vertices.read(); + PoolVector::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<=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<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<::Read trianglesr = triangles.read(); - PoolVector::Read verticesr=vertices.read(); - PoolVector::Read bvhr=bvh.read(); + PoolVector::Read verticesr = vertices.read(); + PoolVector::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<=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 (nd0) - 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<::Read trianglesr = triangles.read(); - PoolVector::Read verticesr=vertices.read(); - PoolVector::Read bvhr=bvh.read(); + PoolVector::Read verticesr = vertices.read(); + PoolVector::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<=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 (nd0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } return inters; @@ -536,13 +502,13 @@ PoolVector TriangleMesh::get_faces() const { int ts = triangles.size(); faces.resize(triangles.size()); - PoolVector::Write w=faces.write(); + PoolVector::Write w = faces.write(); PoolVector::Read r = triangles.read(); PoolVector::Read rv = vertices.read(); - for(int i=0;i 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; 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 get_faces() const; - - void create(const PoolVector& p_faces); + void create(const PoolVector &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 &contour) -{ +real_t Triangulate::get_area(const Vector &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= 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 &p_contour,int u,int v,int w,int n,const Vector& V) -{ - int p; - real_t Ax, Ay, Bx, By, Cx, Cy, Px, Py; - const Vector2 *contour=&p_contour[0]; +bool Triangulate::snip(const Vector &p_contour, int u, int v, int w, int n, const Vector &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 &contour,Vector &result) -{ - /* allocate and initialize list of Vertices in polygon */ - - int n = contour.size(); - if ( n < 3 ) return false; +bool Triangulate::triangulate(const Vector &contour, Vector &result) { + /* allocate and initialize list of Vertices in polygon */ + int n = contour.size(); + if (n < 3) return false; - Vector V; - V.resize(n); + Vector 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; v2; ) - { - /* 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, */ - 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, */ + 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 &contour, Vector &result); + static bool triangulate(const Vector &contour, Vector &result); // compute area of a contour/polygon - static real_t get_area(const Vector< Vector2 > &contour); + static real_t get_area(const Vector &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 &p_contour,int u,int v,int w,int n,const Vector& V); - + static bool snip(const Vector &p_contour, int u, int v, int w, int n, const Vector &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 zdot(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;iget_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 set_count; - Map notify_count; - Map call_count; - int null_count=0; + Map set_count; + Map notify_count; + Map 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::Element *E = set_count.front(); E; E = E->next()) { - for(Map::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::Element *E=call_count.front();E;E=E->next()) { + for (Map::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::Element *E=notify_count.front();E;E=E->next()) { + for (Map::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;icall(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_posinstance_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;iargs;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;itype & 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& p_names) { - - arg_names=p_names; +void MethodBind::set_argument_names(const Vector &p_names) { + arg_names = p_names; } Vector MethodBind::get_argument_names() const { @@ -93,41 +88,36 @@ Vector MethodBind::get_argument_names() const { #endif - - -void MethodBind::set_default_arguments(const Vector& p_defargs) { - default_arguments=p_defargs; - default_argument_count=default_arguments.size(); - +void MethodBind::set_default_arguments(const Vector &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 -#include "method_ptrcall.h" /** @author Juan Linietsky @@ -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 +template struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template -struct VariantCaster { +template +struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template -struct VariantCaster { +template +struct VariantCaster { - 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::cast( (m_idx-1)>=p_arg_count?get_default_argument(m_idx-1):*p_args[m_idx-1] )) +#define _VC(m_idx) \ + (VariantCaster::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 {\ -\ - 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(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 { \ + \ + static _FORCE_INLINE_ m_enum cast(const Variant &p_variant) { \ + return (m_enum)p_variant.operator int(); \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_enum convert(const void *p_ptr) { \ + return m_enum(*reinterpret_cast(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 {\ -\ - 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 { \ + \ + 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)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 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& p_names); + void set_argument_names(const Vector &p_names); Vector 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& p_defargs); + void set_default_arguments(const Vector &p_defargs); MethodBind(); virtual ~MethodBind(); }; - -template +template 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(p_object); - return (instance->*call_method)(p_args,p_arg_count,r_error); + T *instance = static_cast(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 names; names.resize(p_info.arguments.size()); - for(int i=0;i +MethodBind *create_vararg_method_bind(Variant (T::*p_method)(const Variant **, int, Variant::CallError &), const MethodInfo &p_info) { -template -MethodBind* create_vararg_method_bind( Variant (T::*p_method)(const Variant**,int ,Variant::CallError &), const MethodInfo& p_info ) { - - MethodBindVarArg * a = memnew( (MethodBindVarArg) ); + MethodBindVarArg *a = memnew((MethodBindVarArg)); 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 +template struct PtrToArg { - }; -#define MAKE_PTRARG(m_type) \ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_type*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(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 {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_ret*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(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 { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_type *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(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 { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_ret *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(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 -struct PtrToArg< T* > { +template +struct PtrToArg { - _FORCE_INLINE_ static T* convert(const void* p_ptr) { + _FORCE_INLINE_ static T *convert(const void *p_ptr) { - return const_cast(reinterpret_cast(p_ptr)); + return const_cast(reinterpret_cast(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 -struct PtrToArg< const T* > { +template +struct PtrToArg { - _FORCE_INLINE_ static const T* convert(const void* p_ptr) { + _FORCE_INLINE_ static const T *convert(const void *p_ptr) { - return reinterpret_cast(p_ptr); + return reinterpret_cast(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 > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const PoolVector *dvs = reinterpret_cast *>(p_ptr);\ - Vector ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - PoolVector::Read r=dvs->read();\ - for(int i=0;i p_vec, void* p_ptr) {\ - PoolVector *dv = reinterpret_cast *>(p_ptr);\ - int len=p_vec.size();\ - dv->resize(len);\ - {\ - PoolVector::Write w=dv->write();\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const PoolVector *dvs = reinterpret_cast *>(p_ptr);\ - Vector ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - PoolVector::Read r=dvs->read();\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const PoolVector *dvs = reinterpret_cast *>(p_ptr); \ + Vector ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + PoolVector::Read r = dvs->read(); \ + for (int i = 0; i < len; i++) { \ + ret[i] = r[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(Vector p_vec, void *p_ptr) { \ + PoolVector *dv = reinterpret_cast *>(p_ptr); \ + int len = p_vec.size(); \ + dv->resize(len); \ + { \ + PoolVector::Write w = dv->write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = p_vec[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg &> { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const PoolVector *dvs = reinterpret_cast *>(p_ptr); \ + Vector ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + PoolVector::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 > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - Vector ret;\ - int len = arr->size();\ - ret.resize(len);\ - for(int i=0;i p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len);\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - Vector ret;\ - int len = arr->size();\ - ret.resize(len);\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + Vector 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 p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast(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 &> { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + Vector 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 > {\ - _FORCE_INLINE_ static PoolVector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - PoolVector ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - PoolVector::Write w=ret.write();\ - for(int i=0;i p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len);\ - {\ - PoolVector::Read r=p_vec.read();\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static PoolVector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - PoolVector ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - PoolVector::Write w=ret.write();\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static PoolVector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + PoolVector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + PoolVector::Write w = ret.write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = (*arr)[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(PoolVector p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast(p_ptr); \ + int len = p_vec.size(); \ + arr->resize(len); \ + { \ + PoolVector::Read r = p_vec.read(); \ + for (int i = 0; i < len; i++) { \ + (*arr)[i] = r[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg &> { \ + _FORCE_INLINE_ static PoolVector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + PoolVector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + PoolVector::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 {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast(p_ptr);\ - return s;\ - }\ - _FORCE_INLINE_ static void encode(m_type p_vec, void* p_ptr) {\ - String *arr = reinterpret_cast(p_ptr);\ - *arr=p_vec;\ - }\ -};\ -\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast(p_ptr);\ - return s;\ - }\ -} +#define MAKE_STRINGCONV(m_type) \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast(p_ptr); \ + return s; \ + } \ + _FORCE_INLINE_ static void encode(m_type p_vec, void *p_ptr) { \ + String *arr = reinterpret_cast(p_ptr); \ + *arr = p_vec; \ + } \ + }; \ + \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast(p_ptr); \ + return s; \ + } \ + } MAKE_STRINGCONV(StringName); MAKE_STRINGCONV(IP_Address); -template<> +template <> struct PtrToArg > { - _FORCE_INLINE_ static PoolVector convert(const void* p_ptr) { + _FORCE_INLINE_ static PoolVector convert(const void *p_ptr) { const PoolVector *dvs = reinterpret_cast *>(p_ptr); PoolVector ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - PoolVector::Read r=dvs->read(); - PoolVector::Write w=ret.write(); - for(int i=0;i::Read r = dvs->read(); + PoolVector::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 p_vec, void* p_ptr) {\ - PoolVector *arr = reinterpret_cast *>(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len*3);\ - {\ - PoolVector::Read r=p_vec.read();\ - PoolVector::Write w=arr->write();\ - for(int i=0;i p_vec, void *p_ptr) { + PoolVector *arr = reinterpret_cast *>(p_ptr); + int len = p_vec.size(); + arr->resize(len * 3); + { + PoolVector::Read r = p_vec.read(); + PoolVector::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& > { - _FORCE_INLINE_ static PoolVector convert(const void* p_ptr) { +template <> +struct PtrToArg &> { + _FORCE_INLINE_ static PoolVector convert(const void *p_ptr) { const PoolVector *dvs = reinterpret_cast *>(p_ptr); PoolVector ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - PoolVector::Read r=dvs->read(); - PoolVector::Write w=ret.write(); - for(int i=0;i::Read r = dvs->read(); + PoolVector::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 * p_list) { +Array convert_property_list(const List *p_list) { Array va; - for (const List::Element *E=p_list->front();E;E=E->next()) { - + for (const List::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 * 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 *p_parents) { - - } void Object::_get_valid_parents_static(List *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(this),p_name,ret)) { + if (ClassDB::get_property(const_cast(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 *p_list,bool p_reversed) const { +void Object::get_property_list(List *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 *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()) { 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 args; args.resize(p_args.size()); - Vector argptrs; + Vector argptrs; argptrs.resize(p_args.size()); - for(int i=0;i_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;iget_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;iget_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()) { - 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