diff options
Diffstat (limited to 'tests')
61 files changed, 4047 insertions, 375 deletions
diff --git a/tests/core/input/test_input_event_key.h b/tests/core/input/test_input_event_key.h new file mode 100644 index 0000000000..4c9cd2002c --- /dev/null +++ b/tests/core/input/test_input_event_key.h @@ -0,0 +1,298 @@ +/*************************************************************************/ +/* test_input_event_key.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_INPUT_EVENT_KEY_H +#define TEST_INPUT_EVENT_KEY_H + +#include "core/input/input_event.h" +#include "core/os/keyboard.h" + +#include "tests/test_macros.h" + +namespace TestInputEventKey { + +TEST_CASE("[InputEventKey] Key correctly registers being pressed") { + InputEventKey key; + key.set_pressed(true); + CHECK(key.is_pressed() == true); + + key.set_pressed(false); + CHECK(key.is_pressed() == false); +} + +TEST_CASE("[InputEventKey] Key correctly stores and retrieves keycode") { + InputEventKey key; + + key.set_keycode(Key::ENTER); + CHECK(key.get_keycode() == Key::ENTER); + CHECK(key.get_keycode() != Key::PAUSE); + + key.set_physical_keycode(Key::BACKSPACE); + CHECK(key.get_physical_keycode() == Key::BACKSPACE); + CHECK(key.get_physical_keycode() != Key::PAUSE); +} + +TEST_CASE("[InputEventKey] Key correctly stores and retrieves keycode with modifiers") { + InputEventKey key; + + key.set_keycode(Key::ENTER); + key.set_ctrl_pressed(true); + + CHECK(key.get_keycode_with_modifiers() == (Key::ENTER | KeyModifierMask::CTRL)); + CHECK(key.get_keycode_with_modifiers() != (Key::ENTER | KeyModifierMask::SHIFT)); + CHECK(key.get_keycode_with_modifiers() != Key::ENTER); + + key.set_physical_keycode(Key::SPACE); + key.set_ctrl_pressed(true); + + CHECK(key.get_physical_keycode_with_modifiers() == (Key::SPACE | KeyModifierMask::CTRL)); + CHECK(key.get_physical_keycode_with_modifiers() != (Key::SPACE | KeyModifierMask::SHIFT)); + CHECK(key.get_physical_keycode_with_modifiers() != Key::SPACE); +} + +TEST_CASE("[InputEventKey] Key correctly stores and retrieves unicode") { + InputEventKey key; + + key.set_unicode('x'); + CHECK(key.get_unicode() == 'x'); + CHECK(key.get_unicode() != 'y'); +} + +TEST_CASE("[InputEventKey] Key correctly stores and checks echo") { + InputEventKey key; + + key.set_echo(true); + CHECK(key.is_echo() == true); + + key.set_echo(false); + CHECK(key.is_echo() == false); +} + +TEST_CASE("[InputEventKey] Key correctly converts itself to text") { + InputEventKey none_key; + + // These next three tests test the functionality of getting a key that is set to None + // as text. These cases are a bit weird, since None has no textual representation + // (find_keycode_name(Key::NONE) results in a nullptr). Thus, these tests look weird + // with only (Physical) or a lonely modifier with (Physical) but (as far as I + // understand the code, that is intended behaviour. + + // Key is None without a physical key. + none_key.set_keycode(Key::NONE); + CHECK(none_key.as_text() == " (Physical)"); + + // Key is none and has modifiers. + none_key.set_ctrl_pressed(true); + CHECK(none_key.as_text() == "Ctrl+ (Physical)"); + + // Key is None WITH a physical key AND modifiers. + none_key.set_physical_keycode(Key::ENTER); + CHECK(none_key.as_text() == "Ctrl+Enter (Physical)"); + + InputEventKey none_key2; + + // Key is None without modifers with a physical key. + none_key2.set_keycode(Key::NONE); + none_key2.set_physical_keycode(Key::ENTER); + + CHECK(none_key2.as_text() == "Enter (Physical)"); + + InputEventKey key; + + // Key has keycode. + key.set_keycode(Key::SPACE); + CHECK(key.as_text() != ""); + CHECK(key.as_text() == "Space"); + + // Key has keycode and modifiers. + key.set_ctrl_pressed(true); + CHECK(key.as_text() != "Space"); + CHECK(key.as_text() == "Ctrl+Space"); + + // Since the keycode is set to Key::NONE upon initialization of the + // InputEventKey and you can only update it with another Key, the keycode + // cannot be empty, so the kc.is_empty() case cannot be tested. +} + +TEST_CASE("[InputEventKey] Key correctly converts its state to a string representation") { + InputEventKey none_key; + + // Set physical to true. + CHECK(none_key.to_string() == "InputEventKey: keycode=0 (), mods=none, physical=true, pressed=false, echo=false"); + // Set physical key to Escape. + none_key.set_physical_keycode(Key::ESCAPE); + CHECK(none_key.to_string() == "InputEventKey: keycode=4194305 (Escape), mods=none, physical=true, pressed=false, echo=false"); + + InputEventKey key; + + // Set physical to None, set keycode to Space. + key.set_keycode(Key::SPACE); + CHECK(key.to_string() == "InputEventKey: keycode=32 (Space), mods=none, physical=false, pressed=false, echo=false"); + + // Set pressed to true. + key.set_pressed(true); + CHECK(key.to_string() == "InputEventKey: keycode=32 (Space), mods=none, physical=false, pressed=true, echo=false"); + + // set echo to true. + key.set_echo(true); + CHECK(key.to_string() == "InputEventKey: keycode=32 (Space), mods=none, physical=false, pressed=true, echo=true"); + + // Press Ctrl and Alt. + key.set_ctrl_pressed(true); + key.set_alt_pressed(true); +#ifdef MACOS_ENABLED + CHECK(key.to_string() == "InputEventKey: keycode=32 (Space), mods=Ctrl+Option, physical=false, pressed=true, echo=true"); +#else + CHECK(key.to_string() == "InputEventKey: keycode=32 (Space), mods=Ctrl+Alt, physical=false, pressed=true, echo=true"); +#endif +} + +TEST_CASE("[InputEventKey] Key is correctly converted to reference") { + InputEventKey base_key; + Ref<InputEventKey> key_ref = base_key.create_reference(Key::ENTER); + + CHECK(key_ref->get_keycode() == Key::ENTER); +} + +TEST_CASE("[InputEventKey] Keys are correctly matched based on action") { + bool pressed = false; + float strength, raw_strength = 0.0; + + InputEventKey key; + + // Nullptr. + CHECK_MESSAGE(key.action_match(nullptr, false, 0.0f, &pressed, &strength, &raw_strength) == false, "nullptr as key reference should result in false"); + + // Match on keycode. + key.set_keycode(Key::SPACE); + Ref<InputEventKey> match = key.create_reference(Key::SPACE); + Ref<InputEventKey> no_match = key.create_reference(Key::ENTER); + + CHECK(key.action_match(match, false, 0.0f, &pressed, &strength, &raw_strength) == true); + CHECK(key.action_match(no_match, false, 0.0f, &pressed, &strength, &raw_strength) == false); + + // Check that values are correctly transferred to the pointers. + CHECK(pressed == false); + CHECK(strength < 0.5); + CHECK(raw_strength < 0.5); + + match->set_pressed(true); + key.action_match(match, false, 0.0f, &pressed, &strength, &raw_strength); + + CHECK(pressed == true); + CHECK(strength > 0.5); + CHECK(raw_strength > 0.5); + + // Tests when keycode is None: Then you rely on physical keycode. + InputEventKey none_key; + none_key.set_physical_keycode(Key::SPACE); + + Ref<InputEventKey> match_none = none_key.create_reference(Key::NONE); + match_none->set_physical_keycode(Key::SPACE); + + Ref<InputEventKey> no_match_none = none_key.create_reference(Key::NONE); + no_match_none->set_physical_keycode(Key::ENTER); + + CHECK(none_key.action_match(match_none, false, 0.0f, &pressed, &strength, &raw_strength) == true); + CHECK(none_key.action_match(no_match_none, false, 0.0f, &pressed, &strength, &raw_strength) == false); + + // Test exact match. + InputEventKey key2, ref_key; + key2.set_keycode(Key::SPACE); + + Ref<InputEventKey> match2 = ref_key.create_reference(Key::SPACE); + + // Now both press Ctrl and Shift. + key2.set_ctrl_pressed(true); + key2.set_shift_pressed(true); + + match2->set_ctrl_pressed(true); + match2->set_shift_pressed(true); + + // Now they should match. + bool exact_match = true; + CHECK(key2.action_match(match2, exact_match, 0.0f, &pressed, &strength, &raw_strength) == true); + + // Modify matching key such that it does no longer match in terms of modifiers: Shift + // is no longer pressed. + match2->set_shift_pressed(false); + CHECK(match2->is_shift_pressed() == false); + CHECK(key2.action_match(match2, exact_match, 0.0f, &pressed, &strength, &raw_strength) == false); +} + +TEST_CASE("[IsMatch] Keys are correctly matched") { + // Key with NONE as keycode. + InputEventKey key; + key.set_keycode(Key::NONE); + key.set_physical_keycode(Key::SPACE); + + // Nullptr. + CHECK(key.is_match(nullptr, false) == false); + + Ref<InputEventKey> none_ref = key.create_reference(Key::NONE); + + none_ref->set_physical_keycode(Key::SPACE); + CHECK(key.is_match(none_ref, false) == true); + + none_ref->set_physical_keycode(Key::ENTER); + CHECK(key.is_match(none_ref, false) == false); + + none_ref->set_physical_keycode(Key::SPACE); + + key.set_ctrl_pressed(true); + none_ref->set_ctrl_pressed(false); + CHECK(key.is_match(none_ref, true) == false); + + none_ref->set_ctrl_pressed(true); + CHECK(key.is_match(none_ref, true) == true); + + // Ref with actual keycode. + InputEventKey key2; + key2.set_keycode(Key::SPACE); + + Ref<InputEventKey> match = key2.create_reference(Key::SPACE); + Ref<InputEventKey> no_match = key2.create_reference(Key::ENTER); + + CHECK(key2.is_match(match, false) == true); + CHECK(key2.is_match(no_match, false) == false); + + // Now the keycode is the same, but the modifiers differ. + no_match->set_keycode(Key::SPACE); + + key2.set_ctrl_pressed(true); + match->set_ctrl_pressed(true); + no_match->set_shift_pressed(true); + + CHECK(key2.is_match(match, true) == true); + CHECK(key2.is_match(no_match, true) == false); +} +} // namespace TestInputEventKey + +#endif // TEST_INPUT_EVENT_KEY_H diff --git a/tests/core/input/test_shortcut.h b/tests/core/input/test_shortcut.h new file mode 100644 index 0000000000..93edc685ad --- /dev/null +++ b/tests/core/input/test_shortcut.h @@ -0,0 +1,235 @@ +/*************************************************************************/ +/* test_shortcut.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_SHORTCUT_H +#define TEST_SHORTCUT_H + +#include "core/input/input_event.h" +#include "core/input/shortcut.h" +#include "core/io/config_file.h" +#include "core/object/ref_counted.h" +#include "core/os/keyboard.h" +#include "core/os/os.h" + +#include "tests/test_macros.h" + +namespace TestShortcut { + +TEST_CASE("[Shortcut] Empty shortcut should have no valid events and text equal to None") { + Shortcut s; + + CHECK(s.get_as_text() == "None"); + CHECK(s.has_valid_event() == false); +} + +TEST_CASE("[Shortcut] Setting and getting an event should result in the same event as the input") { + Ref<InputEventKey> k1; + Ref<InputEventKey> k2; + k1.instantiate(); + k2.instantiate(); + + k1->set_keycode(Key::ENTER); + k2->set_keycode(Key::BACKSPACE); + + // Cast to InputEvent so the internal code recognizes the objects. + Ref<InputEvent> e1 = k1; + Ref<InputEvent> e2 = k2; + + Array input_array; + input_array.append(e1); + input_array.append(e2); + + Shortcut s; + s.set_events(input_array); + + // Get result, read it out, check whether it equals the input. + Array result_array = s.get_events(); + Ref<InputEventKey> result1 = result_array.front(); + Ref<InputEventKey> result2 = result_array.back(); + + CHECK(result1->get_keycode() == k1->get_keycode()); + CHECK(result2->get_keycode() == k2->get_keycode()); +} + +TEST_CASE("[Shortcut] 'set_events_list' should result in the same events as the input") { + Ref<InputEventKey> k1; + Ref<InputEventKey> k2; + k1.instantiate(); + k2.instantiate(); + + k1->set_keycode(Key::ENTER); + k2->set_keycode(Key::BACKSPACE); + + // Cast to InputEvent so the set_events_list() method recognizes the objects. + Ref<InputEvent> e1 = k1; + Ref<InputEvent> e2 = k2; + + List<Ref<InputEvent>> list; + list.push_back(e1); + list.push_back(e2); + + Shortcut s; + s.set_events_list(&list); + + // Get result, read it out, check whether it equals the input. + Array result_array = s.get_events(); + Ref<InputEventKey> result1 = result_array.front(); + Ref<InputEventKey> result2 = result_array.back(); + + CHECK(result1->get_keycode() == k1->get_keycode()); + CHECK(result2->get_keycode() == k2->get_keycode()); +} + +TEST_CASE("[Shortcut] 'matches_event' should correctly match the same event") { + Ref<InputEventKey> original; // The one we compare with. + Ref<InputEventKey> similar_but_not_equal; // Same keycode, different event. + Ref<InputEventKey> different; // Different event, different keycode. + Ref<InputEventKey> copy; // Copy of original event. + + original.instantiate(); + similar_but_not_equal.instantiate(); + different.instantiate(); + copy.instantiate(); + + original->set_keycode(Key::ENTER); + similar_but_not_equal->set_keycode(Key::ENTER); + similar_but_not_equal->set_keycode(Key::ESCAPE); + copy = original; + + // Only the copy is really the same, so only that one should match. + // The rest should not match. + + Ref<InputEvent> e_original = original; + + Ref<InputEvent> e_similar_but_not_equal = similar_but_not_equal; + Ref<InputEvent> e_different = different; + Ref<InputEvent> e_copy = copy; + + Array a; + a.append(e_original); + Shortcut s; + s.set_events(a); + + CHECK(s.matches_event(e_similar_but_not_equal) == false); + CHECK(s.matches_event(e_different) == false); + + CHECK(s.matches_event(e_copy) == true); +} + +TEST_CASE("[Shortcut] 'get_as_text' text representation should be correct") { + Ref<InputEventKey> same; + // k2 will not go into the shortcut but only be used to compare. + Ref<InputEventKey> different; + + same.instantiate(); + different.instantiate(); + + same->set_keycode(Key::ENTER); + different->set_keycode(Key::ESCAPE); + + Ref<InputEvent> key_event1 = same; + + Array a; + a.append(key_event1); + Shortcut s; + s.set_events(a); + + CHECK(s.get_as_text() == same->as_text()); + CHECK(s.get_as_text() != different->as_text()); +} + +TEST_CASE("[Shortcut] Event validity should be correctly checked.") { + Ref<InputEventKey> valid; + // k2 will not go into the shortcut but only be used to compare. + Ref<InputEventKey> invalid = nullptr; + + valid.instantiate(); + valid->set_keycode(Key::ENTER); + + Ref<InputEvent> valid_event = valid; + Ref<InputEvent> invalid_event = invalid; + + Array a; + a.append(invalid_event); + a.append(valid_event); + + Shortcut s; + s.set_events(a); + + CHECK(s.has_valid_event() == true); + + Array b; + b.append(invalid_event); + + Shortcut shortcut_with_invalid_event; + shortcut_with_invalid_event.set_events(b); + + CHECK(shortcut_with_invalid_event.has_valid_event() == false); +} + +TEST_CASE("[Shortcut] Equal arrays should be recognized as such.") { + Ref<InputEventKey> k1; + // k2 will not go into the shortcut but only be used to compare. + Ref<InputEventKey> k2; + + k1.instantiate(); + k2.instantiate(); + + k1->set_keycode(Key::ENTER); + k2->set_keycode(Key::ESCAPE); + + Ref<InputEvent> key_event1 = k1; + Ref<InputEvent> key_event2 = k2; + + Array same; + same.append(key_event1); + + Array same_as_same; + same_as_same.append(key_event1); + + Array different1; + different1.append(key_event2); + + Array different2; + different2.append(key_event1); + different2.append(key_event2); + + Array different3; + + Shortcut s; + + CHECK(s.is_event_array_equal(same, same_as_same) == true); + CHECK(s.is_event_array_equal(same, different1) == false); + CHECK(s.is_event_array_equal(same, different2) == false); + CHECK(s.is_event_array_equal(same, different3) == false); +} +} // namespace TestShortcut + +#endif // TEST_SHORTCUT_H diff --git a/tests/core/io/test_config_file.h b/tests/core/io/test_config_file.h index 355aca479e..666719febb 100644 --- a/tests/core/io/test_config_file.h +++ b/tests/core/io/test_config_file.h @@ -127,7 +127,7 @@ TEST_CASE("[ConfigFile] Saving file") { config_file.set_value("quoted", "a=b", 7); #ifdef WINDOWS_ENABLED - const String config_path = OS::get_singleton()->get_environment("TEMP").plus_file("config.ini"); + const String config_path = OS::get_singleton()->get_environment("TEMP").path_join("config.ini"); #else const String config_path = "/tmp/config.ini"; #endif diff --git a/tests/core/io/test_image.h b/tests/core/io/test_image.h index 36e6b83bfd..38b616cda0 100644 --- a/tests/core/io/test_image.h +++ b/tests/core/io/test_image.h @@ -78,8 +78,8 @@ TEST_CASE("[Image] Instantiation") { TEST_CASE("[Image] Saving and loading") { Ref<Image> image = memnew(Image(4, 4, false, Image::FORMAT_RGBA8)); - const String save_path_png = OS::get_singleton()->get_cache_path().plus_file("image.png"); - const String save_path_exr = OS::get_singleton()->get_cache_path().plus_file("image.exr"); + const String save_path_png = OS::get_singleton()->get_cache_path().path_join("image.png"); + const String save_path_exr = OS::get_singleton()->get_cache_path().path_join("image.exr"); // Save PNG Error err; diff --git a/tests/core/io/test_marshalls.h b/tests/core/io/test_marshalls.h index 546a2e9358..7490df2b2c 100644 --- a/tests/core/io/test_marshalls.h +++ b/tests/core/io/test_marshalls.h @@ -254,11 +254,13 @@ TEST_CASE("[Marshalls] Invalid data Variant decoding") { uint8_t some_buffer[1] = { 0x00 }; uint8_t out_of_range_type_buffer[4] = { 0xff }; // Greater than Variant::VARIANT_MAX + ERR_PRINT_OFF; CHECK(decode_variant(variant, some_buffer, /* less than 4 */ 1, &r_len) == ERR_INVALID_DATA); CHECK(r_len == 0); CHECK(decode_variant(variant, out_of_range_type_buffer, 4, &r_len) == ERR_INVALID_DATA); CHECK(r_len == 0); + ERR_PRINT_ON; } TEST_CASE("[Marshalls] NIL Variant decoding") { diff --git a/tests/core/io/test_pck_packer.h b/tests/core/io/test_pck_packer.h index d21fbdaf50..8d0e5c402a 100644 --- a/tests/core/io/test_pck_packer.h +++ b/tests/core/io/test_pck_packer.h @@ -42,7 +42,7 @@ namespace TestPCKPacker { TEST_CASE("[PCKPacker] Pack an empty PCK file") { PCKPacker pck_packer; - const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_empty.pck"); + const String output_pck_path = OS::get_singleton()->get_cache_path().path_join("output_empty.pck"); CHECK_MESSAGE( pck_packer.pck_start(output_pck_path) == OK, "Starting a PCK file should return an OK error code."); @@ -66,7 +66,7 @@ TEST_CASE("[PCKPacker] Pack an empty PCK file") { TEST_CASE("[PCKPacker] Pack empty with zero alignment invalid") { PCKPacker pck_packer; - const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_empty.pck"); + const String output_pck_path = OS::get_singleton()->get_cache_path().path_join("output_empty.pck"); ERR_PRINT_OFF; CHECK_MESSAGE(pck_packer.pck_start(output_pck_path, 0) != OK, "PCK with zero alignment should fail."); ERR_PRINT_ON; @@ -74,7 +74,7 @@ TEST_CASE("[PCKPacker] Pack empty with zero alignment invalid") { TEST_CASE("[PCKPacker] Pack empty with invalid key") { PCKPacker pck_packer; - const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_empty.pck"); + const String output_pck_path = OS::get_singleton()->get_cache_path().path_join("output_empty.pck"); ERR_PRINT_OFF; CHECK_MESSAGE(pck_packer.pck_start(output_pck_path, 32, "") != OK, "PCK with invalid key should fail."); ERR_PRINT_ON; @@ -82,7 +82,7 @@ TEST_CASE("[PCKPacker] Pack empty with invalid key") { TEST_CASE("[PCKPacker] Pack a PCK file with some files and directories") { PCKPacker pck_packer; - const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_with_files.pck"); + const String output_pck_path = OS::get_singleton()->get_cache_path().path_join("output_with_files.pck"); CHECK_MESSAGE( pck_packer.pck_start(output_pck_path) == OK, "Starting a PCK file should return an OK error code."); @@ -90,16 +90,16 @@ TEST_CASE("[PCKPacker] Pack a PCK file with some files and directories") { const String base_dir = OS::get_singleton()->get_executable_path().get_base_dir(); CHECK_MESSAGE( - pck_packer.add_file("version.py", base_dir.plus_file("../version.py"), "version.py") == OK, + pck_packer.add_file("version.py", base_dir.path_join("../version.py"), "version.py") == OK, "Adding a file to the PCK should return an OK error code."); CHECK_MESSAGE( - pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.plus_file("../icon.png")) == OK, + pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.path_join("../icon.png")) == OK, "Adding a file to a new subdirectory in the PCK should return an OK error code."); CHECK_MESSAGE( - pck_packer.add_file("some/directories with spaces/to/create/icon.svg", base_dir.plus_file("../icon.svg")) == OK, + pck_packer.add_file("some/directories with spaces/to/create/icon.svg", base_dir.path_join("../icon.svg")) == OK, "Adding a file to an existing subdirectory in the PCK should return an OK error code."); CHECK_MESSAGE( - pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.plus_file("../logo.png")) == OK, + pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.path_join("../logo.png")) == OK, "Overriding a non-flushed file to an existing subdirectory in the PCK should return an OK error code."); CHECK_MESSAGE( pck_packer.flush() == OK, diff --git a/tests/core/io/test_resource.h b/tests/core/io/test_resource.h index c880ca7d2a..2457e06ade 100644 --- a/tests/core/io/test_resource.h +++ b/tests/core/io/test_resource.h @@ -74,8 +74,8 @@ TEST_CASE("[Resource] Saving and loading") { Ref<Resource> child_resource = memnew(Resource); child_resource->set_name("I'm a child resource"); resource->set_meta("other_resource", child_resource); - const String save_path_binary = OS::get_singleton()->get_cache_path().plus_file("resource.res"); - const String save_path_text = OS::get_singleton()->get_cache_path().plus_file("resource.tres"); + const String save_path_binary = OS::get_singleton()->get_cache_path().path_join("resource.res"); + const String save_path_text = OS::get_singleton()->get_cache_path().path_join("resource.tres"); ResourceSaver::save(resource, save_path_binary); ResourceSaver::save(resource, save_path_text); diff --git a/tests/core/io/test_xml_parser.h b/tests/core/io/test_xml_parser.h index 87592b56ce..35e86d8203 100644 --- a/tests/core/io/test_xml_parser.h +++ b/tests/core/io/test_xml_parser.h @@ -66,6 +66,170 @@ TEST_CASE("[XMLParser] End-to-end") { parser.close(); } + +TEST_CASE("[XMLParser] Comments") { + XMLParser parser; + + SUBCASE("Missing end of comment") { + const String input = "<first></first><!-- foo"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT_END); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_COMMENT); + CHECK_EQ(parser.get_node_name(), " foo"); + } + SUBCASE("Bad start of comment") { + const String input = "<first></first><!-"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT_END); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_COMMENT); + CHECK_EQ(parser.get_node_name(), "-"); + } + SUBCASE("Unblanced angle brackets in comment") { + const String input = "<!-- example << --><next-tag></next-tag>"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_COMMENT); + CHECK_EQ(parser.get_node_name(), " example << "); + } + SUBCASE("Doctype") { + const String input = "<!DOCTYPE greeting [<!ELEMENT greeting (#PCDATA)>]>"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_COMMENT); + CHECK_EQ(parser.get_node_name(), "DOCTYPE greeting [<!ELEMENT greeting (#PCDATA)>]"); + } +} + +TEST_CASE("[XMLParser] Premature endings") { + SUBCASE("Simple cases") { + String input; + String expected_name; + XMLParser::NodeType expected_type; + + SUBCASE("Incomplete Unknown") { + input = "<first></first><?xml"; + expected_type = XMLParser::NodeType::NODE_UNKNOWN; + expected_name = "?xml"; + } + SUBCASE("Incomplete CDStart") { + input = "<first></first><![CD"; + expected_type = XMLParser::NodeType::NODE_CDATA; + expected_name = ""; + } + SUBCASE("Incomplete CData") { + input = "<first></first><![CDATA[example"; + expected_type = XMLParser::NodeType::NODE_CDATA; + expected_name = "example"; + } + SUBCASE("Incomplete CDEnd") { + input = "<first></first><![CDATA[example]]"; + expected_type = XMLParser::NodeType::NODE_CDATA; + expected_name = "example]]"; + } + SUBCASE("Incomplete start-tag name") { + input = "<first></first><second"; + expected_type = XMLParser::NodeType::NODE_ELEMENT; + expected_name = "second"; + } + + XMLParser parser; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT_END); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), expected_type); + CHECK_EQ(parser.get_node_name(), expected_name); + } + + SUBCASE("With attributes and texts") { + XMLParser parser; + + SUBCASE("Incomplete start-tag attribute name") { + const String input = "<first></first><second attr1=\"foo\" attr2"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + CHECK_EQ(parser.get_node_name(), "second"); + CHECK_EQ(parser.get_attribute_count(), 1); + CHECK_EQ(parser.get_attribute_name(0), "attr1"); + CHECK_EQ(parser.get_attribute_value(0), "foo"); + } + + SUBCASE("Incomplete start-tag attribute unquoted value") { + const String input = "<first></first><second attr1=\"foo\" attr2=bar"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + CHECK_EQ(parser.get_node_name(), "second"); + CHECK_EQ(parser.get_attribute_count(), 1); + CHECK_EQ(parser.get_attribute_name(0), "attr1"); + CHECK_EQ(parser.get_attribute_value(0), "foo"); + } + + SUBCASE("Incomplete start-tag attribute quoted value") { + const String input = "<first></first><second attr1=\"foo\" attr2=\"bar"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + CHECK_EQ(parser.get_node_name(), "second"); + CHECK_EQ(parser.get_attribute_count(), 2); + CHECK_EQ(parser.get_attribute_name(0), "attr1"); + CHECK_EQ(parser.get_attribute_value(0), "foo"); + CHECK_EQ(parser.get_attribute_name(1), "attr2"); + CHECK_EQ(parser.get_attribute_value(1), "bar"); + } + + SUBCASE("Incomplete end-tag name") { + const String input = "<first></fir"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT_END); + CHECK_EQ(parser.get_node_name(), "fir"); + } + + SUBCASE("Trailing text") { + const String input = "<first></first>example"; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_TEXT); + CHECK_EQ(parser.get_node_data(), "example"); + } + } +} + +TEST_CASE("[XMLParser] CDATA") { + const String input = "<a><![CDATA[my cdata content goes here]]></a>"; + XMLParser parser; + REQUIRE_EQ(parser.open_buffer(input.to_utf8_buffer()), OK); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT); + CHECK_EQ(parser.get_node_name(), "a"); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_CDATA); + CHECK_EQ(parser.get_node_name(), "my cdata content goes here"); + REQUIRE_EQ(parser.read(), OK); + CHECK_EQ(parser.get_node_type(), XMLParser::NodeType::NODE_ELEMENT_END); + CHECK_EQ(parser.get_node_name(), "a"); +} } // namespace TestXMLParser #endif // TEST_XML_PARSER_H diff --git a/tests/core/math/test_aabb.h b/tests/core/math/test_aabb.h index 526972a82f..d5f54a139e 100644 --- a/tests/core/math/test_aabb.h +++ b/tests/core/math/test_aabb.h @@ -94,7 +94,7 @@ TEST_CASE("[AABB] Volume getters") { Math::is_equal_approx(aabb.get_volume(), 120), "get_volume() should return the expected value with positive size."); CHECK_MESSAGE( - !aabb.has_no_volume(), + aabb.has_volume(), "Non-empty volumetric AABB should have a volume."); aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(-4, 5, 6)); @@ -114,27 +114,32 @@ TEST_CASE("[AABB] Volume getters") { aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 0, 6)); CHECK_MESSAGE( - aabb.has_no_volume(), + !aabb.has_volume(), "Non-empty flat AABB should not have a volume."); CHECK_MESSAGE( - AABB().has_no_volume(), + !AABB().has_volume(), "Empty AABB should not have a volume."); } TEST_CASE("[AABB] Surface getters") { AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6)); CHECK_MESSAGE( - !aabb.has_no_surface(), + aabb.has_surface(), "Non-empty volumetric AABB should have an surface."); aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 0, 6)); CHECK_MESSAGE( - !aabb.has_no_surface(), + aabb.has_surface(), "Non-empty flat AABB should have a surface."); + aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 0, 0)); CHECK_MESSAGE( - AABB().has_no_surface(), + aabb.has_surface(), + "Non-empty linear AABB should have a surface."); + + CHECK_MESSAGE( + !AABB().has_surface(), "Empty AABB should not have an surface."); } @@ -299,34 +304,28 @@ TEST_CASE("[AABB] Get longest/shortest axis") { "get_shortest_axis_size() should return the expected value."); } -#ifndef _MSC_VER -#warning Support tests need to be re-done -#endif - -/* Support function was actually broken. As it was fixed, the tests now fail. Tests need to be re-done. - TEST_CASE("[AABB] Get support") { const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6)); CHECK_MESSAGE( - aabb.get_support(Vector3(1, 0, 0)).is_equal_approx(Vector3(-1.5, 7, 3.5)), + aabb.get_support(Vector3(1, 0, 0)).is_equal_approx(Vector3(2.5, 2, -2.5)), "get_support() should return the expected value."); CHECK_MESSAGE( - aabb.get_support(Vector3(0.5, 1, 0)).is_equal_approx(Vector3(-1.5, 2, 3.5)), + aabb.get_support(Vector3(0.5, 1, 0)).is_equal_approx(Vector3(2.5, 7, -2.5)), "get_support() should return the expected value."); CHECK_MESSAGE( - aabb.get_support(Vector3(0.5, 1, -400)).is_equal_approx(Vector3(-1.5, 2, 3.5)), + aabb.get_support(Vector3(0.5, 1, -400)).is_equal_approx(Vector3(2.5, 7, -2.5)), "get_support() should return the expected value."); CHECK_MESSAGE( - aabb.get_support(Vector3(0, -1, 0)).is_equal_approx(Vector3(2.5, 7, 3.5)), + aabb.get_support(Vector3(0, -1, 0)).is_equal_approx(Vector3(-1.5, 2, -2.5)), "get_support() should return the expected value."); CHECK_MESSAGE( - aabb.get_support(Vector3(0, -0.1, 0)).is_equal_approx(Vector3(2.5, 7, 3.5)), + aabb.get_support(Vector3(0, -0.1, 0)).is_equal_approx(Vector3(-1.5, 2, -2.5)), "get_support() should return the expected value."); CHECK_MESSAGE( - aabb.get_support(Vector3()).is_equal_approx(Vector3(2.5, 7, 3.5)), + aabb.get_support(Vector3()).is_equal_approx(Vector3(-1.5, 2, -2.5)), "get_support() should return the expected value with a null vector."); } -*/ + TEST_CASE("[AABB] Grow") { const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6)); CHECK_MESSAGE( diff --git a/tests/core/math/test_geometry_3d.h b/tests/core/math/test_geometry_3d.h index 99a4ef2d46..23bbf1e183 100644 --- a/tests/core/math/test_geometry_3d.h +++ b/tests/core/math/test_geometry_3d.h @@ -63,7 +63,7 @@ TEST_CASE("[Geometry3D] Closest Distance Between Segments") { p_1(p_p_1), p_2(p_p_2), p_3(p_p_3), p_4(p_p_4), want(p_want){}; }; Vector<Case> tt; - tt.push_back(Case(Vector3(1, -2, 0), Vector3(1, 2, 0), Vector3(-1, 2, 0), Vector3(-1, -2, 0), 0.0f)); + tt.push_back(Case(Vector3(1, -2, 0), Vector3(1, 2, 0), Vector3(-1, 2, 0), Vector3(-1, -2, 0), 2.0f)); for (int i = 0; i < tt.size(); ++i) { Case current_case = tt[i]; float out = Geometry3D::get_closest_distance_between_segments(current_case.p_1, current_case.p_2, current_case.p_3, current_case.p_4); diff --git a/tests/core/math/test_quaternion.h b/tests/core/math/test_quaternion.h new file mode 100644 index 0000000000..1b80ffba0b --- /dev/null +++ b/tests/core/math/test_quaternion.h @@ -0,0 +1,389 @@ +/*************************************************************************/ +/* test_quaternion.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_QUATERNION_H +#define TEST_QUATERNION_H + +#include "core/math/math_defs.h" +#include "core/math/math_funcs.h" +#include "core/math/quaternion.h" +#include "core/math/vector3.h" + +#include "tests/test_macros.h" + +namespace TestQuaternion { + +Quaternion quat_euler_yxz_deg(Vector3 angle) { + double yaw = Math::deg_to_rad(angle[1]); + double pitch = Math::deg_to_rad(angle[0]); + double roll = Math::deg_to_rad(angle[2]); + + // Generate YXZ (Z-then-X-then-Y) Quaternion using single-axis Euler + // constructor and quaternion product, both tested separately. + Quaternion q_y(Vector3(0.0, yaw, 0.0)); + Quaternion q_p(Vector3(pitch, 0.0, 0.0)); + Quaternion q_r(Vector3(0.0, 0.0, roll)); + // Roll-Z is followed by Pitch-X, then Yaw-Y. + Quaternion q_yxz = q_y * q_p * q_r; + + return q_yxz; +} + +TEST_CASE("[Quaternion] Default Construct") { + Quaternion q; + + CHECK(q[0] == 0.0); + CHECK(q[1] == 0.0); + CHECK(q[2] == 0.0); + CHECK(q[3] == 1.0); +} + +TEST_CASE("[Quaternion] Construct x,y,z,w") { + // Values are taken from actual use in another project & are valid (except roundoff error). + Quaternion q(0.2391, 0.099, 0.3696, 0.8924); + + CHECK(q[0] == doctest::Approx(0.2391)); + CHECK(q[1] == doctest::Approx(0.099)); + CHECK(q[2] == doctest::Approx(0.3696)); + CHECK(q[3] == doctest::Approx(0.8924)); +} + +TEST_CASE("[Quaternion] Construct AxisAngle 1") { + // Easy to visualize: 120 deg about X-axis. + Quaternion q(Vector3(1.0, 0.0, 0.0), Math::deg_to_rad(120.0)); + + // 0.866 isn't close enough; doctest::Approx doesn't cut much slack! + CHECK(q[0] == doctest::Approx(0.866025)); // Sine of half the angle. + CHECK(q[1] == doctest::Approx(0.0)); + CHECK(q[2] == doctest::Approx(0.0)); + CHECK(q[3] == doctest::Approx(0.5)); // Cosine of half the angle. +} + +TEST_CASE("[Quaternion] Construct AxisAngle 2") { + // Easy to visualize: 30 deg about Y-axis. + Quaternion q(Vector3(0.0, 1.0, 0.0), Math::deg_to_rad(30.0)); + + CHECK(q[0] == doctest::Approx(0.0)); + CHECK(q[1] == doctest::Approx(0.258819)); // Sine of half the angle. + CHECK(q[2] == doctest::Approx(0.0)); + CHECK(q[3] == doctest::Approx(0.965926)); // Cosine of half the angle. +} + +TEST_CASE("[Quaternion] Construct AxisAngle 3") { + // Easy to visualize: 60 deg about Z-axis. + Quaternion q(Vector3(0.0, 0.0, 1.0), Math::deg_to_rad(60.0)); + + CHECK(q[0] == doctest::Approx(0.0)); + CHECK(q[1] == doctest::Approx(0.0)); + CHECK(q[2] == doctest::Approx(0.5)); // Sine of half the angle. + CHECK(q[3] == doctest::Approx(0.866025)); // Cosine of half the angle. +} + +TEST_CASE("[Quaternion] Construct AxisAngle 4") { + // More complex & hard to visualize, so test w/ data from online calculator. + Vector3 axis(1.0, 2.0, 0.5); + Quaternion q(axis.normalized(), Math::deg_to_rad(35.0)); + + CHECK(q[0] == doctest::Approx(0.131239)); + CHECK(q[1] == doctest::Approx(0.262478)); + CHECK(q[2] == doctest::Approx(0.0656194)); + CHECK(q[3] == doctest::Approx(0.953717)); +} + +TEST_CASE("[Quaternion] Construct from Quaternion") { + Vector3 axis(1.0, 2.0, 0.5); + Quaternion q_src(axis.normalized(), Math::deg_to_rad(35.0)); + Quaternion q(q_src); + + CHECK(q[0] == doctest::Approx(0.131239)); + CHECK(q[1] == doctest::Approx(0.262478)); + CHECK(q[2] == doctest::Approx(0.0656194)); + CHECK(q[3] == doctest::Approx(0.953717)); +} + +TEST_CASE("[Quaternion] Construct Euler SingleAxis") { + double yaw = Math::deg_to_rad(45.0); + double pitch = Math::deg_to_rad(30.0); + double roll = Math::deg_to_rad(10.0); + + Vector3 euler_y(0.0, yaw, 0.0); + Quaternion q_y(euler_y); + CHECK(q_y[0] == doctest::Approx(0.0)); + CHECK(q_y[1] == doctest::Approx(0.382684)); + CHECK(q_y[2] == doctest::Approx(0.0)); + CHECK(q_y[3] == doctest::Approx(0.923879)); + + Vector3 euler_p(pitch, 0.0, 0.0); + Quaternion q_p(euler_p); + CHECK(q_p[0] == doctest::Approx(0.258819)); + CHECK(q_p[1] == doctest::Approx(0.0)); + CHECK(q_p[2] == doctest::Approx(0.0)); + CHECK(q_p[3] == doctest::Approx(0.965926)); + + Vector3 euler_r(0.0, 0.0, roll); + Quaternion q_r(euler_r); + CHECK(q_r[0] == doctest::Approx(0.0)); + CHECK(q_r[1] == doctest::Approx(0.0)); + CHECK(q_r[2] == doctest::Approx(0.0871558)); + CHECK(q_r[3] == doctest::Approx(0.996195)); +} + +TEST_CASE("[Quaternion] Construct Euler YXZ dynamic axes") { + double yaw = Math::deg_to_rad(45.0); + double pitch = Math::deg_to_rad(30.0); + double roll = Math::deg_to_rad(10.0); + + // Generate YXZ comparision data (Z-then-X-then-Y) using single-axis Euler + // constructor and quaternion product, both tested separately. + Vector3 euler_y(0.0, yaw, 0.0); + Quaternion q_y(euler_y); + Vector3 euler_p(pitch, 0.0, 0.0); + Quaternion q_p(euler_p); + Vector3 euler_r(0.0, 0.0, roll); + Quaternion q_r(euler_r); + + // Roll-Z is followed by Pitch-X. + Quaternion check_xz = q_p * q_r; + // Then Yaw-Y follows both. + Quaternion check_yxz = q_y * check_xz; + + // Test construction from YXZ Euler angles. + Vector3 euler_yxz(pitch, yaw, roll); + Quaternion q(euler_yxz); + CHECK(q[0] == doctest::Approx(check_yxz[0])); + CHECK(q[1] == doctest::Approx(check_yxz[1])); + CHECK(q[2] == doctest::Approx(check_yxz[2])); + CHECK(q[3] == doctest::Approx(check_yxz[3])); + + // Sneak in a test of is_equal_approx. + CHECK(q.is_equal_approx(check_yxz)); +} + +TEST_CASE("[Quaternion] Construct Basis Euler") { + double yaw = Math::deg_to_rad(45.0); + double pitch = Math::deg_to_rad(30.0); + double roll = Math::deg_to_rad(10.0); + Vector3 euler_yxz(pitch, yaw, roll); + Quaternion q_yxz(euler_yxz); + Basis basis_axes(euler_yxz); + Quaternion q(basis_axes); + CHECK(q.is_equal_approx(q_yxz)); +} + +TEST_CASE("[Quaternion] Construct Basis Axes") { + // Arbitrary Euler angles. + Vector3 euler_yxz(Math::deg_to_rad(31.41), Math::deg_to_rad(-49.16), Math::deg_to_rad(12.34)); + // Basis vectors from online calculation of rotation matrix. + Vector3 i_unit(0.5545787, 0.1823950, 0.8118957); + Vector3 j_unit(-0.5249245, 0.8337420, 0.1712555); + Vector3 k_unit(-0.6456754, -0.5211586, 0.5581192); + // Quaternion from online calculation. + Quaternion q_calc(0.2016913, -0.4245716, 0.206033, 0.8582598); + // Quaternion from local calculation. + Quaternion q_local = quat_euler_yxz_deg(Vector3(31.41, -49.16, 12.34)); + // Quaternion from Euler angles constructor. + Quaternion q_euler(euler_yxz); + CHECK(q_calc.is_equal_approx(q_local)); + CHECK(q_local.is_equal_approx(q_euler)); + + // Calculate Basis and construct Quaternion. + // When this is written, C++ Basis class does not construct from basis vectors. + // This is by design, but may be subject to change. + // Workaround by constructing Basis from Euler angles. + // basis_axes = Basis(i_unit, j_unit, k_unit); + Basis basis_axes(euler_yxz); + Quaternion q(basis_axes); + + CHECK(basis_axes.get_column(0).is_equal_approx(i_unit)); + CHECK(basis_axes.get_column(1).is_equal_approx(j_unit)); + CHECK(basis_axes.get_column(2).is_equal_approx(k_unit)); + + CHECK(q.is_equal_approx(q_calc)); + CHECK_FALSE(q.inverse().is_equal_approx(q_calc)); + CHECK(q.is_equal_approx(q_local)); + CHECK(q.is_equal_approx(q_euler)); + CHECK(q[0] == doctest::Approx(0.2016913)); + CHECK(q[1] == doctest::Approx(-0.4245716)); + CHECK(q[2] == doctest::Approx(0.206033)); + CHECK(q[3] == doctest::Approx(0.8582598)); +} + +TEST_CASE("[Quaternion] Product (book)") { + // Example from "Quaternions and Rotation Sequences" by Jack Kuipers, p. 108. + Quaternion p(1.0, -2.0, 1.0, 3.0); + Quaternion q(-1.0, 2.0, 3.0, 2.0); + + Quaternion pq = p * q; + CHECK(pq[0] == doctest::Approx(-9.0)); + CHECK(pq[1] == doctest::Approx(-2.0)); + CHECK(pq[2] == doctest::Approx(11.0)); + CHECK(pq[3] == doctest::Approx(8.0)); +} + +TEST_CASE("[Quaternion] Product") { + double yaw = Math::deg_to_rad(45.0); + double pitch = Math::deg_to_rad(30.0); + double roll = Math::deg_to_rad(10.0); + + Vector3 euler_y(0.0, yaw, 0.0); + Quaternion q_y(euler_y); + CHECK(q_y[0] == doctest::Approx(0.0)); + CHECK(q_y[1] == doctest::Approx(0.382684)); + CHECK(q_y[2] == doctest::Approx(0.0)); + CHECK(q_y[3] == doctest::Approx(0.923879)); + + Vector3 euler_p(pitch, 0.0, 0.0); + Quaternion q_p(euler_p); + CHECK(q_p[0] == doctest::Approx(0.258819)); + CHECK(q_p[1] == doctest::Approx(0.0)); + CHECK(q_p[2] == doctest::Approx(0.0)); + CHECK(q_p[3] == doctest::Approx(0.965926)); + + Vector3 euler_r(0.0, 0.0, roll); + Quaternion q_r(euler_r); + CHECK(q_r[0] == doctest::Approx(0.0)); + CHECK(q_r[1] == doctest::Approx(0.0)); + CHECK(q_r[2] == doctest::Approx(0.0871558)); + CHECK(q_r[3] == doctest::Approx(0.996195)); + + // Test ZYX dynamic-axes since test data is available online. + // Rotate first about X axis, then new Y axis, then new Z axis. + // (Godot uses YXZ Yaw-Pitch-Roll order). + Quaternion q_yp = q_y * q_p; + CHECK(q_yp[0] == doctest::Approx(0.239118)); + CHECK(q_yp[1] == doctest::Approx(0.369644)); + CHECK(q_yp[2] == doctest::Approx(-0.099046)); + CHECK(q_yp[3] == doctest::Approx(0.892399)); + + Quaternion q_ryp = q_r * q_yp; + CHECK(q_ryp[0] == doctest::Approx(0.205991)); + CHECK(q_ryp[1] == doctest::Approx(0.389078)); + CHECK(q_ryp[2] == doctest::Approx(-0.0208912)); + CHECK(q_ryp[3] == doctest::Approx(0.897636)); +} + +TEST_CASE("[Quaternion] xform unit vectors") { + // Easy to visualize: 120 deg about X-axis. + // Transform the i, j, & k unit vectors. + Quaternion q(Vector3(1.0, 0.0, 0.0), Math::deg_to_rad(120.0)); + Vector3 i_t = q.xform(Vector3(1.0, 0.0, 0.0)); + Vector3 j_t = q.xform(Vector3(0.0, 1.0, 0.0)); + Vector3 k_t = q.xform(Vector3(0.0, 0.0, 1.0)); + // + CHECK(i_t.is_equal_approx(Vector3(1.0, 0.0, 0.0))); + CHECK(j_t.is_equal_approx(Vector3(0.0, -0.5, 0.866025))); + CHECK(k_t.is_equal_approx(Vector3(0.0, -0.866025, -0.5))); + CHECK(i_t.length_squared() == doctest::Approx(1.0)); + CHECK(j_t.length_squared() == doctest::Approx(1.0)); + CHECK(k_t.length_squared() == doctest::Approx(1.0)); + + // Easy to visualize: 30 deg about Y-axis. + q = Quaternion(Vector3(0.0, 1.0, 0.0), Math::deg_to_rad(30.0)); + i_t = q.xform(Vector3(1.0, 0.0, 0.0)); + j_t = q.xform(Vector3(0.0, 1.0, 0.0)); + k_t = q.xform(Vector3(0.0, 0.0, 1.0)); + // + CHECK(i_t.is_equal_approx(Vector3(0.866025, 0.0, -0.5))); + CHECK(j_t.is_equal_approx(Vector3(0.0, 1.0, 0.0))); + CHECK(k_t.is_equal_approx(Vector3(0.5, 0.0, 0.866025))); + CHECK(i_t.length_squared() == doctest::Approx(1.0)); + CHECK(j_t.length_squared() == doctest::Approx(1.0)); + CHECK(k_t.length_squared() == doctest::Approx(1.0)); + + // Easy to visualize: 60 deg about Z-axis. + q = Quaternion(Vector3(0.0, 0.0, 1.0), Math::deg_to_rad(60.0)); + i_t = q.xform(Vector3(1.0, 0.0, 0.0)); + j_t = q.xform(Vector3(0.0, 1.0, 0.0)); + k_t = q.xform(Vector3(0.0, 0.0, 1.0)); + // + CHECK(i_t.is_equal_approx(Vector3(0.5, 0.866025, 0.0))); + CHECK(j_t.is_equal_approx(Vector3(-0.866025, 0.5, 0.0))); + CHECK(k_t.is_equal_approx(Vector3(0.0, 0.0, 1.0))); + CHECK(i_t.length_squared() == doctest::Approx(1.0)); + CHECK(j_t.length_squared() == doctest::Approx(1.0)); + CHECK(k_t.length_squared() == doctest::Approx(1.0)); +} + +TEST_CASE("[Quaternion] xform vector") { + // Arbitrary quaternion rotates an arbitrary vector. + Vector3 euler_yzx(Math::deg_to_rad(31.41), Math::deg_to_rad(-49.16), Math::deg_to_rad(12.34)); + Basis basis_axes(euler_yzx); + Quaternion q(basis_axes); + + Vector3 v_arb(3.0, 4.0, 5.0); + Vector3 v_rot = q.xform(v_arb); + Vector3 v_compare = basis_axes.xform(v_arb); + + CHECK(v_rot.length_squared() == doctest::Approx(v_arb.length_squared())); + CHECK(v_rot.is_equal_approx(v_compare)); +} + +// Test vector xform for a single combination of Quaternion and Vector. +void test_quat_vec_rotate(Vector3 euler_yzx, Vector3 v_in) { + Basis basis_axes(euler_yzx); + Quaternion q(basis_axes); + + Vector3 v_rot = q.xform(v_in); + Vector3 v_compare = basis_axes.xform(v_in); + + CHECK(v_rot.length_squared() == doctest::Approx(v_in.length_squared())); + CHECK(v_rot.is_equal_approx(v_compare)); +} + +TEST_CASE("[Stress][Quaternion] Many vector xforms") { + // Many arbitrary quaternions rotate many arbitrary vectors. + // For each trial, check that rotation by Quaternion yields same result as + // rotation by Basis. + const int STEPS = 100; // Number of test steps in each dimension + const double delta = 2.0 * Math_PI / STEPS; // Angle increment per step + const double delta_vec = 20.0 / STEPS; // Vector increment per step + Vector3 vec_arb(1.0, 1.0, 1.0); + double x_angle = -Math_PI; + double y_angle = -Math_PI; + double z_angle = -Math_PI; + for (double i = 0; i < STEPS; ++i) { + vec_arb[0] = -10.0 + i * delta_vec; + x_angle = i * delta - Math_PI; + for (double j = 0; j < STEPS; ++j) { + vec_arb[1] = -10.0 + j * delta_vec; + y_angle = j * delta - Math_PI; + for (double k = 0; k < STEPS; ++k) { + vec_arb[2] = -10.0 + k * delta_vec; + z_angle = k * delta - Math_PI; + Vector3 euler_yzx(x_angle, y_angle, z_angle); + test_quat_vec_rotate(euler_yzx, vec_arb); + } + } + } +} + +} // namespace TestQuaternion + +#endif // TEST_QUATERNION_H diff --git a/tests/core/math/test_rect2.h b/tests/core/math/test_rect2.h index 0b1106ac3c..6323b214db 100644 --- a/tests/core/math/test_rect2.h +++ b/tests/core/math/test_rect2.h @@ -118,17 +118,17 @@ TEST_CASE("[Rect2] Area getters") { "get_area() should return the expected value."); CHECK_MESSAGE( - !Rect2(0, 100, 1280, 720).has_no_area(), - "has_no_area() should return the expected value on Rect2 with an area."); + Rect2(0, 100, 1280, 720).has_area(), + "has_area() should return the expected value on Rect2 with an area."); CHECK_MESSAGE( - Rect2(0, 100, 0, 500).has_no_area(), - "has_no_area() should return the expected value on Rect2 with no area."); + !Rect2(0, 100, 0, 500).has_area(), + "has_area() should return the expected value on Rect2 with no area."); CHECK_MESSAGE( - Rect2(0, 100, 500, 0).has_no_area(), - "has_no_area() should return the expected value on Rect2 with no area."); + !Rect2(0, 100, 500, 0).has_area(), + "has_area() should return the expected value on Rect2 with no area."); CHECK_MESSAGE( - Rect2(0, 100, 0, 0).has_no_area(), - "has_no_area() should return the expected value on Rect2 with no area."); + !Rect2(0, 100, 0, 0).has_area(), + "has_area() should return the expected value on Rect2 with no area."); } TEST_CASE("[Rect2] Absolute coordinates") { diff --git a/tests/core/math/test_rect2i.h b/tests/core/math/test_rect2i.h index 0d1a088a66..4005300e1f 100644 --- a/tests/core/math/test_rect2i.h +++ b/tests/core/math/test_rect2i.h @@ -118,17 +118,17 @@ TEST_CASE("[Rect2i] Area getters") { "get_area() should return the expected value."); CHECK_MESSAGE( - !Rect2i(0, 100, 1280, 720).has_no_area(), - "has_no_area() should return the expected value on Rect2i with an area."); + Rect2i(0, 100, 1280, 720).has_area(), + "has_area() should return the expected value on Rect2i with an area."); CHECK_MESSAGE( - Rect2i(0, 100, 0, 500).has_no_area(), - "has_no_area() should return the expected value on Rect2i with no area."); + !Rect2i(0, 100, 0, 500).has_area(), + "has_area() should return the expected value on Rect2i with no area."); CHECK_MESSAGE( - Rect2i(0, 100, 500, 0).has_no_area(), - "has_no_area() should return the expected value on Rect2i with no area."); + !Rect2i(0, 100, 500, 0).has_area(), + "has_area() should return the expected value on Rect2i with no area."); CHECK_MESSAGE( - Rect2i(0, 100, 0, 0).has_no_area(), - "has_no_area() should return the expected value on Rect2i with no area."); + !Rect2i(0, 100, 0, 0).has_area(), + "has_area() should return the expected value on Rect2i with no area."); } TEST_CASE("[Rect2i] Absolute coordinates") { diff --git a/tests/core/math/test_transform_2d.h b/tests/core/math/test_transform_2d.h new file mode 100644 index 0000000000..697bf63fc5 --- /dev/null +++ b/tests/core/math/test_transform_2d.h @@ -0,0 +1,88 @@ +/*************************************************************************/ +/* test_transform_2d.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_TRANSFORM_2D_H +#define TEST_TRANSFORM_2D_H + +#include "core/math/transform_2d.h" + +#include "tests/test_macros.h" + +namespace TestTransform2D { + +Transform2D create_dummy_transform() { + return Transform2D(Vector2(1, 2), Vector2(3, 4), Vector2(5, 6)); +} + +Transform2D identity() { + return Transform2D(); +} + +TEST_CASE("[Transform2D] translation") { + Vector2 offset = Vector2(1, 2); + + // Both versions should give the same result applied to identity. + CHECK(identity().translated(offset) == identity().translated_local(offset)); + + // Check both versions against left and right multiplications. + Transform2D orig = create_dummy_transform(); + Transform2D T = identity().translated(offset); + CHECK(orig.translated(offset) == T * orig); + CHECK(orig.translated_local(offset) == orig * T); +} + +TEST_CASE("[Transform2D] scaling") { + Vector2 scaling = Vector2(1, 2); + + // Both versions should give the same result applied to identity. + CHECK(identity().scaled(scaling) == identity().scaled_local(scaling)); + + // Check both versions against left and right multiplications. + Transform2D orig = create_dummy_transform(); + Transform2D S = identity().scaled(scaling); + CHECK(orig.scaled(scaling) == S * orig); + CHECK(orig.scaled_local(scaling) == orig * S); +} + +TEST_CASE("[Transform2D] rotation") { + real_t phi = 1.0; + + // Both versions should give the same result applied to identity. + CHECK(identity().rotated(phi) == identity().rotated_local(phi)); + + // Check both versions against left and right multiplications. + Transform2D orig = create_dummy_transform(); + Transform2D R = identity().rotated(phi); + CHECK(orig.rotated(phi) == R * orig); + CHECK(orig.rotated_local(phi) == orig * R); +} +} // namespace TestTransform2D + +#endif // TEST_TRANSFORM_2D_H diff --git a/tests/core/math/test_transform_3d.h b/tests/core/math/test_transform_3d.h new file mode 100644 index 0000000000..da166b43f7 --- /dev/null +++ b/tests/core/math/test_transform_3d.h @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* test_transform_3d.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_TRANSFORM_3D_H +#define TEST_TRANSFORM_3D_H + +#include "core/math/transform_3d.h" + +#include "tests/test_macros.h" + +namespace TestTransform3D { + +Transform3D create_dummy_transform() { + return Transform3D(Basis(Vector3(1, 2, 3), Vector3(4, 5, 6), Vector3(7, 8, 9)), Vector3(10, 11, 12)); +} + +Transform3D identity() { + return Transform3D(); +} + +TEST_CASE("[Transform3D] translation") { + Vector3 offset = Vector3(1, 2, 3); + + // Both versions should give the same result applied to identity. + CHECK(identity().translated(offset) == identity().translated_local(offset)); + + // Check both versions against left and right multiplications. + Transform3D orig = create_dummy_transform(); + Transform3D T = identity().translated(offset); + CHECK(orig.translated(offset) == T * orig); + CHECK(orig.translated_local(offset) == orig * T); +} + +TEST_CASE("[Transform3D] scaling") { + Vector3 scaling = Vector3(1, 2, 3); + + // Both versions should give the same result applied to identity. + CHECK(identity().scaled(scaling) == identity().scaled_local(scaling)); + + // Check both versions against left and right multiplications. + Transform3D orig = create_dummy_transform(); + Transform3D S = identity().scaled(scaling); + CHECK(orig.scaled(scaling) == S * orig); + CHECK(orig.scaled_local(scaling) == orig * S); +} + +TEST_CASE("[Transform3D] rotation") { + Vector3 axis = Vector3(1, 2, 3).normalized(); + real_t phi = 1.0; + + // Both versions should give the same result applied to identity. + CHECK(identity().rotated(axis, phi) == identity().rotated_local(axis, phi)); + + // Check both versions against left and right multiplications. + Transform3D orig = create_dummy_transform(); + Transform3D R = identity().rotated(axis, phi); + CHECK(orig.rotated(axis, phi) == R * orig); + CHECK(orig.rotated_local(axis, phi) == orig * R); +} +} // namespace TestTransform3D + +#endif // TEST_TRANSFORM_3D_H diff --git a/tests/core/math/test_vector4.h b/tests/core/math/test_vector4.h new file mode 100644 index 0000000000..ccf991401b --- /dev/null +++ b/tests/core/math/test_vector4.h @@ -0,0 +1,315 @@ +/*************************************************************************/ +/* test_vector4.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_VECTOR4_H +#define TEST_VECTOR4_H + +#include "core/math/vector4.h" +#include "tests/test_macros.h" + +#define Math_SQRT3 1.7320508075688772935274463415059 + +namespace TestVector4 { + +TEST_CASE("[Vector4] Axis methods") { + Vector4 vector = Vector4(1.2, 3.4, 5.6, -0.9); + CHECK_MESSAGE( + vector.max_axis_index() == Vector4::Axis::AXIS_Z, + "Vector4 max_axis_index should work as expected."); + CHECK_MESSAGE( + vector.min_axis_index() == Vector4::Axis::AXIS_W, + "Vector4 min_axis_index should work as expected."); + CHECK_MESSAGE( + vector.get_axis(vector.max_axis_index()) == (real_t)5.6, + "Vector4 get_axis should work as expected."); + CHECK_MESSAGE( + vector[vector.min_axis_index()] == (real_t)-0.9, + "Vector4 array operator should work as expected."); + + vector.set_axis(Vector4::Axis::AXIS_Y, 4.7); + CHECK_MESSAGE( + vector.get_axis(Vector4::Axis::AXIS_Y) == (real_t)4.7, + "Vector4 set_axis should work as expected."); + vector[Vector4::Axis::AXIS_Y] = 3.7; + CHECK_MESSAGE( + vector[Vector4::Axis::AXIS_Y] == (real_t)3.7, + "Vector4 array operator setter should work as expected."); +} + +TEST_CASE("[Vector4] Interpolation methods") { + const Vector4 vector1 = Vector4(1, 2, 3, 4); + const Vector4 vector2 = Vector4(4, 5, 6, 7); + CHECK_MESSAGE( + vector1.lerp(vector2, 0.5) == Vector4(2.5, 3.5, 4.5, 5.5), + "Vector4 lerp should work as expected."); + CHECK_MESSAGE( + vector1.lerp(vector2, 1.0 / 3.0).is_equal_approx(Vector4(2, 3, 4, 5)), + "Vector4 lerp should work as expected."); + CHECK_MESSAGE( + vector1.cubic_interpolate(vector2, Vector4(), Vector4(7, 7, 7, 7), 0.5) == Vector4(2.375, 3.5, 4.625, 5.75), + "Vector4 cubic_interpolate should work as expected."); + CHECK_MESSAGE( + vector1.cubic_interpolate(vector2, Vector4(), Vector4(7, 7, 7, 7), 1.0 / 3.0).is_equal_approx(Vector4(1.851851940155029297, 2.962963104248046875, 4.074074268341064453, 5.185185185185)), + "Vector4 cubic_interpolate should work as expected."); +} + +TEST_CASE("[Vector4] Length methods") { + const Vector4 vector1 = Vector4(10, 10, 10, 10); + const Vector4 vector2 = Vector4(20, 30, 40, 50); + CHECK_MESSAGE( + vector1.length_squared() == 400, + "Vector4 length_squared should work as expected and return exact result."); + CHECK_MESSAGE( + Math::is_equal_approx(vector1.length(), 20), + "Vector4 length should work as expected."); + CHECK_MESSAGE( + vector2.length_squared() == 5400, + "Vector4 length_squared should work as expected and return exact result."); + CHECK_MESSAGE( + Math::is_equal_approx(vector2.length(), (real_t)73.484692283495), + "Vector4 length should work as expected."); + CHECK_MESSAGE( + Math::is_equal_approx(vector1.distance_to(vector2), (real_t)54.772255750517), + "Vector4 distance_to should work as expected."); + CHECK_MESSAGE( + Math::is_equal_approx(vector1.distance_squared_to(vector2), 3000), + "Vector4 distance_squared_to should work as expected."); +} + +TEST_CASE("[Vector4] Limiting methods") { + const Vector4 vector = Vector4(10, 10, 10, 10); + CHECK_MESSAGE( + Vector4(-5, 5, 15, -15).clamp(Vector4(), vector) == Vector4(0, 5, 10, 0), + "Vector4 clamp should work as expected."); + CHECK_MESSAGE( + vector.clamp(Vector4(0, 10, 15, 18), Vector4(5, 10, 20, 25)) == Vector4(5, 10, 15, 18), + "Vector4 clamp should work as expected."); +} + +TEST_CASE("[Vector4] Normalization methods") { + CHECK_MESSAGE( + Vector4(1, 0, 0, 0).is_normalized() == true, + "Vector4 is_normalized should return true for a normalized vector."); + CHECK_MESSAGE( + Vector4(1, 1, 1, 1).is_normalized() == false, + "Vector4 is_normalized should return false for a non-normalized vector."); + CHECK_MESSAGE( + Vector4(1, 0, 0, 0).normalized() == Vector4(1, 0, 0, 0), + "Vector4 normalized should return the same vector for a normalized vector."); + CHECK_MESSAGE( + Vector4(1, 1, 0, 0).normalized().is_equal_approx(Vector4(Math_SQRT12, Math_SQRT12, 0, 0)), + "Vector4 normalized should work as expected."); + CHECK_MESSAGE( + Vector4(1, 1, 1, 1).normalized().is_equal_approx(Vector4(0.5, 0.5, 0.5, 0.5)), + "Vector4 normalized should work as expected."); +} + +TEST_CASE("[Vector4] Operators") { + const Vector4 decimal1 = Vector4(2.3, 4.9, 7.8, 3.2); + const Vector4 decimal2 = Vector4(1.2, 3.4, 5.6, 1.7); + const Vector4 power1 = Vector4(0.75, 1.5, 0.625, 0.125); + const Vector4 power2 = Vector4(0.5, 0.125, 0.25, 0.75); + const Vector4 int1 = Vector4(4, 5, 9, 2); + const Vector4 int2 = Vector4(1, 2, 3, 1); + + CHECK_MESSAGE( + -decimal1 == Vector4(-2.3, -4.9, -7.8, -3.2), + "Vector4 change of sign should work as expected."); + CHECK_MESSAGE( + (decimal1 + decimal2).is_equal_approx(Vector4(3.5, 8.3, 13.4, 4.9)), + "Vector4 addition should behave as expected."); + CHECK_MESSAGE( + (power1 + power2) == Vector4(1.25, 1.625, 0.875, 0.875), + "Vector4 addition with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 + int2) == Vector4(5, 7, 12, 3), + "Vector4 addition with integers should give exact results."); + + CHECK_MESSAGE( + (decimal1 - decimal2).is_equal_approx(Vector4(1.1, 1.5, 2.2, 1.5)), + "Vector4 subtraction should behave as expected."); + CHECK_MESSAGE( + (power1 - power2) == Vector4(0.25, 1.375, 0.375, -0.625), + "Vector4 subtraction with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 - int2) == Vector4(3, 3, 6, 1), + "Vector4 subtraction with integers should give exact results."); + + CHECK_MESSAGE( + (decimal1 * decimal2).is_equal_approx(Vector4(2.76, 16.66, 43.68, 5.44)), + "Vector4 multiplication should behave as expected."); + CHECK_MESSAGE( + (power1 * power2) == Vector4(0.375, 0.1875, 0.15625, 0.09375), + "Vector4 multiplication with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 * int2) == Vector4(4, 10, 27, 2), + "Vector4 multiplication with integers should give exact results."); + + CHECK_MESSAGE( + (decimal1 / decimal2).is_equal_approx(Vector4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.88235294118)), + "Vector4 division should behave as expected."); + CHECK_MESSAGE( + (power1 / power2) == Vector4(1.5, 12.0, 2.5, 1.0 / 6.0), + "Vector4 division with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 / int2) == Vector4(4, 2.5, 3, 2), + "Vector4 division with integers should give exact results."); + + CHECK_MESSAGE( + (decimal1 * 2).is_equal_approx(Vector4(4.6, 9.8, 15.6, 6.4)), + "Vector4 multiplication should behave as expected."); + CHECK_MESSAGE( + (power1 * 2) == Vector4(1.5, 3, 1.25, 0.25), + "Vector4 multiplication with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 * 2) == Vector4(8, 10, 18, 4), + "Vector4 multiplication with integers should give exact results."); + + CHECK_MESSAGE( + (decimal1 / 2).is_equal_approx(Vector4(1.15, 2.45, 3.9, 1.6)), + "Vector4 division should behave as expected."); + CHECK_MESSAGE( + (power1 / 2) == Vector4(0.375, 0.75, 0.3125, 0.0625), + "Vector4 division with powers of two should give exact results."); + CHECK_MESSAGE( + (int1 / 2) == Vector4(2, 2.5, 4.5, 1), + "Vector4 division with integers should give exact results."); + + CHECK_MESSAGE( + ((String)decimal1) == "(2.3, 4.9, 7.8, 3.2)", + "Vector4 cast to String should work as expected."); + CHECK_MESSAGE( + ((String)decimal2) == "(1.2, 3.4, 5.6, 1.7)", + "Vector4 cast to String should work as expected."); + CHECK_MESSAGE( + ((String)Vector4(9.7, 9.8, 9.9, -1.8)) == "(9.7, 9.8, 9.9, -1.8)", + "Vector4 cast to String should work as expected."); +#ifdef REAL_T_IS_DOUBLE + CHECK_MESSAGE( + ((String)Vector4(Math_E, Math_SQRT2, Math_SQRT3, Math_SQRT3)) == "(2.71828182845905, 1.4142135623731, 1.73205080756888, 1.73205080756888)", + "Vector4 cast to String should print the correct amount of digits for real_t = double."); +#else + CHECK_MESSAGE( + ((String)Vector4(Math_E, Math_SQRT2, Math_SQRT3, Math_SQRT3)) == "(2.718282, 1.414214, 1.732051, 1.732051)", + "Vector4 cast to String should print the correct amount of digits for real_t = float."); +#endif // REAL_T_IS_DOUBLE +} + +TEST_CASE("[Vector4] Other methods") { + const Vector4 vector = Vector4(1.2, 3.4, 5.6, 1.6); + CHECK_MESSAGE( + vector.direction_to(Vector4()).is_equal_approx(-vector.normalized()), + "Vector4 direction_to should work as expected."); + CHECK_MESSAGE( + Vector4(1, 1, 1, 1).direction_to(Vector4(2, 2, 2, 2)).is_equal_approx(Vector4(0.5, 0.5, 0.5, 0.5)), + "Vector4 direction_to should work as expected."); + CHECK_MESSAGE( + vector.inverse().is_equal_approx(Vector4(1 / 1.2, 1 / 3.4, 1 / 5.6, 1 / 1.6)), + "Vector4 inverse should work as expected."); + CHECK_MESSAGE( + vector.posmod(2).is_equal_approx(Vector4(1.2, 1.4, 1.6, 1.6)), + "Vector4 posmod should work as expected."); + CHECK_MESSAGE( + (-vector).posmod(2).is_equal_approx(Vector4(0.8, 0.6, 0.4, 0.4)), + "Vector4 posmod should work as expected."); + CHECK_MESSAGE( + vector.posmodv(Vector4(1, 2, 3, 4)).is_equal_approx(Vector4(0.2, 1.4, 2.6, 1.6)), + "Vector4 posmodv should work as expected."); + CHECK_MESSAGE( + (-vector).posmodv(Vector4(2, 3, 4, 5)).is_equal_approx(Vector4(0.8, 2.6, 2.4, 3.4)), + "Vector4 posmodv should work as expected."); + CHECK_MESSAGE( + vector.snapped(Vector4(1, 1, 1, 1)) == Vector4(1, 3, 6, 2), + "Vector4 snapped to integers should be the same as rounding."); + CHECK_MESSAGE( + vector.snapped(Vector4(0.25, 0.25, 0.25, 0.25)) == Vector4(1.25, 3.5, 5.5, 1.5), + "Vector4 snapped to 0.25 should give exact results."); +} + +TEST_CASE("[Vector4] Rounding methods") { + const Vector4 vector1 = Vector4(1.2, 3.4, 5.6, 1.6); + const Vector4 vector2 = Vector4(1.2, -3.4, -5.6, -1.6); + CHECK_MESSAGE( + vector1.abs() == vector1, + "Vector4 abs should work as expected."); + CHECK_MESSAGE( + vector2.abs() == vector1, + "Vector4 abs should work as expected."); + CHECK_MESSAGE( + vector1.ceil() == Vector4(2, 4, 6, 2), + "Vector4 ceil should work as expected."); + CHECK_MESSAGE( + vector2.ceil() == Vector4(2, -3, -5, -1), + "Vector4 ceil should work as expected."); + + CHECK_MESSAGE( + vector1.floor() == Vector4(1, 3, 5, 1), + "Vector4 floor should work as expected."); + CHECK_MESSAGE( + vector2.floor() == Vector4(1, -4, -6, -2), + "Vector4 floor should work as expected."); + + CHECK_MESSAGE( + vector1.round() == Vector4(1, 3, 6, 2), + "Vector4 round should work as expected."); + CHECK_MESSAGE( + vector2.round() == Vector4(1, -3, -6, -2), + "Vector4 round should work as expected."); + + CHECK_MESSAGE( + vector1.sign() == Vector4(1, 1, 1, 1), + "Vector4 sign should work as expected."); + CHECK_MESSAGE( + vector2.sign() == Vector4(1, -1, -1, -1), + "Vector4 sign should work as expected."); +} + +TEST_CASE("[Vector4] Linear algebra methods") { + const Vector4 vector_x = Vector4(1, 0, 0, 0); + const Vector4 vector_y = Vector4(0, 1, 0, 0); + const Vector4 vector1 = Vector4(1.7, 2.3, 1, 9.1); + const Vector4 vector2 = Vector4(-8.2, -16, 3, 2.4); + + CHECK_MESSAGE( + vector_x.dot(vector_y) == 0.0, + "Vector4 dot product of perpendicular vectors should be zero."); + CHECK_MESSAGE( + vector_x.dot(vector_x) == 1.0, + "Vector4 dot product of identical unit vectors should be one."); + CHECK_MESSAGE( + (vector_x * 10).dot(vector_x * 10) == 100.0, + "Vector4 dot product of same direction vectors should behave as expected."); + CHECK_MESSAGE( + Math::is_equal_approx((vector1 * 2).dot(vector2 * 4), (real_t)-25.9 * 8), + "Vector4 dot product should work as expected."); +} +} // namespace TestVector4 + +#endif // TEST_VECTOR4_H diff --git a/tests/core/math/test_vector4i.h b/tests/core/math/test_vector4i.h new file mode 100644 index 0000000000..ac63001b24 --- /dev/null +++ b/tests/core/math/test_vector4i.h @@ -0,0 +1,148 @@ +/*************************************************************************/ +/* test_vector4i.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_VECTOR4I_H +#define TEST_VECTOR4I_H + +#include "core/math/vector4i.h" +#include "tests/test_macros.h" + +namespace TestVector4i { + +TEST_CASE("[Vector4i] Axis methods") { + Vector4i vector = Vector4i(1, 2, 3, 4); + CHECK_MESSAGE( + vector.max_axis_index() == Vector4i::Axis::AXIS_W, + "Vector4i max_axis_index should work as expected."); + CHECK_MESSAGE( + vector.min_axis_index() == Vector4i::Axis::AXIS_X, + "Vector4i min_axis_index should work as expected."); + CHECK_MESSAGE( + vector.get_axis(vector.max_axis_index()) == 4, + "Vector4i get_axis should work as expected."); + CHECK_MESSAGE( + vector[vector.min_axis_index()] == 1, + "Vector4i array operator should work as expected."); + + vector.set_axis(Vector4i::Axis::AXIS_Y, 5); + CHECK_MESSAGE( + vector.get_axis(Vector4i::Axis::AXIS_Y) == 5, + "Vector4i set_axis should work as expected."); + vector[Vector4i::Axis::AXIS_Y] = 5; + CHECK_MESSAGE( + vector[Vector4i::Axis::AXIS_Y] == 5, + "Vector4i array operator setter should work as expected."); +} + +TEST_CASE("[Vector4i] Clamp method") { + const Vector4i vector = Vector4i(10, 10, 10, 10); + CHECK_MESSAGE( + Vector4i(-5, 5, 15, INT_MAX).clamp(Vector4i(), vector) == Vector4i(0, 5, 10, 10), + "Vector4i clamp should work as expected."); + CHECK_MESSAGE( + vector.clamp(Vector4i(0, 10, 15, -10), Vector4i(5, 10, 20, -5)) == Vector4i(5, 10, 15, -5), + "Vector4i clamp should work as expected."); +} + +TEST_CASE("[Vector4i] Length methods") { + const Vector4i vector1 = Vector4i(10, 10, 10, 10); + const Vector4i vector2 = Vector4i(20, 30, 40, 50); + CHECK_MESSAGE( + vector1.length_squared() == 400, + "Vector4i length_squared should work as expected and return exact result."); + CHECK_MESSAGE( + Math::is_equal_approx(vector1.length(), 20), + "Vector4i length should work as expected."); + CHECK_MESSAGE( + vector2.length_squared() == 5400, + "Vector4i length_squared should work as expected and return exact result."); + CHECK_MESSAGE( + Math::is_equal_approx(vector2.length(), 73.4846922835), + "Vector4i length should work as expected."); +} + +TEST_CASE("[Vector4i] Operators") { + const Vector4i vector1 = Vector4i(4, 5, 9, 2); + const Vector4i vector2 = Vector4i(1, 2, 3, 4); + + CHECK_MESSAGE( + -vector1 == Vector4i(-4, -5, -9, -2), + "Vector4i change of sign should work as expected."); + CHECK_MESSAGE( + (vector1 + vector2) == Vector4i(5, 7, 12, 6), + "Vector4i addition with integers should give exact results."); + CHECK_MESSAGE( + (vector1 - vector2) == Vector4i(3, 3, 6, -2), + "Vector4i subtraction with integers should give exact results."); + CHECK_MESSAGE( + (vector1 * vector2) == Vector4i(4, 10, 27, 8), + "Vector4i multiplication with integers should give exact results."); + CHECK_MESSAGE( + (vector1 / vector2) == Vector4i(4, 2, 3, 0), + "Vector4i division with integers should give exact results."); + + CHECK_MESSAGE( + (vector1 * 2) == Vector4i(8, 10, 18, 4), + "Vector4i multiplication with integers should give exact results."); + CHECK_MESSAGE( + (vector1 / 2) == Vector4i(2, 2, 4, 1), + "Vector4i division with integers should give exact results."); + + CHECK_MESSAGE( + ((Vector4)vector1) == Vector4(4, 5, 9, 2), + "Vector4i cast to Vector4 should work as expected."); + CHECK_MESSAGE( + ((Vector4)vector2) == Vector4(1, 2, 3, 4), + "Vector4i cast to Vector4 should work as expected."); + CHECK_MESSAGE( + Vector4i(Vector4(1.1, 2.9, 3.9, 100.5)) == Vector4i(1, 2, 3, 100), + "Vector4i constructed from Vector4 should work as expected."); +} + +TEST_CASE("[Vector4i] Abs and sign methods") { + const Vector4i vector1 = Vector4i(1, 3, 5, 7); + const Vector4i vector2 = Vector4i(1, -3, -5, 7); + CHECK_MESSAGE( + vector1.abs() == vector1, + "Vector4i abs should work as expected."); + CHECK_MESSAGE( + vector2.abs() == vector1, + "Vector4i abs should work as expected."); + + CHECK_MESSAGE( + vector1.sign() == Vector4i(1, 1, 1, 1), + "Vector4i sign should work as expected."); + CHECK_MESSAGE( + vector2.sign() == Vector4i(1, -1, -1, 1), + "Vector4i sign should work as expected."); +} +} // namespace TestVector4i + +#endif // TEST_VECTOR4I_H diff --git a/tests/core/object/test_class_db.h b/tests/core/object/test_class_db.h index c7535426df..208923edb9 100644 --- a/tests/core/object/test_class_db.h +++ b/tests/core/object/test_class_db.h @@ -71,6 +71,7 @@ struct ArgumentData { String name; bool has_defval = false; Variant defval; + int position; }; struct MethodData { @@ -371,6 +372,39 @@ void validate_property(const Context &p_context, const ExposedClass &p_class, co } } +void validate_argument(const Context &p_context, const ExposedClass &p_class, const String &p_owner_name, const String &p_owner_type, const ArgumentData &p_arg) { + TEST_COND((p_arg.name.is_empty() || p_arg.name.begins_with("_unnamed_arg")), + vformat("Unnamed argument in position %d of %s '%s.%s'.", p_arg.position, p_owner_type, p_class.name, p_owner_name)); + + const ExposedClass *arg_class = p_context.find_exposed_class(p_arg.type); + if (arg_class) { + TEST_COND(arg_class->is_singleton, + vformat("Argument type is a singleton: '%s' of %s '%s.%s'.", p_arg.name, p_owner_type, p_class.name, p_owner_name)); + + if (p_class.api_type == ClassDB::API_CORE) { + TEST_COND(arg_class->api_type == ClassDB::API_EDITOR, + vformat("Argument '%s' of %s '%s.%s' has type '%s' from the editor API. Core API cannot have dependencies on the editor API.", + p_arg.name, p_owner_type, p_class.name, p_owner_name, arg_class->name)); + } + } else { + // Look for types that don't inherit Object. + TEST_FAIL_COND(!p_context.has_type(p_arg.type), + vformat("Argument type '%s' not found: '%s' of %s '%s.%s'.", p_arg.type.name, p_arg.name, p_owner_type, p_class.name, p_owner_name)); + } + + if (p_arg.has_defval) { + String type_error_msg; + bool arg_defval_assignable_to_type = arg_default_value_is_assignable_to_type(p_context, p_arg.defval, p_arg.type, &type_error_msg); + + String err_msg = vformat("Invalid default value for parameter '%s' of %s '%s.%s'.", p_arg.name, p_owner_type, p_class.name, p_owner_name); + if (!type_error_msg.is_empty()) { + err_msg += " " + type_error_msg; + } + + TEST_COND(!arg_defval_assignable_to_type, err_msg.utf8().get_data()); + } +} + void validate_method(const Context &p_context, const ExposedClass &p_class, const MethodData &p_method) { if (p_method.return_type.name != StringName()) { const ExposedClass *return_class = p_context.find_exposed_class(p_method.return_type); @@ -392,54 +426,14 @@ void validate_method(const Context &p_context, const ExposedClass &p_class, cons for (const ArgumentData &F : p_method.arguments) { const ArgumentData &arg = F; - - const ExposedClass *arg_class = p_context.find_exposed_class(arg.type); - if (arg_class) { - TEST_COND(arg_class->is_singleton, - "Argument type is a singleton: '", arg.name, "' of method '", p_class.name, ".", p_method.name, "'."); - - if (p_class.api_type == ClassDB::API_CORE) { - TEST_COND(arg_class->api_type == ClassDB::API_EDITOR, - "Argument '", arg.name, "' of method '", p_class.name, ".", p_method.name, "' has type '", - arg_class->name, "' from the editor API. Core API cannot have dependencies on the editor API."); - } - } else { - // Look for types that don't inherit Object - TEST_FAIL_COND(!p_context.has_type(arg.type), - "Argument type '", arg.type.name, "' not found: '", arg.name, "' of method", p_class.name, ".", p_method.name, "'."); - } - - if (arg.has_defval) { - String type_error_msg; - bool arg_defval_assignable_to_type = arg_default_value_is_assignable_to_type(p_context, arg.defval, arg.type, &type_error_msg); - String err_msg = vformat("Invalid default value for parameter '%s' of method '%s.%s'.", arg.name, p_class.name, p_method.name); - if (!type_error_msg.is_empty()) { - err_msg += " " + type_error_msg; - } - TEST_COND(!arg_defval_assignable_to_type, err_msg.utf8().get_data()); - } + validate_argument(p_context, p_class, p_method.name, "method", arg); } } void validate_signal(const Context &p_context, const ExposedClass &p_class, const SignalData &p_signal) { for (const ArgumentData &F : p_signal.arguments) { const ArgumentData &arg = F; - - const ExposedClass *arg_class = p_context.find_exposed_class(arg.type); - if (arg_class) { - TEST_COND(arg_class->is_singleton, - "Argument class is a singleton: '", arg.name, "' of signal '", p_class.name, ".", p_signal.name, "'."); - - if (p_class.api_type == ClassDB::API_CORE) { - TEST_COND(arg_class->api_type == ClassDB::API_EDITOR, - "Argument '", arg.name, "' of signal '", p_class.name, ".", p_signal.name, "' has type '", - arg_class->name, "' from the editor API. Core API cannot have dependencies on the editor API."); - } - } else { - // Look for types that don't inherit Object - TEST_FAIL_COND(!p_context.has_type(arg.type), - "Argument type '", arg.type.name, "' not found: '", arg.name, "' of signal", p_class.name, ".", p_signal.name, "'."); - } + validate_argument(p_context, p_class, p_signal.name, "signal", arg); } } @@ -493,13 +487,13 @@ void add_exposed_classes(Context &r_context) { } if (!ClassDB::is_class_exposed(class_name)) { - MESSAGE(vformat("Ignoring class '%s' because it's not exposed.", class_name).utf8().get_data()); + MESSAGE(vformat("Ignoring class '%s' because it's not exposed.", class_name)); class_list.pop_front(); continue; } if (!ClassDB::is_class_enabled(class_name)) { - MESSAGE(vformat("Ignoring class '%s' because it's not enabled.", class_name).utf8().get_data()); + MESSAGE(vformat("Ignoring class '%s' because it's not enabled.", class_name)); class_list.pop_front(); continue; } @@ -625,6 +619,7 @@ void add_exposed_classes(Context &r_context) { ArgumentData arg; arg.name = orig_arg_name; + arg.position = i; if (arg_info.type == Variant::INT && arg_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) { arg.type.name = arg_info.class_name; @@ -693,6 +688,7 @@ void add_exposed_classes(Context &r_context) { ArgumentData arg; arg.name = orig_arg_name; + arg.position = i; if (arg_info.type == Variant::INT && arg_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) { arg.type.name = arg_info.class_name; @@ -841,7 +837,7 @@ TEST_SUITE("[ClassDB]") { add_builtin_types(context); add_global_enums(context); - SUBCASE("[ClassDB] Find exposed class") { + SUBCASE("[ClassDB] Validate exposed classes") { const ExposedClass *object_class = context.find_exposed_class(context.names_cache.object_class); TEST_FAIL_COND(!object_class, "Object class not found."); TEST_FAIL_COND(object_class->base != StringName(), diff --git a/tests/core/object/test_method_bind.h b/tests/core/object/test_method_bind.h index 350a08b6e2..2fe0c264a1 100644 --- a/tests/core/object/test_method_bind.h +++ b/tests/core/object/test_method_bind.h @@ -155,7 +155,6 @@ public: TEST_CASE("[MethodBind] check all method binds") { MethodBindTester *mbt = memnew(MethodBindTester); - print_line("testing method bind"); mbt->run_tests(); CHECK(mbt->test_valid[MethodBindTester::TEST_METHOD]); diff --git a/tests/core/object/test_object.h b/tests/core/object/test_object.h index 88a3e4ccad..f5c5de7fdf 100644 --- a/tests/core/object/test_object.h +++ b/tests/core/object/test_object.h @@ -82,6 +82,12 @@ public: Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override { return Variant::PACKED_FLOAT32_ARRAY; } + bool property_can_revert(const StringName &p_name) const override { + return false; + }; + bool property_get_revert(const StringName &p_name, Variant &r_ret) const override { + return false; + }; void get_method_list(List<MethodInfo> *p_list) const override { } bool has_method(const StringName &p_method) const override { diff --git a/tests/core/string/test_string.h b/tests/core/string/test_string.h index b8b766023a..d97da05c04 100644 --- a/tests/core/string/test_string.h +++ b/tests/core/string/test_string.h @@ -466,11 +466,6 @@ TEST_CASE("[String] String to float") { } } -TEST_CASE("[String] CamelCase to underscore") { - CHECK(String("TestTestStringGD").camelcase_to_underscore(false) == String("Test_Test_String_GD")); - CHECK(String("TestTestStringGD").camelcase_to_underscore(true) == String("test_test_string_gd")); -} - TEST_CASE("[String] Slicing") { String s = "Mars,Jupiter,Saturn,Uranus"; @@ -619,7 +614,7 @@ TEST_CASE("[String] sprintf") { output = format.sprintf(args, &error); REQUIRE(error == false); CHECK(output == String("fish % frog")); - //////// INTS + ///// Ints // Int format = "fish %d frog"; @@ -697,7 +692,9 @@ TEST_CASE("[String] sprintf") { format = "fish %-05d frog"; args.clear(); args.push_back(-5); + ERR_PRINT_OFF; // Silence warning about 0 ignored. output = format.sprintf(args, &error); + ERR_PRINT_ON; REQUIRE(error == false); CHECK(output == String("fish -5 frog")); @@ -725,7 +722,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish 143 frog")); - ////// REALS + ///// Reals // Real format = "fish %f frog"; @@ -735,7 +732,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish 99.990000 frog")); - // Real left-padded + // Real left-padded. format = "fish %11f frog"; args.clear(); args.push_back(99.99); @@ -743,7 +740,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish 99.990000 frog")); - // Real right-padded + // Real right-padded. format = "fish %-11f frog"; args.clear(); args.push_back(99.99); @@ -767,7 +764,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish +99.990000 frog")); - // Real with 1 decimals. + // Real with 1 decimal. format = "fish %.1f frog"; args.clear(); args.push_back(99.99); @@ -795,11 +792,103 @@ TEST_CASE("[String] sprintf") { format = "fish %-011f frog"; args.clear(); args.push_back(-99.99); + ERR_PRINT_OFF; // Silence warning about 0 ignored. output = format.sprintf(args, &error); + ERR_PRINT_ON; REQUIRE(error == false); CHECK(output == String("fish -99.990000 frog")); - /////// Strings. + ///// Vectors + + // Vector2 + format = "fish %v frog"; + args.clear(); + args.push_back(Variant(Vector2(19.99, 1.00))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.990000, 1.000000) frog")); + + // Vector3 + format = "fish %v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.990000, 1.000000, -2.050000) frog")); + + // Vector4 + format = "fish %v frog"; + args.clear(); + args.push_back(Variant(Vector4(19.99, 1.00, -2.05, 5.5))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.990000, 1.000000, -2.050000, 5.500000) frog")); + + // Vector with negative values. + format = "fish %v frog"; + args.clear(); + args.push_back(Variant(Vector2(-19.99, -1.00))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (-19.990000, -1.000000) frog")); + + // Vector left-padded. + format = "fish %11v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish ( 19.990000, 1.000000, -2.050000) frog")); + + // Vector right-padded. + format = "fish %-11v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.990000 , 1.000000 , -2.050000 ) frog")); + + // Vector left-padded with zeros. + format = "fish %011v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (0019.990000, 0001.000000, -002.050000) frog")); + + // Vector given Vector3i. + format = "fish %v frog"; + args.clear(); + args.push_back(Variant(Vector3i(19, 1, -2))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.000000, 1.000000, -2.000000) frog")); + + // Vector with 1 decimal. + format = "fish %.1v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (20.0, 1.0, -2.0) frog")); + + // Vector with 12 decimals. + format = "fish %.12v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.00, 1.00, -2.00))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (19.000000000000, 1.000000000000, -2.000000000000) frog")); + + // Vector with no decimals. + format = "fish %.v frog"; + args.clear(); + args.push_back(Variant(Vector3(19.99, 1.00, -2.05))); + output = format.sprintf(args, &error); + REQUIRE(error == false); + CHECK(output == String("fish (20, 1, -2) frog")); + + ///// Strings // String format = "fish %s frog"; @@ -809,7 +898,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish cheese frog")); - // String left-padded + // String left-padded. format = "fish %10s frog"; args.clear(); args.push_back("cheese"); @@ -817,7 +906,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); CHECK(output == String("fish cheese frog")); - // String right-padded + // String right-padded. format = "fish %-10s frog"; args.clear(); args.push_back("cheese"); @@ -845,7 +934,7 @@ TEST_CASE("[String] sprintf") { ///// Dynamic width - // String dynamic width + // String dynamic width. format = "fish %*s frog"; args.clear(); args.push_back(10); @@ -854,7 +943,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); REQUIRE(output == String("fish cheese frog")); - // Int dynamic width + // Int dynamic width. format = "fish %*d frog"; args.clear(); args.push_back(10); @@ -863,7 +952,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error == false); REQUIRE(output == String("fish 99 frog")); - // Float dynamic width + // Float dynamic width. format = "fish %*.*f frog"; args.clear(); args.push_back(10); @@ -900,7 +989,7 @@ TEST_CASE("[String] sprintf") { REQUIRE(error); CHECK(output == "incomplete format"); - // Bad character in format string + // Bad character in format string. format = "fish %&f frog"; args.clear(); args.push_back("cheese"); @@ -916,14 +1005,14 @@ TEST_CASE("[String] sprintf") { REQUIRE(error); CHECK(output == "too many decimal points in format"); - // * not a number + // * not a number or vector. format = "fish %*f frog"; args.clear(); args.push_back("cheese"); args.push_back(99.99); output = format.sprintf(args, &error); REQUIRE(error); - CHECK(output == "* wants number"); + CHECK(output == "* wants number or vector"); // Character too long. format = "fish %c frog"; @@ -1002,8 +1091,36 @@ TEST_CASE("[String] IPVX address to string") { } TEST_CASE("[String] Capitalize against many strings") { - String input = "bytes2var"; - String output = "Bytes 2 Var"; + String input = "2D"; + String output = "2d"; + CHECK(input.capitalize() == output); + + input = "2d"; + output = "2d"; + CHECK(input.capitalize() == output); + + input = "2db"; + output = "2 Db"; + CHECK(input.capitalize() == output); + + input = "HTML5 Html5 html5 html_5"; + output = "Html 5 Html 5 Html 5 Html 5"; + CHECK(input.capitalize() == output); + + input = "Node2D Node2d NODE2D NODE_2D node_2d"; + output = "Node 2d Node 2d Node 2d Node 2d Node 2d"; + CHECK(input.capitalize() == output); + + input = "Node2DPosition"; + output = "Node 2d Position"; + CHECK(input.capitalize() == output); + + input = "Number2Digits"; + output = "Number 2 Digits"; + CHECK(input.capitalize() == output); + + input = "bytes2var"; + output = "Bytes 2 Var"; CHECK(input.capitalize() == output); input = "linear2db"; @@ -1018,10 +1135,6 @@ TEST_CASE("[String] Capitalize against many strings") { output = "Sha 256"; CHECK(input.capitalize() == output); - input = "2db"; - output = "2 Db"; - CHECK(input.capitalize() == output); - input = "PascalCase"; output = "Pascal Case"; CHECK(input.capitalize() == output); @@ -1059,6 +1172,50 @@ TEST_CASE("[String] Capitalize against many strings") { CHECK(input.capitalize() == output); } +struct StringCasesTestCase { + const char *input; + const char *camel_case; + const char *pascal_case; + const char *snake_case; +}; + +TEST_CASE("[String] Checking case conversion methods") { + StringCasesTestCase test_cases[] = { + /* clang-format off */ + { "2D", "2d", "2d", "2d" }, + { "2d", "2d", "2d", "2d" }, + { "2db", "2Db", "2Db", "2_db" }, + { "Vector3", "vector3", "Vector3", "vector_3" }, + { "sha256", "sha256", "Sha256", "sha_256" }, + { "Node2D", "node2d", "Node2d", "node_2d" }, + { "RichTextLabel", "richTextLabel", "RichTextLabel", "rich_text_label" }, + { "HTML5", "html5", "Html5", "html_5" }, + { "Node2DPosition", "node2dPosition", "Node2dPosition", "node_2d_position" }, + { "Number2Digits", "number2Digits", "Number2Digits", "number_2_digits" }, + { "get_property_list", "getPropertyList", "GetPropertyList", "get_property_list" }, + { "get_camera_2d", "getCamera2d", "GetCamera2d", "get_camera_2d" }, + { "_physics_process", "physicsProcess", "PhysicsProcess", "_physics_process" }, + { "bytes2var", "bytes2Var", "Bytes2Var", "bytes_2_var" }, + { "linear2db", "linear2Db", "Linear2Db", "linear_2_db" }, + { "sha256sum", "sha256Sum", "Sha256Sum", "sha_256_sum" }, + { "camelCase", "camelCase", "CamelCase", "camel_case" }, + { "PascalCase", "pascalCase", "PascalCase", "pascal_case" }, + { "snake_case", "snakeCase", "SnakeCase", "snake_case" }, + { "Test TEST test", "testTestTest", "TestTestTest", "test_test_test" }, + { nullptr, nullptr, nullptr, nullptr }, + /* clang-format on */ + }; + + int idx = 0; + while (test_cases[idx].input != nullptr) { + String input = test_cases[idx].input; + CHECK(input.to_camel_case() == test_cases[idx].camel_case); + CHECK(input.to_pascal_case() == test_cases[idx].pascal_case); + CHECK(input.to_snake_case() == test_cases[idx].snake_case); + idx++; + } +} + TEST_CASE("[String] Checking string is empty when it should be") { bool state = true; bool success; @@ -1265,7 +1422,7 @@ TEST_CASE("[String] Path functions") { CHECK(String(path[i]).get_file() == file[i]); CHECK(String(path[i]).is_absolute_path() == abs[i]); CHECK(String(path[i]).is_relative_path() != abs[i]); - CHECK(String(path[i]).simplify_path().get_base_dir().plus_file(file[i]) == String(path[i]).simplify_path()); + CHECK(String(path[i]).simplify_path().get_base_dir().path_join(file[i]) == String(path[i]).simplify_path()); } static const char *file_name[3] = { "test.tscn", "test://.xscn", "?tes*t.scn" }; @@ -1569,7 +1726,7 @@ TEST_CASE("[String] Variant ptr indexed set") { TEST_CASE("[Stress][String] Empty via ' == String()'") { for (int i = 0; i < 100000; ++i) { String str = "Hello World!"; - if (str.is_empty()) { + if (str == String()) { continue; } } diff --git a/tests/core/templates/test_hash_set.h b/tests/core/templates/test_hash_set.h index 3b9a800641..dad149604b 100644 --- a/tests/core/templates/test_hash_set.h +++ b/tests/core/templates/test_hash_set.h @@ -38,7 +38,6 @@ namespace TestHashSet { TEST_CASE("[HashSet] Insert element") { - print_line("SMALL BEGIN MEM: ", Memory::get_mem_usage()); HashSet<int> set; HashSet<int>::Iterator e = set.insert(42); @@ -47,7 +46,6 @@ TEST_CASE("[HashSet] Insert element") { CHECK(set.has(42)); CHECK(set.find(42)); set.reset(); - print_line("SMALL END MEM: ", Memory::get_mem_usage()); } TEST_CASE("[HashSet] Insert existing element") { diff --git a/tests/core/templates/test_rid.h b/tests/core/templates/test_rid.h new file mode 100644 index 0000000000..8d4dd0703b --- /dev/null +++ b/tests/core/templates/test_rid.h @@ -0,0 +1,101 @@ +/*************************************************************************/ +/* test_rid.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_RID_H +#define TEST_RID_H + +#include "core/templates/rid.h" + +#include "tests/test_macros.h" + +namespace TestRID { +TEST_CASE("[RID] Default Constructor") { + RID rid; + + CHECK(rid.get_id() == 0); +} + +TEST_CASE("[RID] Factory method") { + RID rid = RID::from_uint64(1); + + CHECK(rid.get_id() == 1); +} + +TEST_CASE("[RID] Operators") { + RID rid = RID::from_uint64(1); + + RID rid_zero = RID::from_uint64(0); + RID rid_one = RID::from_uint64(1); + RID rid_two = RID::from_uint64(2); + + CHECK_FALSE(rid == rid_zero); + CHECK(rid == rid_one); + CHECK_FALSE(rid == rid_two); + + CHECK_FALSE(rid < rid_zero); + CHECK_FALSE(rid < rid_one); + CHECK(rid < rid_two); + + CHECK_FALSE(rid <= rid_zero); + CHECK(rid <= rid_one); + CHECK(rid <= rid_two); + + CHECK(rid > rid_zero); + CHECK_FALSE(rid > rid_one); + CHECK_FALSE(rid > rid_two); + + CHECK(rid >= rid_zero); + CHECK(rid >= rid_one); + CHECK_FALSE(rid >= rid_two); + + CHECK(rid != rid_zero); + CHECK_FALSE(rid != rid_one); + CHECK(rid != rid_two); +} + +TEST_CASE("[RID] 'is_valid' & 'is_null'") { + RID rid_zero = RID::from_uint64(0); + RID rid_one = RID::from_uint64(1); + + CHECK_FALSE(rid_zero.is_valid()); + CHECK(rid_zero.is_null()); + + CHECK(rid_one.is_valid()); + CHECK_FALSE(rid_one.is_null()); +} + +TEST_CASE("[RID] 'get_local_index'") { + CHECK(RID::from_uint64(1).get_local_index() == 1); + CHECK(RID::from_uint64(4'294'967'295).get_local_index() == 4'294'967'295); + CHECK(RID::from_uint64(4'294'967'297).get_local_index() == 1); +} +} // namespace TestRID + +#endif // TEST_RID_H diff --git a/tests/core/templates/test_vector.h b/tests/core/templates/test_vector.h index f27d6a332e..3fc9264f5a 100644 --- a/tests/core/templates/test_vector.h +++ b/tests/core/templates/test_vector.h @@ -291,8 +291,10 @@ TEST_CASE("[Vector] Slice") { CHECK(slice6[1] == 3); CHECK(slice6[2] == 4); + ERR_PRINT_OFF; Vector<int> slice7 = vector.slice(5, 1); - CHECK(slice7.size() == 0); + CHECK(slice7.size() == 0); // Expected to fail. + ERR_PRINT_ON; } TEST_CASE("[Vector] Find, has") { diff --git a/tests/core/variant/test_dictionary.h b/tests/core/variant/test_dictionary.h index 729035919d..c98434d42c 100644 --- a/tests/core/variant/test_dictionary.h +++ b/tests/core/variant/test_dictionary.h @@ -500,6 +500,24 @@ TEST_CASE("[Dictionary] Recursive self comparison") { d2.clear(); } +TEST_CASE("[Dictionary] Order and find") { + Dictionary d; + d[4] = "four"; + d[8] = "eight"; + d[12] = "twelve"; + d["4"] = "four"; + + Array keys; + keys.append(4); + keys.append(8); + keys.append(12); + keys.append("4"); + + CHECK_EQ(d.keys(), keys); + CHECK_EQ(d.find_key("four"), Variant(4)); + CHECK_EQ(d.find_key("does not exist"), Variant()); +} + } // namespace TestDictionary #endif // TEST_DICTIONARY_H diff --git a/tests/core/variant/test_variant.h b/tests/core/variant/test_variant.h index 916686d7c1..d6799928b4 100644 --- a/tests/core/variant/test_variant.h +++ b/tests/core/variant/test_variant.h @@ -719,6 +719,7 @@ TEST_CASE("[Variant] Assignment To Color from Bool,Int,Float,String,Vec2,Vec2i,V vec3i_v = col_v; CHECK(vec3i_v.get_type() == Variant::COLOR); } + TEST_CASE("[Variant] Writer and parser array") { Array a = build_array(1, String("hello"), build_array(Variant())); String a_str; @@ -911,6 +912,67 @@ TEST_CASE("[Variant] Nested dictionary comparison") { CHECK_FALSE(v_d1 == v_d_other_val); } +struct ArgumentData { + Variant::Type type; + String name; + bool has_defval = false; + Variant defval; + int position; +}; + +struct MethodData { + StringName name; + Variant::Type return_type; + List<ArgumentData> arguments; + bool is_virtual = false; + bool is_vararg = false; +}; + +TEST_CASE("[Variant] Utility functions") { + List<MethodData> functions; + + List<StringName> function_names; + Variant::get_utility_function_list(&function_names); + function_names.sort_custom<StringName::AlphCompare>(); + + for (const StringName &E : function_names) { + MethodData md; + md.name = E; + + // Utility function's return type. + if (Variant::has_utility_function_return_value(E)) { + md.return_type = Variant::get_utility_function_return_type(E); + } + + // Utility function's arguments. + if (Variant::is_utility_function_vararg(E)) { + md.is_vararg = true; + } else { + for (int i = 0; i < Variant::get_utility_function_argument_count(E); i++) { + ArgumentData arg; + arg.type = Variant::get_utility_function_argument_type(E, i); + arg.name = Variant::get_utility_function_argument_name(E, i); + arg.position = i; + + md.arguments.push_back(arg); + } + } + + functions.push_back(md); + } + + SUBCASE("[Variant] Validate utility functions") { + for (const MethodData &E : functions) { + for (const ArgumentData &F : E.arguments) { + const ArgumentData &arg = F; + + TEST_COND((arg.name.is_empty() || arg.name.begins_with("_unnamed_arg")), + vformat("Unnamed argument in position %d of function '%s'.", arg.position, E.name)); + } + } + } +} + } // namespace TestVariant #endif // TEST_VARIANT_H diff --git a/tests/create_test.py b/tests/create_test.py new file mode 100644 index 0000000000..5a0439084f --- /dev/null +++ b/tests/create_test.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 + +import argparse +import os +import re +import sys +from subprocess import call + + +def main(): + # Change to the directory where the script is located, + # so that the script can be run from any location. + os.chdir(os.path.dirname(os.path.realpath(__file__))) + + parser = argparse.ArgumentParser(description="Creates a new unit test file.") + parser.add_argument("name", type=str, help="The unit test name in PascalCase notation") + parser.add_argument( + "path", + type=str, + nargs="?", + help="The path to the unit test file relative to the tests folder (default: .)", + default=".", + ) + parser.add_argument( + "-i", + "--invasive", + action="store_true", + help="if set, the script will automatically insert the include directive in test_main.cpp. Use with caution!", + ) + args = parser.parse_args() + + snake_case_regex = re.compile(r"(?<!^)(?=[A-Z])") + name_snake_case = snake_case_regex.sub("_", args.name).lower() + + file_path = os.path.normpath(os.path.join(args.path, f"test_{name_snake_case}.h")) + + print(file_path) + if os.path.isfile(file_path): + print(f'ERROR: The file "{file_path}" already exists.') + sys.exit(1) + with open(file_path, "w") as file: + file.write( + """/*************************************************************************/ +/* test_{name_snake_case}.h {padding} */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_{name_upper_snake_case}_H +#define TEST_{name_upper_snake_case}_H + +#include "tests/test_macros.h" + +namespace Test{name_pascal_case} {{ + +TEST_CASE("[{name_pascal_case}] Example test case") {{ + // TODO: Remove this comment and write your test code here. +}} + +}} // namespace Test{name_pascal_case} + +#endif // TEST_{name_upper_snake_case}_H +""".format( + name_snake_case=name_snake_case, + # Capitalize the first letter but keep capitalization for the rest of the string. + # This is done in case the user passes a camelCase string instead of PascalCase. + name_pascal_case=args.name[0].upper() + args.name[1:], + name_upper_snake_case=name_snake_case.upper(), + # The padding length depends on the test name length. + padding=" " * (60 - len(name_snake_case)), + ) + ) + + # Print an absolute path so it can be Ctrl + clicked in some IDEs and terminal emulators. + print("Test header file created:") + print(os.path.abspath(file_path)) + + if args.invasive: + print("Trying to insert include directive in test_main.cpp...") + with open("test_main.cpp", "r") as file: + contents = file.read() + match = re.search(r'#include "tests.*\n', contents) + + if match: + new_string = contents[: match.start()] + f'#include "tests/{file_path}"\n' + contents[match.start() :] + + with open("test_main.cpp", "w") as file: + file.write(new_string) + print("Done.") + # Use clang format to sort include directives afster insertion. + clang_format_args = ["clang-format", "test_main.cpp", "-i"] + retcode = call(clang_format_args) + if retcode != 0: + print( + "Include directives in test_main.cpp could not be sorted automatically using clang-format. Please sort them manually." + ) + else: + print("Could not find a valid position in test_main.cpp to insert the include directive.") + + else: + print("\nRemember to #include the new test header in this file (following alphabetical order):") + print(os.path.abspath("test_main.cpp")) + print("Insert the following line in the appropriate place:") + print(f'#include "tests/{file_path}"') + + +if __name__ == "__main__": + main() diff --git a/tests/python_build/conftest.py b/tests/python_build/conftest.py new file mode 100644 index 0000000000..617230926a --- /dev/null +++ b/tests/python_build/conftest.py @@ -0,0 +1,26 @@ +import os +import sys +from pathlib import Path + +import pytest + +CWD = Path(__file__).parent +ROOT = CWD.parent.parent +# append directory with build files to sys.path to import them +sys.path.append(str(ROOT)) + + +@pytest.fixture +def shader_files(request): + shader_path = request.param + + res = { + "path_input": str(CWD / "fixtures" / f"{shader_path}.glsl"), + "path_output": str(CWD / "fixtures" / f"{shader_path}.glsl.gen.h"), + "path_expected_full": str(CWD / "fixtures" / f"{shader_path}_expected_full.glsl"), + "path_expected_parts": str(CWD / "fixtures" / f"{shader_path}_expected_parts.json"), + } + yield res + + if not os.getenv("PYTEST_KEEP_GENERATED_FILES"): + os.remove(res["path_output"]) diff --git a/tests/python_build/fixtures/gles3/_included.glsl b/tests/python_build/fixtures/gles3/_included.glsl new file mode 100644 index 0000000000..adf5f702d3 --- /dev/null +++ b/tests/python_build/fixtures/gles3/_included.glsl @@ -0,0 +1 @@ +#define M_PI 3.14159265359 diff --git a/tests/python_build/fixtures/gles3/vertex_fragment.glsl b/tests/python_build/fixtures/gles3/vertex_fragment.glsl new file mode 100644 index 0000000000..3004e22f25 --- /dev/null +++ b/tests/python_build/fixtures/gles3/vertex_fragment.glsl @@ -0,0 +1,34 @@ +#include "_included.glsl" + +#[modes] + +mode_ninepatch = #define USE_NINEPATCH + +#[specializations] + +DISABLE_LIGHTING = false + +#[vertex] + +precision highp float; +precision highp int; + +layout(location = 0) in highp vec3 vertex; + +out highp vec4 position_interp; + +void main() { + position_interp = vec4(vertex.x,1,0,1); +} + +#[fragment] + +precision highp float; +precision highp int; + +in highp vec4 position_interp; + +void main() { + highp float depth = ((position_interp.z / position_interp.w) + 1.0); + frag_color = vec4(depth); +} diff --git a/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl new file mode 100644 index 0000000000..7bf56e73cd --- /dev/null +++ b/tests/python_build/fixtures/gles3/vertex_fragment_expected_full.glsl @@ -0,0 +1,50 @@ +/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */ +#ifndef VERTEX_FRAGMENT_GLSL_GEN_HGLES3_GLES3 +#define VERTEX_FRAGMENT_GLSL_GEN_HGLES3_GLES3 + + +#include "drivers/gles3/shader_gles3.h" + + +class VertexFragmentShaderGLES3 : public ShaderGLES3 { + +public: + + enum ShaderVariant { + MODE_NINEPATCH, + }; + + enum Specializations { + DISABLE_LIGHTING=1, + }; + + _FORCE_INLINE_ void version_bind_shader(RID p_version,ShaderVariant p_variant,uint64_t p_specialization=0) { _version_bind_shader(p_version,p_variant,p_specialization); } + +protected: + + virtual void _init() override { + + static const char **_uniform_strings=nullptr; + static const char* _variant_defines[]={ + "#define USE_NINEPATCH", + }; + + static TexUnitPair *_texunit_pairs=nullptr; + static UBOPair *_ubo_pairs=nullptr; + static Specialization _spec_pairs[]={ + {"DISABLE_LIGHTING",false}, + }; + + static const char _vertex_code[]={ +10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,102,108,111,97,116,59,10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,105,110,116,59,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,105,110,32,104,105,103,104,112,32,118,101,99,51,32,118,101,114,116,101,120,59,10,10,111,117,116,32,104,105,103,104,112,32,118,101,99,52,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,32,61,32,118,101,99,52,40,118,101,114,116,101,120,46,120,44,49,44,48,44,49,41,59,10,125,10,10, 0}; + + static const char _fragment_code[]={ +10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,102,108,111,97,116,59,10,112,114,101,99,105,115,105,111,110,32,104,105,103,104,112,32,105,110,116,59,10,10,105,110,32,104,105,103,104,112,32,118,101,99,52,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,104,105,103,104,112,32,102,108,111,97,116,32,100,101,112,116,104,32,61,32,40,40,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,46,122,32,47,32,112,111,115,105,116,105,111,110,95,105,110,116,101,114,112,46,119,41,32,43,32,49,46,48,41,59,10,9,102,114,97,103,95,99,111,108,111,114,32,61,32,118,101,99,52,40,100,101,112,116,104,41,59,10,125,10, 0}; + + _setup(_vertex_code,_fragment_code,"VertexFragmentShaderGLES3",0,_uniform_strings,0,_ubo_pairs,0,_texunit_pairs,1,_spec_pairs,1,_variant_defines); + } + +}; + +#endif + diff --git a/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json new file mode 100644 index 0000000000..eaeb5981c0 --- /dev/null +++ b/tests/python_build/fixtures/gles3/vertex_fragment_expected_parts.json @@ -0,0 +1,52 @@ +{ + "vertex_lines": [ + "", + "precision highp float;", + "precision highp int;", + "", + "layout(location = 0) in highp vec3 vertex;", + "", + "out highp vec4 position_interp;", + "", + "void main() {", + "\tposition_interp = vec4(vertex.x,1,0,1);", + "}", + "" + ], + "fragment_lines": [ + "", + "precision highp float;", + "precision highp int;", + "", + "in highp vec4 position_interp;", + "", + "void main() {", + "\thighp float depth = ((position_interp.z / position_interp.w) + 1.0);", + "\tfrag_color = vec4(depth);", + "}" + ], + "uniforms": [], + "fbos": [], + "texunits": [], + "texunit_names": [], + "ubos": [], + "ubo_names": [], + "vertex_included_files": [], + "fragment_included_files": [], + "reading": "fragment", + "line_offset": 33, + "vertex_offset": 10, + "fragment_offset": 23, + "variant_defines": [ + "#define USE_NINEPATCH" + ], + "variant_names": [ + "MODE_NINEPATCH" + ], + "specialization_names": [ + "DISABLE_LIGHTING" + ], + "specialization_values": [ + " false\n" + ] +} diff --git a/tests/python_build/fixtures/glsl/_included.glsl b/tests/python_build/fixtures/glsl/_included.glsl new file mode 100644 index 0000000000..adf5f702d3 --- /dev/null +++ b/tests/python_build/fixtures/glsl/_included.glsl @@ -0,0 +1 @@ +#define M_PI 3.14159265359 diff --git a/tests/python_build/fixtures/glsl/compute.glsl b/tests/python_build/fixtures/glsl/compute.glsl new file mode 100644 index 0000000000..e81f48d463 --- /dev/null +++ b/tests/python_build/fixtures/glsl/compute.glsl @@ -0,0 +1,12 @@ +#[compute] + +#version 450 + +#VERSION_DEFINES + + +#include "_included.glsl" + +void main() { + vec3 static_light = vec3(0, 1, 0); +} diff --git a/tests/python_build/fixtures/glsl/compute_expected_full.glsl b/tests/python_build/fixtures/glsl/compute_expected_full.glsl new file mode 100644 index 0000000000..b937d732c8 --- /dev/null +++ b/tests/python_build/fixtures/glsl/compute_expected_full.glsl @@ -0,0 +1,8 @@ +/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */ +#ifndef COMPUTE_SHADER_GLSL_RAW_H +#define COMPUTE_SHADER_GLSL_RAW_H + +static const char compute_shader_glsl[] = { + 35,91,99,111,109,112,117,116,101,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,118,101,99,51,32,115,116,97,116,105,99,95,108,105,103,104,116,32,61,32,118,101,99,51,40,48,44,32,49,44,32,48,41,59,10,125,10,0 +}; +#endif diff --git a/tests/python_build/fixtures/glsl/compute_expected_parts.json b/tests/python_build/fixtures/glsl/compute_expected_parts.json new file mode 100644 index 0000000000..025c568ae0 --- /dev/null +++ b/tests/python_build/fixtures/glsl/compute_expected_parts.json @@ -0,0 +1,3 @@ +{ + "code": "#[compute]\n\n#version 450\n\n#VERSION_DEFINES\n\n\n#define M_PI 3.14159265359\n\nvoid main() {\n\tvec3 static_light = vec3(0, 1, 0);\n}\n" +} diff --git a/tests/python_build/fixtures/glsl/vertex_fragment.glsl b/tests/python_build/fixtures/glsl/vertex_fragment.glsl new file mode 100644 index 0000000000..0bdce783d7 --- /dev/null +++ b/tests/python_build/fixtures/glsl/vertex_fragment.glsl @@ -0,0 +1,32 @@ +#[versions] + +lines = "#define MODE_LINES"; + +#[vertex] + +#version 450 + +#VERSION_DEFINES + +layout(location = 0) out vec3 uv_interp; + +void main() { + +#ifdef MODE_LINES + uv_interp = vec3(0,0,1); +#endif +} + +#[fragment] + +#version 450 + +#VERSION_DEFINES + +#include "_included.glsl" + +layout(location = 0) out vec4 dst_color; + +void main() { + dst_color = vec4(1,1,0,0); +} diff --git a/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl new file mode 100644 index 0000000000..3f53a17fac --- /dev/null +++ b/tests/python_build/fixtures/glsl/vertex_fragment_expected_full.glsl @@ -0,0 +1,8 @@ +/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */ +#ifndef VERTEX_FRAGMENT_SHADER_GLSL_RAW_H +#define VERTEX_FRAGMENT_SHADER_GLSL_RAW_H + +static const char vertex_fragment_shader_glsl[] = { + 35,91,118,101,114,115,105,111,110,115,93,10,10,108,105,110,101,115,32,61,32,34,35,100,101,102,105,110,101,32,77,79,68,69,95,76,73,78,69,83,34,59,10,10,35,91,118,101,114,116,101,120,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,51,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,10,35,105,102,100,101,102,32,77,79,68,69,95,76,73,78,69,83,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,51,40,48,44,48,44,49,41,59,10,35,101,110,100,105,102,10,125,10,10,35,91,102,114,97,103,109,101,110,116,93,10,10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,52,32,100,115,116,95,99,111,108,111,114,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,100,115,116,95,99,111,108,111,114,32,61,32,118,101,99,52,40,49,44,49,44,48,44,48,41,59,10,125,10,0 +}; +#endif diff --git a/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json new file mode 100644 index 0000000000..38312367a0 --- /dev/null +++ b/tests/python_build/fixtures/glsl/vertex_fragment_expected_parts.json @@ -0,0 +1,3 @@ +{ + "code": "#[versions]\n\nlines = \"#define MODE_LINES\";\n\n#[vertex]\n\n#version 450\n\n#VERSION_DEFINES\n\nlayout(location = 0) out vec3 uv_interp;\n\nvoid main() {\n\n#ifdef MODE_LINES\n\tuv_interp = vec3(0,0,1);\n#endif\n}\n\n#[fragment]\n\n#version 450\n\n#VERSION_DEFINES\n\n#define M_PI 3.14159265359\n\nlayout(location = 0) out vec4 dst_color;\n\nvoid main() {\n\tdst_color = vec4(1,1,0,0);\n}\n" +} diff --git a/tests/python_build/fixtures/rd_glsl/_included.glsl b/tests/python_build/fixtures/rd_glsl/_included.glsl new file mode 100644 index 0000000000..adf5f702d3 --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/_included.glsl @@ -0,0 +1 @@ +#define M_PI 3.14159265359 diff --git a/tests/python_build/fixtures/rd_glsl/compute.glsl b/tests/python_build/fixtures/rd_glsl/compute.glsl new file mode 100644 index 0000000000..66fbbeb401 --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/compute.glsl @@ -0,0 +1,13 @@ +#[compute] + +#version 450 + +#VERSION_DEFINES + +#define BLOCK_SIZE 8 + +#include "_included.glsl" + +void main() { + uint t = BLOCK_SIZE + 1; +} diff --git a/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl b/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl new file mode 100644 index 0000000000..b59923e28a --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/compute_expected_full.glsl @@ -0,0 +1,20 @@ +/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */ +#ifndef COMPUTE_GLSL_GEN_H_RD +#define COMPUTE_GLSL_GEN_H_RD + +#include "servers/rendering/renderer_rd/shader_rd.h" + +class ComputeShaderRD : public ShaderRD { + +public: + + ComputeShaderRD() { + + static const char _compute_code[] = { +10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,66,76,79,67,75,95,83,73,90,69,32,56,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,105,110,116,32,116,32,61,32,66,76,79,67,75,95,83,73,90,69,32,43,32,49,59,10,125,10,0 + }; + setup(nullptr, nullptr, _compute_code, "ComputeShaderRD"); + } +}; + +#endif diff --git a/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json b/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json new file mode 100644 index 0000000000..26ba9e4fc4 --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/compute_expected_parts.json @@ -0,0 +1,28 @@ +{ + "vertex_lines": [], + "fragment_lines": [], + "compute_lines": [ + "", + "#version 450", + "", + "#VERSION_DEFINES", + "", + "#define BLOCK_SIZE 8", + "", + "#define M_PI 3.14159265359", + "", + "void main() {", + "\tuint t = BLOCK_SIZE + 1;", + "}" + ], + "vertex_included_files": [], + "fragment_included_files": [], + "compute_included_files": [ + "tests/python_build/fixtures/rd_glsl/_included.glsl" + ], + "reading": "compute", + "line_offset": 13, + "vertex_offset": 0, + "fragment_offset": 0, + "compute_offset": 1 +} diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl b/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl new file mode 100644 index 0000000000..27be08a857 --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment.glsl @@ -0,0 +1,25 @@ +#[vertex] + +#version 450 + +#VERSION_DEFINES + +#include "_included.glsl" + +layout(location = 0) out vec2 uv_interp; + +void main() { + uv_interp = vec2(0, 1); +} + +#[fragment] + +#version 450 + +#VERSION_DEFINES + +layout(location = 0) in vec2 uv_interp; + +void main() { + uv_interp = vec2(1, 0); +} diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl new file mode 100644 index 0000000000..ff804dbf89 --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_full.glsl @@ -0,0 +1,23 @@ +/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */ +#ifndef VERTEX_FRAGMENT_GLSL_GEN_H_RD +#define VERTEX_FRAGMENT_GLSL_GEN_H_RD + +#include "servers/rendering/renderer_rd/shader_rd.h" + +class VertexFragmentShaderRD : public ShaderRD { + +public: + + VertexFragmentShaderRD() { + + static const char _vertex_code[] = { +10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,35,100,101,102,105,110,101,32,77,95,80,73,32,51,46,49,52,49,53,57,50,54,53,51,53,57,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,111,117,116,32,118,101,99,50,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,50,40,48,44,32,49,41,59,10,125,10,10,0 + }; + static const char _fragment_code[] = { +10,35,118,101,114,115,105,111,110,32,52,53,48,10,10,35,86,69,82,83,73,79,78,95,68,69,70,73,78,69,83,10,10,108,97,121,111,117,116,40,108,111,99,97,116,105,111,110,32,61,32,48,41,32,105,110,32,118,101,99,50,32,117,118,95,105,110,116,101,114,112,59,10,10,118,111,105,100,32,109,97,105,110,40,41,32,123,10,9,117,118,95,105,110,116,101,114,112,32,61,32,118,101,99,50,40,49,44,32,48,41,59,10,125,10,0 + }; + setup(_vertex_code, _fragment_code, nullptr, "VertexFragmentShaderRD"); + } +}; + +#endif diff --git a/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json new file mode 100644 index 0000000000..dbf833edea --- /dev/null +++ b/tests/python_build/fixtures/rd_glsl/vertex_fragment_expected_parts.json @@ -0,0 +1,40 @@ +{ + "vertex_lines": [ + "", + "#version 450", + "", + "#VERSION_DEFINES", + "", + "#define M_PI 3.14159265359", + "", + "layout(location = 0) out vec2 uv_interp;", + "", + "void main() {", + "\tuv_interp = vec2(0, 1);", + "}", + "" + ], + "fragment_lines": [ + "", + "#version 450", + "", + "#VERSION_DEFINES", + "", + "layout(location = 0) in vec2 uv_interp;", + "", + "void main() {", + "\tuv_interp = vec2(1, 0);", + "}" + ], + "compute_lines": [], + "vertex_included_files": [ + "tests/python_build/fixtures/rd_glsl/_included.glsl" + ], + "fragment_included_files": [], + "compute_included_files": [], + "reading": "fragment", + "line_offset": 25, + "vertex_offset": 1, + "fragment_offset": 15, + "compute_offset": 0 +} diff --git a/tests/python_build/test_gles3_builder.py b/tests/python_build/test_gles3_builder.py new file mode 100644 index 0000000000..861e0b84c4 --- /dev/null +++ b/tests/python_build/test_gles3_builder.py @@ -0,0 +1,31 @@ +import json + +import pytest + +from gles3_builders import build_gles3_header, GLES3HeaderStruct + + +@pytest.mark.parametrize( + ["shader_files", "builder", "header_struct"], + [ + ("gles3/vertex_fragment", build_gles3_header, GLES3HeaderStruct), + ], + indirect=["shader_files"], +) +def test_gles3_builder(shader_files, builder, header_struct): + header = header_struct() + + builder(shader_files["path_input"], "drivers/gles3/shader_gles3.h", "GLES3", header_data=header) + + with open(shader_files["path_expected_parts"], "r") as f: + expected_parts = json.load(f) + assert expected_parts == header.__dict__ + + with open(shader_files["path_output"], "r") as f: + actual_output = f.read() + assert actual_output + + with open(shader_files["path_expected_full"], "r") as f: + expected_output = f.read() + + assert actual_output == expected_output diff --git a/tests/python_build/test_glsl_builder.py b/tests/python_build/test_glsl_builder.py new file mode 100644 index 0000000000..b9dcef48ac --- /dev/null +++ b/tests/python_build/test_glsl_builder.py @@ -0,0 +1,37 @@ +import json + +import pytest + +from glsl_builders import build_raw_header, RAWHeaderStruct, build_rd_header, RDHeaderStruct + + +@pytest.mark.parametrize( + [ + "shader_files", + "builder", + "header_struct", + ], + [ + ("glsl/vertex_fragment", build_raw_header, RAWHeaderStruct), + ("glsl/compute", build_raw_header, RAWHeaderStruct), + ("rd_glsl/vertex_fragment", build_rd_header, RDHeaderStruct), + ("rd_glsl/compute", build_rd_header, RDHeaderStruct), + ], + indirect=["shader_files"], +) +def test_glsl_builder(shader_files, builder, header_struct): + header = header_struct() + builder(shader_files["path_input"], header_data=header) + + with open(shader_files["path_expected_parts"], "r") as f: + expected_parts = json.load(f) + assert expected_parts == header.__dict__ + + with open(shader_files["path_output"], "r") as f: + actual_output = f.read() + assert actual_output + + with open(shader_files["path_expected_full"], "r") as f: + expected_output = f.read() + + assert actual_output == expected_output diff --git a/tests/scene/test_audio_stream_wav.h b/tests/scene/test_audio_stream_wav.h new file mode 100644 index 0000000000..cf369c115b --- /dev/null +++ b/tests/scene/test_audio_stream_wav.h @@ -0,0 +1,243 @@ +/*************************************************************************/ +/* test_audio_stream_wav.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_AUDIO_STREAM_WAV_H +#define TEST_AUDIO_STREAM_WAV_H + +#include "core/math/math_defs.h" +#include "core/math/math_funcs.h" +#include "scene/resources/audio_stream_wav.h" + +#include "tests/test_macros.h" + +#ifdef TOOLS_ENABLED +#include "core/io/resource_loader.h" +#include "editor/import/resource_importer_wav.h" +#endif + +namespace TestAudioStreamWAV { + +// Default wav rate for test cases. +constexpr float WAV_RATE = 44100; +/* Default wav count for test cases. 1 second of audio is used so that the file can be listened +to manually if needed. */ +constexpr int WAV_COUNT = WAV_RATE; + +float gen_wav(float frequency, float wav_rate, int wav_number) { + // formula for generating a sin wave with given frequency. + return Math::sin((Math_TAU * frequency / wav_rate) * wav_number); +} + +/* Generates a 440Hz sin wave in channel 0 (mono channel or left stereo channel) + * and a 261.63Hz wave in channel 1 (right stereo channel). + * These waves correspond to the music notes A4 and C4 respectively. + */ +Vector<uint8_t> gen_pcm8_test(float wav_rate, int wav_count, bool stereo) { + Vector<uint8_t> buffer; + buffer.resize(stereo ? wav_count * 2 : wav_count); + + uint8_t *write_ptr = buffer.ptrw(); + for (int i = 0; i < buffer.size(); i++) { + float wav; + if (stereo) { + if (i % 2 == 0) { + wav = gen_wav(440, wav_rate, i / 2); + } else { + wav = gen_wav(261.63, wav_rate, i / 2); + } + } else { + wav = gen_wav(440, wav_rate, i); + } + + // Map sin wave to full range of 8-bit values. + uint8_t wav_8bit = Math::fast_ftoi(((wav + 1) / 2) * UINT8_MAX); + // Unlike the .wav format, AudioStreamWAV expects signed 8-bit wavs. + uint8_t wav_8bit_signed = wav_8bit - (INT8_MAX + 1); + write_ptr[i] = wav_8bit_signed; + } + + return buffer; +} + +// Same as gen_pcm8_test but with 16-bit wavs. +Vector<uint8_t> gen_pcm16_test(float wav_rate, int wav_count, bool stereo) { + Vector<uint8_t> buffer; + buffer.resize(stereo ? wav_count * 4 : wav_count * 2); + + uint8_t *write_ptr = buffer.ptrw(); + for (int i = 0; i < buffer.size() / 2; i++) { + float wav; + if (stereo) { + if (i % 2 == 0) { + wav = gen_wav(440, wav_rate, i / 2); + } else { + wav = gen_wav(261.63, wav_rate, i / 2); + } + } else { + wav = gen_wav(440, wav_rate, i); + } + + // Map sin wave to full range of 16-bit values. + uint16_t wav_16bit = Math::fast_ftoi(((wav + 1) / 2) * UINT16_MAX); + // The .wav format expects wavs larger than 8 bits to be signed. + uint16_t wav_16bit_signed = wav_16bit - (INT16_MAX + 1); + encode_uint16(wav_16bit_signed, write_ptr + (i * 2)); + } + + return buffer; +} + +void run_test(String file_name, AudioStreamWAV::Format data_format, bool stereo, float wav_rate, float wav_count) { + String save_path = OS::get_singleton()->get_cache_path().path_join(file_name); + + Vector<uint8_t> test_data; + if (data_format == AudioStreamWAV::FORMAT_8_BITS) { + test_data = gen_pcm8_test(wav_rate, wav_count, stereo); + } else { + test_data = gen_pcm16_test(wav_rate, wav_count, stereo); + } + + Ref<AudioStreamWAV> stream = memnew(AudioStreamWAV); + stream->set_mix_rate(wav_rate); + CHECK(stream->get_mix_rate() == wav_rate); + + stream->set_format(data_format); + CHECK(stream->get_format() == data_format); + + stream->set_stereo(stereo); + CHECK(stream->is_stereo() == stereo); + + stream->set_data(test_data); + CHECK(stream->get_data() == test_data); + + SUBCASE("Stream length is computed properly") { + CHECK(Math::is_equal_approx(stream->get_length(), wav_count / wav_rate)); + } + + SUBCASE("Stream can be saved as .wav") { + REQUIRE(stream->save_to_wav(save_path) == OK); + + Error error; + Ref<FileAccess> wav_file = FileAccess::open(save_path, FileAccess::READ, &error); + REQUIRE(error == OK); + +#if TOOLS_ENABLED + // The WAV importer can be used if enabled to check that the saved file is valid. + Ref<ResourceImporterWAV> wav_importer = memnew(ResourceImporterWAV); + + List<ResourceImporter::ImportOption> options_list; + wav_importer->get_import_options("", &options_list); + + HashMap<StringName, Variant> options_map; + for (const ResourceImporter::ImportOption &E : options_list) { + options_map[E.option.name] = E.default_value; + } + + REQUIRE(wav_importer->import(save_path, save_path, options_map, nullptr) == OK); + + String load_path = save_path + "." + wav_importer->get_save_extension(); + Ref<AudioStreamWAV> loaded_stream = ResourceLoader::load(load_path, "AudioStreamWAV", ResourceFormatImporter::CACHE_MODE_IGNORE, &error); + REQUIRE(error == OK); + + CHECK(loaded_stream->get_format() == stream->get_format()); + CHECK(loaded_stream->get_loop_mode() == stream->get_loop_mode()); + CHECK(loaded_stream->get_loop_begin() == stream->get_loop_begin()); + CHECK(loaded_stream->get_loop_end() == stream->get_loop_end()); + CHECK(loaded_stream->get_mix_rate() == stream->get_mix_rate()); + CHECK(loaded_stream->is_stereo() == stream->is_stereo()); + CHECK(loaded_stream->get_length() == stream->get_length()); + CHECK(loaded_stream->is_monophonic() == stream->is_monophonic()); + CHECK(loaded_stream->get_data() == stream->get_data()); +#endif + } +} + +TEST_CASE("[AudioStreamWAV] Mono PCM8 format") { + run_test("test_pcm8_mono.wav", AudioStreamWAV::FORMAT_8_BITS, false, WAV_RATE, WAV_COUNT); +} + +TEST_CASE("[AudioStreamWAV] Mono PCM16 format") { + run_test("test_pcm16_mono.wav", AudioStreamWAV::FORMAT_16_BITS, false, WAV_RATE, WAV_COUNT); +} + +TEST_CASE("[AudioStreamWAV] Stereo PCM8 format") { + run_test("test_pcm8_stereo.wav", AudioStreamWAV::FORMAT_8_BITS, true, WAV_RATE, WAV_COUNT); +} + +TEST_CASE("[AudioStreamWAV] Stereo PCM16 format") { + run_test("test_pcm16_stereo.wav", AudioStreamWAV::FORMAT_16_BITS, true, WAV_RATE, WAV_COUNT); +} + +TEST_CASE("[AudioStreamWAV] Alternate mix rate") { + run_test("test_pcm16_stereo_38000Hz.wav", AudioStreamWAV::FORMAT_16_BITS, true, 38000, 38000); +} + +TEST_CASE("[AudioStreamWAV] save_to_wav() adds '.wav' file extension automatically") { + String save_path = OS::get_singleton()->get_cache_path().path_join("test_wav_extension"); + Vector<uint8_t> test_data = gen_pcm8_test(WAV_RATE, WAV_COUNT, false); + Ref<AudioStreamWAV> stream = memnew(AudioStreamWAV); + stream->set_data(test_data); + + REQUIRE(stream->save_to_wav(save_path) == OK); + Error error; + Ref<FileAccess> wav_file = FileAccess::open(save_path + ".wav", FileAccess::READ, &error); + CHECK(error == OK); +} + +TEST_CASE("[AudioStreamWAV] Default values") { + Ref<AudioStreamWAV> stream = memnew(AudioStreamWAV); + CHECK(stream->get_format() == AudioStreamWAV::FORMAT_8_BITS); + CHECK(stream->get_loop_mode() == AudioStreamWAV::LOOP_DISABLED); + CHECK(stream->get_loop_begin() == 0); + CHECK(stream->get_loop_end() == 0); + CHECK(stream->get_mix_rate() == 44100); + CHECK(stream->is_stereo() == false); + CHECK(stream->get_length() == 0); + CHECK(stream->is_monophonic() == false); + CHECK(stream->get_data() == Vector<uint8_t>{}); + CHECK(stream->get_stream_name() == ""); +} + +TEST_CASE("[AudioStreamWAV] Save empty file") { + run_test("test_empty.wav", AudioStreamWAV::FORMAT_8_BITS, false, WAV_RATE, 0); +} + +TEST_CASE("[AudioStreamWAV] Saving IMA ADPCM is not supported") { + String save_path = OS::get_singleton()->get_cache_path().path_join("test_adpcm.wav"); + Ref<AudioStreamWAV> stream = memnew(AudioStreamWAV); + stream->set_format(AudioStreamWAV::FORMAT_IMA_ADPCM); + ERR_PRINT_OFF; + CHECK(stream->save_to_wav(save_path) == ERR_UNAVAILABLE); + ERR_PRINT_ON; +} + +} // namespace TestAudioStreamWAV + +#endif // TEST_AUDIO_STREAM_WAV_H diff --git a/tests/scene/test_bit_map.h b/tests/scene/test_bit_map.h new file mode 100644 index 0000000000..53afdc38f7 --- /dev/null +++ b/tests/scene/test_bit_map.h @@ -0,0 +1,445 @@ +/*************************************************************************/ +/* test_bit_map.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_BIT_MAP_H +#define TEST_BIT_MAP_H + +#include "core/os/memory.h" +#include "scene/resources/bit_map.h" +#include "tests/test_macros.h" + +namespace TestBitmap { + +void reset_bit_map(BitMap &p_bm) { + Size2i size = p_bm.get_size(); + p_bm.set_bit_rect(Rect2i(0, 0, size.width, size.height), false); +} + +TEST_CASE("[BitMap] Create bit map") { + Size2i dim{ 256, 512 }; + BitMap bit_map{}; + bit_map.create(dim); + CHECK(bit_map.get_size() == Size2i(256, 512)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "This will go through the entire bitmask inside of bitmap, thus hopefully checking if the bitmask was correctly set up."); + + dim = Size2i(0, 256); + bit_map.create(dim); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 512), "We should still have the same dimensions as before, because the new dimension is invalid."); + + dim = Size2i(512, 0); + bit_map.create(dim); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 512), "We should still have the same dimensions as before, because the new dimension is invalid."); + + dim = Size2i(46341, 46341); + bit_map.create(dim); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 512), "We should still have the same dimensions as before, because the new dimension is too large (46341*46341=2147488281)."); +} + +TEST_CASE("[BitMap] Create bit map from image alpha") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + bit_map.create(dim); + + const Ref<Image> null_img = nullptr; + bit_map.create_from_image_alpha(null_img); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Bitmap should have its old values because bitmap creation from a nullptr should fail."); + + Ref<Image> empty_img; + empty_img.instantiate(); + bit_map.create_from_image_alpha(empty_img); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Bitmap should have its old values because bitmap creation from an empty image should fail."); + + Ref<Image> wrong_format_img; + wrong_format_img.instantiate(); + wrong_format_img->create(3, 3, false, Image::Format::FORMAT_DXT1); + bit_map.create_from_image_alpha(wrong_format_img); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Bitmap should have its old values because converting from a compressed image should fail."); + + Ref<Image> img; + img.instantiate(); + img->create(3, 3, false, Image::Format::FORMAT_RGBA8); + img->set_pixel(0, 0, Color(0, 0, 0, 0)); + img->set_pixel(0, 1, Color(0, 0, 0, 0.09f)); + img->set_pixel(0, 2, Color(0, 0, 0, 0.25f)); + img->set_pixel(1, 0, Color(0, 0, 0, 0.5f)); + img->set_pixel(1, 1, Color(0, 0, 0, 0.75f)); + img->set_pixel(1, 2, Color(0, 0, 0, 0.99f)); + img->set_pixel(2, 0, Color(0, 0, 0, 1.f)); + + // Check different threshold values. + bit_map.create_from_image_alpha(img); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 5, "There are 5 values in the image that are smaller than the default threshold of 0.1."); + + bit_map.create_from_image_alpha(img, 0.08f); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 6, "There are 6 values in the image that are smaller than the threshold of 0.08."); + + bit_map.create_from_image_alpha(img, 1); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "There are no values in the image that are smaller than the threshold of 1, there is one value equal to 1, but we check for inequality only."); +} + +TEST_CASE("[BitMap] Set bit") { + Size2i dim{ 256, 256 }; + BitMap bit_map{}; + + // Setting a point before a bit map is created should not crash, because there are checks to see if we are out of bounds. + bit_map.set_bitv(Point2i(128, 128), true); + + bit_map.create(dim); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "All values should be initialized to false."); + bit_map.set_bitv(Point2i(128, 128), true); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 1, "One bit should be set to true."); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 128)) == true, "The bit at (128,128) should be set to true"); + + bit_map.set_bitv(Point2i(128, 128), false); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "The bit should now be set to false again"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 128)) == false, "The bit at (128,128) should now be set to false again"); + + bit_map.create(dim); + bit_map.set_bitv(Point2i(512, 512), true); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "Nothing should change as we were trying to edit a bit outside of the correct range."); +} + +TEST_CASE("[BitMap] Get bit") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 128)) == false, "Trying to access a bit outside of the BitMap's range should always return false"); + + bit_map.create(dim); + CHECK(bit_map.get_bitv(Point2i(128, 128)) == false); + + bit_map.set_bit_rect(Rect2i(-1, -1, 257, 257), true); + + // Checking that range is [0, 256). + CHECK(bit_map.get_bitv(Point2i(-1, 0)) == false); + CHECK(bit_map.get_bitv(Point2i(0, 0)) == true); + CHECK(bit_map.get_bitv(Point2i(128, 128)) == true); + CHECK(bit_map.get_bitv(Point2i(255, 255)) == true); + CHECK(bit_map.get_bitv(Point2i(256, 256)) == false); + CHECK(bit_map.get_bitv(Point2i(257, 257)) == false); +} + +TEST_CASE("[BitMap] Set bit rect") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + + // Although we have not setup the BitMap yet, this should not crash because we get an empty intersection inside of the method. + bit_map.set_bit_rect(Rect2i{ 0, 0, 128, 128 }, true); + + bit_map.create(dim); + CHECK(bit_map.get_true_bit_count() == 0); + + bit_map.set_bit_rect(Rect2i{ 0, 0, 256, 256 }, true); + CHECK(bit_map.get_true_bit_count() == 65536); + + reset_bit_map(bit_map); + + // Checking out of bounds handling. + bit_map.set_bit_rect(Rect2i{ 128, 128, 256, 256 }, true); + CHECK(bit_map.get_true_bit_count() == 16384); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i{ -128, -128, 256, 256 }, true); + CHECK(bit_map.get_true_bit_count() == 16384); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i{ -128, -128, 512, 512 }, true); + CHECK(bit_map.get_true_bit_count() == 65536); +} + +TEST_CASE("[BitMap] Get true bit count") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + + CHECK(bit_map.get_true_bit_count() == 0); + + bit_map.create(dim); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "Unitialized bit map should have no true bits"); + bit_map.set_bit_rect(Rect2i{ 0, 0, 256, 256 }, true); + CHECK(bit_map.get_true_bit_count() == 65536); + bit_map.set_bitv(Point2i{ 0, 0 }, false); + CHECK(bit_map.get_true_bit_count() == 65535); + bit_map.set_bit_rect(Rect2i{ 0, 0, 256, 256 }, false); + CHECK(bit_map.get_true_bit_count() == 0); +} + +TEST_CASE("[BitMap] Get size") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + + CHECK_MESSAGE(bit_map.get_size() == Size2i(0, 0), "Unitialized bit map should have a size of 0x0"); + + bit_map.create(dim); + CHECK(bit_map.get_size() == Size2i(256, 256)); + + bit_map.create(Size2i(-1, 0)); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Invalid size should not be accepted by create"); + + bit_map.create(Size2i(256, 128)); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 128), "Bitmap should have updated size"); +} + +TEST_CASE("[BitMap] Resize") { + const Size2i dim{ 128, 128 }; + BitMap bit_map{}; + + bit_map.resize(dim); + CHECK(bit_map.get_size() == dim); + + bit_map.create(dim); + bit_map.set_bit_rect(Rect2i(0, 0, 10, 10), true); + bit_map.set_bit_rect(Rect2i(118, 118, 10, 10), true); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 200, "There should be 100 bits in the top left corner, and 100 bits in the bottom right corner"); + bit_map.resize(Size2i(64, 64)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 50, "There should be 25 bits in the top left corner, and 25 bits in the bottom right corner"); + + bit_map.create(dim); + bit_map.resize(Size2i(-1, 128)); + CHECK_MESSAGE(bit_map.get_size() == Size2i(128, 128), "When an invalid size is given the bit map will keep its size"); + + bit_map.create(dim); + bit_map.set_bit_rect(Rect2i(0, 0, 10, 10), true); + bit_map.set_bit_rect(Rect2i(118, 118, 10, 10), true); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 200, "There should be 100 bits in the top left corner, and 100 bits in the bottom right corner"); + bit_map.resize(Size2i(256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 800, "There should still be 100 bits in the bottom right corner, and all new bits should be initialized to false"); + CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "The bitmap should now be 256x256"); +} + +TEST_CASE("[BitMap] Grow and shrink mask") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + bit_map.grow_mask(100, Rect2i(0, 0, 128, 128)); // Check if method does not crash when working with an uninitialised bit map. + CHECK_MESSAGE(bit_map.get_size() == Size2i(0, 0), "Size should still be equal to 0x0"); + + bit_map.create(dim); + + bit_map.set_bit_rect(Rect2i(96, 96, 64, 64), true); + + CHECK_MESSAGE(bit_map.get_true_bit_count() == 4096, "Creating a square of 64x64 should be 4096 bits"); + bit_map.grow_mask(0, Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 4096, "Growing with size of 0 should not change any bits"); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i(96, 96, 64, 64), true); + + CHECK_MESSAGE(bit_map.get_bitv(Point2i(95, 128)) == false, "Bits just outside of the square should not be set"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(160, 128)) == false, "Bits just outside of the square should not be set"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 95)) == false, "Bits just outside of the square should not be set"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 160)) == false, "Bits just outside of the square should not be set"); + bit_map.grow_mask(1, Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 4352, "We should have 4*64 (perimeter of square) more bits set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(95, 128)) == true, "Bits that were just outside of the square should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(160, 128)) == true, "Bits that were just outside of the square should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 95)) == true, "Bits that were just outside of the square should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(128, 160)) == true, "Bits that were just outside of the square should now be set to true"); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i(127, 127, 1, 1), true); + + CHECK(bit_map.get_true_bit_count() == 1); + bit_map.grow_mask(32, Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 3209, "Creates a circle around the initial bit with a radius of 32 bits. Any bit that has a distance within this radius will be set to true"); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i(127, 127, 1, 1), true); + for (int i = 0; i < 32; i++) { + bit_map.grow_mask(1, Rect2i(0, 0, 256, 256)); + } + CHECK_MESSAGE(bit_map.get_true_bit_count() == 2113, "Creates a diamond around the initial bit with diagonals that are 65 bits long."); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i(123, 123, 10, 10), true); + + CHECK(bit_map.get_true_bit_count() == 100); + bit_map.grow_mask(-11, Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 0, "Shrinking by more than the width of the square should totally remove it."); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(96, 96, 64, 64), true); + + CHECK_MESSAGE(bit_map.get_bitv(Point2i(96, 129)) == true, "Bits on the edge of the square should be true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(159, 129)) == true, "Bits on the edge of the square should be true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(129, 96)) == true, "Bits on the edge of the square should be true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(129, 159)) == true, "Bits on the edge of the square should be true"); + bit_map.grow_mask(-1, Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 3844, "Shrinking by 1 should set 4*63=252 bits to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(96, 129)) == false, "Bits that were on the edge of the square should now be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(159, 129)) == false, "Bits that were on the edge of the square should now be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(129, 96)) == false, "Bits that were on the edge of the square should now be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(129, 159)) == false, "Bits that were on the edge of the square should now be set to false"); + + reset_bit_map(bit_map); + + bit_map.set_bit_rect(Rect2i(125, 125, 1, 6), true); + bit_map.set_bit_rect(Rect2i(130, 125, 1, 6), true); + bit_map.set_bit_rect(Rect2i(125, 130, 6, 1), true); + + CHECK(bit_map.get_true_bit_count() == 16); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(125, 131)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(131, 131)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(125, 124)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(130, 124)) == false, "Bits that are on the edge of the shape should be set to false"); + bit_map.grow_mask(1, Rect2i(0, 0, 256, 256)); + CHECK(bit_map.get_true_bit_count() == 48); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(125, 131)) == true, "Bits that were on the edge of the shape should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(131, 130)) == true, "Bits that were on the edge of the shape should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(125, 124)) == true, "Bits that were on the edge of the shape should now be set to true"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(130, 124)) == true, "Bits that were on the edge of the shape should now be set to true"); + + CHECK_MESSAGE(bit_map.get_bitv(Point2i(124, 124)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(126, 124)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(124, 131)) == false, "Bits that are on the edge of the shape should be set to false"); + CHECK_MESSAGE(bit_map.get_bitv(Point2i(131, 131)) == false, "Bits that are on the edge of the shape should be set to false"); +} + +TEST_CASE("[BitMap] Blit") { + Point2i blit_pos{ 128, 128 }; + Point2i bit_map_size{ 256, 256 }; + Point2i blit_size{ 32, 32 }; + + BitMap bit_map{}; + Ref<BitMap> blit_bit_map{}; + + // Testing null reference to blit bit map. + bit_map.blit(blit_pos, blit_bit_map); + + blit_bit_map.instantiate(); + + // Testing if uninitialised blit bit map and uninitialised bit map does not crash + bit_map.blit(blit_pos, blit_bit_map); + + // Testing if uninitialised bit map does not crash + blit_bit_map->create(blit_size); + bit_map.blit(blit_pos, blit_bit_map); + + // Testing if uninitialised bit map does not crash + blit_bit_map.unref(); + blit_bit_map.instantiate(); + CHECK_MESSAGE(blit_bit_map->get_size() == Point2i(0, 0), "Size should be cleared by unref and instance calls."); + bit_map.create(bit_map_size); + bit_map.blit(Point2i(128, 128), blit_bit_map); + + // Testing if both initialised does not crash. + blit_bit_map->create(blit_size); + bit_map.blit(blit_pos, blit_bit_map); + + bit_map.set_bit_rect(Rect2i{ 127, 127, 3, 3 }, true); + CHECK(bit_map.get_true_bit_count() == 9); + bit_map.blit(Point2i(112, 112), blit_bit_map); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 9, "No bits should have been changed, as the blit bit map only contains falses"); + + bit_map.create(bit_map_size); + blit_bit_map->create(blit_size); + blit_bit_map->set_bit_rect(Rect2i(15, 15, 3, 3), true); + CHECK(blit_bit_map->get_true_bit_count() == 9); + + CHECK(bit_map.get_true_bit_count() == 0); + bit_map.blit(Point2i(112, 112), blit_bit_map); + CHECK_MESSAGE(bit_map.get_true_bit_count() == 9, "All true bits should have been moved to the bit map"); + for (int x = 127; x < 129; ++x) { + for (int y = 127; y < 129; ++y) { + CHECK_MESSAGE(bit_map.get_bitv(Point2i(x, y)) == true, "All true bits should have been moved to the bit map"); + } + } +} + +TEST_CASE("[BitMap] Convert to image") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + Ref<Image> img; + + img = bit_map.convert_to_image(); + CHECK_MESSAGE(img.is_valid(), "We should receive a valid Image Object even if BitMap is not created yet"); + CHECK_MESSAGE(img->get_format() == Image::FORMAT_L8, "We should receive a valid Image Object even if BitMap is not created yet"); + CHECK_MESSAGE(img->get_size() == (Size2i(0, 0)), "Image should have no width or height, because BitMap has not yet been created"); + + bit_map.create(dim); + img = bit_map.convert_to_image(); + CHECK_MESSAGE(img->get_size() == dim, "Image should have the same dimensions as the BitMap"); + CHECK_MESSAGE(img->get_pixel(0, 0).is_equal_approx(Color(0, 0, 0)), "BitMap is intialized to all 0's, so Image should be all black"); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(0, 0, 128, 128), true); + img = bit_map.convert_to_image(); + CHECK_MESSAGE(img->get_pixel(0, 0).is_equal_approx(Color(1, 1, 1)), "BitMap's top-left quadrant is all 1's, so Image should be white"); + CHECK_MESSAGE(img->get_pixel(256, 256).is_equal_approx(Color(0, 0, 0)), "All other quadrants were 0's, so these should be black"); +} + +TEST_CASE("[BitMap] Clip to polygon") { + const Size2i dim{ 256, 256 }; + BitMap bit_map{}; + Vector<Vector<Vector2>> polygons; + + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 128, 128)); + CHECK_MESSAGE(polygons.size() == 0, "We should have no polygons, because the BitMap was not initialized"); + + bit_map.create(dim); + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 128, 128)); + CHECK_MESSAGE(polygons.size() == 0, "We should have no polygons, because the BitMap was all 0's"); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(0, 0, 64, 64), true); + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 128, 128)); + CHECK_MESSAGE(polygons.size() == 1, "We should have exactly 1 polygon"); + CHECK_MESSAGE(polygons[0].size() == 4, "The polygon should have exactly 4 points"); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(0, 0, 32, 32), true); + bit_map.set_bit_rect(Rect2i(64, 64, 32, 32), true); + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 128, 128)); + CHECK_MESSAGE(polygons.size() == 2, "We should have exactly 2 polygons"); + CHECK_MESSAGE(polygons[0].size() == 4, "The polygon should have exactly 4 points"); + CHECK_MESSAGE(polygons[1].size() == 4, "The polygon should have exactly 4 points"); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(124, 112, 8, 32), true); + bit_map.set_bit_rect(Rect2i(112, 124, 32, 8), true); + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 256, 256)); + CHECK_MESSAGE(polygons.size() == 1, "We should have exactly 1 polygon"); + CHECK_MESSAGE(polygons[0].size() == 12, "The polygon should have exactly 12 points"); + + reset_bit_map(bit_map); + bit_map.set_bit_rect(Rect2i(124, 112, 8, 32), true); + bit_map.set_bit_rect(Rect2i(112, 124, 32, 8), true); + polygons = bit_map.clip_opaque_to_polygons(Rect2i(0, 0, 128, 128)); + CHECK_MESSAGE(polygons.size() == 1, "We should have exactly 1 polygon"); + CHECK_MESSAGE(polygons[0].size() == 6, "The polygon should have exactly 6 points"); +} + +} // namespace TestBitmap + +#endif // TEST_BIT_MAP_H diff --git a/tests/scene/test_code_edit.h b/tests/scene/test_code_edit.h index 7605f24cf8..3940bdb37a 100644 --- a/tests/scene/test_code_edit.h +++ b/tests/scene/test_code_edit.h @@ -74,7 +74,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { code_edit->set_line_as_breakpoint(0, true); CHECK(code_edit->is_line_breakpointed(0)); - CHECK(code_edit->get_breakpointed_lines()[0] == Variant(0)); + CHECK(code_edit->get_breakpointed_lines()[0] == 0); SIGNAL_CHECK("breakpoint_toggled", args); code_edit->set_line_as_breakpoint(0, false); @@ -451,7 +451,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { ERR_PRINT_ON; code_edit->set_line_as_bookmarked(0, true); - CHECK(code_edit->get_bookmarked_lines()[0] == Variant(0)); + CHECK(code_edit->get_bookmarked_lines()[0] == 0); CHECK(code_edit->is_line_bookmarked(0)); code_edit->set_line_as_bookmarked(0, false); @@ -657,7 +657,7 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { ERR_PRINT_ON; code_edit->set_line_as_executing(0, true); - CHECK(code_edit->get_executing_lines()[0] == Variant(0)); + CHECK(code_edit->get_executing_lines()[0] == 0); CHECK(code_edit->is_line_executing(0)); code_edit->set_line_as_executing(0, false); @@ -3245,7 +3245,7 @@ TEST_CASE("[SceneTree][CodeEdit] symbol lookup") { code_edit->set_text("this is some text"); Point2 caret_pos = code_edit->get_caret_draw_pos(); - caret_pos.x += 58; + caret_pos.x += 60; SEND_GUI_MOUSE_BUTTON_EVENT(code_edit, caret_pos, MouseButton::NONE, MouseButton::NONE, Key::NONE); CHECK(code_edit->get_text_for_symbol_lookup() == "this is s" + String::chr(0xFFFF) + "ome text"); diff --git a/tests/scene/test_curve.h b/tests/scene/test_curve.h index 0370ab15fd..ad7625ddc5 100644 --- a/tests/scene/test_curve.h +++ b/tests/scene/test_curve.h @@ -44,13 +44,13 @@ TEST_CASE("[Curve] Default curve") { curve->get_point_count() == 0, "Default curve should contain the expected number of points."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate(0)), + Math::is_zero_approx(curve->sample(0)), "Default curve should return the expected value at offset 0.0."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate(0.5)), + Math::is_zero_approx(curve->sample(0.5)), "Default curve should return the expected value at offset 0.5."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate(1)), + Math::is_zero_approx(curve->sample(1)), "Default curve should return the expected value at offset 1.0."); } @@ -80,57 +80,57 @@ TEST_CASE("[Curve] Custom curve with free tangents") { "Custom free curve should contain the expected number of points."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate(-0.1)), + Math::is_zero_approx(curve->sample(-0.1)), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.1), (real_t)0.352), + Math::is_equal_approx(curve->sample(0.1), (real_t)0.352), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.4), (real_t)0.352), + Math::is_equal_approx(curve->sample(0.4), (real_t)0.352), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.7), (real_t)0.896), + Math::is_equal_approx(curve->sample(0.7), (real_t)0.896), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(1), 1), + Math::is_equal_approx(curve->sample(1), 1), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(2), 1), + Math::is_equal_approx(curve->sample(2), 1), "Custom free curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate_baked(-0.1)), + Math::is_zero_approx(curve->sample_baked(-0.1)), "Custom free curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.1), (real_t)0.352), + Math::is_equal_approx(curve->sample_baked(0.1), (real_t)0.352), "Custom free curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.4), (real_t)0.352), + Math::is_equal_approx(curve->sample_baked(0.4), (real_t)0.352), "Custom free curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.7), (real_t)0.896), + Math::is_equal_approx(curve->sample_baked(0.7), (real_t)0.896), "Custom free curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(1), 1), + Math::is_equal_approx(curve->sample_baked(1), 1), "Custom free curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(2), 1), + Math::is_equal_approx(curve->sample_baked(2), 1), "Custom free curve should return the expected baked value at offset 0.1."); curve->remove_point(1); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.1), 0), + Math::is_equal_approx(curve->sample(0.1), 0), "Custom free curve should return the expected value at offset 0.1 after removing point at index 1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.1), 0), + Math::is_equal_approx(curve->sample_baked(0.1), 0), "Custom free curve should return the expected baked value at offset 0.1 after removing point at index 1."); curve->clear_points(); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.6), 0), + Math::is_equal_approx(curve->sample(0.6), 0), "Custom free curve should return the expected value at offset 0.6 after clearing all points."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.6), 0), + Math::is_equal_approx(curve->sample_baked(0.6), 0), "Custom free curve should return the expected baked value at offset 0.6 after clearing all points."); } @@ -169,51 +169,51 @@ TEST_CASE("[Curve] Custom curve with linear tangents") { "Custom linear curve should contain the expected number of points."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate(-0.1)), + Math::is_zero_approx(curve->sample(-0.1)), "Custom linear curve should return the expected value at offset -0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.1), (real_t)0.4), + Math::is_equal_approx(curve->sample(0.1), (real_t)0.4), "Custom linear curve should return the expected value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.4), (real_t)0.4), + Math::is_equal_approx(curve->sample(0.4), (real_t)0.4), "Custom linear curve should return the expected value at offset 0.4."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.7), (real_t)0.8), + Math::is_equal_approx(curve->sample(0.7), (real_t)0.8), "Custom linear curve should return the expected value at offset 0.7."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(1), 1), + Math::is_equal_approx(curve->sample(1), 1), "Custom linear curve should return the expected value at offset 1.0."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(2), 1), + Math::is_equal_approx(curve->sample(2), 1), "Custom linear curve should return the expected value at offset 2.0."); CHECK_MESSAGE( - Math::is_zero_approx(curve->interpolate_baked(-0.1)), + Math::is_zero_approx(curve->sample_baked(-0.1)), "Custom linear curve should return the expected baked value at offset -0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.1), (real_t)0.4), + Math::is_equal_approx(curve->sample_baked(0.1), (real_t)0.4), "Custom linear curve should return the expected baked value at offset 0.1."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.4), (real_t)0.4), + Math::is_equal_approx(curve->sample_baked(0.4), (real_t)0.4), "Custom linear curve should return the expected baked value at offset 0.4."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.7), (real_t)0.8), + Math::is_equal_approx(curve->sample_baked(0.7), (real_t)0.8), "Custom linear curve should return the expected baked value at offset 0.7."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(1), 1), + Math::is_equal_approx(curve->sample_baked(1), 1), "Custom linear curve should return the expected baked value at offset 1.0."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(2), 1), + Math::is_equal_approx(curve->sample_baked(2), 1), "Custom linear curve should return the expected baked value at offset 2.0."); ERR_PRINT_OFF; curve->remove_point(10); ERR_PRINT_ON; CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate(0.7), (real_t)0.8), + Math::is_equal_approx(curve->sample(0.7), (real_t)0.8), "Custom free curve should return the expected value at offset 0.7 after removing point at invalid index 10."); CHECK_MESSAGE( - Math::is_equal_approx(curve->interpolate_baked(0.7), (real_t)0.8), + Math::is_equal_approx(curve->sample_baked(0.7), (real_t)0.8), "Custom free curve should return the expected baked value at offset 0.7 after removing point at invalid index 10."); } @@ -228,8 +228,8 @@ TEST_CASE("[Curve2D] Linear sampling should return exact value") { CHECK(len == baked_length); for (int i = 0; i < len; i++) { - Vector2 pos = curve->interpolate_baked(i); - CHECK_MESSAGE(pos.x == i, "interpolate_baked should return exact value"); + Vector2 pos = curve->sample_baked(i); + CHECK_MESSAGE(pos.x == i, "sample_baked should return exact value"); } } @@ -244,8 +244,8 @@ TEST_CASE("[Curve3D] Linear sampling should return exact value") { CHECK(len == baked_length); for (int i = 0; i < len; i++) { - Vector3 pos = curve->interpolate_baked(i); - CHECK_MESSAGE(pos.x == i, "interpolate_baked should return exact value"); + Vector3 pos = curve->sample_baked(i); + CHECK_MESSAGE(pos.x == i, "sample_baked should return exact value"); } } diff --git a/tests/scene/test_path_follow_2d.h b/tests/scene/test_path_follow_2d.h index abd12fe862..57261116a2 100644 --- a/tests/scene/test_path_follow_2d.h +++ b/tests/scene/test_path_follow_2d.h @@ -37,7 +37,7 @@ namespace TestPathFollow2D { -TEST_CASE("[PathFollow2D] Sampling with unit offset") { +TEST_CASE("[PathFollow2D] Sampling with progress ratio") { const Ref<Curve2D> &curve = memnew(Curve2D()); curve->add_point(Vector2(0, 0)); curve->add_point(Vector2(100, 0)); @@ -49,37 +49,37 @@ TEST_CASE("[PathFollow2D] Sampling with unit offset") { const PathFollow2D *path_follow_2d = memnew(PathFollow2D); path->add_child(path_follow_2d); - path_follow_2d->set_unit_offset(0); + path_follow_2d->set_progress_ratio(0); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0))); - path_follow_2d->set_unit_offset(0.125); + path_follow_2d->set_progress_ratio(0.125); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0))); - path_follow_2d->set_unit_offset(0.25); + path_follow_2d->set_progress_ratio(0.25); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0))); - path_follow_2d->set_unit_offset(0.375); + path_follow_2d->set_progress_ratio(0.375); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 50))); - path_follow_2d->set_unit_offset(0.5); + path_follow_2d->set_progress_ratio(0.5); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 100))); - path_follow_2d->set_unit_offset(0.625); + path_follow_2d->set_progress_ratio(0.625); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 100))); - path_follow_2d->set_unit_offset(0.75); + path_follow_2d->set_progress_ratio(0.75); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 100))); - path_follow_2d->set_unit_offset(0.875); + path_follow_2d->set_progress_ratio(0.875); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 50))); - path_follow_2d->set_unit_offset(1); + path_follow_2d->set_progress_ratio(1); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0))); memdelete(path); } -TEST_CASE("[PathFollow2D] Sampling with offset") { +TEST_CASE("[PathFollow2D] Sampling with progress") { const Ref<Curve2D> &curve = memnew(Curve2D()); curve->add_point(Vector2(0, 0)); curve->add_point(Vector2(100, 0)); @@ -91,31 +91,31 @@ TEST_CASE("[PathFollow2D] Sampling with offset") { const PathFollow2D *path_follow_2d = memnew(PathFollow2D); path->add_child(path_follow_2d); - path_follow_2d->set_offset(0); + path_follow_2d->set_progress(0); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0))); - path_follow_2d->set_offset(50); + path_follow_2d->set_progress(50); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0))); - path_follow_2d->set_offset(100); + path_follow_2d->set_progress(100); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0))); - path_follow_2d->set_offset(150); + path_follow_2d->set_progress(150); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 50))); - path_follow_2d->set_offset(200); + path_follow_2d->set_progress(200); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 100))); - path_follow_2d->set_offset(250); + path_follow_2d->set_progress(250); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 100))); - path_follow_2d->set_offset(300); + path_follow_2d->set_progress(300); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 100))); - path_follow_2d->set_offset(350); + path_follow_2d->set_progress(350); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 50))); - path_follow_2d->set_offset(400); + path_follow_2d->set_progress(400); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(0, 0))); memdelete(path); @@ -131,7 +131,7 @@ TEST_CASE("[PathFollow2D] Removal of a point in curve") { const PathFollow2D *path_follow_2d = memnew(PathFollow2D); path->add_child(path_follow_2d); - path_follow_2d->set_unit_offset(0.5); + path_follow_2d->set_progress_ratio(0.5); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(100, 0))); curve->remove_point(1); @@ -152,7 +152,7 @@ TEST_CASE("[PathFollow2D] Setting h_offset and v_offset") { const PathFollow2D *path_follow_2d = memnew(PathFollow2D); path->add_child(path_follow_2d); - path_follow_2d->set_unit_offset(0.5); + path_follow_2d->set_progress_ratio(0.5); CHECK(path_follow_2d->get_transform().get_origin().is_equal_approx(Vector2(50, 0))); path_follow_2d->set_h_offset(25); @@ -175,32 +175,32 @@ TEST_CASE("[PathFollow2D] Unit offset out of range") { path_follow_2d->set_loop(true); - path_follow_2d->set_unit_offset(-0.3); + path_follow_2d->set_progress_ratio(-0.3); CHECK_MESSAGE( - path_follow_2d->get_unit_offset() == 0.7, - "Unit Offset should loop back from the end in the opposite direction"); + path_follow_2d->get_progress_ratio() == 0.7, + "Progress Ratio should loop back from the end in the opposite direction"); - path_follow_2d->set_unit_offset(1.3); + path_follow_2d->set_progress_ratio(1.3); CHECK_MESSAGE( - path_follow_2d->get_unit_offset() == 0.3, - "Unit Offset should loop back from the end in the opposite direction"); + path_follow_2d->get_progress_ratio() == 0.3, + "Progress Ratio should loop back from the end in the opposite direction"); path_follow_2d->set_loop(false); - path_follow_2d->set_unit_offset(-0.3); + path_follow_2d->set_progress_ratio(-0.3); CHECK_MESSAGE( - path_follow_2d->get_unit_offset() == 0, - "Unit Offset should be clamped at 0"); + path_follow_2d->get_progress_ratio() == 0, + "Progress Ratio should be clamped at 0"); - path_follow_2d->set_unit_offset(1.3); + path_follow_2d->set_progress_ratio(1.3); CHECK_MESSAGE( - path_follow_2d->get_unit_offset() == 1, - "Unit Offset should be clamped at 1"); + path_follow_2d->get_progress_ratio() == 1, + "Progress Ratio should be clamped at 1"); memdelete(path); } -TEST_CASE("[PathFollow2D] Offset out of range") { +TEST_CASE("[PathFollow2D] Progress out of range") { const Ref<Curve2D> &curve = memnew(Curve2D()); curve->add_point(Vector2(0, 0)); curve->add_point(Vector2(100, 0)); @@ -211,27 +211,27 @@ TEST_CASE("[PathFollow2D] Offset out of range") { path_follow_2d->set_loop(true); - path_follow_2d->set_offset(-50); + path_follow_2d->set_progress(-50); CHECK_MESSAGE( - path_follow_2d->get_offset() == 50, - "Offset should loop back from the end in the opposite direction"); + path_follow_2d->get_progress() == 50, + "Progress should loop back from the end in the opposite direction"); - path_follow_2d->set_offset(150); + path_follow_2d->set_progress(150); CHECK_MESSAGE( - path_follow_2d->get_offset() == 50, - "Offset should loop back from the end in the opposite direction"); + path_follow_2d->get_progress() == 50, + "Progress should loop back from the end in the opposite direction"); path_follow_2d->set_loop(false); - path_follow_2d->set_offset(-50); + path_follow_2d->set_progress(-50); CHECK_MESSAGE( - path_follow_2d->get_offset() == 0, - "Offset should be clamped at 0"); + path_follow_2d->get_progress() == 0, + "Progress should be clamped at 0"); - path_follow_2d->set_offset(150); + path_follow_2d->set_progress(150); CHECK_MESSAGE( - path_follow_2d->get_offset() == 100, - "Offset should be clamped at 1"); + path_follow_2d->get_progress() == 100, + "Progress should be clamped at 1"); memdelete(path); } diff --git a/tests/scene/test_path_follow_3d.h b/tests/scene/test_path_follow_3d.h index 9ffe49e3d6..6334fa56de 100644 --- a/tests/scene/test_path_follow_3d.h +++ b/tests/scene/test_path_follow_3d.h @@ -37,7 +37,7 @@ namespace TestPathFollow3D { -TEST_CASE("[PathFollow3D] Sampling with unit offset") { +TEST_CASE("[PathFollow3D] Sampling with progress ratio") { const Ref<Curve3D> &curve = memnew(Curve3D()); curve->add_point(Vector3(0, 0, 0)); curve->add_point(Vector3(100, 0, 0)); @@ -49,37 +49,37 @@ TEST_CASE("[PathFollow3D] Sampling with unit offset") { const PathFollow3D *path_follow_3d = memnew(PathFollow3D); path->add_child(path_follow_3d); - path_follow_3d->set_unit_offset(0); + path_follow_3d->set_progress_ratio(0); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(0, 0, 0)); - path_follow_3d->set_unit_offset(0.125); + path_follow_3d->set_progress_ratio(0.125); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(50, 0, 0)); - path_follow_3d->set_unit_offset(0.25); + path_follow_3d->set_progress_ratio(0.25); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 0); - path_follow_3d->set_unit_offset(0.375); + path_follow_3d->set_progress_ratio(0.375); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 0))); - path_follow_3d->set_unit_offset(0.5); + path_follow_3d->set_progress_ratio(0.5); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 0))); - path_follow_3d->set_unit_offset(0.625); + path_follow_3d->set_progress_ratio(0.625); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 50))); - path_follow_3d->set_unit_offset(0.75); + path_follow_3d->set_progress_ratio(0.75); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 100))); - path_follow_3d->set_unit_offset(0.875); + path_follow_3d->set_progress_ratio(0.875); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 100))); - path_follow_3d->set_unit_offset(1); + path_follow_3d->set_progress_ratio(1); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 100))); memdelete(path); } -TEST_CASE("[PathFollow3D] Sampling with offset") { +TEST_CASE("[PathFollow3D] Sampling with progress") { const Ref<Curve3D> &curve = memnew(Curve3D()); curve->add_point(Vector3(0, 0, 0)); curve->add_point(Vector3(100, 0, 0)); @@ -91,31 +91,31 @@ TEST_CASE("[PathFollow3D] Sampling with offset") { const PathFollow3D *path_follow_3d = memnew(PathFollow3D); path->add_child(path_follow_3d); - path_follow_3d->set_offset(0); + path_follow_3d->set_progress(0); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(0, 0, 0)); - path_follow_3d->set_offset(50); + path_follow_3d->set_progress(50); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(50, 0, 0)); - path_follow_3d->set_offset(100); + path_follow_3d->set_progress(100); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 0); - path_follow_3d->set_offset(150); + path_follow_3d->set_progress(150); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 0))); - path_follow_3d->set_offset(200); + path_follow_3d->set_progress(200); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 0))); - path_follow_3d->set_offset(250); + path_follow_3d->set_progress(250); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 50))); - path_follow_3d->set_offset(300); + path_follow_3d->set_progress(300); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 100, 100))); - path_follow_3d->set_offset(350); + path_follow_3d->set_progress(350); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 50, 100))); - path_follow_3d->set_offset(400); + path_follow_3d->set_progress(400); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector3(100, 0, 100))); memdelete(path); @@ -131,7 +131,7 @@ TEST_CASE("[PathFollow3D] Removal of a point in curve") { const PathFollow3D *path_follow_3d = memnew(PathFollow3D); path->add_child(path_follow_3d); - path_follow_3d->set_unit_offset(0.5); + path_follow_3d->set_progress_ratio(0.5); CHECK(path_follow_3d->get_transform().get_origin().is_equal_approx(Vector2(100, 0, 0))); curve->remove_point(1); @@ -143,7 +143,7 @@ TEST_CASE("[PathFollow3D] Removal of a point in curve") { memdelete(path); } -TEST_CASE("[PathFollow3D] Unit offset out of range") { +TEST_CASE("[PathFollow3D] Progress ratio out of range") { const Ref<Curve3D> &curve = memnew(Curve3D()); curve->add_point(Vector3(0, 0, 0)); curve->add_point(Vector3(100, 0, 0)); @@ -154,32 +154,32 @@ TEST_CASE("[PathFollow3D] Unit offset out of range") { path_follow_3d->set_loop(true); - path_follow_3d->set_unit_offset(-0.3); + path_follow_3d->set_progress_ratio(-0.3); CHECK_MESSAGE( - path_follow_3d->get_unit_offset() == 0.7, - "Unit Offset should loop back from the end in the opposite direction"); + path_follow_3d->get_progress_ratio() == 0.7, + "Progress Ratio should loop back from the end in the opposite direction"); - path_follow_3d->set_unit_offset(1.3); + path_follow_3d->set_progress_ratio(1.3); CHECK_MESSAGE( - path_follow_3d->get_unit_offset() == 0.3, - "Unit Offset should loop back from the end in the opposite direction"); + path_follow_3d->get_progress_ratio() == 0.3, + "Progress Ratio should loop back from the end in the opposite direction"); path_follow_3d->set_loop(false); - path_follow_3d->set_unit_offset(-0.3); + path_follow_3d->set_progress_ratio(-0.3); CHECK_MESSAGE( - path_follow_3d->get_unit_offset() == 0, - "Unit Offset should be clamped at 0"); + path_follow_3d->get_progress_ratio() == 0, + "Progress Ratio should be clamped at 0"); - path_follow_3d->set_unit_offset(1.3); + path_follow_3d->set_progress_ratio(1.3); CHECK_MESSAGE( - path_follow_3d->get_unit_offset() == 1, - "Unit Offset should be clamped at 1"); + path_follow_3d->get_progress_ratio() == 1, + "Progress Ratio should be clamped at 1"); memdelete(path); } -TEST_CASE("[PathFollow3D] Offset out of range") { +TEST_CASE("[PathFollow3D] Progress out of range") { const Ref<Curve3D> &curve = memnew(Curve3D()); curve->add_point(Vector3(0, 0, 0)); curve->add_point(Vector3(100, 0, 0)); @@ -190,27 +190,27 @@ TEST_CASE("[PathFollow3D] Offset out of range") { path_follow_3d->set_loop(true); - path_follow_3d->set_offset(-50); + path_follow_3d->set_progress(-50); CHECK_MESSAGE( - path_follow_3d->get_offset() == 50, - "Offset should loop back from the end in the opposite direction"); + path_follow_3d->get_progress() == 50, + "Progress should loop back from the end in the opposite direction"); - path_follow_3d->set_offset(150); + path_follow_3d->set_progress(150); CHECK_MESSAGE( - path_follow_3d->get_offset() == 50, - "Offset should loop back from the end in the opposite direction"); + path_follow_3d->get_progress() == 50, + "Progress should loop back from the end in the opposite direction"); path_follow_3d->set_loop(false); - path_follow_3d->set_offset(-50); + path_follow_3d->set_progress(-50); CHECK_MESSAGE( - path_follow_3d->get_offset() == 0, - "Offset should be clamped at 0"); + path_follow_3d->get_progress() == 0, + "Progress should be clamped at 0"); - path_follow_3d->set_offset(150); + path_follow_3d->set_progress(150); CHECK_MESSAGE( - path_follow_3d->get_offset() == 100, - "Offset should be clamped at max value of curve"); + path_follow_3d->get_progress() == 100, + "Progress should be clamped at max value of curve"); memdelete(path); } diff --git a/tests/scene/test_sprite_frames.h b/tests/scene/test_sprite_frames.h new file mode 100644 index 0000000000..61bbd16493 --- /dev/null +++ b/tests/scene/test_sprite_frames.h @@ -0,0 +1,247 @@ +/*************************************************************************/ +/* test_sprite_frames.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_SPRITE_FRAMES_H +#define TEST_SPRITE_FRAMES_H + +#include "scene/resources/sprite_frames.h" + +#include "tests/test_macros.h" + +namespace TestSpriteFrames { +const String test_animation_name = "GodotTest"; + +TEST_CASE("[SpriteFrames] Constructor methods") { + const SpriteFrames frames; + CHECK_MESSAGE( + frames.get_animation_names().size() == 1, + "Should be initialized with 1 entry."); + CHECK_MESSAGE( + frames.get_animation_names().get(0) == "default", + "Should be initialized with default entry."); +} + +TEST_CASE("[SpriteFrames] Animation addition, list getter, renaming, removal, and retrieval") { + SpriteFrames frames; + Vector<String> test_names = { "default", "2", "1", "3" }; + + // "default" is there already + frames.add_animation("2"); + frames.add_animation("1"); + frames.add_animation("3"); + + for (int i = 0; i < test_names.size(); i++) { + CHECK_MESSAGE( + frames.has_animation(test_names[i]), + "Add animation properly worked for each value"); + } + + CHECK_MESSAGE( + !frames.has_animation("999"), + "Return false when checking for animation that does not exist"); + + List<StringName> sname_list; + frames.get_animation_list(&sname_list); + + CHECK_MESSAGE( + sname_list.size() == test_names.size(), + "StringName List getter returned list of expected size"); + + for (int i = 0; i < test_names.size(); i++) { + CHECK_MESSAGE( + sname_list[i] == StringName(test_names[i]), + "StringName List getter returned expected values"); + } + + // get_animation_names() sorts the results. + Vector<String> string_vector = frames.get_animation_names(); + test_names.sort(); + + for (int i = 0; i < test_names.size(); i++) { + CHECK_MESSAGE( + string_vector[i] == test_names[i], + "String Vector getter returned expected values"); + } + + // These error handling cases should not crash. + ERR_PRINT_OFF; + frames.rename_animation("This does not exist", "0"); + ERR_PRINT_ON; + + CHECK_MESSAGE( + !frames.has_animation("0"), + "Correctly handles rename error when entry does not exist"); + + // These error handling cases should not crash. + ERR_PRINT_OFF; + frames.rename_animation("3", "1"); + ERR_PRINT_ON; + + CHECK_MESSAGE( + frames.has_animation("3"), + "Correctly handles rename error when entry exists, but new name already exists"); + + ERR_PRINT_OFF; + frames.add_animation("1"); + ERR_PRINT_ON; + + CHECK_MESSAGE( + frames.get_animation_names().size() == 4, + "Correctly does not add when entry already exists"); + + frames.rename_animation("3", "9"); + + CHECK_MESSAGE( + frames.has_animation("9"), + "Animation renamed correctly"); + + frames.remove_animation("9"); + + CHECK_MESSAGE( + !frames.has_animation("9"), + "Animation removed correctly"); + + frames.clear_all(); + + CHECK_MESSAGE( + frames.get_animation_names().size() == 1, + "Clear all removed all animations and re-added the default animation entry"); +} + +TEST_CASE("[SpriteFrames] Animation Speed getter and setter") { + SpriteFrames frames; + + frames.add_animation(test_animation_name); + + CHECK_MESSAGE( + frames.get_animation_speed(test_animation_name) == 5.0, + "Sets new animation to default speed"); + + frames.set_animation_speed(test_animation_name, 123.0004); + + CHECK_MESSAGE( + frames.get_animation_speed(test_animation_name) == 123.0004, + "Sets animation to positive double"); + + // These error handling cases should not crash. + ERR_PRINT_OFF; + frames.get_animation_speed("This does not exist"); + frames.set_animation_speed("This does not exist", 100); + frames.set_animation_speed(test_animation_name, -999.999); + ERR_PRINT_ON; + + CHECK_MESSAGE( + frames.get_animation_speed(test_animation_name) == 123.0004, + "Prevents speed of animation being set to a negative value"); + + frames.set_animation_speed(test_animation_name, 0.0); + + CHECK_MESSAGE( + frames.get_animation_speed(test_animation_name) == 0.0, + "Sets animation to zero"); +} + +TEST_CASE("[SpriteFrames] Animation Loop getter and setter") { + SpriteFrames frames; + + frames.add_animation(test_animation_name); + + CHECK_MESSAGE( + frames.get_animation_loop(test_animation_name), + "Sets new animation to default loop value."); + + frames.set_animation_loop(test_animation_name, true); + + CHECK_MESSAGE( + frames.get_animation_loop(test_animation_name), + "Sets animation loop to true"); + + frames.set_animation_loop(test_animation_name, false); + + CHECK_MESSAGE( + !frames.get_animation_loop(test_animation_name), + "Sets animation loop to false"); + + // These error handling cases should not crash. + ERR_PRINT_OFF; + frames.get_animation_loop("This does not exist"); + frames.set_animation_loop("This does not exist", false); + ERR_PRINT_ON; +} + +// TODO +TEST_CASE("[SpriteFrames] Frame addition, removal, and retrieval") { + Ref<Texture2D> dummy_frame1; + dummy_frame1.instantiate(); + + SpriteFrames frames; + frames.add_animation(test_animation_name); + frames.add_animation("1"); + frames.add_animation("2"); + + CHECK_MESSAGE( + frames.get_frame_count(test_animation_name) == 0, + "Animation has a default frame count of 0"); + + frames.add_frame(test_animation_name, dummy_frame1, 0); + frames.add_frame(test_animation_name, dummy_frame1, 1); + frames.add_frame(test_animation_name, dummy_frame1, 2); + + CHECK_MESSAGE( + frames.get_frame_count(test_animation_name) == 3, + "Adds multiple frames"); + + frames.remove_frame(test_animation_name, 1); + frames.remove_frame(test_animation_name, 0); + + CHECK_MESSAGE( + frames.get_frame_count(test_animation_name) == 1, + "Removes multiple frames"); + + // These error handling cases should not crash. + ERR_PRINT_OFF; + frames.add_frame("does not exist", dummy_frame1, 0); + frames.remove_frame(test_animation_name, -99); + frames.remove_frame("does not exist", 0); + ERR_PRINT_ON; + + CHECK_MESSAGE( + frames.get_frame_count(test_animation_name) == 1, + "Handles bad values when adding or removing frames."); + + frames.clear(test_animation_name); + + CHECK_MESSAGE( + frames.get_frame_count(test_animation_name) == 0, + "Clears frames."); +} +} // namespace TestSpriteFrames + +#endif // TEST_SPRITE_FRAMES_H diff --git a/tests/scene/test_text_edit.h b/tests/scene/test_text_edit.h index 0fce359c5a..225316b293 100644 --- a/tests/scene/test_text_edit.h +++ b/tests/scene/test_text_edit.h @@ -727,7 +727,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { #ifdef MACOS_ENABLED SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::SHIFT | KeyModifierMask::ALT) #else - SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::SHIFT | KeyModifierMask::CMD) + SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::SHIFT | KeyModifierMask::CMD_OR_CTRL) #endif CHECK(text_edit->has_selection()); CHECK(text_edit->get_selected_text() == "test"); @@ -739,7 +739,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { #ifdef MACOS_ENABLED SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::SHIFT | KeyModifierMask::ALT) #else - SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::SHIFT | KeyModifierMask::CMD) + SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::SHIFT | KeyModifierMask::CMD_OR_CTRL) #endif CHECK_FALSE(text_edit->has_selection()); CHECK(text_edit->get_selected_text() == ""); @@ -1387,7 +1387,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { text_edit->set_caret_column(4); MessageQueue::get_singleton()->flush(); - Ref<InputEvent> tmpevent = InputEventKey::create_reference(Key::BACKSPACE | KeyModifierMask::ALT | KeyModifierMask::CMD); + Ref<InputEvent> tmpevent = InputEventKey::create_reference(Key::BACKSPACE | KeyModifierMask::ALT | KeyModifierMask::CMD_OR_CTRL); InputMap::get_singleton()->action_add_event("ui_text_backspace_all_to_left", tmpevent); SIGNAL_DISCARD("text_set"); @@ -1624,7 +1624,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { } SUBCASE("[TextEdit] ui_text_delete_all_to_right") { - Ref<InputEvent> tmpevent = InputEventKey::create_reference(Key::BACKSPACE | KeyModifierMask::ALT | KeyModifierMask::CMD); + Ref<InputEvent> tmpevent = InputEventKey::create_reference(Key::BACKSPACE | KeyModifierMask::ALT | KeyModifierMask::CMD_OR_CTRL); InputMap::get_singleton()->action_add_event("ui_text_delete_all_to_right", tmpevent); text_edit->set_text("this is some test text.\n"); @@ -1905,7 +1905,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { #ifdef MACOS_ENABLED SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::ALT | KeyModifierMask::SHIFT); #else - SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #endif CHECK(text_edit->get_viewport()->is_input_handled()); CHECK(text_edit->get_text() == "\nthis is some test text."); @@ -2016,7 +2016,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { #ifdef MACOS_ENABLED SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::ALT | KeyModifierMask::SHIFT); #else - SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #endif CHECK(text_edit->get_viewport()->is_input_handled()); CHECK(text_edit->get_text() == "this is some test text\n"); @@ -2245,9 +2245,9 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { SIGNAL_DISCARD("caret_changed"); #ifdef MACOS_ENABLED - SEND_GUI_KEY_EVENT(text_edit, Key::UP | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::UP | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #else - SEND_GUI_KEY_EVENT(text_edit, Key::HOME | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::HOME | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #endif CHECK(text_edit->get_viewport()->is_input_handled()); CHECK(text_edit->get_text() == "this is some\nother test\nlines\ngo here"); @@ -2286,9 +2286,9 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { SIGNAL_DISCARD("caret_changed"); #ifdef MACOS_ENABLED - SEND_GUI_KEY_EVENT(text_edit, Key::DOWN | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::DOWN | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #else - SEND_GUI_KEY_EVENT(text_edit, Key::END | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::END | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #endif CHECK(text_edit->get_viewport()->is_input_handled()); CHECK(text_edit->get_text() == "go here\nlines\nother test\nthis is some"); @@ -2327,7 +2327,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { SIGNAL_DISCARD("caret_changed"); #ifdef MACOS_ENABLED - SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::LEFT | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #else SEND_GUI_KEY_EVENT(text_edit, Key::HOME | KeyModifierMask::SHIFT); #endif @@ -2384,7 +2384,7 @@ TEST_CASE("[SceneTree][TextEdit] text entry") { SIGNAL_DISCARD("caret_changed"); #ifdef MACOS_ENABLED - SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::CMD | KeyModifierMask::SHIFT); + SEND_GUI_KEY_EVENT(text_edit, Key::RIGHT | KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT); #else SEND_GUI_KEY_EVENT(text_edit, Key::END | KeyModifierMask::SHIFT); #endif @@ -2714,15 +2714,15 @@ TEST_CASE("[SceneTree][TextEdit] caret") { text_edit->set_caret_blink_enabled(true); CHECK(text_edit->is_caret_blink_enabled()); - text_edit->set_caret_blink_speed(10); - CHECK(text_edit->get_caret_blink_speed() == 10); + text_edit->set_caret_blink_interval(10); + CHECK(text_edit->get_caret_blink_interval() == 10); ERR_PRINT_OFF; - text_edit->set_caret_blink_speed(-1); - CHECK(text_edit->get_caret_blink_speed() == 10); + text_edit->set_caret_blink_interval(-1); + CHECK(text_edit->get_caret_blink_interval() == 10); - text_edit->set_caret_blink_speed(0); - CHECK(text_edit->get_caret_blink_speed() == 10); + text_edit->set_caret_blink_interval(0); + CHECK(text_edit->get_caret_blink_interval() == 10); ERR_PRINT_ON; text_edit->set_caret_type(TextEdit::CaretType::CARET_TYPE_LINE); @@ -3388,6 +3388,8 @@ TEST_CASE("[SceneTree][TextEdit] gutters") { SUBCASE("[TextEdit] gutter add and remove") { text_edit->add_gutter(); CHECK(text_edit->get_gutter_count() == 1); + CHECK(text_edit->get_gutter_width(0) == 24); + CHECK(text_edit->get_total_gutter_width() == 24 + 2); SIGNAL_CHECK("gutter_added", empty_signal_args); text_edit->set_gutter_name(0, "test_gutter"); @@ -3395,39 +3397,43 @@ TEST_CASE("[SceneTree][TextEdit] gutters") { text_edit->set_gutter_width(0, 10); CHECK(text_edit->get_gutter_width(0) == 10); - CHECK(text_edit->get_total_gutter_width() > 10); - CHECK(text_edit->get_total_gutter_width() < 20); + CHECK(text_edit->get_total_gutter_width() == 10 + 2); text_edit->add_gutter(-100); text_edit->set_gutter_width(1, 10); - CHECK(text_edit->get_total_gutter_width() > 20); - CHECK(text_edit->get_total_gutter_width() < 30); + CHECK(text_edit->get_gutter_width(1) == 10); + CHECK(text_edit->get_total_gutter_width() == 20 + 2); CHECK(text_edit->get_gutter_count() == 2); CHECK(text_edit->get_gutter_name(0) == "test_gutter"); SIGNAL_CHECK("gutter_added", empty_signal_args); text_edit->set_gutter_draw(1, false); - CHECK(text_edit->get_total_gutter_width() > 10); - CHECK(text_edit->get_total_gutter_width() < 20); + CHECK(text_edit->get_total_gutter_width() == 10 + 2); text_edit->add_gutter(100); CHECK(text_edit->get_gutter_count() == 3); + CHECK(text_edit->get_gutter_width(2) == 24); + CHECK(text_edit->get_total_gutter_width() == 34 + 2); CHECK(text_edit->get_gutter_name(0) == "test_gutter"); SIGNAL_CHECK("gutter_added", empty_signal_args); text_edit->add_gutter(0); CHECK(text_edit->get_gutter_count() == 4); + CHECK(text_edit->get_gutter_width(0) == 24); + CHECK(text_edit->get_total_gutter_width() == 58 + 2); CHECK(text_edit->get_gutter_name(1) == "test_gutter"); SIGNAL_CHECK("gutter_added", empty_signal_args); text_edit->remove_gutter(2); CHECK(text_edit->get_gutter_name(1) == "test_gutter"); CHECK(text_edit->get_gutter_count() == 3); + CHECK(text_edit->get_total_gutter_width() == 58 + 2); SIGNAL_CHECK("gutter_removed", empty_signal_args); text_edit->remove_gutter(0); CHECK(text_edit->get_gutter_name(0) == "test_gutter"); CHECK(text_edit->get_gutter_count() == 2); + CHECK(text_edit->get_total_gutter_width() == 34 + 2); SIGNAL_CHECK("gutter_removed", empty_signal_args); ERR_PRINT_OFF; diff --git a/tests/scene/test_theme.h b/tests/scene/test_theme.h index f7cfa0fd5b..f5b21eec32 100644 --- a/tests/scene/test_theme.h +++ b/tests/scene/test_theme.h @@ -101,18 +101,24 @@ TEST_CASE_FIXTURE(Fixture, "[Theme] Good theme type names") { SUBCASE("set_type_variation") { for (const StringName &name : names) { + if (name == StringName()) { // Skip empty here, not allowed. + continue; + } Ref<Theme> theme = memnew(Theme); ErrorDetector ed; theme->set_type_variation(valid_type_name, name); - CHECK(ed.has_error == (name == StringName())); + CHECK_FALSE(ed.has_error); } for (const StringName &name : names) { + if (name == StringName()) { // Skip empty here, not allowed. + continue; + } Ref<Theme> theme = memnew(Theme); ErrorDetector ed; theme->set_type_variation(name, valid_type_name); - CHECK(ed.has_error == (name == StringName())); + CHECK_FALSE(ed.has_error); } } } @@ -125,6 +131,8 @@ TEST_CASE_FIXTURE(Fixture, "[Theme] Bad theme type names") { String::utf8("contains_汉字"), }; + ERR_PRINT_OFF; // All these rightfully print errors. + SUBCASE("add_type") { for (const StringName &name : names) { Ref<Theme> theme = memnew(Theme); @@ -175,6 +183,8 @@ TEST_CASE_FIXTURE(Fixture, "[Theme] Bad theme type names") { CHECK(ed.has_error); } } + + ERR_PRINT_ON; } TEST_CASE_FIXTURE(Fixture, "[Theme] Good theme item names") { @@ -223,6 +233,8 @@ TEST_CASE_FIXTURE(Fixture, "[Theme] Bad theme item names") { String::utf8("contains_汉字"), }; + ERR_PRINT_OFF; // All these rightfully print errors. + SUBCASE("set_theme_item") { for (const StringName &name : names) { for (const DataEntry &entry : valid_data) { @@ -250,6 +262,8 @@ TEST_CASE_FIXTURE(Fixture, "[Theme] Bad theme item names") { } } } + + ERR_PRINT_ON; } } // namespace TestTheme diff --git a/tests/servers/test_text_server.h b/tests/servers/test_text_server.h index 57a2cae37f..9ebd0f34b4 100644 --- a/tests/servers/test_text_server.h +++ b/tests/servers/test_text_server.h @@ -44,7 +44,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Loading fonts") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC)) { continue; @@ -52,7 +52,7 @@ TEST_SUITE("[TextServer]") { RID font = ts->create_font(); ts->font_set_data_ptr(font, _font_NotoSans_Regular, _font_NotoSans_Regular_size); - TEST_FAIL_COND(font == RID(), "Loading font failed."); + CHECK_FALSE_MESSAGE(font == RID(), "Loading font failed."); ts->free_rid(font); } } @@ -60,7 +60,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Text layout: Font fallback") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC) || !ts->has_feature(TextServer::FEATURE_SIMPLE_LAYOUT)) { continue; @@ -79,26 +79,26 @@ TEST_SUITE("[TextServer]") { // 6^ 17^ RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size == 0, "Shaping failed"); + CHECK_FALSE_MESSAGE(gl_size == 0, "Shaping failed"); for (int j = 0; j < gl_size; j++) { if (glyphs[j].start < 6) { - TEST_FAIL_COND(glyphs[j].font_rid != font[1], "Incorrect font selected."); + CHECK_FALSE_MESSAGE(glyphs[j].font_rid != font[1], "Incorrect font selected."); } if ((glyphs[j].start > 6) && (glyphs[j].start < 16)) { - TEST_FAIL_COND(glyphs[j].font_rid != font[0], "Incorrect font selected."); + CHECK_FALSE_MESSAGE(glyphs[j].font_rid != font[0], "Incorrect font selected."); } if (glyphs[j].start > 16) { - TEST_FAIL_COND(glyphs[j].font_rid != RID(), "Incorrect font selected."); - TEST_FAIL_COND(glyphs[j].index != test[glyphs[j].start], "Incorrect glyph index."); + CHECK_FALSE_MESSAGE(glyphs[j].font_rid != RID(), "Incorrect font selected."); + CHECK_FALSE_MESSAGE(glyphs[j].index != test[glyphs[j].start], "Incorrect glyph index."); } - TEST_FAIL_COND((glyphs[j].start < 0 || glyphs[j].end > test.length()), "Incorrect glyph range."); - TEST_FAIL_COND(glyphs[j].font_size != 16, "Incorrect glyph font size."); + CHECK_FALSE_MESSAGE((glyphs[j].start < 0 || glyphs[j].end > test.length()), "Incorrect glyph range."); + CHECK_FALSE_MESSAGE(glyphs[j].font_size != 16, "Incorrect glyph font size."); } ts->free_rid(ctx); @@ -113,7 +113,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Text layout: BiDi") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC) || !ts->has_feature(TextServer::FEATURE_BIDI_LAYOUT)) { continue; @@ -132,23 +132,23 @@ TEST_SUITE("[TextServer]") { // 7^ 26^ RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size == 0, "Shaping failed"); + CHECK_FALSE_MESSAGE(gl_size == 0, "Shaping failed"); for (int j = 0; j < gl_size; j++) { if (glyphs[j].count > 0) { if (glyphs[j].start < 7) { - TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); + CHECK_FALSE_MESSAGE(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); } if ((glyphs[j].start > 8) && (glyphs[j].start < 23)) { - TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) != TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); + CHECK_FALSE_MESSAGE(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) != TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); } if (glyphs[j].start > 26) { - TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); + CHECK_FALSE_MESSAGE(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction."); } } } @@ -165,7 +165,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Text layout: Line break and align points") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC) || !ts->has_feature(TextServer::FEATURE_SIMPLE_LAYOUT)) { continue; @@ -186,16 +186,16 @@ TEST_SUITE("[TextServer]") { { String test = U"Test test long text long text\n"; RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); ts->shaped_text_update_breaks(ctx); ts->shaped_text_update_justification_ops(ctx); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 30, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 30, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -203,11 +203,11 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 4 || j == 9 || j == 14 || j == 19 || j == 24) { - TEST_FAIL_COND((!soft || !space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((!soft || !space || hard || virt || elo), "Invalid glyph flags."); } else if (j == 29) { - TEST_FAIL_COND((soft || !space || !hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || !space || !hard || virt || elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } ts->free_rid(ctx); @@ -216,21 +216,63 @@ TEST_SUITE("[TextServer]") { { String test = U"الحمـد"; RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); ts->shaped_text_update_breaks(ctx); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 6, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 6, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; bool space = (glyphs[j].flags & TextServer::GRAPHEME_IS_SPACE) == TextServer::GRAPHEME_IS_SPACE; bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); + } + if (ts->has_feature(TextServer::FEATURE_KASHIDA_JUSTIFICATION)) { + ts->shaped_text_update_justification_ops(ctx); + + glyphs = ts->shaped_text_get_glyphs(ctx); + gl_size = ts->shaped_text_get_glyph_count(ctx); + + CHECK_FALSE_MESSAGE(gl_size != 6, "Invalid glyph count."); + for (int j = 0; j < gl_size; j++) { + bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; + bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; + bool space = (glyphs[j].flags & TextServer::GRAPHEME_IS_SPACE) == TextServer::GRAPHEME_IS_SPACE; + bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; + bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; + if (j == 1) { + CHECK_FALSE_MESSAGE((soft || space || hard || virt || !elo), "Invalid glyph flags."); + } else { + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); + } + } + } + ts->free_rid(ctx); + } + + { + String test = U"الحمد"; + RID ctx = ts->create_shaped_text(); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); + bool ok = ts->shaped_text_add_string(ctx, test, font, 16); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); + ts->shaped_text_update_breaks(ctx); + + const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); + int gl_size = ts->shaped_text_get_glyph_count(ctx); + CHECK_FALSE_MESSAGE(gl_size != 5, "Invalid glyph count."); + for (int j = 0; j < gl_size; j++) { + bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; + bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; + bool space = (glyphs[j].flags & TextServer::GRAPHEME_IS_SPACE) == TextServer::GRAPHEME_IS_SPACE; + bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; + bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } if (ts->has_feature(TextServer::FEATURE_KASHIDA_JUSTIFICATION)) { @@ -239,7 +281,7 @@ TEST_SUITE("[TextServer]") { glyphs = ts->shaped_text_get_glyphs(ctx); gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 6, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 6, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -247,9 +289,9 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 1) { - TEST_FAIL_COND((soft || space || hard || virt || !elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || !virt || !elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } } @@ -259,15 +301,15 @@ TEST_SUITE("[TextServer]") { { String test = U"الحمـد الرياضي العربي"; RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); ts->shaped_text_update_breaks(ctx); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 21, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 21, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -275,9 +317,9 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 6 || j == 14) { - TEST_FAIL_COND((!soft || !space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((!soft || !space || hard || virt || elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } @@ -287,7 +329,7 @@ TEST_SUITE("[TextServer]") { glyphs = ts->shaped_text_get_glyphs(ctx); gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 23, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 23, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -295,13 +337,13 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 7 || j == 16) { - TEST_FAIL_COND((!soft || !space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((!soft || !space || hard || virt || elo), "Invalid glyph flags."); } else if (j == 3 || j == 9) { - TEST_FAIL_COND((soft || space || hard || !virt || !elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || !virt || !elo), "Invalid glyph flags."); } else if (j == 18) { - TEST_FAIL_COND((soft || space || hard || virt || !elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || !elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } } @@ -312,16 +354,16 @@ TEST_SUITE("[TextServer]") { { String test = U"เป็น ภาษา ราชการ และ ภาษา"; RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); ts->shaped_text_update_breaks(ctx); ts->shaped_text_update_justification_ops(ctx); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 25, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 25, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -329,9 +371,9 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 4 || j == 9 || j == 16 || j == 20) { - TEST_FAIL_COND((!soft || !space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((!soft || !space || hard || virt || elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } ts->free_rid(ctx); @@ -340,16 +382,16 @@ TEST_SUITE("[TextServer]") { if (ts->has_feature(TextServer::FEATURE_BREAK_ITERATORS)) { String test = U"เป็นภาษาราชการและภาษา"; RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); ts->shaped_text_update_breaks(ctx); ts->shaped_text_update_justification_ops(ctx); const Glyph *glyphs = ts->shaped_text_get_glyphs(ctx); int gl_size = ts->shaped_text_get_glyph_count(ctx); - TEST_FAIL_COND(gl_size != 25, "Invalid glyph count."); + CHECK_FALSE_MESSAGE(gl_size != 25, "Invalid glyph count."); for (int j = 0; j < gl_size; j++) { bool hard = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_HARD) == TextServer::GRAPHEME_IS_BREAK_HARD; bool soft = (glyphs[j].flags & TextServer::GRAPHEME_IS_BREAK_SOFT) == TextServer::GRAPHEME_IS_BREAK_SOFT; @@ -357,9 +399,9 @@ TEST_SUITE("[TextServer]") { bool virt = (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) == TextServer::GRAPHEME_IS_VIRTUAL; bool elo = (glyphs[j].flags & TextServer::GRAPHEME_IS_ELONGATION) == TextServer::GRAPHEME_IS_ELONGATION; if (j == 4 || j == 9 || j == 16 || j == 20) { - TEST_FAIL_COND((!soft || !space || hard || !virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((!soft || !space || hard || !virt || elo), "Invalid glyph flags."); } else { - TEST_FAIL_COND((soft || space || hard || virt || elo), "Invalid glyph flags."); + CHECK_FALSE_MESSAGE((soft || space || hard || virt || elo), "Invalid glyph flags."); } } ts->free_rid(ctx); @@ -375,7 +417,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Text layout: Line breaking") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC) || !ts->has_feature(TextServer::FEATURE_SIMPLE_LAYOUT)) { continue; @@ -394,21 +436,21 @@ TEST_SUITE("[TextServer]") { font.push_back(font2); RID ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); bool ok = ts->shaped_text_add_string(ctx, test_1, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); PackedInt32Array brks = ts->shaped_text_get_line_breaks(ctx, 1); - TEST_FAIL_COND(brks.size() != 6, "Invalid line breaks number."); + CHECK_FALSE_MESSAGE(brks.size() != 6, "Invalid line breaks number."); if (brks.size() == 6) { - TEST_FAIL_COND(brks[0] != 0, "Invalid line break position."); - TEST_FAIL_COND(brks[1] != 5, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[0] != 0, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[1] != 5, "Invalid line break position."); - TEST_FAIL_COND(brks[2] != 5, "Invalid line break position."); - TEST_FAIL_COND(brks[3] != 10, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[2] != 5, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[3] != 10, "Invalid line break position."); - TEST_FAIL_COND(brks[4] != 10, "Invalid line break position."); - TEST_FAIL_COND(brks[5] != 14, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[4] != 10, "Invalid line break position."); + CHECK_FALSE_MESSAGE(brks[5] != 14, "Invalid line break position."); } ts->free_rid(ctx); @@ -423,7 +465,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Text layout: Justification") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (!ts->has_feature(TextServer::FEATURE_FONT_DYNAMIC) || !ts->has_feature(TextServer::FEATURE_SIMPLE_LAYOUT)) { continue; @@ -448,40 +490,40 @@ TEST_SUITE("[TextServer]") { float width_old, width; if (ts->has_feature(TextServer::FEATURE_KASHIDA_JUSTIFICATION)) { ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); ok = ts->shaped_text_add_string(ctx, test_1, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); width_old = ts->shaped_text_get_width(ctx); width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND); - TEST_FAIL_COND((width != width_old), "Invalid fill width."); + CHECK_FALSE_MESSAGE((width != width_old), "Invalid fill width."); width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND | TextServer::JUSTIFICATION_KASHIDA); - TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width."); + CHECK_FALSE_MESSAGE((width <= width_old || width > 100), "Invalid fill width."); ts->free_rid(ctx); ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); ok = ts->shaped_text_add_string(ctx, test_2, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); width_old = ts->shaped_text_get_width(ctx); width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND); - TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width."); + CHECK_FALSE_MESSAGE((width <= width_old || width > 100), "Invalid fill width."); width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND | TextServer::JUSTIFICATION_KASHIDA); - TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width."); + CHECK_FALSE_MESSAGE((width <= width_old || width > 100), "Invalid fill width."); ts->free_rid(ctx); } ctx = ts->create_shaped_text(); - TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed."); + CHECK_FALSE_MESSAGE(ctx == RID(), "Creating text buffer failed."); ok = ts->shaped_text_add_string(ctx, test_3, font, 16); - TEST_FAIL_COND(!ok, "Adding text to the buffer failed."); + CHECK_FALSE_MESSAGE(!ok, "Adding text to the buffer failed."); width_old = ts->shaped_text_get_width(ctx); width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND); - TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width."); + CHECK_FALSE_MESSAGE((width <= width_old || width > 100), "Invalid fill width."); ts->free_rid(ctx); @@ -495,7 +537,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Unicode identifiers") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); static const char32_t *data[19] = { U"-30", U"100", U"10.1", U"10,1", U"1e2", U"1e-2", U"1e2e3", U"0xAB", U"AB", U"Test1", U"1Test", U"Test*1", U"test_testeT", U"test_tes teT", U"عَلَيْكُمْ", U"عَلَيْكُمْTest", U"ӒӖӚӜ", U"_test", U"ÂÃÄÅĀĂĄÇĆĈĊ" }; static bool isid[19] = { false, false, false, false, false, false, false, false, true, true, false, false, true, false, true, true, true, true, true }; @@ -516,7 +558,7 @@ TEST_SUITE("[TextServer]") { SUBCASE("[TextServer] Strip Diacritics") { for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) { Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i); - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); if (ts->has_feature(TextServer::FEATURE_SHAPING)) { CHECK(ts->strip_diacritics(U"ٱلسَّلَامُ عَلَيْكُمْ") == U"ٱلسلام عليكم"); @@ -544,7 +586,7 @@ TEST_SUITE("[TextServer]") { continue; } - TEST_FAIL_COND(ts.is_null(), "Invalid TS interface."); + CHECK_FALSE_MESSAGE(ts.is_null(), "Invalid TS interface."); { String text1 = U"linguistically similar and effectively form"; // 14^ 22^ 26^ 38^ diff --git a/tests/test_macros.h b/tests/test_macros.h index 69ae0d3124..3b734b9699 100644 --- a/tests/test_macros.h +++ b/tests/test_macros.h @@ -133,11 +133,11 @@ int register_test_command(String p_command, TestFunc p_function); // Utility macros to send an event actions to a given object // Requires Message Queue and InputMap to be setup. // SEND_GUI_ACTION - takes an object and a input map key. e.g SEND_GUI_ACTION(code_edit, "ui_text_newline"). -// SEND_GUI_KEY_EVENT - takes an object and a keycode set. e.g SEND_GUI_KEY_EVENT(code_edit, Key::A | KeyModifierMask::CMD). +// SEND_GUI_KEY_EVENT - takes an object and a keycode set. e.g SEND_GUI_KEY_EVENT(code_edit, Key::A | KeyModifierMask::META). // SEND_GUI_MOUSE_BUTTON_EVENT - takes an object, position, mouse button, mouse mask and modifiers e.g SEND_GUI_MOUSE_BUTTON_EVENT(code_edit, Vector2(50, 50), MOUSE_BUTTON_NONE, MOUSE_BUTTON_NONE, Key::None); // SEND_GUI_MOUSE_BUTTON_RELEASED_EVENT - takes an object, position, mouse button, mouse mask and modifiers e.g SEND_GUI_MOUSE_BUTTON_RELEASED_EVENT(code_edit, Vector2(50, 50), MOUSE_BUTTON_NONE, MOUSE_BUTTON_NONE, Key::None); -// SEND_GUI_MOUSE_MOTION_EVENT - takes an object, position, mouse mask and modifiers e.g SEND_GUI_MOUSE_MOTION_EVENT(code_edit, Vector2(50, 50), MouseButton::MASK_LEFT, KeyModifierMask::CMD); -// SEND_GUI_DOUBLE_CLICK - takes an object, position and modifiers. e.g SEND_GUI_DOUBLE_CLICK(code_edit, Vector2(50, 50), KeyModifierMask::CMD); +// SEND_GUI_MOUSE_MOTION_EVENT - takes an object, position, mouse mask and modifiers e.g SEND_GUI_MOUSE_MOTION_EVENT(code_edit, Vector2(50, 50), MouseButton::MASK_LEFT, KeyModifierMask::META); +// SEND_GUI_DOUBLE_CLICK - takes an object, position and modifiers. e.g SEND_GUI_DOUBLE_CLICK(code_edit, Vector2(50, 50), KeyModifierMask::META); #define SEND_GUI_ACTION(m_object, m_action) \ { \ @@ -161,7 +161,6 @@ int register_test_command(String p_command, TestFunc p_function); m_event->set_shift_pressed(((m_modifers)&KeyModifierMask::SHIFT) != Key::NONE); \ m_event->set_alt_pressed(((m_modifers)&KeyModifierMask::ALT) != Key::NONE); \ m_event->set_ctrl_pressed(((m_modifers)&KeyModifierMask::CTRL) != Key::NONE); \ - m_event->set_command_pressed(((m_modifers)&KeyModifierMask::CMD) != Key::NONE); \ m_event->set_meta_pressed(((m_modifers)&KeyModifierMask::META) != Key::NONE); #define _CREATE_GUI_MOUSE_EVENT(m_object, m_local_pos, m_input, m_mask, m_modifers) \ diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 16654181c6..4c861eacba 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -30,6 +30,8 @@ #include "test_main.h" +#include "tests/core/input/test_input_event_key.h" +#include "tests/core/input/test_shortcut.h" #include "tests/core/io/test_config_file.h" #include "tests/core/io/test_file_access.h" #include "tests/core/io/test_image.h" @@ -46,13 +48,18 @@ #include "tests/core/math/test_geometry_2d.h" #include "tests/core/math/test_geometry_3d.h" #include "tests/core/math/test_plane.h" +#include "tests/core/math/test_quaternion.h" #include "tests/core/math/test_random_number_generator.h" #include "tests/core/math/test_rect2.h" #include "tests/core/math/test_rect2i.h" +#include "tests/core/math/test_transform_2d.h" +#include "tests/core/math/test_transform_3d.h" #include "tests/core/math/test_vector2.h" #include "tests/core/math/test_vector2i.h" #include "tests/core/math/test_vector3.h" #include "tests/core/math/test_vector3i.h" +#include "tests/core/math/test_vector4.h" +#include "tests/core/math/test_vector4i.h" #include "tests/core/object/test_class_db.h" #include "tests/core/object/test_method_bind.h" #include "tests/core/object/test_object.h" @@ -67,6 +74,7 @@ #include "tests/core/templates/test_local_vector.h" #include "tests/core/templates/test_lru.h" #include "tests/core/templates/test_paged_array.h" +#include "tests/core/templates/test_rid.h" #include "tests/core/templates/test_vector.h" #include "tests/core/test_crypto.h" #include "tests/core/test_hashing_context.h" @@ -76,10 +84,13 @@ #include "tests/core/variant/test_dictionary.h" #include "tests/core/variant/test_variant.h" #include "tests/scene/test_animation.h" +#include "tests/scene/test_audio_stream_wav.h" +#include "tests/scene/test_bit_map.h" #include "tests/scene/test_code_edit.h" #include "tests/scene/test_curve.h" #include "tests/scene/test_gradient.h" #include "tests/scene/test_path_3d.h" +#include "tests/scene/test_sprite_frames.h" #include "tests/scene/test_text_edit.h" #include "tests/scene/test_theme.h" #include "tests/servers/test_text_server.h" @@ -89,7 +100,7 @@ #include "tests/test_macros.h" -#include "scene/resources/default_theme/default_theme.h" +#include "scene/theme/theme_db.h" #include "servers/navigation_server_2d.h" #include "servers/navigation_server_3d.h" #include "servers/physics_server_2d.h" @@ -169,6 +180,7 @@ struct GodotTestCaseListener : public doctest::IReporter { PhysicsServer2D *physics_server_2d = nullptr; NavigationServer3D *navigation_server_3d = nullptr; NavigationServer2D *navigation_server_2d = nullptr; + ThemeDB *theme_db = nullptr; void test_case_start(const doctest::TestCaseData &p_in) override { SignalWatcher::get_singleton()->_clear_signals(); @@ -195,10 +207,10 @@ struct GodotTestCaseListener : public doctest::IReporter { RenderingServerDefault::get_singleton()->init(); RenderingServerDefault::get_singleton()->set_render_loop_enabled(false); - physics_server_3d = PhysicsServer3DManager::new_default_server(); + physics_server_3d = PhysicsServer3DManager::get_singleton()->new_default_server(); physics_server_3d->init(); - physics_server_2d = PhysicsServer2DManager::new_default_server(); + physics_server_2d = PhysicsServer2DManager::get_singleton()->new_default_server(); physics_server_2d->init(); navigation_server_3d = NavigationServer3DManager::new_default_server(); @@ -207,12 +219,22 @@ struct GodotTestCaseListener : public doctest::IReporter { memnew(InputMap); InputMap::get_singleton()->load_default(); - make_default_theme(1.0, Ref<Font>()); + theme_db = memnew(ThemeDB); + theme_db->initialize_theme_noproject(); memnew(SceneTree); SceneTree::get_singleton()->initialize(); return; } + + if (name.find("Audio") != -1) { + // The last driver index should always be the dummy driver. + int dummy_idx = AudioDriverManager::get_driver_count() - 1; + AudioDriverManager::initialize(dummy_idx); + AudioServer *audio_server = memnew(AudioServer); + audio_server->init(); + return; + } } void test_case_end(const doctest::CurrentTestCaseStats &) override { @@ -228,7 +250,10 @@ struct GodotTestCaseListener : public doctest::IReporter { memdelete(SceneTree::get_singleton()); } - clear_default_theme(); + if (theme_db) { + memdelete(theme_db); + theme_db = nullptr; + } if (navigation_server_3d) { memdelete(navigation_server_3d); @@ -258,7 +283,7 @@ struct GodotTestCaseListener : public doctest::IReporter { if (RenderingServer::get_singleton()) { RenderingServer::get_singleton()->sync(); - RenderingServer::get_singleton()->global_shader_uniforms_clear(); + RenderingServer::get_singleton()->global_shader_parameters_clear(); RenderingServer::get_singleton()->finish(); memdelete(RenderingServer::get_singleton()); } @@ -275,6 +300,11 @@ struct GodotTestCaseListener : public doctest::IReporter { MessageQueue::get_singleton()->flush(); memdelete(MessageQueue::get_singleton()); } + + if (AudioServer::get_singleton()) { + AudioServer::get_singleton()->finish(); + memdelete(AudioServer::get_singleton()); + } } void test_run_start() override { diff --git a/tests/test_utils.cpp b/tests/test_utils.cpp index 11cb6398aa..ce12a30381 100644 --- a/tests/test_utils.cpp +++ b/tests/test_utils.cpp @@ -34,7 +34,7 @@ String TestUtils::get_data_path(const String &p_file) { String data_path = "../tests/data"; - return get_executable_dir().plus_file(data_path.plus_file(p_file)); + return get_executable_dir().path_join(data_path.path_join(p_file)); } String TestUtils::get_executable_dir() { |