summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.md11
-rw-r--r--.github/config.yml14
-rw-r--r--COPYRIGHT.txt2
-rw-r--r--SConstruct68
-rw-r--r--core/bind/core_bind.cpp62
-rw-r--r--core/bind/core_bind.h5
-rw-r--r--core/callable_method_pointer.h36
-rw-r--r--core/color.cpp2
-rw-r--r--core/cowdata.h6
-rw-r--r--core/debugger/remote_debugger_peer.cpp6
-rw-r--r--core/engine.cpp4
-rw-r--r--core/image.cpp5
-rw-r--r--core/input/input.cpp26
-rw-r--r--core/io/file_access_buffered_fa.h20
-rw-r--r--core/io/file_access_memory.cpp2
-rw-r--r--core/io/file_access_pack.cpp14
-rw-r--r--core/io/file_access_pack.h2
-rw-r--r--core/io/ip.cpp2
-rw-r--r--core/io/ip_address.cpp40
-rw-r--r--core/io/json.cpp18
-rw-r--r--core/io/marshalls.h2
-rw-r--r--core/io/packet_peer.cpp4
-rw-r--r--core/io/pck_packer.cpp32
-rw-r--r--core/io/xml_parser.cpp6
-rw-r--r--core/io/zip_io.cpp2
-rw-r--r--core/list.h60
-rw-r--r--core/local_vector.h4
-rw-r--r--core/make_binders.py6
-rw-r--r--core/map.h10
-rw-r--r--core/math/aabb.h2
-rw-r--r--core/math/camera_matrix.cpp18
-rw-r--r--core/math/expression.cpp48
-rw-r--r--core/math/geometry.cpp5
-rw-r--r--core/math/rect2.h4
-rw-r--r--core/math/triangulate.cpp2
-rw-r--r--core/math/vector2.cpp13
-rw-r--r--core/math/vector2.h13
-rw-r--r--core/message_queue.cpp15
-rw-r--r--core/message_queue.h1
-rw-r--r--core/oa_hash_map.h42
-rw-r--r--core/object.cpp2
-rw-r--r--core/ordered_hash_map.h16
-rw-r--r--core/os/dir_access.cpp8
-rw-r--r--core/os/file_access.cpp22
-rw-r--r--core/os/os.cpp17
-rw-r--r--core/os/os.h7
-rw-r--r--core/os/thread.cpp2
-rw-r--r--core/os/thread_dummy.cpp8
-rw-r--r--core/packed_data_container.cpp12
-rw-r--r--core/pool_allocator.cpp8
-rw-r--r--core/project_settings.cpp83
-rw-r--r--core/ring_buffer.h48
-rw-r--r--core/translation.cpp4
-rw-r--r--core/ustring.cpp44
-rw-r--r--core/variant.cpp52
-rw-r--r--core/variant.h4
-rw-r--r--core/variant_call.cpp11
-rw-r--r--core/variant_op.cpp30
-rw-r--r--core/variant_parser.cpp26
-rw-r--r--core/vector.h4
-rw-r--r--doc/classes/DisplayServer.xml4
-rw-r--r--doc/classes/KinematicBody3D.xml16
-rw-r--r--doc/classes/OS.xml21
-rw-r--r--doc/classes/PopupMenu.xml2
-rw-r--r--doc/classes/ProjectSettings.xml6
-rw-r--r--doc/classes/TabContainer.xml4
-rw-r--r--doc/classes/TextEdit.xml16
-rw-r--r--drivers/dummy/rasterizer_dummy.h7
-rw-r--r--editor/SCsub26
-rw-r--r--editor/animation_track_editor.cpp4
-rw-r--r--editor/doc_data.h18
-rw-r--r--editor/editor_feature_profile.cpp36
-rw-r--r--editor/editor_feature_profile.h3
-rw-r--r--editor/editor_settings.cpp37
-rw-r--r--editor/icons/SCsub9
-rw-r--r--editor/import_dock.cpp4
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp2
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp196
-rw-r--r--editor/plugins/node_3d_editor_plugin.h1
-rw-r--r--editor/scene_tree_dock.cpp12
-rw-r--r--main/main.cpp77
-rw-r--r--main/tests/test_class_db.cpp68
-rw-r--r--main/tests/test_math.cpp2
-rw-r--r--main/tests/test_oa_hash_map.cpp83
-rw-r--r--methods.py69
-rw-r--r--modules/SCsub13
-rw-r--r--modules/gdscript/gdscript_editor.cpp6
-rw-r--r--modules/gdscript/gdscript_function.cpp2
-rw-r--r--modules/gdscript/gdscript_parser.cpp51
-rw-r--r--modules/mono/SCsub2
-rw-r--r--modules/mono/config.py1
-rw-r--r--modules/mono/csharp_script.cpp60
-rw-r--r--modules/mono/csharp_script.h6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs2
-rw-r--r--modules/mono/mono_gd/gd_mono.cpp3
-rw-r--r--modules/xatlas_unwrap/register_types.cpp2
-rw-r--r--platform/android/display_server_android.cpp23
-rw-r--r--platform/android/display_server_android.h4
-rw-r--r--platform/android/export/export.cpp29
-rw-r--r--platform/android/java/app/build.gradle5
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotIO.java4
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotLib.java11
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java2
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java39
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java10
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt11
-rw-r--r--platform/android/java/plugins/godotpayment/build.gradle2
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl281
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java116
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java309
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java93
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java70
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java403
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java118
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java140
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java143
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/CustomSSLSocketFactory.java72
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/GodotPaymentUtils.java66
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/HttpRequester.java230
-rw-r--r--platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/RequestParams.java84
-rw-r--r--platform/android/java_godot_io_wrapper.cpp6
-rw-r--r--platform/android/java_godot_io_wrapper.h2
-rw-r--r--platform/android/java_godot_lib_jni.cpp25
-rw-r--r--platform/android/java_godot_lib_jni.h6
-rw-r--r--platform/android/plugin/godot_plugin_config.h18
-rw-r--r--platform/android/plugin/godot_plugin_jni.cpp5
-rw-r--r--platform/iphone/os_iphone.cpp2
-rw-r--r--platform/iphone/os_iphone.h2
-rw-r--r--platform/javascript/audio_driver_javascript.cpp4
-rw-r--r--platform/uwp/os_uwp.cpp2
-rw-r--r--platform/uwp/os_uwp.h2
-rw-r--r--platform/windows/display_server_windows.cpp131
-rw-r--r--platform/windows/display_server_windows.h14
-rw-r--r--platform/windows/os_windows.cpp109
-rw-r--r--platform/windows/os_windows.h10
-rw-r--r--scene/debugger/scene_debugger.cpp9
-rw-r--r--scene/gui/color_picker.cpp2
-rw-r--r--scene/gui/container.cpp4
-rw-r--r--scene/gui/line_edit.cpp12
-rw-r--r--scene/gui/tab_container.cpp4
-rw-r--r--scene/gui/text_edit.cpp14
-rw-r--r--scene/gui/text_edit.h8
-rw-r--r--scene/resources/default_theme/default_theme.cpp2
-rw-r--r--servers/display_server.cpp4
-rw-r--r--servers/display_server.h2
-rw-r--r--thirdparty/README.md2
-rw-r--r--thirdparty/xatlas/LICENSE2
-rw-r--r--thirdparty/xatlas/xatlas.cpp6479
-rw-r--r--thirdparty/xatlas/xatlas.h63
149 files changed, 5623 insertions, 5500 deletions
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 91528465c0..7e8c5fd740 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -6,13 +6,24 @@ labels: ''
assignees: ''
---
+<!-- Please search existing issues for potential duplicates before filing yours:
+https://github.com/godotengine/godot/issues?q=is%3Aissue
+-->
**Godot version:**
+<!-- Specify commit hash if using non-official build. -->
+
**OS/device including version:**
+<!-- Specify GPU model, drivers, and the backend (GLES2, GLES3, Vulkan) if graphics-related. -->
+
**Issue description:**
+<!-- What happened, and what was expected. -->
+
**Steps to reproduce:**
+
**Minimal reproduction project:**
+<!-- A small Godot project which reproduces the issue. Drag and drop a zip archive to upload it. -->
diff --git a/.github/config.yml b/.github/config.yml
new file mode 100644
index 0000000000..f787bec00e
--- /dev/null
+++ b/.github/config.yml
@@ -0,0 +1,14 @@
+blank_issues_enabled: false
+
+contact_links:
+ - name: Godot proposals
+ url: https://github.com/godotengine/godot-proposals
+ about: Please submit feature proposals on the Godot proposals repository, not here.
+
+ - name: Godot documentation repository
+ url: https://github.com/godotengine/godot-docs
+ about: Please report issues with documentation on the Godot documentation repository, not here.
+
+ - name: Godot community channels
+ url: https://godotengine.org/community
+ about: Please ask for technical support on one of the other community channels, not here.
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt
index 7741573039..2d32bf1fd9 100644
--- a/COPYRIGHT.txt
+++ b/COPYRIGHT.txt
@@ -368,7 +368,7 @@ License: Expat
Files: ./thirdparty/xatlas/
Comment: xatlas
-Copyright: 2018, Jonathan Young
+Copyright: 2018-2020, Jonathan Young
2013, Thekla, Inc
2006, NVIDIA Corporation, Ignacio Castano
License: Expat
diff --git a/SConstruct b/SConstruct
index f74940b059..515cad57d0 100644
--- a/SConstruct
+++ b/SConstruct
@@ -50,8 +50,6 @@ for x in sorted(glob.glob("platform/*")):
sys.path.remove(tmppath)
sys.modules.pop("detect")
-module_list = methods.detect_modules()
-
methods.save_active_platforms(active_platforms, active_platform_ids)
custom_tools = ["default"]
@@ -123,6 +121,7 @@ opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise e
opts.Add(BoolVariable("deprecated", "Enable deprecated features", True))
opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver", False))
+opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
# Advanced options
opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
@@ -181,18 +180,41 @@ for k in platform_opts.keys():
for o in opt_list:
opts.Add(o)
-for x in module_list:
- module_enabled = True
- tmppath = "./modules/" + x
- sys.path.insert(0, tmppath)
+# Detect modules.
+modules_detected = {}
+module_search_paths = ["modules"] # Built-in path.
+
+if ARGUMENTS.get("custom_modules"):
+ paths = ARGUMENTS.get("custom_modules").split(",")
+ for p in paths:
+ try:
+ module_search_paths.append(methods.convert_custom_modules_path(p))
+ except ValueError as e:
+ print(e)
+ sys.exit(255)
+
+for path in module_search_paths:
+ # Note: custom modules can override built-in ones.
+ modules_detected.update(methods.detect_modules(path))
+ include_path = os.path.dirname(path)
+ if include_path:
+ env_base.Prepend(CPPPATH=[include_path])
+
+# Add module options.
+for name, path in modules_detected.items():
+ enabled = True
+ sys.path.insert(0, path)
import config
- enabled_attr = getattr(config, "is_enabled", None)
- if callable(enabled_attr) and not config.is_enabled():
- module_enabled = False
- sys.path.remove(tmppath)
+ try:
+ enabled = config.is_enabled()
+ except AttributeError:
+ pass
+ sys.path.remove(path)
sys.modules.pop("config")
- opts.Add(BoolVariable("module_" + x + "_enabled", "Enable module '%s'" % (x,), module_enabled))
+ opts.Add(BoolVariable("module_" + name + "_enabled", "Enable module '%s'" % (name,), enabled))
+
+methods.write_modules(modules_detected)
opts.Update(env_base) # update environment
Help(opts.GenerateHelpText(env_base)) # generate help
@@ -501,41 +523,41 @@ if selected_platform in platform_list:
sys.path.remove(tmppath)
sys.modules.pop("detect")
- env.module_list = []
+ modules_enabled = {}
env.module_icons_paths = []
env.doc_class_path = {}
- for x in sorted(module_list):
- if not env["module_" + x + "_enabled"]:
+ for name, path in sorted(modules_detected.items()):
+ if not env["module_" + name + "_enabled"]:
continue
- tmppath = "./modules/" + x
- sys.path.insert(0, tmppath)
- env.current_module = x
+ sys.path.insert(0, path)
+ env.current_module = name
import config
if config.can_build(env, selected_platform):
config.configure(env)
- env.module_list.append(x)
-
# Get doc classes paths (if present)
try:
doc_classes = config.get_doc_classes()
doc_path = config.get_doc_path()
for c in doc_classes:
- env.doc_class_path[c] = "modules/" + x + "/" + doc_path
+ env.doc_class_path[c] = path + "/" + doc_path
except:
pass
# Get icon paths (if present)
try:
icons_path = config.get_icons_path()
- env.module_icons_paths.append("modules/" + x + "/" + icons_path)
+ env.module_icons_paths.append(path + "/" + icons_path)
except:
# Default path for module icons
- env.module_icons_paths.append("modules/" + x + "/" + "icons")
+ env.module_icons_paths.append(path + "/" + "icons")
+ modules_enabled[name] = path
- sys.path.remove(tmppath)
+ sys.path.remove(path)
sys.modules.pop("config")
+ env.module_list = modules_enabled
+
methods.update_version(env.module_version_string)
env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp
index 607e17eae4..10f44d357b 100644
--- a/core/bind/core_bind.cpp
+++ b/core/bind/core_bind.cpp
@@ -117,7 +117,7 @@ PackedStringArray _ResourceLoader::get_dependencies(const String &p_path) {
}
return ret;
-};
+}
bool _ResourceLoader::has_cached(const String &p_path) {
String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
@@ -224,7 +224,7 @@ Error _OS::shell_open(String p_uri) {
WARN_PRINT("Attempting to open an URL with the \"user://\" protocol. Use `ProjectSettings.globalize_path()` to convert a Godot-specific path to a system path before opening it with `OS.shell_open()`.");
}
return OS::get_singleton()->shell_open(p_uri);
-};
+}
int _OS::execute(const String &p_path, const Vector<String> &p_arguments, bool p_blocking, Array p_output, bool p_read_stderr) {
OS::ProcessID pid = -2;
@@ -252,7 +252,7 @@ Error _OS::kill(int p_pid) {
int _OS::get_process_id() const {
return OS::get_singleton()->get_process_id();
-};
+}
bool _OS::has_environment(const String &p_var) const {
return OS::get_singleton()->has_environment(p_var);
@@ -286,7 +286,7 @@ String _OS::get_model_name() const {
Error _OS::set_thread_name(const String &p_name) {
return Thread::set_name(p_name);
-};
+}
bool _OS::has_feature(const String &p_feature) const {
return OS::get_singleton()->has_feature(p_feature);
@@ -620,7 +620,7 @@ void _OS::print_resources_by_type(const Vector<String> &p_types) {
type_count[r->get_class()]++;
}
-};
+}
void _OS::print_all_resources(const String &p_to_file) {
OS::get_singleton()->print_all_resources(p_to_file);
@@ -636,7 +636,7 @@ void _OS::dump_resources_to_file(const String &p_file) {
String _OS::get_user_data_dir() const {
return OS::get_singleton()->get_user_data_dir();
-};
+}
bool _OS::is_debug_build() const {
#ifdef DEBUG_ENABLED
@@ -678,6 +678,22 @@ String _OS::get_unique_id() const {
return OS::get_singleton()->get_unique_id();
}
+int _OS::get_tablet_driver_count() const {
+ return OS::get_singleton()->get_tablet_driver_count();
+}
+
+String _OS::get_tablet_driver_name(int p_driver) const {
+ return OS::get_singleton()->get_tablet_driver_name(p_driver);
+}
+
+String _OS::get_current_tablet_driver() const {
+ return OS::get_singleton()->get_current_tablet_driver();
+}
+
+void _OS::set_current_tablet_driver(const String &p_driver) {
+ OS::get_singleton()->set_current_tablet_driver(p_driver);
+}
+
_OS *_OS::singleton = nullptr;
void _OS::_bind_methods() {
@@ -762,9 +778,15 @@ void _OS::_bind_methods() {
ClassDB::bind_method(D_METHOD("request_permissions"), &_OS::request_permissions);
ClassDB::bind_method(D_METHOD("get_granted_permissions"), &_OS::get_granted_permissions);
+ ClassDB::bind_method(D_METHOD("get_tablet_driver_count"), &_OS::get_tablet_driver_count);
+ ClassDB::bind_method(D_METHOD("get_tablet_driver_name", "idx"), &_OS::get_tablet_driver_name);
+ ClassDB::bind_method(D_METHOD("get_current_tablet_driver"), &_OS::get_current_tablet_driver);
+ ClassDB::bind_method(D_METHOD("set_current_tablet_driver", "name"), &_OS::set_current_tablet_driver);
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "exit_code"), "set_exit_code", "get_exit_code");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "low_processor_usage_mode"), "set_low_processor_usage_mode", "is_in_low_processor_usage_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "low_processor_usage_mode_sleep_usec"), "set_low_processor_usage_mode_sleep_usec", "get_low_processor_usage_mode_sleep_usec");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "tablet_driver"), "set_current_tablet_driver", "get_current_tablet_driver");
// Those default values need to be specified for the docs generator,
// to avoid using values from the documentation writer's own OS instance.
@@ -840,8 +862,8 @@ Variant _Geometry::segment_intersects_segment_2d(const Vector2 &p_from_a, const
return result;
} else {
return Variant();
- };
-};
+ }
+}
Variant _Geometry::line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b) {
Vector2 result;
@@ -1071,7 +1093,7 @@ Dictionary _Geometry::make_atlas(const Vector<Size2> &p_rects) {
Vector<Size2i> rects;
for (int i = 0; i < p_rects.size(); i++) {
rects.push_back(p_rects[i]);
- };
+ }
Vector<Point2i> result;
Size2i size;
@@ -1082,13 +1104,13 @@ Dictionary _Geometry::make_atlas(const Vector<Size2> &p_rects) {
Vector<Point2> r_result;
for (int i = 0; i < result.size(); i++) {
r_result.push_back(result[i]);
- };
+ }
ret["points"] = r_result;
ret["size"] = r_size;
return ret;
-};
+}
int _Geometry::get_uv84_normal_bit(const Vector3 &p_vector) {
return Geometry::get_uv84_normal_bit(p_vector);
@@ -1436,13 +1458,13 @@ void _File::store_pascal_string(const String &p_string) {
ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
f->store_pascal_string(p_string);
-};
+}
String _File::get_pascal_string() {
ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
return f->get_pascal_string();
-};
+}
void _File::store_line(const String &p_string) {
ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
@@ -1784,7 +1806,7 @@ String _Marshalls::variant_to_base64(const Variant &p_var, bool p_full_objects)
ERR_FAIL_COND_V(ret == "", ret);
return ret;
-};
+}
Variant _Marshalls::base64_to_variant(const String &p_str, bool p_allow_objects) {
int strlen = p_str.length();
@@ -1802,13 +1824,13 @@ Variant _Marshalls::base64_to_variant(const String &p_str, bool p_allow_objects)
ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to decode Variant.");
return v;
-};
+}
String _Marshalls::raw_to_base64(const Vector<uint8_t> &p_arr) {
String ret = CryptoCore::b64_encode_str(p_arr.ptr(), p_arr.size());
ERR_FAIL_COND_V(ret == "", ret);
return ret;
-};
+}
Vector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
int strlen = p_str.length();
@@ -1825,14 +1847,14 @@ Vector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
buf.resize(arr_len);
return buf;
-};
+}
String _Marshalls::utf8_to_base64(const String &p_str) {
CharString cstr = p_str.utf8();
String ret = CryptoCore::b64_encode_str((unsigned char *)cstr.get_data(), cstr.length());
ERR_FAIL_COND_V(ret == "", ret);
return ret;
-};
+}
String _Marshalls::base64_to_utf8(const String &p_str) {
int strlen = p_str.length();
@@ -1849,7 +1871,7 @@ String _Marshalls::base64_to_utf8(const String &p_str) {
String ret = String::utf8((char *)&w[0]);
return ret;
-};
+}
void _Marshalls::_bind_methods() {
ClassDB::bind_method(D_METHOD("variant_to_base64", "variant", "full_objects"), &_Marshalls::variant_to_base64, DEFVAL(false));
@@ -1860,7 +1882,7 @@ void _Marshalls::_bind_methods() {
ClassDB::bind_method(D_METHOD("utf8_to_base64", "utf8_str"), &_Marshalls::utf8_to_base64);
ClassDB::bind_method(D_METHOD("base64_to_utf8", "base64_str"), &_Marshalls::base64_to_utf8);
-};
+}
////// _Semaphore //////
diff --git a/core/bind/core_bind.h b/core/bind/core_bind.h
index 32ddcf2c74..e5bd70262d 100644
--- a/core/bind/core_bind.h
+++ b/core/bind/core_bind.h
@@ -243,6 +243,11 @@ public:
bool request_permissions();
Vector<String> get_granted_permissions() const;
+ int get_tablet_driver_count() const;
+ String get_tablet_driver_name(int p_driver) const;
+ String get_current_tablet_driver() const;
+ void set_current_tablet_driver(const String &p_driver);
+
static _OS *get_singleton() { return singleton; }
_OS() { singleton = this; }
diff --git a/core/callable_method_pointer.h b/core/callable_method_pointer.h
index 3b0503e259..22db7d1c82 100644
--- a/core/callable_method_pointer.h
+++ b/core/callable_method_pointer.h
@@ -161,19 +161,35 @@ template <class T, class... P>
class CallableCustomMethodPointer : public CallableCustomMethodPointerBase {
struct Data {
T *instance;
+#ifdef DEBUG_ENABLED
+ uint64_t object_id;
+#endif
void (T::*method)(P...);
} data;
public:
- virtual ObjectID get_object() const { return data.instance->get_instance_id(); }
+ virtual ObjectID get_object() const {
+#ifdef DEBUG_ENABLED
+ if (ObjectDB::get_instance(ObjectID(data.object_id)) == nullptr) {
+ return ObjectID();
+ }
+#endif
+ return data.instance->get_instance_id();
+ }
virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_COND_MSG(ObjectDB::get_instance(ObjectID(data.object_id)) == nullptr, "Invalid Object id '" + uitos(data.object_id) + "', can't call method.");
+#endif
call_with_variant_args(data.instance, data.method, p_arguments, p_argcount, r_call_error);
}
CallableCustomMethodPointer(T *p_instance, void (T::*p_method)(P...)) {
zeromem(&data, sizeof(Data)); // Clear beforehand, may have padding bytes.
data.instance = p_instance;
+#ifdef DEBUG_ENABLED
+ data.object_id = p_instance->get_instance_id();
+#endif
data.method = p_method;
_setup((uint32_t *)&data, sizeof(Data));
}
@@ -242,20 +258,36 @@ template <class T, class R, class... P>
class CallableCustomMethodPointerRet : public CallableCustomMethodPointerBase {
struct Data {
T *instance;
+#ifdef DEBUG_ENABLED
+ uint64_t object_id;
+#endif
R(T::*method)
(P...);
} data;
public:
- virtual ObjectID get_object() const { return data.instance->get_instance_id(); }
+ virtual ObjectID get_object() const {
+#ifdef DEBUG_ENABLED
+ if (ObjectDB::get_instance(ObjectID(data.object_id)) == nullptr) {
+ return ObjectID();
+ }
+#endif
+ return data.instance->get_instance_id();
+ }
virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_COND_MSG(ObjectDB::get_instance(ObjectID(data.object_id)) == nullptr, "Invalid Object id '" + uitos(data.object_id) + "', can't call method.");
+#endif
call_with_variant_args_ret(data.instance, data.method, p_arguments, p_argcount, r_return_value, r_call_error);
}
CallableCustomMethodPointerRet(T *p_instance, R (T::*p_method)(P...)) {
zeromem(&data, sizeof(Data)); // Clear beforehand, may have padding bytes.
data.instance = p_instance;
+#ifdef DEBUG_ENABLED
+ data.object_id = p_instance->get_instance_id();
+#endif
data.method = p_method;
_setup((uint32_t *)&data, sizeof(Data));
}
diff --git a/core/color.cpp b/core/color.cpp
index fa3f6475d4..27a2d0af5c 100644
--- a/core/color.cpp
+++ b/core/color.cpp
@@ -588,7 +588,7 @@ void Color::operator/=(const real_t &rvalue) {
b = b / rvalue;
a = a / rvalue;
}
-};
+}
Color Color::operator-() const {
return Color(
diff --git a/core/cowdata.h b/core/cowdata.h
index 3f72362e29..82daefb5bd 100644
--- a/core/cowdata.h
+++ b/core/cowdata.h
@@ -161,10 +161,10 @@ public:
int len = size();
for (int i = p_index; i < len - 1; i++) {
p[i] = p[i + 1];
- };
+ }
resize(len - 1);
- };
+ }
Error insert(int p_pos, const T &p_val) {
ERR_FAIL_INDEX_V(p_pos, size() + 1, ERR_INVALID_PARAMETER);
@@ -175,7 +175,7 @@ public:
set(p_pos, p_val);
return OK;
- };
+ }
int find(const T &p_val, int p_from = 0) const;
diff --git a/core/debugger/remote_debugger_peer.cpp b/core/debugger/remote_debugger_peer.cpp
index fd1eee0654..faa3a75fda 100644
--- a/core/debugger/remote_debugger_peer.cpp
+++ b/core/debugger/remote_debugger_peer.cpp
@@ -178,13 +178,13 @@ Error RemoteDebuggerPeerTCP::connect_to_host(const String &p_host, uint16_t p_po
const int ms = waits[i];
OS::get_singleton()->delay_usec(ms * 1000);
print_verbose("Remote Debugger: Connection failed with status: '" + String::num(tcp_client->get_status()) + "', retrying in " + String::num(ms) + " msec.");
- };
- };
+ }
+ }
if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
ERR_PRINT("Remote Debugger: Unable to connect. Status: " + String::num(tcp_client->get_status()) + ".");
return FAILED;
- };
+ }
connected = true;
#ifndef NO_THREADS
running = true;
diff --git a/core/engine.cpp b/core/engine.cpp
index 43c5766431..c8bfffd020 100644
--- a/core/engine.cpp
+++ b/core/engine.cpp
@@ -188,11 +188,11 @@ Object *Engine::get_singleton_object(const String &p_name) const {
const Map<StringName, Object *>::Element *E = singleton_ptrs.find(p_name);
ERR_FAIL_COND_V_MSG(!E, nullptr, "Failed to retrieve non-existent singleton '" + p_name + "'.");
return E->get();
-};
+}
bool Engine::has_singleton(const String &p_name) const {
return singleton_ptrs.has(p_name);
-};
+}
void Engine::get_singletons(List<Singleton> *p_singletons) {
for (List<Singleton>::Element *E = singletons.front(); E; E = E->next()) {
diff --git a/core/image.cpp b/core/image.cpp
index 51216c8c31..4ab71128cd 100644
--- a/core/image.cpp
+++ b/core/image.cpp
@@ -1399,7 +1399,7 @@ int Image::_get_dst_image_size(int p_width, int p_height, Format p_format, int &
h = MAX(minh, h >> 1);
}
mm++;
- };
+ }
r_mipmaps = mm;
return size;
@@ -2031,7 +2031,7 @@ void Image::create(const char **p_xpm) {
case 5:
col_b |= v;
break;
- };
+ }
}
// magenta mask
@@ -3018,6 +3018,7 @@ void Image::_bind_methods() {
ClassDB::bind_method(D_METHOD("load", "path"), &Image::load);
ClassDB::bind_method(D_METHOD("save_png", "path"), &Image::save_png);
+ ClassDB::bind_method(D_METHOD("save_png_to_buffer"), &Image::save_png_to_buffer);
ClassDB::bind_method(D_METHOD("save_exr", "path", "grayscale"), &Image::save_exr, DEFVAL(false));
ClassDB::bind_method(D_METHOD("detect_alpha"), &Image::detect_alpha);
diff --git a/core/input/input.cpp b/core/input/input.cpp
index dc1c207524..4d152c1ac4 100644
--- a/core/input/input.cpp
+++ b/core/input/input.cpp
@@ -339,7 +339,7 @@ float Input::get_joy_axis(int p_device, int p_axis) const {
String Input::get_joy_name(int p_idx) {
_THREAD_SAFE_METHOD_
return joy_names[p_idx].name;
-};
+}
Vector2 Input::get_joy_vibration_strength(int p_device) {
if (joy_vibration.has(p_device)) {
@@ -374,7 +374,7 @@ static String _hex_str(uint8_t p_byte) {
ret[1] = dict[p_byte & 0xf];
return ret;
-};
+}
void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) {
_THREAD_SAFE_METHOD_
@@ -388,8 +388,8 @@ void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, S
int uidlen = MIN(p_name.length(), 16);
for (int i = 0; i < uidlen; i++) {
uidname = uidname + _hex_str(p_name[i]);
- };
- };
+ }
+ }
js.uid = uidname;
js.connected = true;
int mapping = fallback_mapping;
@@ -397,8 +397,8 @@ void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, S
if (js.uid == map_db[i].uid) {
mapping = i;
js.name = map_db[i].name;
- };
- };
+ }
+ }
js.mapping = mapping;
} else {
js.connected = false;
@@ -409,11 +409,11 @@ void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, S
for (int i = 0; i < JOY_AXIS_MAX; i++) {
set_joy_axis(p_idx, i, 0.0f);
}
- };
+ }
joy_names[p_idx] = js;
emit_signal("joy_connection_changed", p_idx, p_connected);
-};
+}
Vector3 Input::get_gravity() const {
_THREAD_SAFE_METHOD_
@@ -918,7 +918,7 @@ void Input::joy_axis(int p_device, int p_axis, const JoyAxis &p_value) {
if (joy.mapping == -1) {
_axis_event(p_device, p_axis, val);
return;
- };
+ }
JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value);
@@ -1003,7 +1003,7 @@ void Input::joy_hat(int p_device, int p_val) {
if (joy.mapping != -1) {
_get_mapped_hat_events(map_db[joy.mapping], 0, map);
- };
+ }
int cur_val = joy_names[p_device].hat_current;
@@ -1042,7 +1042,7 @@ void Input::_axis_event(int p_device, int p_axis, float p_value) {
ievent->set_axis_value(p_value);
parse_input_event(ievent);
-};
+}
Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, int p_button) {
JoyEvent event;
@@ -1274,10 +1274,10 @@ void Input::parse_mapping(String p_mapping) {
}
mapping.bindings.push_back(binding);
- };
+ }
map_db.push_back(mapping);
-};
+}
void Input::add_joy_mapping(String p_mapping, bool p_update_existing) {
parse_mapping(p_mapping);
diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h
index 3ea98584a4..f22e54e154 100644
--- a/core/io/file_access_buffered_fa.h
+++ b/core/io/file_access_buffered_fa.h
@@ -58,35 +58,35 @@ class FileAccessBufferedFA : public FileAccessBuffered {
f.get_buffer(cache.buffer.ptrw(), p_size);
return p_size;
- };
- };
+ }
+ }
static FileAccess *create() {
return memnew(FileAccessBufferedFA<T>());
- };
+ }
protected:
virtual void _set_access_type(AccessType p_access) {
f._set_access_type(p_access);
FileAccessBuffered::_set_access_type(p_access);
- };
+ }
public:
void flush() {
f.flush();
- };
+ }
void store_8(uint8_t p_dest) {
f.store_8(p_dest);
- };
+ }
void store_buffer(const uint8_t *p_src, int p_length) {
f.store_buffer(p_src, p_length);
- };
+ }
bool file_exists(const String &p_name) {
return f.file_exists(p_name);
- };
+ }
Error _open(const String &p_path, int p_mode_flags) {
close();
@@ -106,7 +106,7 @@ public:
cache.offset = 0;
return set_error(OK);
- };
+ }
void close() {
f.close();
@@ -119,7 +119,7 @@ public:
cache.buffer.resize(0);
cache.offset = 0;
set_error(OK);
- };
+ }
virtual uint64_t _get_modified_time(const String &p_file) {
return f._get_modified_time(p_file);
diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp
index 3c5f846941..a65ff92a89 100644
--- a/core/io/file_access_memory.cpp
+++ b/core/io/file_access_memory.cpp
@@ -145,7 +145,7 @@ int FileAccessMemory::get_buffer(uint8_t *p_dst, int p_length) const {
if (read < p_length) {
WARN_PRINT("Reading less data than requested");
- };
+ }
copymem(p_dst, &data[pos], read);
pos += p_length;
diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp
index 00c4e76efe..37240f234a 100644
--- a/core/io/file_access_pack.cpp
+++ b/core/io/file_access_pack.cpp
@@ -38,11 +38,11 @@ Error PackedData::add_pack(const String &p_path, bool p_replace_files) {
for (int i = 0; i < sources.size(); i++) {
if (sources[i]->try_open_pack(p_path, p_replace_files)) {
return OK;
- };
- };
+ }
+ }
return ERR_FILE_UNRECOGNIZED;
-};
+}
void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src, bool p_replace_files) {
PathMD5 pmd5(path.md5_buffer());
@@ -96,7 +96,7 @@ void PackedData::add_pack_source(PackSource *p_source) {
if (p_source != nullptr) {
sources.push_back(p_source);
}
-};
+}
PackedData *PackedData::singleton = nullptr;
@@ -192,16 +192,16 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files)
uint8_t md5[16];
f->get_buffer(md5, 16);
PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this, p_replace_files);
- };
+ }
f->close();
memdelete(f);
return true;
-};
+}
FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) {
return memnew(FileAccessPack(p_path, *p_file));
-};
+}
//////////////////////////////////////////////////////////////////
diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h
index 320a6cb216..348bc0c450 100644
--- a/core/io/file_access_pack.h
+++ b/core/io/file_access_pack.h
@@ -79,7 +79,7 @@ private:
bool operator==(const PathMD5 &p_md5) const {
return a == p_md5.a && b == p_md5.b;
- };
+ }
PathMD5() {}
diff --git a/core/io/ip.cpp b/core/io/ip.cpp
index 653959b393..24b8ec7cc1 100644
--- a/core/io/ip.cpp
+++ b/core/io/ip.cpp
@@ -54,7 +54,7 @@ struct _IP_ResolverPrivate {
QueueItem() {
clear();
- };
+ }
};
QueueItem queue[IP::RESOLVER_MAX_QUERIES];
diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp
index 89b317bf93..c7a0ae5605 100644
--- a/core/io/ip_address.cpp
+++ b/core/io/ip_address.cpp
@@ -58,7 +58,7 @@ IP_Address::operator String() const {
}
uint16_t num = (field8[i * 2] << 8) + field8[i * 2 + 1];
ret = ret + String::num_int64(num, 16);
- };
+ }
return ret;
}
@@ -68,7 +68,7 @@ static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) {
for (int i = p_start; i < p_start + 4; i++) {
if (i >= p_string.length()) {
break;
- };
+ }
int n = 0;
CharType c = p_string[i];
@@ -82,14 +82,14 @@ static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) {
break;
} else {
ERR_FAIL_MSG("Invalid character in IPv6 address: " + p_string + ".");
- };
+ }
ret = ret << 4;
ret += n;
- };
+ }
p_dst[0] = ret >> 8;
p_dst[1] = ret & 0xff;
-};
+}
void IP_Address::_parse_ipv6(const String &p_string) {
static const int parts_total = 8;
@@ -105,11 +105,11 @@ void IP_Address::_parse_ipv6(const String &p_string) {
if (c == ':') {
if (i == 0) {
continue; // next must be a ":"
- };
+ }
if (!part_found) {
part_skip = true;
parts[parts_idx++] = -1;
- };
+ }
part_found = false;
} else if (c == '.') {
part_ipv4 = true;
@@ -119,33 +119,33 @@ void IP_Address::_parse_ipv6(const String &p_string) {
parts[parts_idx++] = i;
part_found = true;
++parts_count;
- };
+ }
} else {
ERR_FAIL_MSG("Invalid character in IPv6 address: " + p_string + ".");
- };
- };
+ }
+ }
int parts_extra = 0;
if (part_skip) {
parts_extra = parts_total - parts_count;
- };
+ }
int idx = 0;
for (int i = 0; i < parts_idx; i++) {
if (parts[i] == -1) {
for (int j = 0; j < parts_extra; j++) {
field16[idx++] = 0;
- };
+ }
continue;
- };
+ }
if (part_ipv4 && i == parts_idx - 1) {
_parse_ipv4(p_string, parts[i], (uint8_t *)&field16[idx]); // should be the last one
} else {
_parse_hex(p_string, parts[i], (uint8_t *)&(field16[idx++]));
- };
- };
-};
+ }
+ }
+}
void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret) {
String ip;
@@ -153,20 +153,20 @@ void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret
ip = p_string.substr(p_start, p_string.length() - p_start);
} else {
ip = p_string;
- };
+ }
int slices = ip.get_slice_count(".");
ERR_FAIL_COND_MSG(slices != 4, "Invalid IP address string: " + ip + ".");
for (int i = 0; i < 4; i++) {
p_ret[i] = ip.get_slicec('.', i).to_int();
}
-};
+}
void IP_Address::clear() {
memset(&field8[0], 0, sizeof(field8));
valid = false;
wildcard = false;
-};
+}
bool IP_Address::is_ipv4() const {
return (field32[0] == 0 && field32[1] == 0 && field16[4] == 0 && field16[5] == 0xffff);
@@ -224,7 +224,7 @@ _FORCE_INLINE_ static void _32_to_buf(uint8_t *p_dst, uint32_t p_n) {
p_dst[1] = (p_n >> 16) & 0xff;
p_dst[2] = (p_n >> 8) & 0xff;
p_dst[3] = (p_n >> 0) & 0xff;
-};
+}
IP_Address::IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6) {
clear();
diff --git a/core/io/json.cpp b/core/io/json.cpp
index 03f4e65220..1c603865ad 100644
--- a/core/io/json.cpp
+++ b/core/io/json.cpp
@@ -91,7 +91,7 @@ String JSON::_print_var(const Variant &p_var, const String &p_indent, int p_cur_
}
s += end_statement + _make_indent(p_indent, p_cur_indent) + "]";
return s;
- };
+ }
case Variant::DICTIONARY: {
String s = "{";
s += end_statement;
@@ -115,7 +115,7 @@ String JSON::_print_var(const Variant &p_var, const String &p_indent, int p_cur_
s += end_statement + _make_indent(p_indent, p_cur_indent) + "}";
return s;
- };
+ }
default:
return "\"" + String(p_var).json_escape() + "\"";
}
@@ -132,7 +132,7 @@ Error JSON::_get_token(const CharType *p_str, int &index, int p_len, Token &r_to
line++;
index++;
break;
- };
+ }
case 0: {
r_token.type = TK_EOF;
return OK;
@@ -141,32 +141,32 @@ Error JSON::_get_token(const CharType *p_str, int &index, int p_len, Token &r_to
r_token.type = TK_CURLY_BRACKET_OPEN;
index++;
return OK;
- };
+ }
case '}': {
r_token.type = TK_CURLY_BRACKET_CLOSE;
index++;
return OK;
- };
+ }
case '[': {
r_token.type = TK_BRACKET_OPEN;
index++;
return OK;
- };
+ }
case ']': {
r_token.type = TK_BRACKET_CLOSE;
index++;
return OK;
- };
+ }
case ':': {
r_token.type = TK_COLON;
index++;
return OK;
- };
+ }
case ',': {
r_token.type = TK_COMMA;
index++;
return OK;
- };
+ }
case '"': {
index++;
String str;
diff --git a/core/io/marshalls.h b/core/io/marshalls.h
index c21a97ac8a..c8ed497528 100644
--- a/core/io/marshalls.h
+++ b/core/io/marshalls.h
@@ -106,7 +106,7 @@ static inline int encode_cstring(const char *p_string, uint8_t *p_data) {
}
p_string++;
len++;
- };
+ }
if (p_data) {
*p_data = 0;
diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp
index 6d37d95994..dacd548a3e 100644
--- a/core/io/packet_peer.cpp
+++ b/core/io/packet_peer.cpp
@@ -147,7 +147,7 @@ void PacketPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_encode_buffer_max_size", "max_size"), &PacketPeer::set_encode_buffer_max_size);
ADD_PROPERTY(PropertyInfo(Variant::INT, "encode_buffer_max_size"), "set_encode_buffer_max_size", "get_encode_buffer_max_size");
-};
+}
/***************/
@@ -267,7 +267,7 @@ void PacketPeerStream::set_stream_peer(const Ref<StreamPeer> &p_peer) {
if (p_peer.ptr() != peer.ptr()) {
ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer
- };
+ }
peer = p_peer;
}
diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp
index 06d22ce897..374b2a5e07 100644
--- a/core/io/pck_packer.cpp
+++ b/core/io/pck_packer.cpp
@@ -45,19 +45,19 @@ static uint64_t _align(uint64_t p_n, int p_alignment) {
} else {
return p_n + (p_alignment - rest);
}
-};
+}
static void _pad(FileAccess *p_file, int p_bytes) {
for (int i = 0; i < p_bytes; i++) {
p_file->store_8(0);
- };
-};
+ }
+}
void PCKPacker::_bind_methods() {
ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start, DEFVAL(0));
ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file);
ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush, DEFVAL(false));
-};
+}
Error PCKPacker::pck_start(const String &p_file, int p_alignment) {
if (file != nullptr) {
@@ -78,18 +78,18 @@ Error PCKPacker::pck_start(const String &p_file, int p_alignment) {
for (int i = 0; i < 16; i++) {
file->store_32(0); // reserved
- };
+ }
files.clear();
return OK;
-};
+}
Error PCKPacker::add_file(const String &p_file, const String &p_src) {
FileAccess *f = FileAccess::open(p_src, FileAccess::READ);
if (!f) {
return ERR_FILE_CANT_OPEN;
- };
+ }
File pf;
pf.path = p_file;
@@ -103,7 +103,7 @@ Error PCKPacker::add_file(const String &p_file, const String &p_src) {
memdelete(f);
return OK;
-};
+}
Error PCKPacker::flush(bool p_verbose) {
ERR_FAIL_COND_V_MSG(!file, ERR_INVALID_PARAMETER, "File must be opened before use.");
@@ -123,7 +123,7 @@ Error PCKPacker::flush(bool p_verbose) {
file->store_32(0);
file->store_32(0);
file->store_32(0);
- };
+ }
uint64_t ofs = file->get_position();
ofs = _align(ofs, alignment);
@@ -141,7 +141,7 @@ Error PCKPacker::flush(bool p_verbose) {
int read = src->get_buffer(buf, MIN(to_write, buf_max));
file->store_buffer(buf, read);
to_write -= read;
- };
+ }
uint64_t pos = file->get_position();
file->seek(files[i].offset_offset); // go back to store the file's offset
@@ -158,9 +158,9 @@ Error PCKPacker::flush(bool p_verbose) {
if (count % 100 == 0) {
printf("%i/%i (%.2f)\r", count, files.size(), float(count) / files.size() * 100);
fflush(stdout);
- };
- };
- };
+ }
+ }
+ }
if (p_verbose) {
printf("\n");
@@ -170,11 +170,11 @@ Error PCKPacker::flush(bool p_verbose) {
memdelete_arr(buf);
return OK;
-};
+}
PCKPacker::~PCKPacker() {
if (file != nullptr) {
memdelete(file);
- };
+ }
file = nullptr;
-};
+}
diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp
index 11f82fef9d..b11267b60f 100644
--- a/core/io/xml_parser.cpp
+++ b/core/io/xml_parser.cpp
@@ -361,7 +361,7 @@ void XMLParser::_parse_current_node() {
uint64_t XMLParser::get_node_offset() const {
return node_offset;
-};
+}
Error XMLParser::seek(uint64_t p_pos) {
ERR_FAIL_COND_V(!data, ERR_FILE_EOF);
@@ -370,7 +370,7 @@ Error XMLParser::seek(uint64_t p_pos) {
P = data + p_pos;
return read();
-};
+}
void XMLParser::_bind_methods() {
ClassDB::bind_method(D_METHOD("read"), &XMLParser::read);
@@ -398,7 +398,7 @@ void XMLParser::_bind_methods() {
BIND_ENUM_CONSTANT(NODE_COMMENT);
BIND_ENUM_CONSTANT(NODE_CDATA);
BIND_ENUM_CONSTANT(NODE_UNKNOWN);
-};
+}
Error XMLParser::read() {
// if not end reached, parse the node
diff --git a/core/io/zip_io.cpp b/core/io/zip_io.cpp
index 1979e91b8c..b8e7fd34d0 100644
--- a/core/io/zip_io.cpp
+++ b/core/io/zip_io.cpp
@@ -80,7 +80,7 @@ long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) {
break;
default:
break;
- };
+ }
f->seek(pos);
return 0;
diff --git a/core/list.h b/core/list.h
index 86e4a45036..6052a619fb 100644
--- a/core/list.h
+++ b/core/list.h
@@ -63,70 +63,70 @@ public:
*/
_FORCE_INLINE_ const Element *next() const {
return next_ptr;
- };
+ }
/**
* Get NEXT Element iterator,
*/
_FORCE_INLINE_ Element *next() {
return next_ptr;
- };
+ }
/**
* Get PREV Element iterator, for constant lists.
*/
_FORCE_INLINE_ const Element *prev() const {
return prev_ptr;
- };
+ }
/**
* Get PREV Element iterator,
*/
_FORCE_INLINE_ Element *prev() {
return prev_ptr;
- };
+ }
/**
* * operator, for using as *iterator, when iterators are defined on stack.
*/
_FORCE_INLINE_ const T &operator*() const {
return value;
- };
+ }
/**
* operator->, for using as iterator->, when iterators are defined on stack, for constant lists.
*/
_FORCE_INLINE_ const T *operator->() const {
return &value;
- };
+ }
/**
* * operator, for using as *iterator, when iterators are defined on stack,
*/
_FORCE_INLINE_ T &operator*() {
return value;
- };
+ }
/**
* operator->, for using as iterator->, when iterators are defined on stack, for constant lists.
*/
_FORCE_INLINE_ T *operator->() {
return &value;
- };
+ }
/**
* get the value stored in this element.
*/
_FORCE_INLINE_ T &get() {
return value;
- };
+ }
/**
* get the value stored in this element, for constant lists
*/
_FORCE_INLINE_ const T &get() const {
return value;
- };
+ }
/**
* set the value stored in this element.
*/
_FORCE_INLINE_ void set(const T &p_value) {
value = (T &)p_value;
- };
+ }
void erase() {
data->erase(this);
@@ -147,7 +147,7 @@ private:
if (first == p_I) {
first = p_I->next_ptr;
- };
+ }
if (last == p_I) {
last = p_I->prev_ptr;
@@ -176,28 +176,28 @@ public:
*/
_FORCE_INLINE_ const Element *front() const {
return _data ? _data->first : nullptr;
- };
+ }
/**
* return an iterator to the beginning of the list.
*/
_FORCE_INLINE_ Element *front() {
return _data ? _data->first : nullptr;
- };
+ }
/**
* return a const iterator to the last member of the list.
*/
_FORCE_INLINE_ const Element *back() const {
return _data ? _data->last : nullptr;
- };
+ }
/**
* return an iterator to the last member of the list.
*/
_FORCE_INLINE_ Element *back() {
return _data ? _data->last : nullptr;
- };
+ }
/**
* store a new element at the end of the list
@@ -230,7 +230,7 @@ public:
_data->size_cache++;
return n;
- };
+ }
void pop_back() {
if (_data && _data->last) {
@@ -268,7 +268,7 @@ public:
_data->size_cache++;
return n;
- };
+ }
void pop_front() {
if (_data && _data->first) {
@@ -339,10 +339,10 @@ public:
return it;
}
it = it->next();
- };
+ }
return nullptr;
- };
+ }
/**
* erase an element in the list, by iterator pointing to it. Return true if it was found/erased.
@@ -360,7 +360,7 @@ public:
}
return false;
- };
+ }
/**
* erase the first element in the list, that contains value
@@ -368,7 +368,7 @@ public:
bool erase(const T &value) {
Element *I = find(value);
return erase(I);
- };
+ }
/**
* return whether the list is empty
@@ -383,8 +383,8 @@ public:
void clear() {
while (front()) {
erase(front());
- };
- };
+ }
+ }
_FORCE_INLINE_ int size() const {
return _data ? _data->size_cache : 0;
@@ -464,7 +464,7 @@ public:
if (_data->first == p_I) {
_data->first = p_I->next_ptr;
- };
+ }
if (_data->last == p_I) {
_data->last = p_I->prev_ptr;
@@ -501,7 +501,7 @@ public:
if (_data->first == p_I) {
_data->first = p_I->next_ptr;
- };
+ }
if (_data->last == p_I) {
_data->last = p_I->prev_ptr;
@@ -536,7 +536,7 @@ public:
value->prev_ptr = _data->last;
_data->last = value;
return;
- };
+ }
value->prev_ptr = where->prev_ptr;
@@ -544,10 +544,10 @@ public:
where->prev_ptr->next_ptr = value;
} else {
_data->first = value;
- };
+ }
where->prev_ptr = value;
- };
+ }
/**
* simple insertion sort
@@ -672,7 +672,7 @@ public:
ERR_FAIL_COND(_data->size_cache);
memdelete_allocator<_Data, A>(_data);
}
- };
+ }
};
#endif // LIST_H
diff --git a/core/local_vector.h b/core/local_vector.h
index c8abb32bf5..b09a28b25a 100644
--- a/core/local_vector.h
+++ b/core/local_vector.h
@@ -185,8 +185,8 @@ public:
for (i = 0; i < count; i++) {
if (p_val < data[i]) {
break;
- };
- };
+ }
+ }
insert(i, p_val);
}
diff --git a/core/make_binders.py b/core/make_binders.py
index 94bee95bfb..7d0d08cde6 100644
--- a/core/make_binders.py
+++ b/core/make_binders.py
@@ -75,7 +75,7 @@ public:
#endif
$ifret _set_returns(true); $
- };
+ }
};
template<class T $ifret ,class R$ $ifargs ,$ $arg, class P@$>
@@ -170,7 +170,7 @@ public:
$ifret _set_returns(true); $
- };
+ }
};
template<class T $ifret ,class R$ $ifargs ,$ $arg, class P@$>
@@ -266,7 +266,7 @@ public:
#endif
$ifret _set_returns(true); $
- };
+ }
};
template<class T $ifret ,class R$ $ifargs ,$ $arg, class P@$>
diff --git a/core/map.h b/core/map.h
index 4861d6a026..fd4f500556 100644
--- a/core/map.h
+++ b/core/map.h
@@ -74,19 +74,19 @@ public:
}
const K &key() const {
return _key;
- };
+ }
V &value() {
return _value;
- };
+ }
const V &value() const {
return _value;
- };
+ }
V &get() {
return _value;
- };
+ }
const V &get() const {
return _value;
- };
+ }
Element() {}
};
diff --git a/core/math/aabb.h b/core/math/aabb.h
index 9bbedfe59c..4106fbb93c 100644
--- a/core/math/aabb.h
+++ b/core/math/aabb.h
@@ -198,7 +198,7 @@ Vector3 AABB::get_endpoint(int p_point) const {
return Vector3(position.x + size.x, position.y + size.y, position.z);
case 7:
return Vector3(position.x + size.x, position.y + size.y, position.z + size.z);
- };
+ }
ERR_FAIL_V(Vector3());
}
diff --git a/core/math/camera_matrix.cpp b/core/math/camera_matrix.cpp
index 81c602d8fe..22ab83f358 100644
--- a/core/math/camera_matrix.cpp
+++ b/core/math/camera_matrix.cpp
@@ -116,18 +116,18 @@ void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_
left = -xmax + frustumshift;
right = xmax + frustumshift;
modeltranslation = p_intraocular_dist / 2.0;
- }; break;
+ } break;
case 2: { // right eye
left = -xmax - frustumshift;
right = xmax - frustumshift;
modeltranslation = -p_intraocular_dist / 2.0;
- }; break;
+ } break;
default: { // mono, should give the same result as set_perspective(p_fovy_degrees,p_aspect,p_z_near,p_z_far,p_flip_fov)
left = -xmax;
right = xmax;
modeltranslation = 0.0;
- }; break;
- };
+ } break;
+ }
set_frustum(left, right, -ymax, ymax, p_z_near, p_z_far);
@@ -157,14 +157,14 @@ void CameraMatrix::set_for_hmd(int p_eye, real_t p_aspect, real_t p_intraocular_
switch (p_eye) {
case 1: { // left eye
set_frustum(-f2 * p_z_near, f1 * p_z_near, -f3 * p_z_near, f3 * p_z_near, p_z_near, p_z_far);
- }; break;
+ } break;
case 2: { // right eye
set_frustum(-f1 * p_z_near, f2 * p_z_near, -f3 * p_z_near, f3 * p_z_near, p_z_near, p_z_far);
- }; break;
+ } break;
default: { // mono, does not apply here!
- }; break;
- };
-};
+ } break;
+ }
+}
void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar) {
set_identity();
diff --git a/core/math/expression.cpp b/core/math/expression.cpp
index 81c1e7f564..db3bf2f830 100644
--- a/core/math/expression.cpp
+++ b/core/math/expression.cpp
@@ -753,39 +753,39 @@ Error Expression::_get_token(Token &r_token) {
case 0: {
r_token.type = TK_EOF;
return OK;
- };
+ }
case '{': {
r_token.type = TK_CURLY_BRACKET_OPEN;
return OK;
- };
+ }
case '}': {
r_token.type = TK_CURLY_BRACKET_CLOSE;
return OK;
- };
+ }
case '[': {
r_token.type = TK_BRACKET_OPEN;
return OK;
- };
+ }
case ']': {
r_token.type = TK_BRACKET_CLOSE;
return OK;
- };
+ }
case '(': {
r_token.type = TK_PARENTHESIS_OPEN;
return OK;
- };
+ }
case ')': {
r_token.type = TK_PARENTHESIS_CLOSE;
return OK;
- };
+ }
case ',': {
r_token.type = TK_COMMA;
return OK;
- };
+ }
case ':': {
r_token.type = TK_COLON;
return OK;
- };
+ }
case '$': {
r_token.type = TK_INPUT;
int index = 0;
@@ -803,7 +803,7 @@ Error Expression::_get_token(Token &r_token) {
r_token.value = index;
return OK;
- };
+ }
case '=': {
cchar = GET_CHAR();
if (cchar == '=') {
@@ -814,7 +814,7 @@ Error Expression::_get_token(Token &r_token) {
return ERR_PARSE_ERROR;
}
return OK;
- };
+ }
case '!': {
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_NOT_EQUAL;
@@ -823,7 +823,7 @@ Error Expression::_get_token(Token &r_token) {
r_token.type = TK_OP_NOT;
}
return OK;
- };
+ }
case '>': {
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_GREATER_EQUAL;
@@ -835,7 +835,7 @@ Error Expression::_get_token(Token &r_token) {
r_token.type = TK_OP_GREATER;
}
return OK;
- };
+ }
case '<': {
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_LESS_EQUAL;
@@ -847,27 +847,27 @@ Error Expression::_get_token(Token &r_token) {
r_token.type = TK_OP_LESS;
}
return OK;
- };
+ }
case '+': {
r_token.type = TK_OP_ADD;
return OK;
- };
+ }
case '-': {
r_token.type = TK_OP_SUB;
return OK;
- };
+ }
case '/': {
r_token.type = TK_OP_DIV;
return OK;
- };
+ }
case '*': {
r_token.type = TK_OP_MUL;
return OK;
- };
+ }
case '%': {
r_token.type = TK_OP_MOD;
return OK;
- };
+ }
case '&': {
if (expression[str_ofs] == '&') {
r_token.type = TK_OP_AND;
@@ -876,7 +876,7 @@ Error Expression::_get_token(Token &r_token) {
r_token.type = TK_OP_BIT_AND;
}
return OK;
- };
+ }
case '|': {
if (expression[str_ofs] == '|') {
r_token.type = TK_OP_OR;
@@ -885,17 +885,17 @@ Error Expression::_get_token(Token &r_token) {
r_token.type = TK_OP_BIT_OR;
}
return OK;
- };
+ }
case '^': {
r_token.type = TK_OP_BIT_XOR;
return OK;
- };
+ }
case '~': {
r_token.type = TK_OP_BIT_INVERT;
return OK;
- };
+ }
case '"': {
String str;
while (true) {
@@ -1666,7 +1666,7 @@ Expression::ENode *Expression::_parse_expression() {
op = Variant::OP_BIT_NEGATE;
break;
default: {
- };
+ }
}
if (op == Variant::OP_MAX) { //stop appending stuff
diff --git a/core/math/geometry.cpp b/core/math/geometry.cpp
index f6f22e1db2..a4e9169a6f 100644
--- a/core/math/geometry.cpp
+++ b/core/math/geometry.cpp
@@ -42,16 +42,15 @@
// This implementation is very inefficient, commenting unless bugs happen. See the other one.
/*
bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
-
Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
for (int j = 0; j + 3 <= indices.size(); j += 3) {
int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
- if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
+ if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3])) {
return true;
+ }
}
return false;
}
-
*/
void Geometry::MeshData::optimize_vertices() {
diff --git a/core/math/rect2.h b/core/math/rect2.h
index 1b86dbd49a..14393325ec 100644
--- a/core/math/rect2.h
+++ b/core/math/rect2.h
@@ -156,7 +156,7 @@ struct Rect2 {
new_rect.size = new_rect.size - new_rect.position; //make relative again
return new_rect;
- };
+ }
inline bool has_point(const Point2 &p_point) const {
if (p_point.x < position.x) {
return false;
@@ -323,7 +323,7 @@ struct Rect2i {
new_rect.size = new_rect.size - new_rect.position; //make relative again
return new_rect;
- };
+ }
bool has_point(const Point2 &p_point) const {
if (p_point.x < position.x) {
return false;
diff --git a/core/math/triangulate.cpp b/core/math/triangulate.cpp
index 7fab36ff50..12bd384c6a 100644
--- a/core/math/triangulate.cpp
+++ b/core/math/triangulate.cpp
@@ -79,7 +79,7 @@ bool Triangulate::is_inside_triangle(real_t Ax, real_t Ay,
} else {
return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0));
}
-};
+}
bool Triangulate::snip(const Vector<Vector2> &p_contour, int u, int v, int w, int n, const Vector<int> &V, bool relaxed) {
int p;
diff --git a/core/math/vector2.cpp b/core/math/vector2.cpp
index 7f264ce119..233421e070 100644
--- a/core/math/vector2.cpp
+++ b/core/math/vector2.cpp
@@ -209,28 +209,29 @@ void Vector2i::operator-=(const Vector2i &p_v) {
Vector2i Vector2i::operator*(const Vector2i &p_v1) const {
return Vector2i(x * p_v1.x, y * p_v1.y);
-};
+}
Vector2i Vector2i::operator*(const int &rvalue) const {
return Vector2i(x * rvalue, y * rvalue);
-};
+}
+
void Vector2i::operator*=(const int &rvalue) {
x *= rvalue;
y *= rvalue;
-};
+}
Vector2i Vector2i::operator/(const Vector2i &p_v1) const {
return Vector2i(x / p_v1.x, y / p_v1.y);
-};
+}
Vector2i Vector2i::operator/(const int &rvalue) const {
return Vector2i(x / rvalue, y / rvalue);
-};
+}
void Vector2i::operator/=(const int &rvalue) {
x /= rvalue;
y /= rvalue;
-};
+}
Vector2i Vector2i::operator-() const {
return Vector2i(-x, -y);
diff --git a/core/math/vector2.h b/core/math/vector2.h
index e5774f1d55..8a08d3bf64 100644
--- a/core/math/vector2.h
+++ b/core/math/vector2.h
@@ -174,28 +174,29 @@ _FORCE_INLINE_ void Vector2::operator-=(const Vector2 &p_v) {
_FORCE_INLINE_ Vector2 Vector2::operator*(const Vector2 &p_v1) const {
return Vector2(x * p_v1.x, y * p_v1.y);
-};
+}
_FORCE_INLINE_ Vector2 Vector2::operator*(const real_t &rvalue) const {
return Vector2(x * rvalue, y * rvalue);
-};
+}
+
_FORCE_INLINE_ void Vector2::operator*=(const real_t &rvalue) {
x *= rvalue;
y *= rvalue;
-};
+}
_FORCE_INLINE_ Vector2 Vector2::operator/(const Vector2 &p_v1) const {
return Vector2(x / p_v1.x, y / p_v1.y);
-};
+}
_FORCE_INLINE_ Vector2 Vector2::operator/(const real_t &rvalue) const {
return Vector2(x / rvalue, y / rvalue);
-};
+}
_FORCE_INLINE_ void Vector2::operator/=(const real_t &rvalue) {
x /= rvalue;
y /= rvalue;
-};
+}
_FORCE_INLINE_ Vector2 Vector2::operator-() const {
return Vector2(-x, -y);
diff --git a/core/message_queue.cpp b/core/message_queue.cpp
index 8c71f760b2..6dcf24e7ed 100644
--- a/core/message_queue.cpp
+++ b/core/message_queue.cpp
@@ -155,6 +155,21 @@ Error MessageQueue::push_callable(const Callable &p_callable, const Variant **p_
return OK;
}
+Error MessageQueue::push_callable(const Callable &p_callable, VARIANT_ARG_DECLARE) {
+ VARIANT_ARGPTRS;
+
+ int argc = 0;
+
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL) {
+ break;
+ }
+ argc++;
+ }
+
+ return push_callable(p_callable, argptr, argc);
+}
+
void MessageQueue::statistics() {
Map<StringName, int> set_count;
Map<int, int> notify_count;
diff --git a/core/message_queue.h b/core/message_queue.h
index 8e50f1b2b7..7d13e26208 100644
--- a/core/message_queue.h
+++ b/core/message_queue.h
@@ -79,6 +79,7 @@ public:
Error push_notification(ObjectID p_id, int p_notification);
Error push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value);
Error push_callable(const Callable &p_callable, const Variant **p_args, int p_argcount, bool p_show_error = false);
+ Error push_callable(const Callable &p_callable, VARIANT_ARG_LIST);
Error push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_LIST);
Error push_notification(Object *p_object, int p_notification);
diff --git a/core/oa_hash_map.h b/core/oa_hash_map.h
index c595e445d5..775e17fdb5 100644
--- a/core/oa_hash_map.h
+++ b/core/oa_hash_map.h
@@ -48,17 +48,19 @@
*
* Only used keys and values are constructed. For free positions there's space
* in the arrays for each, but that memory is kept uninitialized.
+ *
+ * The assignment operator copy the pairs from one map to the other.
*/
template <class TKey, class TValue,
class Hasher = HashMapHasherDefault,
class Comparator = HashMapComparatorDefault<TKey>>
class OAHashMap {
private:
- TValue *values;
- TKey *keys;
- uint32_t *hashes;
+ TValue *values = nullptr;
+ TKey *keys = nullptr;
+ uint32_t *hashes = nullptr;
- uint32_t capacity;
+ uint32_t capacity = 0;
uint32_t num_elements = 0;
@@ -142,7 +144,9 @@ private:
void _resize_and_rehash(uint32_t p_new_capacity) {
uint32_t old_capacity = capacity;
- capacity = p_new_capacity;
+
+ // Capacity can't be 0.
+ capacity = MAX(1, p_new_capacity);
TKey *old_keys = keys;
TValue *old_values = values;
@@ -157,6 +161,11 @@ private:
hashes[i] = 0;
}
+ if (old_capacity == 0) {
+ // Nothing to do.
+ return;
+ }
+
for (uint32_t i = 0; i < old_capacity; i++) {
if (old_hashes[i] == EMPTY_HASH) {
continue;
@@ -341,17 +350,32 @@ public:
return it;
}
- OAHashMap(const OAHashMap &) = delete; // Delete the copy constructor so we don't get unexpected copies and dangling pointers.
- OAHashMap &operator=(const OAHashMap &) = delete; // Same for assignment operator.
+ OAHashMap(const OAHashMap &p_other) {
+ (*this) = p_other;
+ }
+
+ OAHashMap &operator=(const OAHashMap &p_other) {
+ if (capacity != 0) {
+ clear();
+ }
+
+ _resize_and_rehash(p_other.capacity);
+
+ for (Iterator it = p_other.iter(); it.valid; it = p_other.next_iter(it)) {
+ set(*it.key, *it.value);
+ }
+ return *this;
+ }
OAHashMap(uint32_t p_initial_capacity = 64) {
- capacity = p_initial_capacity;
+ // Capacity can't be 0.
+ capacity = MAX(1, p_initial_capacity);
keys = static_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
values = static_cast<TValue *>(Memory::alloc_static(sizeof(TValue) * capacity));
hashes = static_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
- for (uint32_t i = 0; i < p_initial_capacity; i++) {
+ for (uint32_t i = 0; i < capacity; i++) {
hashes[i] = EMPTY_HASH;
}
}
diff --git a/core/object.cpp b/core/object.cpp
index 0a4e8a5890..f3c5a13809 100644
--- a/core/object.cpp
+++ b/core/object.cpp
@@ -1000,7 +1000,7 @@ void Object::set_meta(const String &p_name, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL) {
metadata.erase(p_name);
return;
- };
+ }
metadata[p_name] = p_value;
}
diff --git a/core/ordered_hash_map.h b/core/ordered_hash_map.h
index 1f1be71741..e6a6340a2f 100644
--- a/core/ordered_hash_map.h
+++ b/core/ordered_hash_map.h
@@ -106,27 +106,27 @@ public:
const K &key() const {
CRASH_COND(!list_element);
return *(list_element->get().first);
- };
+ }
V &value() {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
const V &value() const {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
V &get() {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
const V &get() const {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
};
class ConstElement {
@@ -172,17 +172,17 @@ public:
const K &key() const {
CRASH_COND(!list_element);
return *(list_element->get().first);
- };
+ }
const V &value() const {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
const V &get() const {
CRASH_COND(!list_element);
return list_element->get().second;
- };
+ }
};
ConstElement find(const K &p_key) const {
diff --git a/core/os/dir_access.cpp b/core/os/dir_access.cpp
index 9f2672e038..5e1cb8ea29 100644
--- a/core/os/dir_access.cpp
+++ b/core/os/dir_access.cpp
@@ -131,7 +131,7 @@ Error DirAccess::erase_contents_recursive() {
Error DirAccess::make_dir_recursive(String p_dir) {
if (p_dir.length() < 1) {
return OK;
- };
+ }
String full_dir;
@@ -185,7 +185,7 @@ String DirAccess::fix_path(String p_path) const {
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
if (resource_path != "") {
return p_path.replace_first("res:/", resource_path);
- };
+ }
return p_path.replace_first("res://", "");
}
}
@@ -196,7 +196,7 @@ String DirAccess::fix_path(String p_path) const {
String data_dir = OS::get_singleton()->get_user_data_dir();
if (data_dir != "") {
return p_path.replace_first("user:/", data_dir);
- };
+ }
return p_path.replace_first("user://", "");
}
@@ -249,7 +249,7 @@ DirAccess *DirAccess::create(AccessType p_access) {
}
return da;
-};
+}
String DirAccess::get_full_path(const String &p_path, AccessType p_access) {
DirAccess *d = DirAccess::create(p_access);
diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp
index f9ba8ff2d2..20b3435911 100644
--- a/core/os/file_access.cpp
+++ b/core/os/file_access.cpp
@@ -65,7 +65,7 @@ bool FileAccess::exists(const String &p_name) {
void FileAccess::_set_access_type(AccessType p_access) {
_access_type = p_access;
-};
+}
FileAccess *FileAccess::create_for_path(const String &p_path) {
FileAccess *ret = nullptr;
@@ -83,7 +83,7 @@ FileAccess *FileAccess::create_for_path(const String &p_path) {
Error FileAccess::reopen(const String &p_path, int p_mode_flags) {
return _open(p_path, p_mode_flags);
-};
+}
FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) {
//try packed data first
@@ -115,7 +115,7 @@ FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_er
FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) {
return create_func[p_access];
-};
+}
String FileAccess::fix_path(const String &p_path) const {
//helper used by file accesses that use a single filesystem
@@ -129,7 +129,7 @@ String FileAccess::fix_path(const String &p_path) const {
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
if (resource_path != "") {
return r_path.replace("res:/", resource_path);
- };
+ }
return r_path.replace("res://", "");
}
}
@@ -140,7 +140,7 @@ String FileAccess::fix_path(const String &p_path) const {
String data_dir = OS::get_singleton()->get_user_data_dir();
if (data_dir != "") {
return r_path.replace("user:/", data_dir);
- };
+ }
return r_path.replace("user://", "");
}
@@ -215,7 +215,7 @@ float FileAccess::get_float() const {
MarshallFloat m;
m.i = get_32();
return m.f;
-};
+}
real_t FileAccess::get_real() const {
if (real_is_double) {
@@ -229,7 +229,7 @@ double FileAccess::get_double() const {
MarshallDouble m;
m.l = get_64();
return m.d;
-};
+}
String FileAccess::get_token() const {
CharString token;
@@ -447,13 +447,13 @@ void FileAccess::store_float(float p_dest) {
MarshallFloat m;
m.f = p_dest;
store_32(m.i);
-};
+}
void FileAccess::store_double(double p_dest) {
MarshallDouble m;
m.d = p_dest;
store_64(m.l);
-};
+}
uint64_t FileAccess::get_modified_time(const String &p_file) {
if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && PackedData::get_singleton()->has_path(p_file)) {
@@ -503,7 +503,7 @@ void FileAccess::store_pascal_string(const String &p_string) {
CharString cs = p_string.utf8();
store_32(cs.length());
store_buffer((uint8_t *)&cs[0], cs.length());
-};
+}
String FileAccess::get_pascal_string() {
uint32_t sl = get_32();
@@ -516,7 +516,7 @@ String FileAccess::get_pascal_string() {
ret.parse_utf8(cs.ptr());
return ret;
-};
+}
void FileAccess::store_line(const String &p_line) {
store_string(p_line);
diff --git a/core/os/os.cpp b/core/os/os.cpp
index b2f92d566e..c29930e485 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -85,7 +85,8 @@ uint64_t OS::get_splash_tick_msec() const {
uint64_t OS::get_unix_time() const {
return 0;
-};
+}
+
uint64_t OS::get_system_time_secs() const {
return 0;
}
@@ -126,7 +127,7 @@ void OS::print(const char *p_format, ...) {
_logger->logv(p_format, argp, false);
va_end(argp);
-};
+}
void OS::printerr(const char *p_format, ...) {
va_list argp;
@@ -135,7 +136,7 @@ void OS::printerr(const char *p_format, ...) {
_logger->logv(p_format, argp, true);
va_end(argp);
-};
+}
void OS::set_low_processor_usage_mode(bool p_enabled) {
low_processor_usage_mode = p_enabled;
@@ -159,7 +160,7 @@ String OS::get_executable_path() const {
int OS::get_process_id() const {
return -1;
-};
+}
void OS::vibrate_handheld(int p_duration_ms) {
WARN_PRINT("vibrate_handheld() only works with Android and iOS");
@@ -281,12 +282,12 @@ String OS::get_cache_path() const {
// Path to macOS .app bundle resources
String OS::get_bundle_resource_dir() const {
return ".";
-};
+}
// OS specific path for user://
String OS::get_user_data_dir() const {
return ".";
-};
+}
// Absolute path to res://
String OS::get_resource_dir() const {
@@ -300,7 +301,7 @@ String OS::get_system_dir(SystemDir p_dir) const {
Error OS::shell_open(String p_uri) {
return ERR_UNAVAILABLE;
-};
+}
// implement these with the canvas?
@@ -345,7 +346,7 @@ String OS::get_model_name() const {
void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) {
_execpath = p_execpath;
_cmdline = p_args;
-};
+}
String OS::get_unique_id() const {
ERR_FAIL_V("");
diff --git a/core/os/os.h b/core/os/os.h
index 9296e17bb2..9ca034a01c 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -58,7 +58,6 @@ class OS {
bool _allow_layered = false;
bool _use_vsync;
bool _vsync_via_compositor;
- bool _disable_wintab;
char *last_error;
@@ -148,7 +147,11 @@ public:
bool is_layered_allowed() const { return _allow_layered; }
bool is_hidpi_allowed() const { return _allow_hidpi; }
- bool is_wintab_disabled() const { return _disable_wintab; }
+
+ virtual int get_tablet_driver_count() const { return 0; };
+ virtual String get_tablet_driver_name(int p_driver) const { return ""; };
+ virtual String get_current_tablet_driver() const { return ""; };
+ virtual void set_current_tablet_driver(const String &p_driver){};
void ensure_user_data_dir();
diff --git a/core/os/thread.cpp b/core/os/thread.cpp
index 70f960ed2a..fc0ce3c9b4 100644
--- a/core/os/thread.cpp
+++ b/core/os/thread.cpp
@@ -63,4 +63,4 @@ Error Thread::set_name(const String &p_name) {
}
return ERR_UNAVAILABLE;
-};
+}
diff --git a/core/os/thread_dummy.cpp b/core/os/thread_dummy.cpp
index 9dcddcae11..2672cd7ad9 100644
--- a/core/os/thread_dummy.cpp
+++ b/core/os/thread_dummy.cpp
@@ -34,16 +34,16 @@
Thread *ThreadDummy::create(ThreadCreateCallback p_callback, void *p_user, const Thread::Settings &p_settings) {
return memnew(ThreadDummy);
-};
+}
void ThreadDummy::make_default() {
Thread::create_func = &ThreadDummy::create;
-};
+}
RWLock *RWLockDummy::create() {
return memnew(RWLockDummy);
-};
+}
void RWLockDummy::make_default() {
RWLock::create_func = &RWLockDummy::create;
-};
+}
diff --git a/core/packed_data_container.cpp b/core/packed_data_container.cpp
index b5aefd6f2c..e335ec0daa 100644
--- a/core/packed_data_container.cpp
+++ b/core/packed_data_container.cpp
@@ -44,7 +44,7 @@ Variant PackedDataContainer::getvar(const Variant &p_key, bool *r_valid) const {
int PackedDataContainer::size() const {
return _size(0);
-};
+}
Variant PackedDataContainer::_iter_init_ofs(const Array &p_iter, uint32_t p_offset) {
Array ref = p_iter;
@@ -124,7 +124,7 @@ uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const {
uint32_t type = decode_uint32(r);
return type;
-};
+}
int PackedDataContainer::_size(uint32_t p_ofs) const {
const uint8_t *rd = data.ptr();
@@ -139,10 +139,10 @@ int PackedDataContainer::_size(uint32_t p_ofs) const {
} else if (type == TYPE_DICT) {
uint32_t len = decode_uint32(r + 4);
return len;
- };
+ }
return -1;
-};
+}
Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const {
const uint8_t *rd = data.ptr();
@@ -368,7 +368,7 @@ Variant PackedDataContainerRef::_iter_get(const Variant &p_iter) {
bool PackedDataContainerRef::_is_dictionary() const {
return from->_type_at_ofs(offset) == PackedDataContainer::TYPE_DICT;
-};
+}
void PackedDataContainerRef::_bind_methods() {
ClassDB::bind_method(D_METHOD("size"), &PackedDataContainerRef::size);
@@ -389,4 +389,4 @@ Variant PackedDataContainerRef::getvar(const Variant &p_key, bool *r_valid) cons
int PackedDataContainerRef::size() const {
return from->_size(offset);
-};
+}
diff --git a/core/pool_allocator.cpp b/core/pool_allocator.cpp
index 1dd215a787..b222c20a00 100644
--- a/core/pool_allocator.cpp
+++ b/core/pool_allocator.cpp
@@ -341,7 +341,7 @@ Error PoolAllocator::resize(ID p_mem, int p_new_size) {
if (uint32_t(_free + aligned(e->len)) < alloc_size) {
mt_unlock();
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
- };
+ }
EntryIndicesPos entry_indices_pos;
@@ -358,7 +358,7 @@ Error PoolAllocator::resize(ID p_mem, int p_new_size) {
next_pos = pool_size; // - static_area_size;
} else {
next_pos = entry_array[entry_indices[entry_indices_pos + 1]].pos;
- };
+ }
if ((next_pos - e->pos) > alloc_size) {
free_mem += aligned(e->len);
@@ -564,8 +564,8 @@ PoolAllocator::PoolAllocator(void *p_mem, int p_size, int p_align, bool p_needs_
mem8 += p_align - (ofs % p_align);
p_size -= dif;
p_mem = (void *)mem8;
- };
- };
+ }
+ }
create_pool(p_mem, p_size, p_max_entries);
needs_locking = p_needs_locking;
diff --git a/core/project_settings.cpp b/core/project_settings.cpp
index cedc7f731f..5247f6da40 100644
--- a/core/project_settings.cpp
+++ b/core/project_settings.cpp
@@ -51,7 +51,7 @@ ProjectSettings *ProjectSettings::get_singleton() {
String ProjectSettings::get_resource_path() const {
return resource_path;
-};
+}
String ProjectSettings::localize_path(const String &p_path) const {
if (resource_path == "") {
@@ -87,7 +87,7 @@ String ProjectSettings::localize_path(const String &p_path) const {
if (!cwd.begins_with(res_path)) {
return p_path;
- };
+ }
return cwd.replace_first(res_path, "res://");
} else {
@@ -96,20 +96,20 @@ String ProjectSettings::localize_path(const String &p_path) const {
int sep = path.find_last("/");
if (sep == -1) {
return "res://" + path;
- };
+ }
String parent = path.substr(0, sep);
String plocal = localize_path(parent);
if (plocal == "") {
return "";
- };
+ }
// Only strip the starting '/' from 'path' if its parent ('plocal') ends with '/'
if (plocal[plocal.length() - 1] == '/') {
sep += 1;
}
return plocal + path.substr(sep, path.size() - sep);
- };
+ }
}
void ProjectSettings::set_initial_value(const String &p_name, const Variant &p_value) {
@@ -126,13 +126,13 @@ String ProjectSettings::globalize_path(const String &p_path) const {
if (p_path.begins_with("res://")) {
if (resource_path != "") {
return p_path.replace("res:/", resource_path);
- };
+ }
return p_path.replace("res://", "");
} else if (p_path.begins_with("user://")) {
String data_dir = OS::get_singleton()->get_user_data_dir();
if (data_dir != "") {
return p_path.replace("user:/", data_dir);
- };
+ }
return p_path.replace("user://", "");
}
@@ -295,10 +295,16 @@ void ProjectSettings::_convert_to_last_version(int p_from_version) {
* using the following merit order:
* - If using NetworkClient, try to lookup project file or fail.
* - If --main-pack was passed by the user (`p_main_pack`), load it or fail.
- * - Search for .pck file matching binary name. There are two possibilities:
- * o exec_path.get_basename() + '.pck' (e.g. 'win_game.exe' -> 'win_game.pck')
- * o exec_path + '.pck' (e.g. 'linux_game' -> 'linux_game.pck')
- * For each tentative, if the file exists, load it or fail.
+ * - Search for project PCKs automatically. For each step we try loading a potential
+ * PCK, and if it doesn't work, we proceed to the next step. If any step succeeds,
+ * we try loading the project settings, and abort if it fails. Steps:
+ * o Bundled PCK in the executable.
+ * o [macOS only] PCK with same basename as the binary in the .app resource dir.
+ * o PCK with same basename as the binary in the binary's directory. We handle both
+ * changing the extension to '.pck' (e.g. 'win_game.exe' -> 'win_game.pck') and
+ * appending '.pck' to the binary name (e.g. 'linux_game' -> 'linux_game.pck').
+ * o PCK with the same basename as the binary in the current working directory.
+ * Same as above for the two possible PCK file names.
* - On relevant platforms (Android/iOS), lookup project file in OS resource path.
* If found, load it or fail.
* - Lookup project file in passed `p_path` (--path passed by the user), i.e. we
@@ -339,65 +345,68 @@ Error ProjectSettings::_setup(const String &p_path, const String &p_main_pack, b
String exec_path = OS::get_singleton()->get_executable_path();
if (exec_path != "") {
- // Attempt with exec_name.pck
- // (This is the usual case when distributing a Godot game.)
+ // We do several tests sequentially until one succeeds to find a PCK,
+ // and if so we attempt loading it at the end.
- // Based on the OS, it can be the exec path + '.pck' (Linux w/o extension, macOS in .app bundle)
- // or the exec path's basename + '.pck' (Windows).
- // We need to test both possibilities as extensions for Linux binaries are optional
- // (so both 'mygame.bin' and 'mygame' should be able to find 'mygame.pck').
+ // Attempt with PCK bundled into executable.
+ bool found = _load_resource_pack(exec_path);
+ // Attempt with exec_name.pck.
+ // (This is the usual case when distributing a Godot game.)
String exec_dir = exec_path.get_base_dir();
String exec_filename = exec_path.get_file();
String exec_basename = exec_filename.get_basename();
- // Attempt with PCK bundled into executable
- bool found = _load_resource_pack(exec_path);
+ // Based on the OS, it can be the exec path + '.pck' (Linux w/o extension, macOS in .app bundle)
+ // or the exec path's basename + '.pck' (Windows).
+ // We need to test both possibilities as extensions for Linux binaries are optional
+ // (so both 'mygame.bin' and 'mygame' should be able to find 'mygame.pck').
#ifdef OSX_ENABLED
if (!found) {
- // Attempt to load PCK from macOS .app bundle resources
+ // Attempt to load PCK from macOS .app bundle resources.
found = _load_resource_pack(OS::get_singleton()->get_bundle_resource_dir().plus_file(exec_basename + ".pck"));
}
#endif
if (!found) {
- // Try to load data pack at the location of the executable
- // As mentioned above, we have two potential names to attempt
+ // Try to load data pack at the location of the executable.
+ // As mentioned above, we have two potential names to attempt.
found = _load_resource_pack(exec_dir.plus_file(exec_basename + ".pck")) || _load_resource_pack(exec_dir.plus_file(exec_filename + ".pck"));
+ }
- if (!found) {
- // If we couldn't find them next to the executable, we attempt
- // the current working directory. Same story, two tests.
- found = _load_resource_pack(exec_basename + ".pck") || _load_resource_pack(exec_filename + ".pck");
- }
+ if (!found) {
+ // If we couldn't find them next to the executable, we attempt
+ // the current working directory. Same story, two tests.
+ found = _load_resource_pack(exec_basename + ".pck") || _load_resource_pack(exec_filename + ".pck");
}
- // If we opened our package, try and load our project
+ // If we opened our package, try and load our project.
if (found) {
Error err = _load_settings_text_or_binary("res://project.godot", "res://project.binary");
if (err == OK) {
- // Load override from location of executable
- // Optional, we don't mind if it fails
+ // Load override from location of the executable.
+ // Optional, we don't mind if it fails.
_load_settings_text(exec_path.get_base_dir().plus_file("override.cfg"));
}
return err;
}
}
- // Try to use the filesystem for files, according to OS. (only Android -when reading from pck- and iOS use this)
+ // Try to use the filesystem for files, according to OS.
+ // (Only Android -when reading from pck- and iOS use this.)
if (OS::get_singleton()->get_resource_dir() != "") {
// OS will call ProjectSettings->get_resource_path which will be empty if not overridden!
// If the OS would rather use a specific location, then it will not be empty.
resource_path = OS::get_singleton()->get_resource_dir().replace("\\", "/");
if (resource_path != "" && resource_path[resource_path.length() - 1] == '/') {
- resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
+ resource_path = resource_path.substr(0, resource_path.length() - 1); // Chop end.
}
Error err = _load_settings_text_or_binary("res://project.godot", "res://project.binary");
if (err == OK) {
- // Optional, we don't mind if it fails
+ // Optional, we don't mind if it fails.
_load_settings_text("res://override.cfg");
}
return err;
@@ -418,7 +427,7 @@ Error ProjectSettings::_setup(const String &p_path, const String &p_main_pack, b
while (true) {
err = _load_settings_text_or_binary(current_dir.plus_file("project.godot"), current_dir.plus_file("project.binary"));
if (err == OK) {
- // Optional, we don't mind if it fails
+ // Optional, we don't mind if it fails.
_load_settings_text(current_dir.plus_file("override.cfg"));
candidate = current_dir;
found = true;
@@ -438,7 +447,7 @@ Error ProjectSettings::_setup(const String &p_path, const String &p_main_pack, b
}
resource_path = candidate;
- resource_path = resource_path.replace("\\", "/"); // windows path to unix path just in case
+ resource_path = resource_path.replace("\\", "/"); // Windows path to Unix path just in case.
memdelete(d);
if (!found) {
@@ -446,7 +455,7 @@ Error ProjectSettings::_setup(const String &p_path, const String &p_main_pack, b
}
if (resource_path.length() && resource_path[resource_path.length() - 1] == '/') {
- resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
+ resource_path = resource_path.substr(0, resource_path.length() - 1); // Chop end.
}
return OK;
@@ -759,7 +768,7 @@ Error ProjectSettings::_save_settings_text(const String &p_file, const Map<Strin
Error ProjectSettings::_save_custom_bnd(const String &p_file) { // add other params as dictionary and array?
return save_custom(p_file);
-};
+}
Error ProjectSettings::save_custom(const String &p_path, const CustomMap &p_custom, const Vector<String> &p_custom_features, bool p_merge_with_current) {
ERR_FAIL_COND_V_MSG(p_path == "", ERR_INVALID_PARAMETER, "Project settings save path cannot be empty.");
diff --git a/core/ring_buffer.h b/core/ring_buffer.h
index 2fd622b86f..6b71d12cf3 100644
--- a/core/ring_buffer.h
+++ b/core/ring_buffer.h
@@ -45,13 +45,13 @@ class RingBuffer {
p_var += p_size;
p_var = p_var & size_mask;
return ret;
- };
+ }
public:
T read() {
ERR_FAIL_COND_V(space_left() < 1, T());
return data.ptr()[inc(read_pos, 1)];
- };
+ }
int read(T *p_buf, int p_size, bool p_advance = true) {
int left = data_left();
@@ -66,15 +66,15 @@ public:
const T *read = data.ptr();
for (int i = 0; i < total; i++) {
p_buf[dst++] = read[pos + i];
- };
+ }
to_read -= total;
pos = 0;
- };
+ }
if (p_advance) {
inc(read_pos, p_size);
- };
+ }
return p_size;
- };
+ }
int copy(T *p_buf, int p_offset, int p_size) const {
int left = data_left();
@@ -95,12 +95,12 @@ public:
int total = end - pos;
for (int i = 0; i < total; i++) {
p_buf[dst++] = data[pos + i];
- };
+ }
to_read -= total;
pos = 0;
- };
+ }
return p_size;
- };
+ }
int find(const T &t, int p_offset, int p_max_size) const {
int left = data_left();
@@ -122,7 +122,7 @@ public:
if (data[pos + i] == t) {
return i + (p_max_size - to_read);
}
- };
+ }
to_read -= total;
pos = 0;
}
@@ -133,7 +133,7 @@ public:
p_n = MIN(p_n, data_left());
inc(read_pos, p_n);
return p_n;
- };
+ }
inline int decrease_write(int p_n) {
p_n = MIN(p_n, data_left());
@@ -145,7 +145,7 @@ public:
ERR_FAIL_COND_V(space_left() < 1, FAILED);
data.write[inc(write_pos, 1)] = p_v;
return OK;
- };
+ }
int write(const T *p_buf, int p_size) {
int left = space_left();
@@ -161,32 +161,32 @@ public:
for (int i = 0; i < total; i++) {
data.write[pos + i] = p_buf[src++];
- };
+ }
to_write -= total;
pos = 0;
- };
+ }
inc(write_pos, p_size);
return p_size;
- };
+ }
inline int space_left() const {
int left = read_pos - write_pos;
if (left < 0) {
return size() + left - 1;
- };
+ }
if (left == 0) {
return size() - 1;
- };
+ }
return left - 1;
- };
+ }
inline int data_left() const {
return size() - space_left() - 1;
- };
+ }
inline int size() const {
return data.size();
- };
+ }
inline void clear() {
read_pos = 0;
@@ -201,19 +201,19 @@ public:
if (old_size < new_size && read_pos > write_pos) {
for (int i = 0; i < write_pos; i++) {
data.write[(old_size + i) & mask] = data[i];
- };
+ }
write_pos = (old_size + write_pos) & mask;
} else {
read_pos = read_pos & mask;
write_pos = write_pos & mask;
- };
+ }
size_mask = mask;
- };
+ }
RingBuffer<T>(int p_power = 0) {
resize(p_power);
- };
+ }
~RingBuffer<T>() {}
};
diff --git a/core/translation.cpp b/core/translation.cpp
index f3c1489ce4..4f835bd7b4 100644
--- a/core/translation.cpp
+++ b/core/translation.cpp
@@ -873,7 +873,7 @@ void Translation::get_message_list(List<StringName> *r_messages) const {
int Translation::get_message_count() const {
return translation_map.size();
-};
+}
void Translation::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_locale", "locale"), &Translation::set_locale);
@@ -1022,7 +1022,7 @@ void TranslationServer::remove_translation(const Ref<Translation> &p_translation
void TranslationServer::clear() {
translations.clear();
-};
+}
StringName TranslationServer::translate(const StringName &p_message) const {
// Match given message against the translation catalog for the project locale.
diff --git a/core/ustring.cpp b/core/ustring.cpp
index ed096bd475..7dbaed9fbe 100644
--- a/core/ustring.cpp
+++ b/core/ustring.cpp
@@ -247,15 +247,6 @@ String String::operator+(const String &p_str) const {
return res;
}
-/*
-String String::operator+(CharType p_chr) const {
-
- String res=*this;
- res+=p_chr;
- return res;
-}
-
-*/
String &String::operator+=(const String &p_str) {
if (empty()) {
*this = p_str;
@@ -1371,7 +1362,7 @@ String String::utf8(const char *p_utf8, int p_len) {
ret.parse_utf8(p_utf8, p_len);
return ret;
-};
+}
bool String::parse_utf8(const char *p_utf8, int p_len) {
#define _UNICERROR(m_err) print_line("Unicode parsing error: " + String(m_err) + ". Is the string valid UTF-8?");
@@ -1608,6 +1599,7 @@ String::String(CharType p_char) {
copy_from(p_char);
}
+
*/
String::String(const char *p_str) {
@@ -1833,7 +1825,7 @@ int String::to_int(const char *p_str, int p_len) {
bool String::is_numeric() const {
if (length() == 0) {
return false;
- };
+ }
int s = 0;
if (operator[](0) == '-') {
@@ -1845,16 +1837,16 @@ bool String::is_numeric() const {
if (c == '.') {
if (dot) {
return false;
- };
+ }
dot = true;
}
if (c < '0' || c > '9') {
return false;
- };
- };
+ }
+ }
return true; // TODO: Use the parser below for this instead
-};
+}
template <class C>
static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number,
@@ -2278,7 +2270,7 @@ Vector<uint8_t> String::md5_buffer() const {
ret.write[i] = hash[i];
}
return ret;
-};
+}
Vector<uint8_t> String::sha1_buffer() const {
CharString cs = utf8();
@@ -2387,7 +2379,7 @@ int String::find(const String &p_str, int p_from) const {
if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
- };
+ }
if (src[read_pos] != str[j]) {
found = false;
@@ -2439,7 +2431,7 @@ int String::find(const char *p_str, int p_from) const {
if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
- };
+ }
if (src[read_pos] != p_str[j]) {
found = false;
@@ -2495,7 +2487,7 @@ int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
if (read_pos >= len) {
found = false;
break;
- };
+ }
if (src[read_pos] != cmp[j]) {
found = false;
@@ -2536,7 +2528,7 @@ int String::findn(const String &p_str, int p_from) const {
if (read_pos >= length()) {
ERR_PRINT("read_pos>=length()");
return -1;
- };
+ }
CharType src = _find_lower(srcd[read_pos]);
CharType dst = _find_lower(p_str[j]);
@@ -2586,7 +2578,7 @@ int String::rfind(const String &p_str, int p_from) const {
if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
- };
+ }
if (src[read_pos] != p_str[j]) {
found = false;
@@ -2633,7 +2625,7 @@ int String::rfindn(const String &p_str, int p_from) const {
if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
- };
+ }
CharType srcc = _find_lower(src[read_pos]);
CharType dstc = _find_lower(p_str[j]);
@@ -3691,7 +3683,7 @@ bool String::is_valid_hex_number(bool p_with_prefix) const {
}
return true;
-};
+}
bool String::is_valid_float() const {
int len = length();
@@ -3851,11 +3843,11 @@ bool String::is_valid_ip_address() const {
return false;
}
continue;
- };
+ }
if (!n.is_valid_ip_address()) {
return false;
}
- };
+ }
} else {
Vector<String> ip = split(".");
@@ -3872,7 +3864,7 @@ bool String::is_valid_ip_address() const {
return false;
}
}
- };
+ }
return true;
}
diff --git a/core/variant.cpp b/core/variant.cpp
index 62d710e493..21aaa0fe9e 100644
--- a/core/variant.cpp
+++ b/core/variant.cpp
@@ -191,7 +191,7 @@ bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) {
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
- };
+ }
const Type *valid_types = nullptr;
const Type *invalid_types = nullptr;
@@ -498,7 +498,7 @@ bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
- };
+ }
const Type *valid_types = nullptr;
@@ -870,11 +870,6 @@ bool Variant::is_zero() const {
return *reinterpret_cast<const Plane *>(_data._mem) == Plane();
} break;
- /*
- case QUAT: {
-
-
- } break;*/
case AABB: {
return *_data._aabb == ::AABB();
} break;
@@ -1284,7 +1279,7 @@ void Variant::clear() {
COLOR,
VECTOR2,
RECT2
- */
+ */
case TRANSFORM2D: {
memdelete(_data._transform2d);
} break;
@@ -1421,26 +1416,6 @@ Variant::operator int64_t() const {
}
}
-/*
-Variant::operator long unsigned int() const {
-
- switch( type ) {
-
- case NIL: return 0;
- case BOOL: return _data._bool ? 1 : 0;
- case INT: return _data._int;
- case FLOAT: return _data._real;
- case STRING: return operator String().to_int();
- default: {
-
- return 0;
- }
- }
-
- return 0;
-};
-*/
-
Variant::operator uint64_t() const {
switch (type) {
case NIL:
@@ -1488,7 +1463,7 @@ Variant::operator signed long() const {
}
return 0;
-};
+}
Variant::operator unsigned long() const {
switch (type) {
@@ -1508,7 +1483,7 @@ Variant::operator unsigned long() const {
}
return 0;
-};
+}
#endif
Variant::operator signed short() const {
@@ -1858,7 +1833,7 @@ String Variant::stringify(List<const void *> &stack) const {
if (_get_obj().obj) {
if (!_get_obj().id.is_reference() && ObjectDB::get_instance(_get_obj().id) == nullptr) {
return "[Freed Object]";
- };
+ }
return _get_obj().obj->to_string();
} else {
@@ -2075,7 +2050,7 @@ Variant::operator RID() const {
#ifdef DEBUG_ENABLED
if (EngineDebugger::is_active()) {
ERR_FAIL_COND_V_MSG(ObjectDB::get_instance(_get_obj().id) == nullptr, RID(), "Invalid pointer (object was freed).");
- };
+ }
#endif
Callable::CallError ce;
Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid, nullptr, 0, ce);
@@ -2387,14 +2362,6 @@ Variant::Variant(bool p_bool) {
_data._bool = p_bool;
}
-/*
-Variant::Variant(long unsigned int p_long) {
-
- type=INT;
- _data._int=p_long;
-};
-*/
-
Variant::Variant(signed int p_int) {
type = INT;
_data._int = p_int;
@@ -2939,11 +2906,6 @@ uint32_t Variant::hash() const {
return hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->d, hash);
} break;
- /*
- case QUAT: {
-
-
- } break;*/
case AABB: {
uint32_t hash = 5831;
for (int i = 0; i < 3; i++) {
diff --git a/core/variant.h b/core/variant.h
index b24cf968de..50b7a21eda 100644
--- a/core/variant.h
+++ b/core/variant.h
@@ -219,10 +219,10 @@ public:
bool is_ref() const;
_FORCE_INLINE_ bool is_num() const {
return type == INT || type == FLOAT;
- };
+ }
_FORCE_INLINE_ bool is_array() const {
return type >= ARRAY;
- };
+ }
bool is_shared() const;
bool is_zero() const;
bool is_one() const;
diff --git a/core/variant_call.cpp b/core/variant_call.cpp
index 82b1f29805..404468a7b4 100644
--- a/core/variant_call.cpp
+++ b/core/variant_call.cpp
@@ -1174,6 +1174,9 @@ struct _VariantCall {
List<StringName> value_ordered;
#endif
Map<StringName, Variant> variant_value;
+#ifdef DEBUG_ENABLED
+ List<StringName> variant_value_ordered;
+#endif
};
static ConstantData *constant_data;
@@ -1187,6 +1190,9 @@ struct _VariantCall {
static void add_variant_constant(int p_type, StringName p_constant_name, const Variant &p_constant_value) {
constant_data[p_type].variant_value[p_constant_name] = p_constant_value;
+#ifdef DEBUG_ENABLED
+ constant_data[p_type].variant_value_ordered.push_back(p_constant_name);
+#endif
}
};
@@ -1652,8 +1658,13 @@ void Variant::get_constants_for_type(Variant::Type p_type, List<StringName> *p_c
#endif
}
+#ifdef DEBUG_ENABLED
+ for (List<StringName>::Element *E = cd.variant_value_ordered.front(); E; E = E->next()) {
+ p_constants->push_back(E->get());
+#else
for (Map<StringName, Variant>::Element *E = cd.variant_value.front(); E; E = E->next()) {
p_constants->push_back(E->key());
+#endif
}
}
diff --git a/core/variant_op.cpp b/core/variant_op.cpp
index 8641187f97..2c79e2029e 100644
--- a/core/variant_op.cpp
+++ b/core/variant_op.cpp
@@ -189,7 +189,7 @@ bool Variant::booleanize() const {
_RETURN(p_a._data.m_type m_op p_b._data._float); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_NUM_NULL(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -201,7 +201,7 @@ bool Variant::booleanize() const {
_RETURN(!(p_b.type m_op NIL)); \
\
_RETURN_FAIL \
- };
+ }
#ifdef DEBUG_ENABLED
#define DEFAULT_OP_NUM_DIV(m_prefix, m_op_name, m_name, m_type) \
@@ -222,7 +222,7 @@ bool Variant::booleanize() const {
} \
\
_RETURN_FAIL \
- };
+ }
#else
#define DEFAULT_OP_NUM_DIV(m_prefix, m_op_name, m_name, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -232,18 +232,18 @@ bool Variant::booleanize() const {
_RETURN(p_a._data.m_type / p_b._data._float); \
\
_RETURN_FAIL \
- };
+ }
#endif
#define DEFAULT_OP_NUM_NEG(m_prefix, m_op_name, m_name, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
_RETURN(-p_a._data.m_type); \
- };
+ }
#define DEFAULT_OP_NUM_POS(m_prefix, m_op_name, m_name, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
_RETURN(p_a._data.m_type); \
- };
+ }
#define DEFAULT_OP_NUM_VEC(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -261,7 +261,7 @@ bool Variant::booleanize() const {
_RETURN(p_a._data.m_type m_op *reinterpret_cast<const Vector3 *>(p_b._data._mem)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_STR_REV(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -273,7 +273,7 @@ bool Variant::booleanize() const {
_RETURN(*reinterpret_cast<const m_type *>(p_b._data._mem) m_op *reinterpret_cast<const NodePath *>(p_a._data._mem)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_STR(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -285,7 +285,7 @@ bool Variant::booleanize() const {
_RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const NodePath *>(p_b._data._mem)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_STR_NULL(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -299,7 +299,7 @@ bool Variant::booleanize() const {
_RETURN(!(p_b.type m_op NIL)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_STR_NULL_NP(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -311,7 +311,7 @@ bool Variant::booleanize() const {
_RETURN(!(p_b.type m_op NIL)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_STR_NULL_SN(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -323,7 +323,7 @@ bool Variant::booleanize() const {
_RETURN(!(p_b.type m_op NIL)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_LOCALMEM_REV(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -331,7 +331,7 @@ bool Variant::booleanize() const {
_RETURN(*reinterpret_cast<const m_type *>(p_b._data._mem) m_op *reinterpret_cast<const m_type *>(p_a._data._mem)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_LOCALMEM(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -339,7 +339,7 @@ bool Variant::booleanize() const {
_RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const m_type *>(p_b._data._mem)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_LOCALMEM_NULL(m_prefix, m_op_name, m_name, m_op, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
@@ -349,7 +349,7 @@ bool Variant::booleanize() const {
_RETURN(!(p_b.type m_op NIL)); \
\
_RETURN_FAIL \
- };
+ }
#define DEFAULT_OP_LOCALMEM_NEG(m_prefix, m_op_name, m_name, m_type) \
CASE_TYPE(m_prefix, m_op_name, m_name) { \
diff --git a/core/variant_parser.cpp b/core/variant_parser.cpp
index 9fe98265dd..bdcad03353 100644
--- a/core/variant_parser.cpp
+++ b/core/variant_parser.cpp
@@ -110,7 +110,7 @@ Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, Stri
case '\n': {
line++;
break;
- };
+ }
case 0: {
r_token.type = TK_EOF;
return OK;
@@ -118,31 +118,31 @@ Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, Stri
case '{': {
r_token.type = TK_CURLY_BRACKET_OPEN;
return OK;
- };
+ }
case '}': {
r_token.type = TK_CURLY_BRACKET_CLOSE;
return OK;
- };
+ }
case '[': {
r_token.type = TK_BRACKET_OPEN;
return OK;
- };
+ }
case ']': {
r_token.type = TK_BRACKET_CLOSE;
return OK;
- };
+ }
case '(': {
r_token.type = TK_PARENTHESIS_OPEN;
return OK;
- };
+ }
case ')': {
r_token.type = TK_PARENTHESIS_CLOSE;
return OK;
- };
+ }
case ':': {
r_token.type = TK_COLON;
return OK;
- };
+ }
case ';': {
while (true) {
CharType ch = p_stream->get_char();
@@ -156,19 +156,19 @@ Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, Stri
}
break;
- };
+ }
case ',': {
r_token.type = TK_COMMA;
return OK;
- };
+ }
case '.': {
r_token.type = TK_PERIOD;
return OK;
- };
+ }
case '=': {
r_token.type = TK_EQUAL;
return OK;
- };
+ }
case '#': {
StringBuffer<> color_str;
color_str += '#';
@@ -189,7 +189,7 @@ Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, Stri
r_token.value = Color::html(color_str.as_string());
r_token.type = TK_COLOR;
return OK;
- };
+ }
case '@': {
cchar = p_stream->get_char();
if (cchar != '"') {
diff --git a/core/vector.h b/core/vector.h
index 696984ac28..4c152fb084 100644
--- a/core/vector.h
+++ b/core/vector.h
@@ -113,8 +113,8 @@ public:
for (i = 0; i < _cowdata.size(); i++) {
if (p_val < operator[](i)) {
break;
- };
- };
+ }
+ }
insert(i, p_val);
}
diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml
index 90828089f9..7fe712753c 100644
--- a/doc/classes/DisplayServer.xml
+++ b/doc/classes/DisplayServer.xml
@@ -592,6 +592,10 @@
</argument>
<argument index="2" name="max_length" type="int" default="-1">
</argument>
+ <argument index="3" name="cursor_start" type="int" default="-1">
+ </argument>
+ <argument index="4" name="cursor_end" type="int" default="-1">
+ </argument>
<description>
</description>
</method>
diff --git a/doc/classes/KinematicBody3D.xml b/doc/classes/KinematicBody3D.xml
index 830d63ed11..5477c6bab6 100644
--- a/doc/classes/KinematicBody3D.xml
+++ b/doc/classes/KinematicBody3D.xml
@@ -18,7 +18,7 @@
<argument index="0" name="axis" type="int" enum="PhysicsServer3D.BodyAxis">
</argument>
<description>
- Returns [code]true[/code] if the specified [code]axis[/code] is locked. See also [member move_lock_x], [member move_lock_y] and [member move_lock_z].
+ Returns [code]true[/code] if the specified [code]axis[/code] is locked. See also [member axis_lock_motion_x], [member axis_lock_motion_y] and [member axis_lock_motion_z].
</description>
</method>
<method name="get_floor_normal" qualifiers="const">
@@ -145,7 +145,7 @@
<argument index="1" name="lock" type="bool">
</argument>
<description>
- Locks or unlocks the specified [code]axis[/code] depending on the value of [code]lock[/code]. See also [member move_lock_x], [member move_lock_y] and [member move_lock_z].
+ Locks or unlocks the specified [code]axis[/code] depending on the value of [code]lock[/code]. See also [member axis_lock_motion_x], [member axis_lock_motion_y] and [member axis_lock_motion_z].
</description>
</method>
<method name="test_move">
@@ -163,18 +163,18 @@
</method>
</methods>
<members>
- <member name="collision/safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.001">
- If the body is at least this close to another body, this body will consider them to be colliding.
- </member>
- <member name="move_lock_x" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
+ <member name="axis_lock_motion_x" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
Lock the body's X axis movement.
</member>
- <member name="move_lock_y" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
+ <member name="axis_lock_motion_y" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
Lock the body's Y axis movement.
</member>
- <member name="move_lock_z" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
+ <member name="axis_lock_motion_z" type="bool" setter="set_axis_lock" getter="get_axis_lock" default="false">
Lock the body's Z axis movement.
</member>
+ <member name="collision/safe_margin" type="float" setter="set_safe_margin" getter="get_safe_margin" default="0.001">
+ If the body is at least this close to another body, this body will consider them to be colliding.
+ </member>
</members>
<constants>
</constants>
diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index 6a70297f40..03203e2ebb 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -268,6 +268,24 @@
Returns the epoch time of the operating system in seconds.
</description>
</method>
+ <method name="get_tablet_driver_count" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ Returns the total number of available tablet drivers.
+ [b]Note:[/b] This method is implemented on Windows.
+ </description>
+ </method>
+ <method name="get_tablet_driver_name" qualifiers="const">
+ <return type="String">
+ </return>
+ <argument index="0" name="idx" type="int">
+ </argument>
+ <description>
+ Returns the tablet driver name for the given index.
+ [b]Note:[/b] This method is implemented on Windows.
+ </description>
+ </method>
<method name="get_ticks_msec" qualifiers="const">
<return type="int">
</return>
@@ -500,6 +518,9 @@
<member name="low_processor_usage_mode_sleep_usec" type="int" setter="set_low_processor_usage_mode_sleep_usec" getter="get_low_processor_usage_mode_sleep_usec" default="6900">
The amount of sleeping between frames when the low-processor usage mode is enabled (in microseconds). Higher values will result in lower CPU usage.
</member>
+ <member name="tablet_driver" type="String" setter="set_current_tablet_driver" getter="get_current_tablet_driver" default="&quot;&quot;">
+ The current tablet drvier in use.
+ </member>
</members>
<constants>
<constant name="VIDEO_DRIVER_GLES2" value="0" enum="VideoDriver">
diff --git a/doc/classes/PopupMenu.xml b/doc/classes/PopupMenu.xml
index 59450b7ea2..ce55c90c68 100644
--- a/doc/classes/PopupMenu.xml
+++ b/doc/classes/PopupMenu.xml
@@ -591,7 +591,7 @@
</method>
</methods>
<members>
- <member name="allow_search" type="bool" setter="set_allow_search" getter="get_allow_search" default="false">
+ <member name="allow_search" type="bool" setter="set_allow_search" getter="get_allow_search" default="true">
If [code]true[/code], allows to navigate [PopupMenu] with letter keys.
</member>
<member name="hide_on_checkable_item_selection" type="bool" setter="set_hide_on_checkable_item_selection" getter="is_hide_on_checkable_item_selection" default="true">
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 055af18e25..daf8cb1d2f 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -414,9 +414,6 @@
<member name="display/mouse_cursor/tooltip_position_offset" type="Vector2" setter="" getter="" default="Vector2( 10, 10 )">
Position offset for tooltips, relative to the mouse cursor's hotspot.
</member>
- <member name="display/window/disable_wintab_api" type="bool" setter="" getter="" default="false">
- Disables WinTab API and always use Windows Ink API for the pen input (Windows only).
- </member>
<member name="display/window/dpi/allow_hidpi" type="bool" setter="" getter="" default="false">
If [code]true[/code], allows HiDPI display on Windows and macOS. This setting has no effect on desktop Linux, as DPI-awareness fallbacks are not supported there.
</member>
@@ -453,6 +450,9 @@
<member name="display/window/size/width" type="int" setter="" getter="" default="1024">
Sets the game's main viewport width. On desktop platforms, this is the default window size. Stretch mode settings also use this as a reference when enabled.
</member>
+ <member name="display/window/tablet_driver" type="String" setter="" getter="" default="&quot;&quot;">
+ Specifies the tablet driver to use. If left empty, the default driver will be used.
+ </member>
<member name="display/window/vsync/use_vsync" type="bool" setter="" getter="" default="true">
If [code]true[/code], enables vertical synchronization. This eliminates tearing that may appear in moving scenes, at the cost of higher input latency and stuttering at lower framerates. If [code]false[/code], vertical synchronization will be disabled, however, many platforms will enforce it regardless (such as mobile platforms and HTML5).
</member>
diff --git a/doc/classes/TabContainer.xml b/doc/classes/TabContainer.xml
index 22e92ae5d9..d56781105b 100644
--- a/doc/classes/TabContainer.xml
+++ b/doc/classes/TabContainer.xml
@@ -204,8 +204,8 @@
<theme_item name="font_color_fg" type="Color" default="Color( 0.94, 0.94, 0.94, 1 )">
Font color of the currently selected tab.
</theme_item>
- <theme_item name="hseparation" type="int" default="4">
- Horizontal separation between tabs.
+ <theme_item name="icon_separation" type="int" default="4">
+ Space between tab's name and its icon.
</theme_item>
<theme_item name="increment" type="Texture2D">
Icon for the right arrow button that appears when there are too many tabs to fit in the container width. When the button is disabled (i.e. the last tab is visible) it appears semi-transparent.
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index e553518b39..0c6615c53b 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -299,7 +299,7 @@
</description>
</method>
<method name="search" qualifiers="const">
- <return type="PackedInt32Array">
+ <return type="Dictionary">
</return>
<argument index="0" name="key" type="String">
</argument>
@@ -311,13 +311,13 @@
</argument>
<description>
Perform a search inside the text. Search flags can be specified in the [enum SearchFlags] enum.
- Returns an empty [code]PackedInt32Array[/code] if no result was found. Otherwise, the result line and column can be accessed at indices specified in the [enum SearchResult] enum, e.g:
+ Returns an empty [code]Dictionary[/code] if no result was found. Otherwise, returns a [code]Dictionary[/code] containing [code]line[/code] and [code]column[/code] entries, e.g:
[codeblock]
var result = search(key, flags, line, column)
- if result.size() &gt; 0:
+ if !result.empty():
# Result found.
- var res_line = result[TextEdit.SEARCH_RESULT_LINE]
- var res_column = result[TextEdit.SEARCH_RESULT_COLUMN]
+ var line_number = result.line
+ var column_number = result.column
[/codeblock]
</description>
</method>
@@ -536,12 +536,6 @@
<constant name="SEARCH_BACKWARDS" value="4" enum="SearchFlags">
Search from end to beginning.
</constant>
- <constant name="SEARCH_RESULT_COLUMN" value="0" enum="SearchResult">
- Used to access the result column from [method search].
- </constant>
- <constant name="SEARCH_RESULT_LINE" value="1" enum="SearchResult">
- Used to access the result line from [method search].
- </constant>
<constant name="MENU_CUT" value="0" enum="MenuItems">
Cuts (copies and clears) the selected text.
</constant>
diff --git a/drivers/dummy/rasterizer_dummy.h b/drivers/dummy/rasterizer_dummy.h
index d619a20745..7af7678f63 100644
--- a/drivers/dummy/rasterizer_dummy.h
+++ b/drivers/dummy/rasterizer_dummy.h
@@ -861,6 +861,13 @@ public:
texture_owner.free(p_rid);
memdelete(texture);
}
+
+ if (mesh_owner.owns(p_rid)) {
+ // delete the mesh
+ DummyMesh *mesh = mesh_owner.getornull(p_rid);
+ mesh_owner.free(p_rid);
+ memdelete(mesh);
+ }
return true;
}
diff --git a/editor/SCsub b/editor/SCsub
index 13ae85bbf0..651dd5fffd 100644
--- a/editor/SCsub
+++ b/editor/SCsub
@@ -6,6 +6,7 @@ env.editor_sources = []
import os
import os.path
+import glob
from platform_methods import run_in_subprocess
import editor_builders
@@ -40,20 +41,21 @@ if env["tools"]:
f.write(reg_exporters_inc)
f.write(reg_exporters)
- # API documentation
+ # Core API documentation.
docs = []
- doc_dirs = ["doc/classes"]
+ docs += Glob("#doc/classes/*.xml")
- for p in env.doc_class_path.values():
- if p not in doc_dirs:
- doc_dirs.append(p)
+ # Module API documentation.
+ module_dirs = []
+ for d in env.doc_class_path.values():
+ if d not in module_dirs:
+ module_dirs.append(d)
- for d in doc_dirs:
- try:
- for f in os.listdir(os.path.join(env.Dir("#").abspath, d)):
- docs.append("#" + os.path.join(d, f))
- except OSError:
- pass
+ for d in module_dirs:
+ if not os.path.isabs(d):
+ docs += Glob("#" + d + "/*.xml") # Built-in.
+ else:
+ docs += Glob(d + "/*.xml") # Custom.
_make_doc_data_class_path(os.path.join(env.Dir("#").abspath, "editor"))
@@ -61,8 +63,6 @@ if env["tools"]:
env.Depends("#editor/doc_data_compressed.gen.h", docs)
env.CommandNoCache("#editor/doc_data_compressed.gen.h", docs, run_in_subprocess(editor_builders.make_doc_header))
- import glob
-
path = env.Dir(".").abspath
# Editor translations
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 2a8e0d856e..75e7542abb 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -4882,12 +4882,12 @@ void AnimationTrackEditor::_box_selection_draw() {
void AnimationTrackEditor::_scroll_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> mb = p_event;
- if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_DOWN) {
+ if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_UP) {
timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() * 1.05);
scroll->accept_event();
}
- if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_UP) {
+ if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_DOWN) {
timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() / 1.05);
scroll->accept_event();
}
diff --git a/editor/doc_data.h b/editor/doc_data.h
index 06d0889af6..8c93bfa597 100644
--- a/editor/doc_data.h
+++ b/editor/doc_data.h
@@ -42,6 +42,9 @@ public:
String type;
String enumeration;
String default_value;
+ bool operator<(const ArgumentDoc &p_arg) const {
+ return name < p_arg.name;
+ }
};
struct MethodDoc {
@@ -51,8 +54,8 @@ public:
String qualifiers;
String description;
Vector<ArgumentDoc> arguments;
- bool operator<(const MethodDoc &p_md) const {
- return name < p_md.name;
+ bool operator<(const MethodDoc &p_method) const {
+ return name < p_method.name;
}
};
@@ -61,6 +64,9 @@ public:
String value;
String enumeration;
String description;
+ bool operator<(const ConstantDoc &p_const) const {
+ return name < p_const.name;
+ }
};
struct PropertyDoc {
@@ -70,13 +76,10 @@ public:
String description;
String setter, getter;
String default_value;
- bool overridden;
+ bool overridden = false;
bool operator<(const PropertyDoc &p_prop) const {
return name < p_prop.name;
}
- PropertyDoc() {
- overridden = false;
- }
};
struct ClassDoc {
@@ -91,6 +94,9 @@ public:
Vector<ConstantDoc> constants;
Vector<PropertyDoc> properties;
Vector<PropertyDoc> theme_properties;
+ bool operator<(const ClassDoc &p_class) const {
+ return name < p_class.name;
+ }
};
String version;
diff --git a/editor/editor_feature_profile.cpp b/editor/editor_feature_profile.cpp
index d3749477cc..2a410c03e7 100644
--- a/editor/editor_feature_profile.cpp
+++ b/editor/editor_feature_profile.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "editor_feature_profile.h"
+
#include "core/io/json.h"
#include "core/os/dir_access.h"
#include "editor/editor_settings.h"
@@ -353,7 +354,7 @@ void EditorFeatureProfileManager::_update_profile_list(const String &p_select_pr
}
if (name == current_profile) {
- name += " (current)";
+ name += " " + TTR("(current)");
}
profile_list->add_item(name);
int index = profile_list->get_item_count() - 1;
@@ -363,12 +364,15 @@ void EditorFeatureProfileManager::_update_profile_list(const String &p_select_pr
}
}
+ class_list_vbc->set_visible(selected_profile != String());
+ property_list_vbc->set_visible(selected_profile != String());
+ no_profile_selected_help->set_visible(selected_profile == String());
profile_actions[PROFILE_CLEAR]->set_disabled(current_profile == String());
profile_actions[PROFILE_ERASE]->set_disabled(selected_profile == String());
profile_actions[PROFILE_EXPORT]->set_disabled(selected_profile == String());
profile_actions[PROFILE_SET]->set_disabled(selected_profile == String());
- current_profile_name->set_text(current_profile);
+ current_profile_name->set_text(current_profile != String() ? current_profile : TTR("(none)"));
_update_selected_profile();
}
@@ -451,6 +455,10 @@ void EditorFeatureProfileManager::_create_new_profile() {
new_profile->save_to_file(file);
_update_profile_list(name);
+ // The newly created profile is the first one, make it the current profile automatically.
+ if (profile_list->get_item_count() == 1) {
+ _profile_action(PROFILE_SET);
+ }
}
void EditorFeatureProfileManager::_profile_selected(int p_what) {
@@ -730,6 +738,10 @@ void EditorFeatureProfileManager::_import_profiles(const Vector<String> &p_paths
}
_update_profile_list();
+ // The newly imported profile is the first one, make it the current profile automatically.
+ if (profile_list->get_item_count() == 1) {
+ _profile_action(PROFILE_SET);
+ }
}
void EditorFeatureProfileManager::_export_profile(const String &p_path) {
@@ -779,6 +791,7 @@ EditorFeatureProfileManager::EditorFeatureProfileManager() {
HBoxContainer *name_hbc = memnew(HBoxContainer);
current_profile_name = memnew(LineEdit);
name_hbc->add_child(current_profile_name);
+ current_profile_name->set_text(TTR("(none)"));
current_profile_name->set_editable(false);
current_profile_name->set_h_size_flags(Control::SIZE_EXPAND_FILL);
profile_actions[PROFILE_CLEAR] = memnew(Button(TTR("Unset")));
@@ -827,7 +840,7 @@ EditorFeatureProfileManager::EditorFeatureProfileManager() {
h_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
main_vbc->add_child(h_split);
- VBoxContainer *class_list_vbc = memnew(VBoxContainer);
+ class_list_vbc = memnew(VBoxContainer);
h_split->add_child(class_list_vbc);
class_list_vbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
@@ -837,17 +850,30 @@ EditorFeatureProfileManager::EditorFeatureProfileManager() {
class_list->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
class_list->connect("cell_selected", callable_mp(this, &EditorFeatureProfileManager::_class_list_item_selected));
class_list->connect("item_edited", callable_mp(this, &EditorFeatureProfileManager::_class_list_item_edited), varray(), CONNECT_DEFERRED);
+ // It will be displayed once the user creates or chooses a profile.
+ class_list_vbc->hide();
- VBoxContainer *property_list_vbc = memnew(VBoxContainer);
+ property_list_vbc = memnew(VBoxContainer);
h_split->add_child(property_list_vbc);
property_list_vbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
property_list = memnew(Tree);
- property_list_vbc->add_margin_child(TTR("Class Options"), property_list, true);
+ property_list_vbc->add_margin_child(TTR("Class Options:"), property_list, true);
property_list->set_hide_root(true);
property_list->set_hide_folding(true);
property_list->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
property_list->connect("item_edited", callable_mp(this, &EditorFeatureProfileManager::_property_item_edited), varray(), CONNECT_DEFERRED);
+ // It will be displayed once the user creates or chooses a profile.
+ property_list_vbc->hide();
+
+ no_profile_selected_help = memnew(Label(TTR("Create or import a profile to edit available classes and properties.")));
+ // Add some spacing above the help label.
+ Ref<StyleBoxEmpty> sb = memnew(StyleBoxEmpty);
+ sb->set_default_margin(MARGIN_TOP, 20 * EDSCALE);
+ no_profile_selected_help->add_theme_style_override("normal", sb);
+ no_profile_selected_help->set_align(Label::ALIGN_CENTER);
+ no_profile_selected_help->set_v_size_flags(Control::SIZE_EXPAND_FILL);
+ h_split->add_child(no_profile_selected_help);
new_profile_dialog = memnew(ConfirmationDialog);
new_profile_dialog->set_title(TTR("New profile name:"));
diff --git a/editor/editor_feature_profile.h b/editor/editor_feature_profile.h
index 4036ec7ec6..38413e35a2 100644
--- a/editor/editor_feature_profile.h
+++ b/editor/editor_feature_profile.h
@@ -120,8 +120,11 @@ class EditorFeatureProfileManager : public AcceptDialog {
HSplitContainer *h_split;
+ VBoxContainer *class_list_vbc;
Tree *class_list;
+ VBoxContainer *property_list_vbc;
Tree *property_list;
+ Label *no_profile_selected_help;
EditorFileDialog *import_profiles;
EditorFileDialog *export_profile;
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index a16605ab44..5f293f1fb3 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -503,17 +503,38 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_initial_set("editors/grid_map/pick_distance", 5000.0);
// 3D
- _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56));
- hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ _initial_set("editors/3d/primary_grid_color", Color(0.56, 0.56, 0.56, 0.5));
+ hints["editors/3d/primary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/primary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT);
- _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38));
- hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_COLOR_NO_ALPHA, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
-
- _initial_set("editors/3d/grid_size", 50);
- hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,500,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ _initial_set("editors/3d/secondary_grid_color", Color(0.38, 0.38, 0.38, 0.5));
+ hints["editors/3d/secondary_grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/secondary_grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT);
+ // If a line is a multiple of this, it uses the primary grid color.
_initial_set("editors/3d/primary_grid_steps", 10);
- hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ hints["editors/3d/primary_grid_steps"] = PropertyInfo(Variant::INT, "editors/3d/primary_grid_steps", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT);
+
+ // At 1000, the grid mostly looks like it has no edge.
+ _initial_set("editors/3d/grid_size", 200);
+ hints["editors/3d/grid_size"] = PropertyInfo(Variant::INT, "editors/3d/grid_size", PROPERTY_HINT_RANGE, "1,2000,1", PROPERTY_USAGE_DEFAULT);
+
+ // Default largest grid size is 100m, 10^2 (primary grid lines are 1km apart when primary_grid_steps is 10).
+ _initial_set("editors/3d/grid_division_level_max", 2);
+ // Higher values produce graphical artifacts when far away unless View Z-Far
+ // is increased significantly more than it really should need to be.
+ hints["editors/3d/grid_division_level_max"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_max", PROPERTY_HINT_RANGE, "-1,3,1", PROPERTY_USAGE_DEFAULT);
+
+ // Default smallest grid size is 1cm, 10^-2.
+ _initial_set("editors/3d/grid_division_level_min", -2);
+ // Lower values produce graphical artifacts regardless of view clipping planes, so limit to -2 as a lower bound.
+ hints["editors/3d/grid_division_level_min"] = PropertyInfo(Variant::INT, "editors/3d/grid_division_level_min", PROPERTY_HINT_RANGE, "-2,2,1", PROPERTY_USAGE_DEFAULT);
+
+ // -0.2 seems like a sensible default. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
+ _initial_set("editors/3d/grid_division_level_bias", -0.2);
+ hints["editors/3d/grid_division_level_bias"] = PropertyInfo(Variant::FLOAT, "editors/3d/grid_division_level_bias", PROPERTY_HINT_RANGE, "-1.0,0.5,0.1", PROPERTY_USAGE_DEFAULT);
+
+ _initial_set("editors/3d/grid_xz_plane", true);
+ _initial_set("editors/3d/grid_xy_plane", false);
+ _initial_set("editors/3d/grid_yz_plane", false);
_initial_set("editors/3d/default_fov", 70.0);
_initial_set("editors/3d/default_z_near", 0.05);
diff --git a/editor/icons/SCsub b/editor/icons/SCsub
index f0d51999f0..e143276259 100644
--- a/editor/icons/SCsub
+++ b/editor/icons/SCsub
@@ -2,6 +2,8 @@
Import("env")
+import os
+
from platform_methods import run_in_subprocess
import editor_icons_builders
@@ -15,7 +17,10 @@ env["BUILDERS"]["MakeEditorIconsBuilder"] = make_editor_icons_builder
icon_sources = Glob("*.svg")
# Module icons
-for module_icons in env.module_icons_paths:
- icon_sources += Glob("#" + module_icons + "/*.svg")
+for path in env.module_icons_paths:
+ if not os.path.isabs(path):
+ icon_sources += Glob("#" + path + "/*.svg") # Built-in.
+ else:
+ icon_sources += Glob(path + "/*.svg") # Custom.
env.Alias("editor_icons", [env.MakeEditorIconsBuilder("#editor/editor_icons.gen.h", icon_sources)])
diff --git a/editor/import_dock.cpp b/editor/import_dock.cpp
index 1128b72c5a..8ab2e0aef1 100644
--- a/editor/import_dock.cpp
+++ b/editor/import_dock.cpp
@@ -441,7 +441,9 @@ void ImportDock::_reimport() {
} else {
//override entirely
config->set_value("remap", "importer", importer_name);
- config->erase_section("params");
+ if (config->has_section("params")) {
+ config->erase_section("params");
+ }
for (List<PropertyInfo>::Element *E = params->properties.front(); E; E = E->next()) {
config->set_value("params", E->get().name, params->values[E->get().name]);
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 744c7907af..8f88612ffa 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -2240,7 +2240,7 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
return true;
}
- if (k.is_valid() && !k->is_pressed() && drag_type == DRAG_KEY_MOVE && tool == TOOL_SELECT &&
+ if (k.is_valid() && !k->is_pressed() && drag_type == DRAG_KEY_MOVE && (tool == TOOL_SELECT || tool == TOOL_MOVE) &&
(k->get_keycode() == KEY_UP || k->get_keycode() == KEY_DOWN || k->get_keycode() == KEY_LEFT || k->get_keycode() == KEY_RIGHT)) {
// Confirm canvas items move by arrow keys
if ((!Input::get_singleton()->is_key_pressed(KEY_UP)) &&
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 3c12022854..8466ee86e5 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -328,17 +328,13 @@ void Node3DEditorViewport::_update_camera(float p_interp_delta) {
//-------
// Apply camera transform
- float tolerance = 0.001;
+ real_t tolerance = 0.001;
bool equal = true;
- if (Math::abs(old_camera_cursor.x_rot - camera_cursor.x_rot) > tolerance || Math::abs(old_camera_cursor.y_rot - camera_cursor.y_rot) > tolerance) {
+ if (!Math::is_equal_approx(old_camera_cursor.x_rot, camera_cursor.x_rot, tolerance) || !Math::is_equal_approx(old_camera_cursor.y_rot, camera_cursor.y_rot, tolerance)) {
equal = false;
- }
-
- if (equal && old_camera_cursor.pos.distance_squared_to(camera_cursor.pos) > tolerance * tolerance) {
+ } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
equal = false;
- }
-
- if (equal && Math::abs(old_camera_cursor.distance - camera_cursor.distance) > tolerance) {
+ } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
equal = false;
}
@@ -356,6 +352,7 @@ void Node3DEditorViewport::_update_camera(float p_interp_delta) {
update_transform_gizmo_view();
rotation_control->update();
}
+ spatial_editor->update_grid();
}
Transform Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
@@ -4929,8 +4926,10 @@ void Node3DEditor::_menu_item_pressed(int p_option) {
for (int i = 0; i < 3; ++i) {
if (grid_enable[i]) {
- RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled);
grid_visible[i] = grid_enabled;
+ if (grid_instance[i].is_valid()) {
+ RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled);
+ }
}
}
@@ -5054,6 +5053,7 @@ void Node3DEditor::_init_indicators() {
indicator_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
indicator_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
indicator_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
+ indicator_mat->set_transparency(StandardMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
Vector<Color> origin_colors;
Vector<Vector3> origin_points;
@@ -5082,12 +5082,27 @@ void Node3DEditor::_init_indicators() {
origin_colors.push_back(origin_color);
origin_colors.push_back(origin_color);
- origin_points.push_back(axis * 4096);
- origin_points.push_back(axis * -4096);
- }
-
- grid_enable[1] = true;
- grid_visible[1] = true;
+ origin_colors.push_back(origin_color);
+ origin_colors.push_back(origin_color);
+ origin_colors.push_back(origin_color);
+ origin_colors.push_back(origin_color);
+ // To both allow having a large origin size and avoid jitter
+ // at small scales, we should segment the line into pieces.
+ // 3 pieces seems to do the trick, and let's use powers of 2.
+ origin_points.push_back(axis * 1048576);
+ origin_points.push_back(axis * 1024);
+ origin_points.push_back(axis * 1024);
+ origin_points.push_back(axis * -1024);
+ origin_points.push_back(axis * -1024);
+ origin_points.push_back(axis * -1048576);
+ }
+
+ grid_enable[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
+ grid_enable[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
+ grid_enable[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
+ grid_visible[0] = grid_enable[0];
+ grid_visible[1] = grid_enable[1];
+ grid_visible[2] = grid_enable[2];
_init_grid();
@@ -5418,6 +5433,15 @@ void Node3DEditor::_update_gizmos_menu_theme() {
}
void Node3DEditor::_init_grid() {
+ if (!grid_enabled) {
+ return;
+ }
+ Camera3D *camera = get_editor_viewport(0)->camera;
+ Vector3 camera_position = camera->get_translation();
+ if (camera_position == Vector3()) {
+ return; // Camera3D is invalid, don't draw the grid.
+ }
+
Vector<Color> grid_colors[3];
Vector<Vector3> grid_points[3];
@@ -5426,52 +5450,111 @@ void Node3DEditor::_init_grid() {
int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size");
int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps");
- for (int i = 0; i < 3; i++) {
- Vector3 axis;
- axis[i] = 1;
- Vector3 axis_n1;
- axis_n1[(i + 1) % 3] = 1;
- Vector3 axis_n2;
- axis_n2[(i + 2) % 3] = 1;
-
- for (int j = -grid_size; j <= grid_size; j++) {
- Vector3 p1 = axis_n1 * j + axis_n2 * -grid_size;
- Vector3 p1_dest = p1 * (-axis_n2 + axis_n1);
- Vector3 p2 = axis_n2 * j + axis_n1 * -grid_size;
- Vector3 p2_dest = p2 * (-axis_n1 + axis_n2);
-
- Color line_color = secondary_grid_color;
- if (origin_enabled && j == 0) {
- // Don't draw the center lines of the grid if the origin is enabled
- // The origin would overlap the grid lines in this case, causing flickering
- continue;
- } else if (j % primary_grid_steps == 0) {
- line_color = primary_grid_color;
+ // Which grid planes are enabled? Which should we generate?
+ grid_enable[0] = grid_visible[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
+ grid_enable[1] = grid_visible[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
+ grid_enable[2] = grid_visible[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
+
+ // Offsets division_level for bigger or smaller grids.
+ // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
+ real_t division_level_bias = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_bias");
+ // Default largest grid size is 100m, 10^2 (default value is 2).
+ int division_level_max = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_max");
+ // Default smallest grid size is 1cm, 10^-2 (default value is -2).
+ int division_level_min = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_min");
+ ERR_FAIL_COND_MSG(division_level_max < division_level_min, "The 3D grid's maximum division level cannot be lower than its minimum division level.");
+
+ if (primary_grid_steps != 10) { // Log10 of 10 is 1.
+ // Change of base rule, divide by ln(10).
+ real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
+ // Trucation (towards zero) is intentional.
+ division_level_max = (int)(division_level_max / div);
+ division_level_min = (int)(division_level_min / div);
+ }
+
+ for (int a = 0; a < 3; a++) {
+ if (!grid_enable[a]) {
+ continue; // If this grid plane is disabled, skip generation.
+ }
+ int b = (a + 1) % 3;
+ int c = (a + 2) % 3;
+
+ real_t division_level = Math::log(Math::abs(camera_position[c])) / Math::log((double)primary_grid_steps) + division_level_bias;
+ division_level = CLAMP(division_level, division_level_min, division_level_max);
+ real_t division_level_floored = Math::floor(division_level);
+ real_t division_level_decimals = division_level - division_level_floored;
+
+ real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
+ real_t large_step_size = small_step_size * primary_grid_steps;
+ real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
+ real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
+
+ real_t bgn_a = center_a - grid_size * small_step_size;
+ real_t end_a = center_a + grid_size * small_step_size;
+ real_t bgn_b = center_b - grid_size * small_step_size;
+ real_t end_b = center_b + grid_size * small_step_size;
+
+ // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
+ for (int i = -grid_size; i <= grid_size; i++) {
+ Color line_color;
+ // Is this a primary line? Set the appropriate color.
+ if (i % primary_grid_steps == 0) {
+ line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals);
+ } else {
+ line_color = secondary_grid_color;
+ line_color.a = line_color.a * (1 - division_level_decimals);
+ }
+ // Makes lines farther from the center fade out.
+ // Due to limitations of lines, any that come near the camera have full opacity always.
+ // This should eventually be replaced by some kind of "distance fade" system, outside of this function.
+ // But the effect is still somewhat convincing...
+ line_color.a *= 1 - (1 - division_level_decimals * 0.9) * (Math::abs(i / (float)grid_size));
+
+ real_t position_a = center_a + i * small_step_size;
+ real_t position_b = center_b + i * small_step_size;
+
+ // Don't draw lines over the origin if it's enabled.
+ if (!(origin_enabled && Math::is_zero_approx(position_a))) {
+ Vector3 line_bgn = Vector3();
+ Vector3 line_end = Vector3();
+ line_bgn[a] = position_a;
+ line_end[a] = position_a;
+ line_bgn[b] = bgn_b;
+ line_end[b] = end_b;
+ grid_points[c].push_back(line_bgn);
+ grid_points[c].push_back(line_end);
+ grid_colors[c].push_back(line_color);
+ grid_colors[c].push_back(line_color);
}
- grid_points[i].push_back(p1);
- grid_points[i].push_back(p1_dest);
- grid_colors[i].push_back(line_color);
- grid_colors[i].push_back(line_color);
-
- grid_points[i].push_back(p2);
- grid_points[i].push_back(p2_dest);
- grid_colors[i].push_back(line_color);
- grid_colors[i].push_back(line_color);
+ if (!(origin_enabled && Math::is_zero_approx(position_b))) {
+ Vector3 line_bgn = Vector3();
+ Vector3 line_end = Vector3();
+ line_bgn[b] = position_b;
+ line_end[b] = position_b;
+ line_bgn[a] = bgn_a;
+ line_end[a] = end_a;
+ grid_points[c].push_back(line_bgn);
+ grid_points[c].push_back(line_end);
+ grid_colors[c].push_back(line_color);
+ grid_colors[c].push_back(line_color);
+ }
}
- grid[i] = RenderingServer::get_singleton()->mesh_create();
+ // Create a mesh from the pushed vector points and colors.
+ grid[c] = RenderingServer::get_singleton()->mesh_create();
Array d;
d.resize(RS::ARRAY_MAX);
- d[RenderingServer::ARRAY_VERTEX] = grid_points[i];
- d[RenderingServer::ARRAY_COLOR] = grid_colors[i];
- RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], RenderingServer::PRIMITIVE_LINES, d);
- RenderingServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid());
- grid_instance[i] = RenderingServer::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ d[RenderingServer::ARRAY_VERTEX] = grid_points[c];
+ d[RenderingServer::ARRAY_COLOR] = grid_colors[c];
+ RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d);
+ RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, indicator_mat->get_rid());
+ grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario());
- RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], grid_visible[i]);
- RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
- RS::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
+ // Yes, the end of this line is supposed to be a.
+ RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
+ RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF);
+ RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
}
}
@@ -5489,6 +5572,11 @@ void Node3DEditor::_finish_grid() {
}
}
+void Node3DEditor::update_grid() {
+ _finish_grid();
+ _init_grid();
+}
+
bool Node3DEditor::is_any_freelook_active() const {
for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) {
if (viewports[i]->is_freelook_active()) {
diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h
index 3d92e7e7e1..32b087c372 100644
--- a/editor/plugins/node_3d_editor_plugin.h
+++ b/editor/plugins/node_3d_editor_plugin.h
@@ -766,6 +766,7 @@ public:
Ref<ArrayMesh> get_scale_gizmo(int idx) const { return scale_gizmo[idx]; }
Ref<ArrayMesh> get_scale_plane_gizmo(int idx) const { return scale_plane_gizmo[idx]; }
+ void update_grid();
void update_transform_gizmo();
void update_all_gizmos(Node *p_node = nullptr);
void snap_selected_nodes_to_floor();
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 514bb8dd03..a81a2ff4e9 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -2064,9 +2064,21 @@ void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node, bool p_keep_prop
if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) {
continue;
}
+
if (E->get().name == "__meta__") {
+ if (Object::cast_to<CanvasItem>(newnode)) {
+ Dictionary metadata = n->get(E->get().name);
+ if (metadata.has("_edit_group_") && metadata["_edit_group_"]) {
+ newnode->set_meta("_edit_group_", true);
+ }
+ if (metadata.has("_edit_lock_") && metadata["_edit_lock_"]) {
+ newnode->set_meta("_edit_lock_", true);
+ }
+ }
+
continue;
}
+
if (default_oldnode->get(E->get().name) != n->get(E->get().name)) {
newnode->set(E->get().name, n->get(E->get().name));
}
diff --git a/main/main.cpp b/main/main.cpp
index f35e73cdc2..94dd895a26 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -139,7 +139,6 @@ static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCRE
static uint32_t window_flags = 0;
static Size2i window_size = Size2i(1024, 600);
static bool window_vsync_via_compositor = false;
-static bool disable_wintab = false;
static int init_screen = -1;
static bool init_fullscreen = false;
@@ -313,7 +312,13 @@ void Main::print_help(const char *p_binary) {
OS::get_singleton()->print(" --enable-vsync-via-compositor When vsync is enabled, vsync via the OS' window compositor (Windows only).\n");
OS::get_singleton()->print(" --disable-vsync-via-compositor Disable vsync via the OS' window compositor (Windows only).\n");
OS::get_singleton()->print(" --single-window Use a single window (no separate subwindows).\n");
- OS::get_singleton()->print(" --disable-wintab Disable WinTab API and always use Windows Ink API for the pen input (Windows only).\n");
+ OS::get_singleton()->print(" --tablet-driver Tablet input driver (");
+ for (int i = 0; i < OS::get_singleton()->get_tablet_driver_count(); i++) {
+ if (i != 0)
+ OS::get_singleton()->print(", ");
+ OS::get_singleton()->print("'%s'", OS::get_singleton()->get_tablet_driver_name(i).utf8().get_data());
+ }
+ OS::get_singleton()->print(") (Windows only).\n");
OS::get_singleton()->print("\n");
#endif
@@ -438,6 +443,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
String display_driver = "";
String audio_driver = "";
+ String tablet_driver = "";
String project_path = ".";
bool upwards = false;
String debug_uri = "";
@@ -590,8 +596,26 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
} else if (I->get() == "--gpu-abort") { // force windowed window
Engine::singleton->abort_on_gpu_errors = true;
- } else if (I->get() == "--disable-wintab") {
- disable_wintab = true;
+ } else if (I->get() == "--tablet-driver") {
+ if (I->next()) {
+ tablet_driver = I->next()->get();
+ bool found = false;
+ for (int i = 0; i < OS::get_singleton()->get_tablet_driver_count(); i++) {
+ if (tablet_driver == OS::get_singleton()->get_tablet_driver_name(i)) {
+ found = true;
+ }
+ }
+
+ if (!found) {
+ OS::get_singleton()->print("Unknown tablet driver '%s', aborting.\n", tablet_driver.utf8().get_data());
+ goto error;
+ }
+
+ N = I->next()->next();
+ } else {
+ OS::get_singleton()->print("Missing tablet driver argument, aborting.\n");
+ goto error;
+ }
} else if (I->get() == "--single-window") { // force single window
single_window = true;
@@ -1056,12 +1080,20 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
OS::get_singleton()->_vsync_via_compositor = window_vsync_via_compositor;
- if (!disable_wintab) {
- // No "--disable_wintab" option
- disable_wintab = GLOBAL_DEF("display/window/disable_wintab_api", false);
+ if (tablet_driver == "") { // specified in project.godot
+ tablet_driver = GLOBAL_DEF_RST("display/window/tablet_driver", OS::get_singleton()->get_tablet_driver_name(0));
}
- OS::get_singleton()->_disable_wintab = disable_wintab;
+ for (int i = 0; i < OS::get_singleton()->get_tablet_driver_count(); i++) {
+ if (tablet_driver == OS::get_singleton()->get_tablet_driver_name(i)) {
+ OS::get_singleton()->set_current_tablet_driver(OS::get_singleton()->get_tablet_driver_name(i));
+ break;
+ }
+ }
+
+ if (tablet_driver == "") {
+ OS::get_singleton()->set_current_tablet_driver(OS::get_singleton()->get_tablet_driver_name(0));
+ }
/* todo restore
OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
@@ -1175,6 +1207,7 @@ error:
display_driver = "";
audio_driver = "";
+ tablet_driver = "";
project_path = "";
args.clear();
@@ -1532,7 +1565,11 @@ bool Main::start() {
} else if (args[i].length() && args[i][0] != '-' && positional_arg == "") {
positional_arg = args[i];
- if (args[i].ends_with(".scn") || args[i].ends_with(".tscn") || args[i].ends_with(".escn")) {
+ if (args[i].ends_with(".scn") ||
+ args[i].ends_with(".tscn") ||
+ args[i].ends_with(".escn") ||
+ args[i].ends_with(".res") ||
+ args[i].ends_with(".tres")) {
// Only consider the positional argument to be a scene path if it ends with
// a file extension associated with Godot scenes. This makes it possible
// for projects to parse command-line arguments for custom CLI arguments
@@ -1608,7 +1645,11 @@ bool Main::start() {
print_line("Loading docs...");
for (int i = 0; i < _doc_data_class_path_count; i++) {
- String path = doc_tool.plus_file(_doc_data_class_paths[i].path);
+ // Custom modules are always located by absolute path.
+ String path = _doc_data_class_paths[i].path;
+ if (path.is_rel_path()) {
+ path = doc_tool.plus_file(path);
+ }
String name = _doc_data_class_paths[i].name;
doc_data_classes[name] = path;
if (!checked_paths.has(path)) {
@@ -1921,6 +1962,16 @@ bool Main::start() {
ProjectSettings::get_singleton()->set_custom_property_info("rendering/canvas_textures/default_texture_repeat", PropertyInfo(Variant::INT, "rendering/canvas_textures/default_texture_repeat", PROPERTY_HINT_ENUM, "Disable,Enable,Mirror"));
}
+#ifdef TOOLS_ENABLED
+ if (editor) {
+ bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting("interface/editor/single_window_mode");
+
+ if (editor_embed_subwindows) {
+ sml->get_root()->set_embed_subwindows_hint(true);
+ }
+ }
+#endif
+
String local_game_path;
if (game_path != "" && !project_manager) {
local_game_path = game_path.replace("\\", "/");
@@ -1954,12 +2005,6 @@ bool Main::start() {
#ifdef TOOLS_ENABLED
if (editor) {
- bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting("interface/editor/single_window_mode");
-
- if (editor_embed_subwindows) {
- sml->get_root()->set_embed_subwindows_hint(true);
- }
-
if (game_path != GLOBAL_GET("application/run/main_scene") || !editor_node->has_scenes_in_session()) {
Error serr = editor_node->load_scene(local_game_path);
if (serr != OK) {
diff --git a/main/tests/test_class_db.cpp b/main/tests/test_class_db.cpp
index 4c00a09e9c..3171091402 100644
--- a/main/tests/test_class_db.cpp
+++ b/main/tests/test_class_db.cpp
@@ -44,21 +44,21 @@ enum class [[nodiscard]] TestResult{
PASS
};
-#define TEST_FAIL_COND_FATAL(m_cond, m_msg) \
- if (unlikely(m_cond)) { \
- ERR_PRINT(m_msg); \
- return TestResult::FAILED; \
- } else \
+#define TEST_FAIL_COND(m_cond, m_msg) \
+ if (unlikely(m_cond)) { \
+ ERR_PRINT(m_msg); \
+ return TestResult::FAILED; \
+ } else \
((void)0)
-#define TEST_FAIL_COND(m_cond, m_msg) \
+#define TEST_COND(m_cond, m_msg) \
if (unlikely(m_cond)) { \
ERR_PRINT(m_msg); \
__test_result__ = TestResult::FAILED; \
} else \
((void)0)
-#define TEST_CHECK_FATAL(m_test_expr) \
+#define TEST_FAIL_CHECK(m_test_expr) \
if (unlikely((m_test_expr) == TestResult::FAILED)) { \
return TestResult::FAILED; \
} else \
@@ -229,18 +229,18 @@ struct Context {
return elem ? &elem.value() : nullptr;
}
- bool has_type(const Context &p_context, const TypeReference &p_type_ref) const {
- if (p_context.builtin_types.find(p_type_ref.name) >= 0) {
+ bool has_type(const TypeReference &p_type_ref) const {
+ if (builtin_types.find(p_type_ref.name) >= 0) {
return true;
}
if (p_type_ref.is_enum) {
- if (p_context.enum_types.find(p_type_ref.name) >= 0) {
+ if (enum_types.find(p_type_ref.name) >= 0) {
return true;
}
// Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
- return p_context.builtin_types.find(p_context.names_cache.int_type);
+ return builtin_types.find(names_cache.int_type);
}
return false;
@@ -370,10 +370,10 @@ TestResult validate_property(const Context &p_context, const ExposedClass &p_cla
const ExposedClass *prop_class = p_context.find_exposed_class(prop_type_ref);
if (prop_class) {
- TEST_FAIL_COND(prop_class->is_singleton,
+ TEST_COND(prop_class->is_singleton,
"Property type is a singleton: '" + p_class.name + "." + String(p_prop.name) + "'.");
} else {
- TEST_FAIL_COND(!p_context.has_type(p_context, prop_type_ref),
+ TEST_FAIL_COND(!p_context.has_type(prop_type_ref),
"Property type '" + prop_type_ref.name + "' not found: '" + p_class.name + "." + String(p_prop.name) + "'.");
}
@@ -382,7 +382,7 @@ TestResult validate_property(const Context &p_context, const ExposedClass &p_cla
const ArgumentData &idx_arg = getter->arguments.front()->get();
if (idx_arg.type.name != p_context.names_cache.int_type) {
// If not an int, it can be an enum
- TEST_FAIL_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
+ TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
"Invalid type '" + idx_arg.type.name + "' for index argument of property getter: '" + p_class.name + "." + String(p_prop.name) + "'.");
}
}
@@ -394,7 +394,7 @@ TestResult validate_property(const Context &p_context, const ExposedClass &p_cla
if (idx_arg.type.name != p_context.names_cache.int_type) {
// Assume the index parameter is an enum
// If not an int, it can be an enum
- TEST_FAIL_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
+ TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
"Invalid type '" + idx_arg.type.name + "' for index argument of property setter: '" + p_class.name + "." + String(p_prop.name) + "'.");
}
}
@@ -408,7 +408,7 @@ TestResult validate_method(const Context &p_context, const ExposedClass &p_class
const ExposedClass *return_class = p_context.find_exposed_class(p_method.return_type);
if (return_class) {
- TEST_FAIL_COND(return_class->is_singleton,
+ TEST_COND(return_class->is_singleton,
"Method return type is a singleton: '" + p_class.name + "." + p_method.name + "'.");
}
@@ -417,15 +417,15 @@ TestResult validate_method(const Context &p_context, const ExposedClass &p_class
const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
if (arg_class) {
- TEST_FAIL_COND(arg_class->is_singleton,
+ TEST_COND(arg_class->is_singleton,
"Argument type is a singleton: '" + arg.name + "' of method '" + p_class.name + "." + p_method.name + "'.");
} else {
- TEST_FAIL_COND(!p_context.has_type(p_context, arg.type),
+ 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) {
- TEST_FAIL_COND(!arg_default_value_is_assignable_to_type(p_context, arg.defval, arg.type),
+ TEST_COND(!arg_default_value_is_assignable_to_type(p_context, arg.defval, arg.type),
"Invalid default value for parameter '" + arg.name + "' of method '" + p_class.name + "." + p_method.name + "'.");
}
}
@@ -441,10 +441,10 @@ TestResult validate_signal(const Context &p_context, const ExposedClass &p_class
const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
if (arg_class) {
- TEST_FAIL_COND(arg_class->is_singleton,
+ TEST_COND(arg_class->is_singleton,
"Argument class is a singleton: '" + arg.name + "' of signal" + p_class.name + "." + p_signal.name + "'.");
} else {
- TEST_FAIL_COND(!p_context.has_type(p_context, arg.type),
+ 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 + "'.");
}
}
@@ -459,20 +459,20 @@ TestResult validate_class(const Context &p_context, const ExposedClass &p_expose
if (!is_derived_type) {
// Asserts about the base Object class
- TEST_FAIL_COND_FATAL(p_exposed_class.name != p_context.names_cache.object_class,
+ TEST_FAIL_COND(p_exposed_class.name != p_context.names_cache.object_class,
"Class '" + p_exposed_class.name + "' has no base class.");
- TEST_FAIL_COND_FATAL(!p_exposed_class.is_instantiable,
+ TEST_FAIL_COND(!p_exposed_class.is_instantiable,
"Object class is not instantiable.");
- TEST_FAIL_COND_FATAL(p_exposed_class.api_type != ClassDB::API_CORE,
+ TEST_FAIL_COND(p_exposed_class.api_type != ClassDB::API_CORE,
"Object class is API is not API_CORE.");
- TEST_FAIL_COND_FATAL(p_exposed_class.is_singleton,
+ TEST_FAIL_COND(p_exposed_class.is_singleton,
"Object class is registered as a singleton.");
}
- CRASH_COND_MSG(p_exposed_class.is_singleton && p_exposed_class.base != p_context.names_cache.object_class,
+ TEST_FAIL_COND(p_exposed_class.is_singleton && p_exposed_class.base != p_context.names_cache.object_class,
"Singleton base class '" + String(p_exposed_class.base) + "' is not Object, for class '" + p_exposed_class.name + "'.");
- CRASH_COND_MSG(is_derived_type && !p_context.exposed_classes.has(p_exposed_class.base),
+ TEST_FAIL_COND(is_derived_type && !p_context.exposed_classes.has(p_exposed_class.base),
"Base type '" + p_exposed_class.base.operator String() + "' does not exist, for class '" + p_exposed_class.name + "'.");
for (const List<PropertyData>::Element *F = p_exposed_class.properties.front(); F; F = F->next()) {
@@ -619,9 +619,9 @@ TestResult add_exposed_classes(Context &r_context) {
bool bad_reference_hint = !method.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
ClassDB::is_parent_class(return_info.class_name, r_context.names_cache.reference_class);
- TEST_FAIL_COND(bad_reference_hint, String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
- " Are you returning a reference type by pointer? Method: '" +
- exposed_class.name + "." + method.name + "'.");
+ TEST_COND(bad_reference_hint, String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
+ " Are you returning a reference type by pointer? Method: '" +
+ exposed_class.name + "." + method.name + "'.");
} else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
method.return_type.name = return_info.hint_string;
} else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
@@ -670,7 +670,7 @@ TestResult add_exposed_classes(Context &r_context) {
method.arguments.push_back(vararg);
}
- TEST_FAIL_COND(exposed_class.find_property_by_name(method.name),
+ TEST_COND(exposed_class.find_property_by_name(method.name),
"Method name conflicts with property: '" + String(class_name) + "." + String(method.name) + "'.");
// Classes starting with an underscore are ignored unless they're used as a property setter or getter
@@ -851,13 +851,13 @@ TestResult run_class_db_tests() {
Context context;
- TEST_CHECK_FATAL(add_exposed_classes(context));
+ TEST_FAIL_CHECK(add_exposed_classes(context));
add_builtin_types(context);
add_global_enums(context);
const ExposedClass *object_class = context.find_exposed_class(context.names_cache.object_class);
- TEST_FAIL_COND_FATAL(!object_class, "Object class not found.");
- TEST_FAIL_COND_FATAL(object_class->base != StringName(),
+ TEST_FAIL_COND(!object_class, "Object class not found.");
+ TEST_FAIL_COND(object_class->base != StringName(),
"Object class derives from another class: '" + object_class->base + "'.");
for (ExposedClasses::Element E = context.exposed_classes.front(); E; E = E.next()) {
diff --git a/main/tests/test_math.cpp b/main/tests/test_math.cpp
index 11aa164709..9e159798bb 100644
--- a/main/tests/test_math.cpp
+++ b/main/tests/test_math.cpp
@@ -482,7 +482,7 @@ MainLoop *test() {
float gb = (rgbe >> 9) & 0x1ff;
float bb = (rgbe >> 18) & 0x1ff;
float eb = (rgbe >> 27);
- float mb = Math::pow(2, eb - 15.0 - 9.0);
+ float mb = Math::pow(2.0, eb - 15.0 - 9.0);
float rd = rb * mb;
float gd = gb * mb;
float bd = bb * mb;
diff --git a/main/tests/test_oa_hash_map.cpp b/main/tests/test_oa_hash_map.cpp
index 719817baf4..9182f66b61 100644
--- a/main/tests/test_oa_hash_map.cpp
+++ b/main/tests/test_oa_hash_map.cpp
@@ -210,6 +210,89 @@ MainLoop *test() {
}
}
+ // Test map with 0 capacity.
+ {
+ OAHashMap<int, String> original_map(0);
+ original_map.set(1, "1");
+ OS::get_singleton()->print("OAHashMap 0 capacity initialization passed.\n");
+ }
+
+ // Test copy constructor.
+ {
+ OAHashMap<int, String> original_map;
+ original_map.set(1, "1");
+ original_map.set(2, "2");
+ original_map.set(3, "3");
+ original_map.set(4, "4");
+ original_map.set(5, "5");
+
+ OAHashMap<int, String> map_copy(original_map);
+
+ bool pass = true;
+ for (
+ OAHashMap<int, String>::Iterator it = original_map.iter();
+ it.valid;
+ it = original_map.next_iter(it)) {
+ if (map_copy.lookup_ptr(*it.key) == nullptr) {
+ pass = false;
+ }
+ if (*it.value != *map_copy.lookup_ptr(*it.key)) {
+ pass = false;
+ }
+ }
+ if (pass) {
+ OS::get_singleton()->print("OAHashMap copy constructor test passed.\n");
+ } else {
+ OS::get_singleton()->print("OAHashMap copy constructor test FAILED.\n");
+ }
+
+ map_copy.set(1, "Random String");
+ if (*map_copy.lookup_ptr(1) == *original_map.lookup_ptr(1)) {
+ OS::get_singleton()->print("OAHashMap copy constructor, atomic copy test FAILED.\n");
+ } else {
+ OS::get_singleton()->print("OAHashMap copy constructor, atomic copy test passed.\n");
+ }
+ }
+
+ // Test assign operator.
+ {
+ OAHashMap<int, String> original_map;
+ original_map.set(1, "1");
+ original_map.set(2, "2");
+ original_map.set(3, "3");
+ original_map.set(4, "4");
+ original_map.set(5, "5");
+
+ OAHashMap<int, String> map_copy(100000);
+ map_copy.set(1, "Just a string.");
+ map_copy = original_map;
+
+ bool pass = true;
+ for (
+ OAHashMap<int, String>::Iterator it = map_copy.iter();
+ it.valid;
+ it = map_copy.next_iter(it)) {
+ if (original_map.lookup_ptr(*it.key) == nullptr) {
+ pass = false;
+ }
+ if (*it.value != *original_map.lookup_ptr(*it.key)) {
+ pass = false;
+ }
+ }
+ if (pass) {
+ OS::get_singleton()->print("OAHashMap assign operation test passed.\n");
+ } else {
+ OS::get_singleton()->print("OAHashMap assign operation test FAILED.\n");
+ }
+
+ map_copy.set(1, "Random String");
+ if (*map_copy.lookup_ptr(1) == *original_map.lookup_ptr(1)) {
+ OS::get_singleton()->print("OAHashMap assign operation atomic copy test FAILED.\n");
+ } else {
+ OS::get_singleton()->print("OAHashMap assign operation atomic copy test passed.\n");
+ }
+ }
+
return nullptr;
}
diff --git a/methods.py b/methods.py
index 805ae256c3..46b58a13cd 100644
--- a/methods.py
+++ b/methods.py
@@ -137,37 +137,47 @@ def parse_cg_file(fname, uniforms, sizes, conditionals):
fs.close()
-def detect_modules():
+def detect_modules(at_path):
+ module_list = {} # name : path
- module_list = []
+ modules_glob = os.path.join(at_path, "*")
+ files = glob.glob(modules_glob)
+ files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
+
+ for x in files:
+ if not is_module(x):
+ continue
+ name = os.path.basename(x)
+ path = x.replace("\\", "/") # win32
+ module_list[name] = path
+
+ return module_list
+
+
+def is_module(path):
+ return os.path.isdir(path) and os.path.exists(path + "/config.py")
+
+
+def write_modules(module_list):
includes_cpp = ""
+ preregister_cpp = ""
register_cpp = ""
unregister_cpp = ""
- preregister_cpp = ""
- files = glob.glob("modules/*")
- files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
- for x in files:
- if not os.path.isdir(x):
- continue
- if not os.path.exists(x + "/config.py"):
- continue
- x = x.replace("modules/", "") # rest of world
- x = x.replace("modules\\", "") # win32
- module_list.append(x)
+ for name, path in module_list.items():
try:
- with open("modules/" + x + "/register_types.h"):
- includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
- register_cpp += "#ifdef MODULE_" + x.upper() + "_ENABLED\n"
- register_cpp += "\tregister_" + x + "_types();\n"
- register_cpp += "#endif\n"
- preregister_cpp += "#ifdef MODULE_" + x.upper() + "_ENABLED\n"
- preregister_cpp += "#ifdef MODULE_" + x.upper() + "_HAS_PREREGISTER\n"
- preregister_cpp += "\tpreregister_" + x + "_types();\n"
+ with open(os.path.join(path, "register_types.h")):
+ includes_cpp += '#include "' + path + '/register_types.h"\n'
+ preregister_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
+ preregister_cpp += "#ifdef MODULE_" + name.upper() + "_HAS_PREREGISTER\n"
+ preregister_cpp += "\tpreregister_" + name + "_types();\n"
preregister_cpp += "#endif\n"
preregister_cpp += "#endif\n"
- unregister_cpp += "#ifdef MODULE_" + x.upper() + "_ENABLED\n"
- unregister_cpp += "\tunregister_" + x + "_types();\n"
+ register_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
+ register_cpp += "\tregister_" + name + "_types();\n"
+ register_cpp += "#endif\n"
+ unregister_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
+ unregister_cpp += "\tunregister_" + name + "_types();\n"
unregister_cpp += "#endif\n"
except IOError:
pass
@@ -202,7 +212,18 @@ void unregister_module_types() {
with open("modules/register_module_types.gen.cpp", "w") as f:
f.write(modules_cpp)
- return module_list
+
+def convert_custom_modules_path(path):
+ if not path:
+ return path
+ err_msg = "Build option 'custom_modules' must %s"
+ if not os.path.isdir(path):
+ raise ValueError(err_msg % "point to an existing directory.")
+ if os.path.realpath(path) == os.path.realpath("modules"):
+ raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
+ if is_module(path):
+ raise ValueError(err_msg % "point to a directory with modules, not a single module.")
+ return os.path.realpath(os.path.expanduser(path))
def disable_module(self):
diff --git a/modules/SCsub b/modules/SCsub
index fb46c5f877..9155a53eaf 100644
--- a/modules/SCsub
+++ b/modules/SCsub
@@ -3,6 +3,7 @@
Import("env")
import modules_builders
+import os
env_modules = env.Clone()
@@ -13,16 +14,20 @@ env.CommandNoCache("modules_enabled.gen.h", Value(env.module_list), modules_buil
vs_sources = []
# libmodule_<name>.a for each active module.
-for module in env.module_list:
+for name, path in env.module_list.items():
env.modules_sources = []
- SConscript(module + "/SCsub")
+
+ if not os.path.isabs(path):
+ SConscript(name + "/SCsub") # Built-in.
+ else:
+ SConscript(path + "/SCsub") # Custom.
# Some modules are not linked automatically but can be enabled optionally
# on iOS, so we handle those specially.
- if env["platform"] == "iphone" and module in ["arkit", "camera"]:
+ if env["platform"] == "iphone" and name in ["arkit", "camera"]:
continue
- lib = env_modules.add_library("module_%s" % module, env.modules_sources)
+ lib = env_modules.add_library("module_%s" % name, env.modules_sources)
env.Prepend(LIBS=[lib])
if env["vsproj"]:
vs_sources += env.modules_sources
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index 7433c4a5bc..50d8289fd1 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -2082,7 +2082,11 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
if (!p_only_functions) {
List<PropertyInfo> members;
- tmp.get_property_list(&members);
+ if (p_base.value.get_type() != Variant::NIL) {
+ p_base.value.get_property_list(&members);
+ } else {
+ tmp.get_property_list(&members);
+ }
for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
if (String(E->get().name).find("/") == -1) {
diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp
index 8445eee1fa..37177a8cfd 100644
--- a/modules/gdscript/gdscript_function.cpp
+++ b/modules/gdscript/gdscript_function.cpp
@@ -1821,8 +1821,6 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
state.result = Variant();
if (completed) {
- _clear_stack();
-
if (first_state.is_valid()) {
first_state->emit_signal("completed", ret);
} else {
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index fbb5f91139..0e498f6895 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -3167,7 +3167,6 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
if (error_set) {
return;
}
- p_block->has_return = cf_while->body->has_return;
p_block->statements.push_back(cf_while);
} break;
case GDScriptTokenizer::TK_CF_FOR: {
@@ -3308,7 +3307,6 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
if (error_set) {
return;
}
- p_block->has_return = cf_for->body->has_return;
p_block->statements.push_back(cf_for);
} break;
case GDScriptTokenizer::TK_CF_CONTINUE: {
@@ -4123,6 +4121,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
sig.name = tokenizer->get_token_identifier();
sig.emissions = 0;
sig.line = tokenizer->get_token_line();
+
+ for (int i = 0; i < current_class->_signals.size(); i++) {
+ if (current_class->_signals[i].name == sig.name) {
+ _set_error("The signal \"" + sig.name + "\" already exists in this class (at line: " + itos(current_class->_signals[i].line) + ").");
+ return;
+ }
+ }
+
tokenizer->advance();
if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
@@ -7948,6 +7954,47 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
}
}
+ // Signals
+ DataType base = p_class->base_type;
+
+ while (base.kind == DataType::CLASS) {
+ ClassNode *base_class = base.class_type;
+ for (int i = 0; i < p_class->_signals.size(); i++) {
+ for (int j = 0; j < base_class->_signals.size(); j++) {
+ if (p_class->_signals[i].name == base_class->_signals[j].name) {
+ _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line);
+ return;
+ }
+ }
+ }
+ base = base_class->base_type;
+ }
+
+ StringName native;
+ if (base.kind == DataType::GDSCRIPT || base.kind == DataType::SCRIPT) {
+ Ref<Script> scr = base.script_type;
+ if (scr.is_valid() && scr->is_valid()) {
+ native = scr->get_instance_base_type();
+ for (int i = 0; i < p_class->_signals.size(); i++) {
+ if (scr->has_script_signal(p_class->_signals[i].name)) {
+ _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line);
+ return;
+ }
+ }
+ }
+ } else if (base.kind == DataType::NATIVE) {
+ native = base.native_type;
+ }
+
+ if (native != StringName()) {
+ for (int i = 0; i < p_class->_signals.size(); i++) {
+ if (ClassDB::has_signal(native, p_class->_signals[i].name)) {
+ _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line);
+ return;
+ }
+ }
+ }
+
// Inner classes
for (int i = 0; i < p_class->subclasses.size(); i++) {
current_class = p_class->subclasses[i];
diff --git a/modules/mono/SCsub b/modules/mono/SCsub
index c723b210cb..e8f3174a0a 100644
--- a/modules/mono/SCsub
+++ b/modules/mono/SCsub
@@ -29,7 +29,7 @@ if env_mono["tools"] or env_mono["target"] != "release":
mono_configure.configure(env, env_mono)
-if env_mono["tools"] and env_mono["mono_glue"]:
+if env_mono["tools"] and env_mono["mono_glue"] and env_mono["build_cil"]:
# Build Godot API solution
import build_scripts.api_solution_build as api_solution_build
diff --git a/modules/mono/config.py b/modules/mono/config.py
index d41f3755b5..7980a86cb3 100644
--- a/modules/mono/config.py
+++ b/modules/mono/config.py
@@ -30,6 +30,7 @@ def configure(env):
)
envvars.Add(BoolVariable("mono_static", "Statically link mono", default_mono_static))
envvars.Add(BoolVariable("mono_glue", "Build with the mono glue sources", True))
+ envvars.Add(BoolVariable("build_cil", "Build C# solutions", True))
envvars.Add(
BoolVariable(
"copy_mono_root", "Make a copy of the mono installation directory to bundle with the editor", False
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index a5aae5175b..958d72adb1 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -2419,15 +2419,22 @@ bool CSharpScript::_update_exports() {
StringName member_name = field->get_name();
member_info[member_name] = prop_info;
+
+ if (exported) {
#ifdef TOOLS_ENABLED
- if (is_editor && exported) {
- exported_members_cache.push_front(prop_info);
+ if (is_editor) {
+ exported_members_cache.push_front(prop_info);
- if (tmp_object) {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
+ if (tmp_object) {
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
+ }
}
- }
#endif
+
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ exported_members_names.insert(member_name);
+#endif
+ }
}
}
@@ -2440,21 +2447,28 @@ bool CSharpScript::_update_exports() {
StringName member_name = property->get_name();
member_info[member_name] = prop_info;
+
+ if (exported) {
#ifdef TOOLS_ENABLED
- if (is_editor && exported) {
- exported_members_cache.push_front(prop_info);
- if (tmp_object) {
- MonoException *exc = nullptr;
- MonoObject *ret = property->get_value(tmp_object, &exc);
- if (exc) {
- exported_members_defval_cache[member_name] = Variant();
- GDMonoUtils::debug_print_unhandled_exception(exc);
- } else {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
+ if (is_editor) {
+ exported_members_cache.push_front(prop_info);
+ if (tmp_object) {
+ MonoException *exc = nullptr;
+ MonoObject *ret = property->get_value(tmp_object, &exc);
+ if (exc) {
+ exported_members_defval_cache[member_name] = Variant();
+ GDMonoUtils::debug_print_unhandled_exception(exc);
+ } else {
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
+ }
}
}
- }
#endif
+
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ exported_members_names.insert(member_name);
+#endif
+ }
}
}
@@ -3240,9 +3254,7 @@ Error CSharpScript::reload(bool p_keep_state) {
ERR_FAIL_NULL_V(namespace_, ERR_BUG);
ERR_FAIL_NULL_V(class_name, ERR_BUG);
GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
- if (klass) {
- bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass);
- ERR_FAIL_COND_V(!obj_type, ERR_BUG);
+ if (klass && CACHED_CLASS(GodotObject)->is_assignable_from(klass)) {
script_class = klass;
}
} else {
@@ -3593,6 +3605,16 @@ CSharpScript::~CSharpScript() {
#endif
}
+void CSharpScript::get_members(Set<StringName> *p_members) {
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ if (p_members) {
+ for (Set<StringName>::Element *E = exported_members_names.front(); E; E = E->next()) {
+ p_members->insert(E->get());
+ }
+ }
+#endif
+}
+
/*************** RESOURCE ***************/
RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index 52b0783a6e..0bf08ceafd 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -138,6 +138,10 @@ private:
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
#endif
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ Set<StringName> exported_members_names;
+#endif
+
Map<StringName, PropertyInfo> member_info;
void _clear();
@@ -191,6 +195,8 @@ public:
virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
virtual void update_exports();
+ void get_members(Set<StringName> *p_members) override;
+
virtual bool is_tool() const { return tool; }
virtual bool is_valid() const { return valid; }
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
index eb7696685f..c874025be0 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -421,7 +421,7 @@ namespace GodotTools
aboutLabel.Text =
"C# support in Godot Engine is in late alpha stage and, while already usable, " +
"it is not meant for use in production.\n\n" +
- "Projects can be exported to Linux, macOS, Windows and Android, but not yet to iOS, HTML5 or UWP. " +
+ "Projects can be exported to Linux, macOS, Windows, Android, iOS and HTML5, but not yet to UWP. " +
"Bugs and usability issues will be addressed gradually over future releases, " +
"potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" +
"If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" +
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp
index 080f366692..5f518d0613 100644
--- a/modules/mono/mono_gd/gd_mono.cpp
+++ b/modules/mono/mono_gd/gd_mono.cpp
@@ -424,6 +424,9 @@ void GDMono::initialize_load_assemblies() {
CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
#endif
+ if (Main::is_project_manager())
+ return;
+
// Load the project's main assembly. This doesn't necessarily need to succeed.
// The game may not be using .NET at all, or if the project does use .NET and
// we're running in the editor, it may just happen to be it wasn't built yet.
diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp
index b996be2a4c..6242009f67 100644
--- a/modules/xatlas_unwrap/register_types.cpp
+++ b/modules/xatlas_unwrap/register_types.cpp
@@ -145,7 +145,7 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver
ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Enum::Success, false, xatlas::StringForEnum(err));
printf("Generate..\n");
- xatlas::Generate(atlas, chart_options, nullptr, pack_options);
+ xatlas::Generate(atlas, chart_options, xatlas::ParameterizeOptions(), pack_options);
*r_size_hint_x = atlas->width;
*r_size_hint_y = atlas->height;
diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp
index 48c23d3c31..1436d832de 100644
--- a/platform/android/display_server_android.cpp
+++ b/platform/android/display_server_android.cpp
@@ -155,12 +155,12 @@ bool DisplayServerAndroid::screen_is_touchscreen(int p_screen) const {
return true;
}
-void DisplayServerAndroid::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_length) {
+void DisplayServerAndroid::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_length, int p_cursor_start, int p_cursor_end) {
GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java();
ERR_FAIL_COND(!godot_io_java);
if (godot_io_java->has_vk()) {
- godot_io_java->show_vk(p_existing_text, p_max_length);
+ godot_io_java->show_vk(p_existing_text, p_max_length, p_cursor_start, p_cursor_end);
} else {
ERR_PRINT("Virtual keyboard not available");
}
@@ -367,6 +367,25 @@ void DisplayServerAndroid::register_android_driver() {
register_create_function("android", create_func, get_rendering_drivers_func);
}
+void DisplayServerAndroid::reset_window() {
+#if defined(VULKAN_ENABLED)
+ if (rendering_driver == "vulkan") {
+ ANativeWindow *native_window = OS_Android::get_singleton()->get_native_window();
+ ERR_FAIL_COND(!native_window);
+
+ ERR_FAIL_COND(!context_vulkan);
+ context_vulkan->window_destroy(MAIN_WINDOW_ID);
+
+ Size2i display_size = OS_Android::get_singleton()->get_display_size();
+ if (context_vulkan->window_create(native_window, display_size.width, display_size.height) == -1) {
+ memdelete(context_vulkan);
+ context_vulkan = nullptr;
+ ERR_FAIL_MSG("Failed to reset Vulkan window.");
+ }
+ }
+#endif
+}
+
DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
rendering_driver = p_rendering_driver;
diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h
index b2909f258b..d64542df58 100644
--- a/platform/android/display_server_android.h
+++ b/platform/android/display_server_android.h
@@ -106,7 +106,7 @@ public:
virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const;
virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const;
- virtual void virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_length = -1);
+ virtual void virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_length = -1, int p_cursor_start = -1, int p_cursor_end = -1);
virtual void virtual_keyboard_hide();
virtual int virtual_keyboard_get_height() const;
@@ -166,6 +166,8 @@ public:
static Vector<String> get_rendering_drivers_func();
static void register_android_driver();
+ void reset_window();
+
DisplayServerAndroid(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
~DisplayServerAndroid();
};
diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp
index dfaaf68b69..1bd198ccc0 100644
--- a/platform/android/export/export.cpp
+++ b/platform/android/export/export.cpp
@@ -254,6 +254,8 @@ class EditorExportPlatformAndroid : public EditorExportPlatform {
};
Vector<PluginConfig> plugins;
+ String last_plugin_names;
+ uint64_t last_custom_build_time = 0;
volatile bool plugins_changed;
Mutex plugins_lock;
Vector<Device> devices;
@@ -1831,6 +1833,29 @@ public:
return list;
}
+ inline bool is_clean_build_required(Vector<PluginConfig> enabled_plugins) {
+ String plugin_names = get_plugins_names(enabled_plugins);
+ bool first_build = last_custom_build_time == 0;
+ bool have_plugins_changed = false;
+
+ if (!first_build) {
+ have_plugins_changed = plugin_names != last_plugin_names;
+ if (!have_plugins_changed) {
+ for (int i = 0; i < enabled_plugins.size(); i++) {
+ if (enabled_plugins.get(i).last_updated > last_custom_build_time) {
+ have_plugins_changed = true;
+ break;
+ }
+ }
+ }
+ }
+
+ last_custom_build_time = OS::get_singleton()->get_unix_time();
+ last_plugin_names = plugin_names;
+
+ return have_plugins_changed || first_build;
+ }
+
virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) {
ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
@@ -1877,8 +1902,12 @@ public:
String local_plugins_binaries = get_plugins_binaries(BINARY_TYPE_LOCAL, enabled_plugins);
String remote_plugins_binaries = get_plugins_binaries(BINARY_TYPE_REMOTE, enabled_plugins);
String custom_maven_repos = get_plugins_custom_maven_repos(enabled_plugins);
+ bool clean_build_required = is_clean_build_required(enabled_plugins);
List<String> cmdline;
+ if (clean_build_required) {
+ cmdline.push_back("clean");
+ }
cmdline.push_back("build");
cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.
cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies.
diff --git a/platform/android/java/app/build.gradle b/platform/android/java/app/build.gradle
index ea341b37b1..19202d2310 100644
--- a/platform/android/java/app/build.gradle
+++ b/platform/android/java/app/build.gradle
@@ -75,6 +75,11 @@ android {
}
defaultConfig {
+ // The default ignore pattern for the 'assets' directory includes hidden files and directories which are used by Godot projects.
+ aaptOptions {
+ ignoreAssetsPattern "!.svn:!.git:!.ds_store:!*.scc:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"
+ }
+
// Feel free to modify the application id to your own.
applicationId getExportPackageName()
minSdkVersion versions.minSdk
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java
index 410b93824d..93f4786e83 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java
@@ -460,9 +460,9 @@ public class GodotIO {
return (int)(metrics.density * 160f);
}
- public void showKeyboard(String p_existing_text, int p_max_input_length) {
+ public void showKeyboard(String p_existing_text, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
if (edit != null)
- edit.showKeyboard(p_existing_text, p_max_input_length);
+ edit.showKeyboard(p_existing_text, p_max_input_length, p_cursor_start, p_cursor_end);
//InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
index 72198ba123..3693f36557 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
@@ -66,11 +66,12 @@ public class GodotLib {
/**
* Invoked on the GL thread when the underlying Android surface has changed size.
- * @param width
- * @param height
+ * @param p_surface
+ * @param p_width
+ * @param p_height
* @see android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
*/
- public static native void resize(int width, int height);
+ public static native void resize(Surface p_surface, int p_width, int p_height);
/**
* Invoked on the render thread when the underlying Android surface is created or recreated.
@@ -189,7 +190,7 @@ public class GodotLib {
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
- public static native void callobject(int p_id, String p_method, Object[] p_params);
+ public static native void callobject(long p_id, String p_method, Object[] p_params);
/**
* Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
@@ -197,7 +198,7 @@ public class GodotLib {
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
- public static native void calldeferred(int p_id, String p_method, Object[] p_params);
+ public static native void calldeferred(long p_id, String p_method, Object[] p_params);
/**
* Forward the results from a permission request.
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java
index 99d3662317..64395f7d1e 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java
@@ -64,7 +64,7 @@ class GodotRenderer implements GLSurfaceView.Renderer {
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
- GodotLib.resize(width, height);
+ GodotLib.resize(null, width, height);
for (GodotPlugin plugin : pluginRegistry.getAllPlugins()) {
plugin.onGLSurfaceChanged(gl, width, height);
}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java
index 547c093419..7f596575a8 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java
@@ -58,6 +58,7 @@ public class GodotEditText extends EditText {
private GodotTextInputWrapper mInputWrapper;
private EditHandler sHandler = new EditHandler(this);
private String mOriginText;
+ private int mMaxInputLength;
private static class EditHandler extends Handler {
private final WeakReference<GodotEditText> mEdit;
@@ -104,11 +105,18 @@ public class GodotEditText extends EditText {
String text = edit.mOriginText;
if (edit.requestFocus()) {
edit.removeTextChangedListener(edit.mInputWrapper);
+ setMaxInputLength(edit);
edit.setText("");
edit.append(text);
+ if (msg.arg2 != -1) {
+ edit.setSelection(msg.arg1, msg.arg2);
+ edit.mInputWrapper.setSelection(true);
+ } else {
+ edit.mInputWrapper.setSelection(false);
+ }
+
edit.mInputWrapper.setOriginText(text);
edit.addTextChangedListener(edit.mInputWrapper);
- setMaxInputLength(edit, msg.arg1);
final InputMethodManager imm = (InputMethodManager)mRenderView.getView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
}
@@ -125,14 +133,10 @@ public class GodotEditText extends EditText {
}
}
- private void setMaxInputLength(EditText p_edit_text, int p_max_input_length) {
- if (p_max_input_length > 0) {
- InputFilter[] filters = new InputFilter[1];
- filters[0] = new InputFilter.LengthFilter(p_max_input_length);
- p_edit_text.setFilters(filters);
- } else {
- p_edit_text.setFilters(new InputFilter[] {});
- }
+ private void setMaxInputLength(EditText p_edit_text) {
+ InputFilter[] filters = new InputFilter[1];
+ filters[0] = new InputFilter.LengthFilter(this.mMaxInputLength);
+ p_edit_text.setFilters(filters);
}
// ===========================================================
@@ -164,13 +168,24 @@ public class GodotEditText extends EditText {
// ===========================================================
// Methods
// ===========================================================
- public void showKeyboard(String p_existing_text, int p_max_input_length) {
- mOriginText = p_existing_text;
+ public void showKeyboard(String p_existing_text, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
+ int maxInputLength = (p_max_input_length <= 0) ? Integer.MAX_VALUE : p_max_input_length;
+ if (p_cursor_start == -1) { // cursor position not given
+ this.mOriginText = p_existing_text;
+ this.mMaxInputLength = maxInputLength;
+ } else if (p_cursor_end == -1) { // not text selection
+ this.mOriginText = p_existing_text.substring(0, p_cursor_start);
+ this.mMaxInputLength = maxInputLength - (p_existing_text.length() - p_cursor_start);
+ } else {
+ this.mOriginText = p_existing_text.substring(0, p_cursor_end);
+ this.mMaxInputLength = maxInputLength - (p_existing_text.length() - p_cursor_end);
+ }
final Message msg = new Message();
msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = this;
- msg.arg1 = p_max_input_length;
+ msg.arg1 = p_cursor_start;
+ msg.arg2 = p_cursor_end;
sHandler.sendMessage(msg);
}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java
index 9cd08de529..9c7cf9f341 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java
@@ -53,6 +53,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
private final GodotRenderView mRenderView;
private final GodotEditText mEdit;
private String mOriginText;
+ private boolean mHasSelection;
// ===========================================================
// Constructors
@@ -77,6 +78,10 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
mOriginText = originText;
}
+ public void setSelection(boolean selection) {
+ mHasSelection = selection;
+ }
+
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@@ -95,6 +100,11 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
for (int i = 0; i < count; ++i) {
GodotLib.key(KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, 0, true);
GodotLib.key(KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, 0, false);
+
+ if (mHasSelection) {
+ mHasSelection = false;
+ break;
+ }
}
}
});
diff --git a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt
index 608ad48df9..aeb4628d5d 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt
+++ b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt
@@ -59,9 +59,7 @@ internal class VkRenderer {
* Called when the surface is created and signals the beginning of rendering.
*/
fun onVkSurfaceCreated(surface: Surface) {
- // TODO: properly implement surface re-creation:
- // GodotLib.newcontext should be called here once it's done.
- //GodotLib.newcontext(surface, false)
+ GodotLib.newcontext(surface, false)
for (plugin in pluginRegistry.getAllPlugins()) {
plugin.onVkSurfaceCreated(surface)
@@ -72,12 +70,7 @@ internal class VkRenderer {
* Called after the surface is created and whenever its size changes.
*/
fun onVkSurfaceChanged(surface: Surface, width: Int, height: Int) {
- GodotLib.resize(width, height)
-
- // TODO: properly implement surface re-creation:
- // Update the native renderer instead of restarting the app.
- // GodotLib.newcontext should not be called here once it's done.
- GodotLib.newcontext(surface, false)
+ GodotLib.resize(surface, width, height)
for (plugin in pluginRegistry.getAllPlugins()) {
plugin.onVkSurfaceChanged(surface, width, height)
diff --git a/platform/android/java/plugins/godotpayment/build.gradle b/platform/android/java/plugins/godotpayment/build.gradle
index ffab86e26e..fb3aa8bba2 100644
--- a/platform/android/java/plugins/godotpayment/build.gradle
+++ b/platform/android/java/plugins/godotpayment/build.gradle
@@ -3,7 +3,6 @@ apply plugin: 'com.android.library'
android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools
- useLibrary 'org.apache.http.legacy'
defaultConfig {
minSdkVersion versions.minSdk
@@ -21,6 +20,7 @@ android {
dependencies {
implementation libraries.supportCoreUtils
implementation libraries.v4Support
+ implementation 'com.android.billingclient:billing:2.2.1'
if (rootProject.findProject(":lib")) {
compileOnly project(":lib")
diff --git a/platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl b/platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl
deleted file mode 100644
index 0f2bcae338..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.vending.billing;
-
-import android.os.Bundle;
-
-/**
- * InAppBillingService is the service that provides in-app billing version 3 and beyond.
- * This service provides the following features:
- * 1. Provides a new API to get details of in-app items published for the app including
- * price, type, title and description.
- * 2. The purchase flow is synchronous and purchase information is available immediately
- * after it completes.
- * 3. Purchase information of in-app purchases is maintained within the Google Play system
- * till the purchase is consumed.
- * 4. An API to consume a purchase of an inapp item. All purchases of one-time
- * in-app items are consumable and thereafter can be purchased again.
- * 5. An API to get current purchases of the user immediately. This will not contain any
- * consumed purchases.
- *
- * All calls will give a response code with the following possible values
- * RESULT_OK = 0 - success
- * RESULT_USER_CANCELED = 1 - User pressed back or canceled a dialog
- * RESULT_SERVICE_UNAVAILABLE = 2 - The network connection is down
- * RESULT_BILLING_UNAVAILABLE = 3 - This billing API version is not supported for the type requested
- * RESULT_ITEM_UNAVAILABLE = 4 - Requested SKU is not available for purchase
- * RESULT_DEVELOPER_ERROR = 5 - Invalid arguments provided to the API
- * RESULT_ERROR = 6 - Fatal error during the API action
- * RESULT_ITEM_ALREADY_OWNED = 7 - Failure to purchase since item is already owned
- * RESULT_ITEM_NOT_OWNED = 8 - Failure to consume since item is not owned
- */
-interface IInAppBillingService {
- /**
- * Checks support for the requested billing API version, package and in-app type.
- * Minimum API version supported by this interface is 3.
- * @param apiVersion billing API version that the app is using
- * @param packageName the package name of the calling app
- * @param type type of the in-app item being purchased ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @return RESULT_OK(0) on success and appropriate response code on failures.
- */
- int isBillingSupported(int apiVersion, String packageName, String type);
-
- /**
- * Provides details of a list of SKUs
- * Given a list of SKUs of a valid type in the skusBundle, this returns a bundle
- * with a list JSON strings containing the productId, price, title and description.
- * This API can be called with a maximum of 20 SKUs.
- * @param apiVersion billing API version that the app is using
- * @param packageName the package name of the calling app
- * @param type of the in-app items ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @param skusBundle bundle containing a StringArrayList of SKUs with key "ITEM_ID_LIST"
- * @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
- * on failures.
- * "DETAILS_LIST" with a StringArrayList containing purchase information
- * in JSON format similar to:
- * '{ "productId" : "exampleSku",
- * "type" : "inapp",
- * "price" : "$5.00",
- * "price_currency": "USD",
- * "price_amount_micros": 5000000,
- * "title : "Example Title",
- * "description" : "This is an example description" }'
- */
- Bundle getSkuDetails(int apiVersion, String packageName, String type, in Bundle skusBundle);
-
- /**
- * Returns a pending intent to launch the purchase flow for an in-app item by providing a SKU,
- * the type, a unique purchase token and an optional developer payload.
- * @param apiVersion billing API version that the app is using
- * @param packageName package name of the calling app
- * @param sku the SKU of the in-app item as published in the developer console
- * @param type of the in-app item being purchased ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @param developerPayload optional argument to be sent back with the purchase information
- * @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
- * on failures.
- * "BUY_INTENT" - PendingIntent to start the purchase flow
- *
- * The Pending intent should be launched with startIntentSenderForResult. When purchase flow
- * has completed, the onActivityResult() will give a resultCode of OK or CANCELED.
- * If the purchase is successful, the result data will contain the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response
- * codes on failures.
- * "INAPP_PURCHASE_DATA" - String in JSON format similar to
- * '{"orderId":"12999763169054705758.1371079406387615",
- * "packageName":"com.example.app",
- * "productId":"exampleSku",
- * "purchaseTime":1345678900000,
- * "purchaseToken" : "122333444455555",
- * "developerPayload":"example developer payload" }'
- * "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that
- * was signed with the private key of the developer
- */
- Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type,
- String developerPayload);
-
- /**
- * Returns the current SKUs owned by the user of the type and package name specified along with
- * purchase information and a signature of the data to be validated.
- * This will return all SKUs that have been purchased in V3 and managed items purchased using
- * V1 and V2 that have not been consumed.
- * @param apiVersion billing API version that the app is using
- * @param packageName package name of the calling app
- * @param type of the in-app items being requested ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @param continuationToken to be set as null for the first call, if the number of owned
- * skus are too many, a continuationToken is returned in the response bundle.
- * This method can be called again with the continuation token to get the next set of
- * owned skus.
- * @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
- on failures.
- * "INAPP_PURCHASE_ITEM_LIST" - StringArrayList containing the list of SKUs
- * "INAPP_PURCHASE_DATA_LIST" - StringArrayList containing the purchase information
- * "INAPP_DATA_SIGNATURE_LIST"- StringArrayList containing the signatures
- * of the purchase information
- * "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the
- * next set of in-app purchases. Only set if the
- * user has more owned skus than the current list.
- */
- Bundle getPurchases(int apiVersion, String packageName, String type, String continuationToken);
-
- /**
- * Consume the last purchase of the given SKU. This will result in this item being removed
- * from all subsequent responses to getPurchases() and allow re-purchase of this item.
- * @param apiVersion billing API version that the app is using
- * @param packageName package name of the calling app
- * @param purchaseToken token in the purchase information JSON that identifies the purchase
- * to be consumed
- * @return RESULT_OK(0) if consumption succeeded, appropriate response codes on failures.
- */
- int consumePurchase(int apiVersion, String packageName, String purchaseToken);
-
- /**
- * This API is currently under development.
- */
- int stub(int apiVersion, String packageName, String type);
-
- /**
- * Returns a pending intent to launch the purchase flow for upgrading or downgrading a
- * subscription. The existing owned SKU(s) should be provided along with the new SKU that
- * the user is upgrading or downgrading to.
- * @param apiVersion billing API version that the app is using, must be 5 or later
- * @param packageName package name of the calling app
- * @param oldSkus the SKU(s) that the user is upgrading or downgrading from,
- * if null or empty this method will behave like {@link #getBuyIntent}
- * @param newSku the SKU that the user is upgrading or downgrading to
- * @param type of the item being purchased, currently must be "subs"
- * @param developerPayload optional argument to be sent back with the purchase information
- * @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
- * on failures.
- * "BUY_INTENT" - PendingIntent to start the purchase flow
- *
- * The Pending intent should be launched with startIntentSenderForResult. When purchase flow
- * has completed, the onActivityResult() will give a resultCode of OK or CANCELED.
- * If the purchase is successful, the result data will contain the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response
- * codes on failures.
- * "INAPP_PURCHASE_DATA" - String in JSON format similar to
- * '{"orderId":"12999763169054705758.1371079406387615",
- * "packageName":"com.example.app",
- * "productId":"exampleSku",
- * "purchaseTime":1345678900000,
- * "purchaseToken" : "122333444455555",
- * "developerPayload":"example developer payload" }'
- * "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that
- * was signed with the private key of the developer
- */
- Bundle getBuyIntentToReplaceSkus(int apiVersion, String packageName,
- in List<String> oldSkus, String newSku, String type, String developerPayload);
-
- /**
- * Returns a pending intent to launch the purchase flow for an in-app item. This method is
- * a variant of the {@link #getBuyIntent} method and takes an additional {@code extraParams}
- * parameter. This parameter is a Bundle of optional keys and values that affect the
- * operation of the method.
- * @param apiVersion billing API version that the app is using, must be 6 or later
- * @param packageName package name of the calling app
- * @param sku the SKU of the in-app item as published in the developer console
- * @param type of the in-app item being purchased ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @param developerPayload optional argument to be sent back with the purchase information
- * @extraParams a Bundle with the following optional keys:
- * "skusToReplace" - List<String> - an optional list of SKUs that the user is
- * upgrading or downgrading from.
- * Pass this field if the purchase is upgrading or downgrading
- * existing subscriptions.
- * The specified SKUs are replaced with the SKUs that the user is
- * purchasing. Google Play replaces the specified SKUs at the start of
- * the next billing cycle.
- * "replaceSkusProration" - Boolean - whether the user should be credited for any unused
- * subscription time on the SKUs they are upgrading or downgrading.
- * If you set this field to true, Google Play swaps out the old SKUs
- * and credits the user with the unused value of their subscription
- * time on a pro-rated basis.
- * Google Play applies this credit to the new subscription, and does
- * not begin billing the user for the new subscription until after
- * the credit is used up.
- * If you set this field to false, the user does not receive credit for
- * any unused subscription time and the recurrence date does not
- * change.
- * Default value is true. Ignored if you do not pass skusToReplace.
- * "accountId" - String - an optional obfuscated string that is uniquely
- * associated with the user's account in your app.
- * If you pass this value, Google Play can use it to detect irregular
- * activity, such as many devices making purchases on the same
- * account in a short period of time.
- * Do not use the developer ID or the user's Google ID for this field.
- * In addition, this field should not contain the user's ID in
- * cleartext.
- * We recommend that you use a one-way hash to generate a string from
- * the user's ID, and store the hashed string in this field.
- * "vr" - Boolean - an optional flag indicating whether the returned intent
- * should start a VR purchase flow. The apiVersion must also be 7 or
- * later to use this flag.
- */
- Bundle getBuyIntentExtraParams(int apiVersion, String packageName, String sku,
- String type, String developerPayload, in Bundle extraParams);
-
- /**
- * Returns the most recent purchase made by the user for each SKU, even if that purchase is
- * expired, canceled, or consumed.
- * @param apiVersion billing API version that the app is using, must be 6 or later
- * @param packageName package name of the calling app
- * @param type of the in-app items being requested ("inapp" for one-time purchases
- * and "subs" for subscriptions)
- * @param continuationToken to be set as null for the first call, if the number of owned
- * skus is too large, a continuationToken is returned in the response bundle.
- * This method can be called again with the continuation token to get the next set of
- * owned skus.
- * @param extraParams a Bundle with extra params that would be appended into http request
- * query string. Not used at this moment. Reserved for future functionality.
- * @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value: RESULT_OK(0) if success,
- * {@link IabHelper#BILLING_RESPONSE_RESULT_*} response codes on failures.
- *
- * "INAPP_PURCHASE_ITEM_LIST" - ArrayList<String> containing the list of SKUs
- * "INAPP_PURCHASE_DATA_LIST" - ArrayList<String> containing the purchase information
- * "INAPP_DATA_SIGNATURE_LIST"- ArrayList<String> containing the signatures
- * of the purchase information
- * "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the
- * next set of in-app purchases. Only set if the
- * user has more owned skus than the current list.
- */
- Bundle getPurchaseHistory(int apiVersion, String packageName, String type,
- String continuationToken, in Bundle extraParams);
-
- /**
- * This method is a variant of {@link #isBillingSupported}} that takes an additional
- * {@code extraParams} parameter.
- * @param apiVersion billing API version that the app is using, must be 7 or later
- * @param packageName package name of the calling app
- * @param type of the in-app item being purchased ("inapp" for one-time purchases and "subs"
- * for subscriptions)
- * @param extraParams a Bundle with the following optional keys:
- * "vr" - Boolean - an optional flag to indicate whether {link #getBuyIntentExtraParams}
- * supports returning a VR purchase flow.
- * @return RESULT_OK(0) on success and appropriate response code on failures.
- */
- int isBillingSupportedExtraParams(int apiVersion, String packageName, String type,
- in Bundle extraParams);
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java
deleted file mode 100644
index de009f6d16..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*************************************************************************/
-/* ConsumeTask.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.content.Context;
-import android.os.AsyncTask;
-import android.os.RemoteException;
-
-import com.android.vending.billing.IInAppBillingService;
-
-import java.lang.ref.WeakReference;
-
-abstract public class ConsumeTask {
- private Context context;
- private IInAppBillingService mService;
-
- private String mSku;
- private String mToken;
-
- private static class ConsumeAsyncTask extends AsyncTask<String, String, String> {
- private WeakReference<ConsumeTask> mTask;
-
- ConsumeAsyncTask(ConsumeTask consume) {
- mTask = new WeakReference<>(consume);
- }
-
- @Override
- protected String doInBackground(String... strings) {
- ConsumeTask consume = mTask.get();
- if (consume != null) {
- return consume.doInBackground(strings);
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(String param) {
- ConsumeTask consume = mTask.get();
- if (consume != null) {
- consume.onPostExecute(param);
- }
- }
- }
-
- public ConsumeTask(IInAppBillingService mService, Context context) {
- this.context = context;
- this.mService = mService;
- }
-
- public void consume(final String sku) {
- mSku = sku;
- PaymentsCache pc = new PaymentsCache(context);
- Boolean isBlocked = pc.getConsumableFlag("block", sku);
- mToken = pc.getConsumableValue("token", sku);
- if (!isBlocked && mToken == null) {
- // Consuming task is processing
- } else if (!isBlocked) {
- return;
- } else if (mToken == null) {
- this.error("No token for sku:" + sku);
- return;
- }
- new ConsumeAsyncTask(this).execute();
- }
-
- private String doInBackground(String... params) {
- try {
- int response = mService.consumePurchase(3, context.getPackageName(), mToken);
- if (response == 0 || response == 8) {
- return null;
- }
- } catch (RemoteException e) {
- return e.getMessage();
- }
- return "Some error";
- }
-
- private void onPostExecute(String param) {
- if (param == null) {
- success(new PaymentsCache(context).getConsumableValue("ticket", mSku));
- } else {
- error(param);
- }
- }
-
- abstract protected void success(String ticket);
- abstract protected void error(String message);
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java
index ded7f0a9aa..9e55ab5027 100644
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java
+++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java
@@ -32,214 +32,177 @@ package org.godotengine.godot.plugin.payment;
import org.godotengine.godot.Dictionary;
import org.godotengine.godot.Godot;
-import org.godotengine.godot.GodotLib;
import org.godotengine.godot.plugin.GodotPlugin;
-
-import android.content.Intent;
-import android.util.Log;
+import org.godotengine.godot.plugin.SignalInfo;
+import org.godotengine.godot.plugin.payment.utils.GodotPaymentUtils;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.collection.ArraySet;
+
+import com.android.billingclient.api.AcknowledgePurchaseParams;
+import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
+import com.android.billingclient.api.BillingClient;
+import com.android.billingclient.api.BillingClientStateListener;
+import com.android.billingclient.api.BillingFlowParams;
+import com.android.billingclient.api.BillingResult;
+import com.android.billingclient.api.ConsumeParams;
+import com.android.billingclient.api.ConsumeResponseListener;
+import com.android.billingclient.api.Purchase;
+import com.android.billingclient.api.PurchasesUpdatedListener;
+import com.android.billingclient.api.SkuDetails;
+import com.android.billingclient.api.SkuDetailsParams;
+import com.android.billingclient.api.SkuDetailsResponseListener;
-import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Set;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-public class GodotPayment extends GodotPlugin {
- private Integer purchaseCallbackId = 0;
- private String accessToken;
- private String purchaseValidationUrlPrefix;
- private String transactionId;
- private final PaymentsManager mPaymentManager;
- private final Dictionary mSkuDetails = new Dictionary();
+public class GodotPayment extends GodotPlugin implements PurchasesUpdatedListener, BillingClientStateListener {
+ private final BillingClient billingClient;
+ private final HashMap<String, SkuDetails> skuDetailsCache = new HashMap<>(); // sku → SkuDetails
public GodotPayment(Godot godot) {
super(godot);
- mPaymentManager = new PaymentsManager(godot, this);
- mPaymentManager.initService();
- }
- @Override
- public void onMainActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE) {
- mPaymentManager.processPurchaseResponse(resultCode, data);
- }
+ billingClient = BillingClient
+ .newBuilder(getGodot())
+ .enablePendingPurchases()
+ .setListener(this)
+ .build();
}
- @Override
- public void onMainDestroy() {
- super.onMainDestroy();
- if (mPaymentManager != null) {
- mPaymentManager.destroy();
- }
+ public void startConnection() {
+ billingClient.startConnection(this);
}
- public void purchase(final String sku, final String transactionId) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mPaymentManager.requestPurchase(sku, transactionId);
- }
- });
- }
-
- public void consumeUnconsumedPurchases() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mPaymentManager.consumeUnconsumedPurchases();
- }
- });
+ public void endConnection() {
+ billingClient.endConnection();
}
- private String signature;
-
- public String getSignature() {
- return this.signature;
+ public boolean isReady() {
+ return this.billingClient.isReady();
}
- public void callbackSuccess(String ticket, String signature, String sku) {
- GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[] { ticket, signature, sku });
- }
+ public Dictionary queryPurchases(String type) {
+ Purchase.PurchasesResult result = billingClient.queryPurchases(type);
- public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) {
- Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku);
- GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[] { ticket, signature, sku });
- }
-
- public void callbackSuccessNoUnconsumedPurchases() {
- GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {});
- }
-
- public void callbackFailConsume(String message) {
- GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] { message });
- }
-
- public void callbackFail(String message) {
- GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] { message });
- }
-
- public void callbackCancel() {
- GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {});
- }
-
- public void callbackAlreadyOwned(String sku) {
- GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku });
- }
-
- public int getPurchaseCallbackId() {
- return purchaseCallbackId;
- }
-
- public void setPurchaseCallbackId(int purchaseCallbackId) {
- this.purchaseCallbackId = purchaseCallbackId;
- }
+ Dictionary returnValue = new Dictionary();
+ if (result.getBillingResult().getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ returnValue.put("status", 0); // OK = 0
+ returnValue.put("purchases", GodotPaymentUtils.convertPurchaseListToDictionaryObjectArray(result.getPurchasesList()));
+ } else {
+ returnValue.put("status", 1); // FAILED = 1
+ returnValue.put("response_code", result.getBillingResult().getResponseCode());
+ returnValue.put("debug_message", result.getBillingResult().getDebugMessage());
+ }
- public String getPurchaseValidationUrlPrefix() {
- return this.purchaseValidationUrlPrefix;
+ return returnValue;
}
- public void setPurchaseValidationUrlPrefix(String url) {
- this.purchaseValidationUrlPrefix = url;
- }
+ public void querySkuDetails(final String[] list, String type) {
+ List<String> skuList = Arrays.asList(list);
- public String getAccessToken() {
- return accessToken;
- }
+ SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder()
+ .setSkusList(skuList)
+ .setType(type);
- public void setAccessToken(String accessToken) {
- this.accessToken = accessToken;
+ billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {
+ @Override
+ public void onSkuDetailsResponse(BillingResult billingResult,
+ List<SkuDetails> skuDetailsList) {
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ for (SkuDetails skuDetails : skuDetailsList) {
+ skuDetailsCache.put(skuDetails.getSku(), skuDetails);
+ }
+ emitSignal("sku_details_query_completed", (Object)GodotPaymentUtils.convertSkuDetailsListToDictionaryObjectArray(skuDetailsList));
+ } else {
+ emitSignal("sku_details_query_error", billingResult.getResponseCode(), billingResult.getDebugMessage(), list);
+ }
+ }
+ });
}
- public void setTransactionId(String transactionId) {
- this.transactionId = transactionId;
+ public void acknowledgePurchase(final String purchaseToken) {
+ AcknowledgePurchaseParams acknowledgePurchaseParams =
+ AcknowledgePurchaseParams.newBuilder()
+ .setPurchaseToken(purchaseToken)
+ .build();
+ billingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
+ @Override
+ public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ emitSignal("purchase_acknowledged", purchaseToken);
+ } else {
+ emitSignal("purchase_acknowledgement_error", billingResult.getResponseCode(), billingResult.getDebugMessage(), purchaseToken);
+ }
+ }
+ });
}
- public String getTransactionId() {
- return this.transactionId;
- }
+ public void consumePurchase(String purchaseToken) {
+ ConsumeParams consumeParams = ConsumeParams.newBuilder()
+ .setPurchaseToken(purchaseToken)
+ .build();
- // request purchased items are not consumed
- public void requestPurchased() {
- runOnUiThread(new Runnable() {
+ billingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
- public void run() {
- mPaymentManager.requestPurchased();
+ public void onConsumeResponse(BillingResult billingResult, String purchaseToken) {
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ emitSignal("purchase_consumed", purchaseToken);
+ } else {
+ emitSignal("purchase_consumption_error", billingResult.getResponseCode(), billingResult.getDebugMessage(), purchaseToken);
+ }
}
});
}
- // callback for requestPurchased()
- public void callbackPurchased(String receipt, String signature, String sku) {
- GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[] { receipt, signature, sku });
- }
-
- public void callbackDisconnected() {
- GodotLib.calldeferred(purchaseCallbackId, "iap_disconnected", new Object[] {});
+ @Override
+ public void onBillingSetupFinished(BillingResult billingResult) {
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ emitSignal("connected");
+ } else {
+ emitSignal("connect_error", billingResult.getResponseCode(), billingResult.getDebugMessage());
+ }
}
- public void callbackConnected() {
- GodotLib.calldeferred(purchaseCallbackId, "iap_connected", new Object[] {});
+ @Override
+ public void onBillingServiceDisconnected() {
+ emitSignal("disconnected");
}
- // true if connected, false otherwise
- public boolean isConnected() {
- return mPaymentManager.isConnected();
- }
+ public Dictionary purchase(String sku) {
+ if (!skuDetailsCache.containsKey(sku)) {
+ emitSignal("purchase_error", null, "You must query the sku details and wait for the result before purchasing!");
+ }
- // consume item automatically after purchase. default is true.
- public void setAutoConsume(boolean autoConsume) {
- mPaymentManager.setAutoConsume(autoConsume);
- }
+ SkuDetails skuDetails = skuDetailsCache.get(sku);
+ BillingFlowParams purchaseParams = BillingFlowParams.newBuilder()
+ .setSkuDetails(skuDetails)
+ .build();
- // consume a specific item
- public void consume(String sku) {
- mPaymentManager.consume(sku);
- }
+ BillingResult result = billingClient.launchBillingFlow(getGodot(), purchaseParams);
- // query in app item detail info
- public void querySkuDetails(String[] list) {
- List<String> nKeys = Arrays.asList(list);
- List<String> cKeys = Arrays.asList(mSkuDetails.get_keys());
- ArrayList<String> fKeys = new ArrayList<String>();
- for (String key : nKeys) {
- if (!cKeys.contains(key)) {
- fKeys.add(key);
- }
- }
- if (fKeys.size() > 0) {
- mPaymentManager.querySkuDetails(fKeys.toArray(new String[0]));
+ Dictionary returnValue = new Dictionary();
+ if (result.getResponseCode() == BillingClient.BillingResponseCode.OK) {
+ returnValue.put("status", 0); // OK = 0
} else {
- completeSkuDetail();
- }
- }
-
- public void addSkuDetail(String itemJson) {
- JSONObject o = null;
- try {
- o = new JSONObject(itemJson);
- Dictionary item = new Dictionary();
- item.put("type", o.optString("type"));
- item.put("product_id", o.optString("productId"));
- item.put("title", o.optString("title"));
- item.put("description", o.optString("description"));
- item.put("price", o.optString("price"));
- item.put("price_currency_code", o.optString("price_currency_code"));
- item.put("price_amount", 0.000001d * o.optLong("price_amount_micros"));
- mSkuDetails.put(item.get("product_id").toString(), item);
- } catch (JSONException e) {
- e.printStackTrace();
+ returnValue.put("status", 1); // FAILED = 1
+ returnValue.put("response_code", result.getResponseCode());
+ returnValue.put("debug_message", result.getDebugMessage());
}
- }
- public void completeSkuDetail() {
- GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[] { mSkuDetails });
+ return returnValue;
}
- public void errorSkuDetail(String errorMessage) {
- GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage });
+ @Override
+ public void onPurchasesUpdated(final BillingResult billingResult, @Nullable final List<Purchase> list) {
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null) {
+ emitSignal("purchases_updated", (Object)GodotPaymentUtils.convertPurchaseListToDictionaryObjectArray(list));
+ } else {
+ emitSignal("purchase_error", billingResult.getResponseCode(), billingResult.getDebugMessage());
+ }
}
@NonNull
@@ -251,8 +214,26 @@ public class GodotPayment extends GodotPlugin {
@NonNull
@Override
public List<String> getPluginMethods() {
- return Arrays.asList("purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix",
- "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased",
- "setAutoConsume", "consume", "querySkuDetails", "isConnected");
+ return Arrays.asList("startConnection", "endConnection", "purchase", "querySkuDetails", "isReady", "queryPurchases", "acknowledgePurchase");
+ }
+
+ @NonNull
+ @Override
+ public Set<SignalInfo> getPluginSignals() {
+ Set<SignalInfo> signals = new ArraySet<>();
+
+ signals.add(new SignalInfo("connected"));
+ signals.add(new SignalInfo("disconnected"));
+ signals.add(new SignalInfo("connect_error", Integer.class, String.class));
+ signals.add(new SignalInfo("purchases_updated", Object[].class));
+ signals.add(new SignalInfo("purchase_error", Integer.class, String.class));
+ signals.add(new SignalInfo("sku_details_query_completed", Object[].class));
+ signals.add(new SignalInfo("sku_details_query_error", Integer.class, String.class, String[].class));
+ signals.add(new SignalInfo("purchase_acknowledged", String.class));
+ signals.add(new SignalInfo("purchase_acknowledgement_error", Integer.class, String.class, String.class));
+ signals.add(new SignalInfo("purchase_consumed", String.class));
+ signals.add(new SignalInfo("purchase_consumption_error", Integer.class, String.class, String.class));
+
+ return signals;
}
}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java
deleted file mode 100644
index 00e216e8c0..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*************************************************************************/
-/* HandlePurchaseTask.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.app.Activity;
-import android.content.Intent;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-abstract public class HandlePurchaseTask {
- private Activity context;
-
- public HandlePurchaseTask(Activity context) {
- this.context = context;
- }
-
- public void handlePurchaseRequest(int resultCode, Intent data) {
- //Log.d("XXX", "Handling purchase response");
- if (resultCode == Activity.RESULT_OK) {
- try {
- //int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
- PaymentsCache pc = new PaymentsCache(context);
-
- String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
- //Log.d("XXX", "Purchase data:" + purchaseData);
- String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
- //Log.d("XXX", "Purchase signature:" + dataSignature);
- //Log.d("SARLANGA", purchaseData);
-
- JSONObject jo = new JSONObject(purchaseData);
- //String sku = jo.getString("productId");
- //alert("You have bought the " + sku + ". Excellent choice, aventurer!");
- //String orderId = jo.getString("orderId");
- //String packageName = jo.getString("packageName");
- String productId = jo.getString("productId");
- //Long purchaseTime = jo.getLong("purchaseTime");
- //Integer state = jo.getInt("purchaseState");
- String developerPayload = jo.getString("developerPayload");
- String purchaseToken = jo.getString("purchaseToken");
-
- if (!pc.getConsumableValue("validation_hash", productId).equals(developerPayload)) {
- error("Untrusted callback");
- return;
- }
- //Log.d("XXX", "Este es el product ID:" + productId);
- pc.setConsumableValue("ticket_signautre", productId, dataSignature);
- pc.setConsumableValue("ticket", productId, purchaseData);
- pc.setConsumableFlag("block", productId, true);
- pc.setConsumableValue("token", productId, purchaseToken);
-
- success(productId, dataSignature, purchaseData);
- return;
- } catch (JSONException e) {
- error(e.getMessage());
- }
- } else if (resultCode == Activity.RESULT_CANCELED) {
- canceled();
- }
- }
-
- abstract protected void success(String sku, String signature, String ticket);
- abstract protected void error(String message);
- abstract protected void canceled();
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java
deleted file mode 100644
index 435f43c49d..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*************************************************************************/
-/* PaymentsCache.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-
-public class PaymentsCache {
- public Context context;
-
- public PaymentsCache(Context context) {
- this.context = context;
- }
-
- public void setConsumableFlag(String set, String sku, Boolean flag) {
- SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPref.edit();
- editor.putBoolean(sku, flag);
- editor.apply();
- }
-
- public boolean getConsumableFlag(String set, String sku) {
- SharedPreferences sharedPref = context.getSharedPreferences(
- "consumables_" + set, Context.MODE_PRIVATE);
- return sharedPref.getBoolean(sku, false);
- }
-
- public void setConsumableValue(String set, String sku, String value) {
- SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPref.edit();
- editor.putString(sku, value);
- //Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku);
- editor.apply();
- }
-
- public String getConsumableValue(String set, String sku) {
- SharedPreferences sharedPref = context.getSharedPreferences(
- "consumables_" + set, Context.MODE_PRIVATE);
- //Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku);
- return sharedPref.getString(sku, null);
- }
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java
deleted file mode 100644
index 9b3a338866..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*************************************************************************/
-/* PaymentsManager.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.app.Activity;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.text.TextUtils;
-import android.util.Log;
-
-import com.android.vending.billing.IInAppBillingService;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-public class PaymentsManager {
- public static final int BILLING_RESPONSE_RESULT_OK = 0;
- public static final int REQUEST_CODE_FOR_PURCHASE = 0x1001;
- private static boolean auto_consume = true;
-
- private final Activity activity;
- private final GodotPayment godotPayment;
- IInAppBillingService mService;
-
- PaymentsManager(Activity activity, GodotPayment godotPayment) {
- this.activity = activity;
- this.godotPayment = godotPayment;
- }
-
- public PaymentsManager initService() {
- Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
- intent.setPackage("com.android.vending");
- activity.bindService(
- intent,
- mServiceConn,
- Context.BIND_AUTO_CREATE);
- return this;
- }
-
- public void destroy() {
- if (mService != null) {
- activity.unbindService(mServiceConn);
- }
- }
-
- ServiceConnection mServiceConn = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- mService = null;
-
- // At this stage, godotPayment might not have been initialized yet.
- if (godotPayment != null) {
- godotPayment.callbackDisconnected();
- }
- }
-
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- mService = IInAppBillingService.Stub.asInterface(service);
-
- // At this stage, godotPayment might not have been initialized yet.
- if (godotPayment != null) {
- godotPayment.callbackConnected();
- }
- }
- };
-
- public void requestPurchase(final String sku, String transactionId) {
- new PurchaseTask(mService, activity) {
- @Override
- protected void error(String message) {
- godotPayment.callbackFail(message);
- }
-
- @Override
- protected void canceled() {
- godotPayment.callbackCancel();
- }
-
- @Override
- protected void alreadyOwned() {
- godotPayment.callbackAlreadyOwned(sku);
- }
- }
- .purchase(sku, transactionId);
- }
-
- public boolean isConnected() {
- return mService != null;
- }
-
- public void consumeUnconsumedPurchases() {
- new ReleaseAllConsumablesTask(mService, activity) {
- @Override
- protected void success(String sku, String receipt, String signature, String token) {
- godotPayment.callbackSuccessProductMassConsumed(receipt, signature, sku);
- }
-
- @Override
- protected void error(String message) {
- Log.d("godot", "consumeUnconsumedPurchases :" + message);
- godotPayment.callbackFailConsume(message);
- }
-
- @Override
- protected void notRequired() {
- Log.d("godot", "callbackSuccessNoUnconsumedPurchases :");
- godotPayment.callbackSuccessNoUnconsumedPurchases();
- }
- }
- .consumeItAll();
- }
-
- public void requestPurchased() {
- try {
- PaymentsCache pc = new PaymentsCache(activity);
-
- String continueToken = null;
-
- do {
- Bundle bundle = mService.getPurchases(3, activity.getPackageName(), "inapp", continueToken);
-
- if (bundle.getInt("RESPONSE_CODE") == 0) {
- final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
- final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
-
- if (myPurchases == null || myPurchases.size() == 0) {
- godotPayment.callbackPurchased("", "", "");
- return;
- }
-
- for (int i = 0; i < myPurchases.size(); i++) {
- try {
- String receipt = myPurchases.get(i);
- JSONObject inappPurchaseData = new JSONObject(receipt);
- String sku = inappPurchaseData.getString("productId");
- String token = inappPurchaseData.getString("purchaseToken");
- String signature = mySignatures.get(i);
-
- pc.setConsumableValue("ticket_signautre", sku, signature);
- pc.setConsumableValue("ticket", sku, receipt);
- pc.setConsumableFlag("block", sku, true);
- pc.setConsumableValue("token", sku, token);
-
- godotPayment.callbackPurchased(receipt, signature, sku);
- } catch (JSONException e) {
- }
- }
- }
- continueToken = bundle.getString("INAPP_CONTINUATION_TOKEN");
- Log.d("godot", "continue token = " + continueToken);
- } while (!TextUtils.isEmpty(continueToken));
- } catch (Exception e) {
- Log.d("godot", "Error requesting purchased products:" + e.getClass().getName() + ":" + e.getMessage());
- }
- }
-
- public void processPurchaseResponse(int resultCode, Intent data) {
- new HandlePurchaseTask(activity) {
- @Override
- protected void success(final String sku, final String signature, final String ticket) {
- godotPayment.callbackSuccess(ticket, signature, sku);
-
- if (auto_consume) {
- new ConsumeTask(mService, activity) {
- @Override
- protected void success(String ticket) {
- }
-
- @Override
- protected void error(String message) {
- godotPayment.callbackFail(message);
- }
- }
- .consume(sku);
- }
- }
-
- @Override
- protected void error(String message) {
- godotPayment.callbackFail(message);
- }
-
- @Override
- protected void canceled() {
- godotPayment.callbackCancel();
- }
- }
- .handlePurchaseRequest(resultCode, data);
- }
-
- public void validatePurchase(String purchaseToken, final String sku) {
- new ValidateTask(activity, godotPayment) {
- @Override
- protected void success() {
- new ConsumeTask(mService, activity) {
- @Override
- protected void success(String ticket) {
- godotPayment.callbackSuccess(ticket, null, sku);
- }
-
- @Override
- protected void error(String message) {
- godotPayment.callbackFail(message);
- }
- }
- .consume(sku);
- }
-
- @Override
- protected void error(String message) {
- godotPayment.callbackFail(message);
- }
-
- @Override
- protected void canceled() {
- godotPayment.callbackCancel();
- }
- }
- .validatePurchase(sku);
- }
-
- public void setAutoConsume(boolean autoConsume) {
- auto_consume = autoConsume;
- }
-
- public void consume(final String sku) {
- new ConsumeTask(mService, activity) {
- @Override
- protected void success(String ticket) {
- godotPayment.callbackSuccessProductMassConsumed(ticket, "", sku);
- }
-
- @Override
- protected void error(String message) {
- godotPayment.callbackFailConsume(message);
- }
- }
- .consume(sku);
- }
-
- // Workaround to bug where sometimes response codes come as Long instead of Integer
- int getResponseCodeFromBundle(Bundle b) {
- Object o = b.get("RESPONSE_CODE");
- if (o == null) {
- //logDebug("Bundle with null response code, assuming OK (known issue)");
- return BILLING_RESPONSE_RESULT_OK;
- } else if (o instanceof Integer)
- return ((Integer)o).intValue();
- else if (o instanceof Long)
- return (int)((Long)o).longValue();
- else {
- //logError("Unexpected type for bundle response code.");
- //logError(o.getClass().getName());
- throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
- }
- }
-
- /**
- * Returns a human-readable description for the given response code.
- *
- * @param code The response code
- * @return A human-readable string explaining the result code.
- * It also includes the result code numerically.
- */
- public static String getResponseDesc(int code) {
- String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/"
- +
- "3:Billing Unavailable/4:Item unavailable/"
- +
- "5:Developer Error/6:Error/7:Item Already Owned/"
- +
- "8:Item not owned")
- .split("/");
- String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/"
- +
- "-1002:Bad response received/"
- +
- "-1003:Purchase signature verification failed/"
- +
- "-1004:Send intent failed/"
- +
- "-1005:User cancelled/"
- +
- "-1006:Unknown purchase response/"
- +
- "-1007:Missing token/"
- +
- "-1008:Unknown error/"
- +
- "-1009:Subscriptions not available/"
- +
- "-1010:Invalid consumption attempt")
- .split("/");
-
- if (code <= -1000) {
- int index = -1000 - code;
- if (index >= 0 && index < iabhelper_msgs.length)
- return iabhelper_msgs[index];
- else
- return String.valueOf(code) + ":Unknown IAB Helper Error";
- } else if (code < 0 || code >= iab_msgs.length)
- return String.valueOf(code) + ":Unknown";
- else
- return iab_msgs[code];
- }
-
- public void querySkuDetails(final String[] list) {
- (new Thread(new Runnable() {
- @Override
- public void run() {
- ArrayList<String> skuList = new ArrayList<String>(Arrays.asList(list));
- if (skuList.size() == 0) {
- return;
- }
- // Split the sku list in blocks of no more than 20 elements.
- ArrayList<ArrayList<String>> packs = new ArrayList<ArrayList<String>>();
- ArrayList<String> tempList;
- int n = skuList.size() / 20;
- int mod = skuList.size() % 20;
- for (int i = 0; i < n; i++) {
- tempList = new ArrayList<String>();
- for (String s : skuList.subList(i * 20, i * 20 + 20)) {
- tempList.add(s);
- }
- packs.add(tempList);
- }
- if (mod != 0) {
- tempList = new ArrayList<String>();
- for (String s : skuList.subList(n * 20, n * 20 + mod)) {
- tempList.add(s);
- }
- packs.add(tempList);
- }
- for (ArrayList<String> skuPartList : packs) {
- Bundle querySkus = new Bundle();
- querySkus.putStringArrayList("ITEM_ID_LIST", skuPartList);
- Bundle skuDetails = null;
- try {
- skuDetails = mService.getSkuDetails(3, activity.getPackageName(), "inapp", querySkus);
- if (!skuDetails.containsKey("DETAILS_LIST")) {
- int response = getResponseCodeFromBundle(skuDetails);
- if (response != BILLING_RESPONSE_RESULT_OK) {
- godotPayment.errorSkuDetail(getResponseDesc(response));
- } else {
- godotPayment.errorSkuDetail("No error but no detail list.");
- }
- return;
- }
-
- ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
-
- for (String thisResponse : responseList) {
- Log.d("godot", "response = " + thisResponse);
- godotPayment.addSkuDetail(thisResponse);
- }
- } catch (RemoteException e) {
- e.printStackTrace();
- godotPayment.errorSkuDetail("RemoteException error!");
- }
- }
- godotPayment.completeSkuDetail();
- }
- }))
- .start();
- }
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java
deleted file mode 100644
index f894bd5132..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*************************************************************************/
-/* PurchaseTask.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.content.Intent;
-import android.content.IntentSender.SendIntentException;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.vending.billing.IInAppBillingService;
-
-abstract public class PurchaseTask {
- private Activity context;
-
- private IInAppBillingService mService;
- public PurchaseTask(IInAppBillingService mService, Activity context) {
- this.context = context;
- this.mService = mService;
- }
-
- private boolean isLooping = false;
-
- public void purchase(final String sku, final String transactionId) {
- Log.d("XXX", "Starting purchase for: " + sku);
- PaymentsCache pc = new PaymentsCache(context);
- Boolean isBlocked = pc.getConsumableFlag("block", sku);
- /*
- if(isBlocked) {
- Log.d("XXX", "Is awaiting payment confirmation");
- error("Awaiting payment confirmation");
- return;
- }
- */
- final String hash = transactionId;
-
- Bundle buyIntentBundle;
- try {
- buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash);
- } catch (RemoteException e) {
- //Log.d("XXX", "Error: " + e.getMessage());
- error(e.getMessage());
- return;
- }
- Object rc = buyIntentBundle.get("RESPONSE_CODE");
- int responseCode = 0;
- if (rc == null) {
- responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK;
- } else if (rc instanceof Integer) {
- responseCode = ((Integer)rc).intValue();
- } else if (rc instanceof Long) {
- responseCode = (int)((Long)rc).longValue();
- }
- //Log.d("XXX", "Buy intent response code: " + responseCode);
- if (responseCode == 1 || responseCode == 3 || responseCode == 4) {
- canceled();
- return;
- }
- if (responseCode == 7) {
- alreadyOwned();
- return;
- }
-
- PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
- pc.setConsumableValue("validation_hash", sku, hash);
- try {
- if (context == null) {
- //Log.d("XXX", "No context!");
- }
- if (pendingIntent == null) {
- //Log.d("XXX", "No pending intent");
- }
- //Log.d("XXX", "Starting activity for purchase!");
- context.startIntentSenderForResult(
- pendingIntent.getIntentSender(),
- PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
- new Intent(),
- Integer.valueOf(0), Integer.valueOf(0),
- Integer.valueOf(0));
- } catch (SendIntentException e) {
- error(e.getMessage());
- }
- }
-
- abstract protected void error(String message);
- abstract protected void canceled();
- abstract protected void alreadyOwned();
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java
deleted file mode 100644
index 1d52cf0fa5..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*************************************************************************/
-/* ReleaseAllConsumablesTask.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import android.content.Context;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.util.Log;
-
-import com.android.vending.billing.IInAppBillingService;
-
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-abstract public class ReleaseAllConsumablesTask {
- private Context context;
- private IInAppBillingService mService;
-
- private static class ReleaseAllConsumablesAsyncTask extends AsyncTask<String, String, String> {
- private WeakReference<ReleaseAllConsumablesTask> mTask;
- private String mSku;
- private String mReceipt;
- private String mSignature;
- private String mToken;
-
- ReleaseAllConsumablesAsyncTask(ReleaseAllConsumablesTask task, String sku, String receipt, String signature, String token) {
- mTask = new WeakReference<ReleaseAllConsumablesTask>(task);
-
- mSku = sku;
- mReceipt = receipt;
- mSignature = signature;
- mToken = token;
- }
-
- @Override
- protected String doInBackground(String... params) {
- ReleaseAllConsumablesTask consume = mTask.get();
- if (consume != null) {
- return consume.doInBackground(mToken);
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(String param) {
- ReleaseAllConsumablesTask consume = mTask.get();
- if (consume != null) {
- consume.success(mSku, mReceipt, mSignature, mToken);
- }
- }
- }
-
- public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) {
- this.context = context;
- this.mService = mService;
- }
-
- public void consumeItAll() {
- try {
- //Log.d("godot", "consumeItall for " + context.getPackageName());
- Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp", null);
-
- if (bundle.getInt("RESPONSE_CODE") == 0) {
- final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
- final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
-
- if (myPurchases == null || myPurchases.size() == 0) {
- //Log.d("godot", "No purchases!");
- notRequired();
- return;
- }
-
- //Log.d("godot", "# products to be consumed:" + myPurchases.size());
- for (int i = 0; i < myPurchases.size(); i++) {
- try {
- String receipt = myPurchases.get(i);
- JSONObject inappPurchaseData = new JSONObject(receipt);
- String sku = inappPurchaseData.getString("productId");
- String token = inappPurchaseData.getString("purchaseToken");
- String signature = mySignatures.get(i);
- //Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt);
- new ReleaseAllConsumablesAsyncTask(this, sku, receipt, signature, token).execute();
- } catch (JSONException e) {
- }
- }
- }
- } catch (Exception e) {
- Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage());
- }
- }
-
- private String doInBackground(String token) {
- try {
- //Log.d("godot", "Requesting to consume an item with token ." + token);
- int response = mService.consumePurchase(3, context.getPackageName(), token);
- //Log.d("godot", "consumePurchase response: " + response);
- if (response == 0 || response == 8) {
- return null;
- }
- } catch (Exception e) {
- Log.d("godot", "Error " + e.getClass().getName() + ":" + e.getMessage());
- }
- return null;
- }
-
- abstract protected void success(String sku, String receipt, String signature, String token);
- abstract protected void error(String message);
- abstract protected void notRequired();
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java
deleted file mode 100644
index a7156152ce..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*************************************************************************/
-/* ValidateTask.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment;
-
-import org.godotengine.godot.plugin.payment.utils.HttpRequester;
-import org.godotengine.godot.plugin.payment.utils.RequestParams;
-
-import android.app.Activity;
-import android.app.ProgressDialog;
-import android.os.AsyncTask;
-
-import java.lang.ref.WeakReference;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-abstract public class ValidateTask {
- private Activity context;
- private GodotPayment godotPayments;
- private ProgressDialog dialog;
- private String mSku;
-
- private static class ValidateAsyncTask extends AsyncTask<String, String, String> {
- private WeakReference<ValidateTask> mTask;
-
- ValidateAsyncTask(ValidateTask task) {
- mTask = new WeakReference<>(task);
- }
-
- @Override
- protected void onPreExecute() {
- ValidateTask task = mTask.get();
- if (task != null) {
- task.onPreExecute();
- }
- }
-
- @Override
- protected String doInBackground(String... params) {
- ValidateTask task = mTask.get();
- if (task != null) {
- return task.doInBackground(params);
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(String response) {
- ValidateTask task = mTask.get();
- if (task != null) {
- task.onPostExecute(response);
- }
- }
- }
-
- public ValidateTask(Activity context, GodotPayment godotPayments) {
- this.context = context;
- this.godotPayments = godotPayments;
- }
-
- public void validatePurchase(final String sku) {
- mSku = sku;
- new ValidateAsyncTask(this).execute();
- }
-
- private void onPreExecute() {
- dialog = ProgressDialog.show(context, null, "Please wait...");
- }
-
- private String doInBackground(String... params) {
- PaymentsCache pc = new PaymentsCache(context);
- String url = godotPayments.getPurchaseValidationUrlPrefix();
- RequestParams param = new RequestParams();
- param.setUrl(url);
- param.put("ticket", pc.getConsumableValue("ticket", mSku));
- param.put("purchaseToken", pc.getConsumableValue("token", mSku));
- param.put("sku", mSku);
- //Log.d("XXX", "Haciendo request a " + url);
- //Log.d("XXX", "ticket: " + pc.getConsumableValue("ticket", sku));
- //Log.d("XXX", "purchaseToken: " + pc.getConsumableValue("token", sku));
- //Log.d("XXX", "sku: " + sku);
- param.put("package", context.getApplicationContext().getPackageName());
- HttpRequester requester = new HttpRequester();
- String jsonResponse = requester.post(param);
- //Log.d("XXX", "Validation response:\n"+jsonResponse);
- return jsonResponse;
- }
-
- private void onPostExecute(String response) {
- if (dialog != null) {
- dialog.dismiss();
- dialog = null;
- }
- JSONObject j;
- try {
- j = new JSONObject(response);
- if (j.getString("status").equals("OK")) {
- success();
- return;
- } else if (j.getString("status") != null) {
- error(j.getString("message"));
- } else {
- error("Connection error");
- }
- } catch (JSONException e) {
- error(e.getMessage());
- } catch (Exception e) {
- error(e.getMessage());
- }
- }
-
- abstract protected void success();
- abstract protected void error(String message);
- abstract protected void canceled();
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/CustomSSLSocketFactory.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/CustomSSLSocketFactory.java
deleted file mode 100644
index 55b87b49e5..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/CustomSSLSocketFactory.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*************************************************************************/
-/* CustomSSLSocketFactory.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment.utils;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.http.conn.ssl.SSLSocketFactory;
-
-/**
- *
- * @author Luis Linietsky <luis.linietsky@gmail.com>
- */
-public class CustomSSLSocketFactory extends SSLSocketFactory {
- SSLContext sslContext = SSLContext.getInstance("TLS");
-
- public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
- super(truststore);
-
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
- tmf.init(truststore);
-
- sslContext.init(null, tmf.getTrustManagers(), null);
- }
-
- @Override
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
- return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
- }
-
- @Override
- public Socket createSocket() throws IOException {
- return sslContext.getSocketFactory().createSocket();
- }
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/GodotPaymentUtils.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/GodotPaymentUtils.java
new file mode 100644
index 0000000000..f569c1b8bf
--- /dev/null
+++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/GodotPaymentUtils.java
@@ -0,0 +1,66 @@
+package org.godotengine.godot.plugin.payment.utils;
+
+import org.godotengine.godot.Dictionary;
+
+import com.android.billingclient.api.Purchase;
+import com.android.billingclient.api.SkuDetails;
+
+import java.util.List;
+
+public class GodotPaymentUtils {
+ public static Dictionary convertPurchaseToDictionary(Purchase purchase) {
+ Dictionary dictionary = new Dictionary();
+ dictionary.put("order_id", purchase.getOrderId());
+ dictionary.put("package_name", purchase.getPackageName());
+ dictionary.put("purchase_state", Integer.valueOf(purchase.getPurchaseState()));
+ dictionary.put("purchase_time", Long.valueOf(purchase.getPurchaseTime()));
+ dictionary.put("purchase_token", purchase.getPurchaseToken());
+ dictionary.put("signature", purchase.getSignature());
+ dictionary.put("sku", purchase.getSku());
+ dictionary.put("is_acknowledged", Boolean.valueOf(purchase.isAcknowledged()));
+ dictionary.put("is_auto_renewing", Boolean.valueOf(purchase.isAutoRenewing()));
+ return dictionary;
+ }
+
+ public static Dictionary convertSkuDetailsToDictionary(SkuDetails details) {
+ Dictionary dictionary = new Dictionary();
+ dictionary.put("sku", details.getSku());
+ dictionary.put("title", details.getTitle());
+ dictionary.put("description", details.getDescription());
+ dictionary.put("price", details.getPrice());
+ dictionary.put("price_currency_code", details.getPriceCurrencyCode());
+ dictionary.put("price_amount_micros", Long.valueOf(details.getPriceAmountMicros()));
+ dictionary.put("free_trial_period", details.getFreeTrialPeriod());
+ dictionary.put("icon_url", details.getIconUrl());
+ dictionary.put("introductory_price", details.getIntroductoryPrice());
+ dictionary.put("introductory_price_amount_micros", Long.valueOf(details.getIntroductoryPriceAmountMicros()));
+ dictionary.put("introductory_price_cycles", details.getIntroductoryPriceCycles());
+ dictionary.put("introductory_price_period", details.getIntroductoryPricePeriod());
+ dictionary.put("original_price", details.getOriginalPrice());
+ dictionary.put("original_price_amount_micros", Long.valueOf(details.getOriginalPriceAmountMicros()));
+ dictionary.put("subscription_period", details.getSubscriptionPeriod());
+ dictionary.put("type", details.getType());
+ dictionary.put("is_rewarded", Boolean.valueOf(details.isRewarded()));
+ return dictionary;
+ }
+
+ public static Object[] convertPurchaseListToDictionaryObjectArray(List<Purchase> purchases) {
+ Object[] purchaseDictionaries = new Object[purchases.size()];
+
+ for (int i = 0; i < purchases.size(); i++) {
+ purchaseDictionaries[i] = GodotPaymentUtils.convertPurchaseToDictionary(purchases.get(i));
+ }
+
+ return purchaseDictionaries;
+ }
+
+ public static Object[] convertSkuDetailsListToDictionaryObjectArray(List<SkuDetails> skuDetails) {
+ Object[] skuDetailsDictionaries = new Object[skuDetails.size()];
+
+ for (int i = 0; i < skuDetails.size(); i++) {
+ skuDetailsDictionaries[i] = GodotPaymentUtils.convertSkuDetailsToDictionary(skuDetails.get(i));
+ }
+
+ return skuDetailsDictionaries;
+ }
+}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/HttpRequester.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/HttpRequester.java
deleted file mode 100644
index 0afcf60f38..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/HttpRequester.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*************************************************************************/
-/* HttpRequester.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment.utils;
-
-import org.godotengine.godot.utils.Crypt;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.util.Log;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.security.KeyStore;
-import java.util.Date;
-
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpVersion;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.conn.scheme.PlainSocketFactory;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.conn.scheme.SchemeRegistry;
-import org.apache.http.conn.ssl.SSLSocketFactory;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.params.HttpProtocolParams;
-import org.apache.http.protocol.HTTP;
-import org.apache.http.util.EntityUtils;
-
-/**
- *
- * @author Luis Linietsky <luis.linietsky@gmail.com>
- */
-public class HttpRequester {
- private Context context;
- private static final int TTL = 600000; // 10 minutos
- private long cttl = 0;
-
- public HttpRequester() {
- //Log.d("XXX", "Creando http request sin contexto");
- }
-
- public HttpRequester(Context context) {
- this.context = context;
- //Log.d("XXX", "Creando http request con contexto");
- }
-
- public String post(RequestParams params) {
- HttpPost httppost = new HttpPost(params.getUrl());
- try {
- httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList()));
- return request(httppost);
- } catch (UnsupportedEncodingException e) {
- return null;
- }
- }
-
- public String get(RequestParams params) {
- String response = getResponseFromCache(params.getUrl());
- if (response == null) {
- //Log.d("XXX", "Cache miss!");
- HttpGet httpget = new HttpGet(params.getUrl());
- long timeInit = new Date().getTime();
- response = request(httpget);
- long delay = new Date().getTime() - timeInit;
- Log.d("HttpRequest::get(url)", "Url: " + params.getUrl() + " downloaded in " + String.format("%.03f", delay / 1000.0f) + " seconds");
- if (response == null || response.length() == 0) {
- response = "";
- } else {
- saveResponseIntoCache(params.getUrl(), response);
- }
- }
- Log.d("XXX", "Req: " + params.getUrl());
- Log.d("XXX", "Resp: " + response);
- return response;
- }
-
- private String request(HttpUriRequest request) {
- //Log.d("XXX", "Haciendo request a: " + request.getURI() );
- Log.d("PPP", "Haciendo request a: " + request.getURI());
- long init = new Date().getTime();
- HttpClient httpclient = getNewHttpClient();
- HttpParams httpParameters = httpclient.getParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, 0);
- HttpConnectionParams.setSoTimeout(httpParameters, 0);
- HttpConnectionParams.setTcpNoDelay(httpParameters, true);
- try {
- HttpResponse response = httpclient.execute(request);
- Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI());
- //Log.d("XXX1", "Status:" + response.getStatusLine().toString());
- if (response.getStatusLine().getStatusCode() == 200) {
- String strResponse = EntityUtils.toString(response.getEntity());
- //Log.d("XXX2", strResponse);
- return strResponse;
- } else {
- Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity()));
- return null;
- }
-
- } catch (ClientProtocolException e) {
- Log.d("XXX3", e.getMessage());
- } catch (IOException e) {
- Log.d("XXX4", e.getMessage());
- }
- return null;
- }
-
- private HttpClient getNewHttpClient() {
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null, null);
-
- SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
- sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
-
- HttpParams params = new BasicHttpParams();
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
-
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", sf, 443));
-
- ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
-
- return new DefaultHttpClient(ccm, params);
- } catch (Exception e) {
- return new DefaultHttpClient();
- }
- }
-
- private static String convertStreamToString(InputStream is) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- StringBuilder sb = new StringBuilder();
- String line = null;
- try {
- while ((line = reader.readLine()) != null) {
- sb.append((line + "\n"));
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
-
- public void saveResponseIntoCache(String request, String response) {
- if (context == null) {
- //Log.d("XXX", "No context, cache failed!");
- return;
- }
- SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPref.edit();
- editor.putString("request_" + Crypt.md5(request), response);
- editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl());
- editor.apply();
- }
-
- public String getResponseFromCache(String request) {
- if (context == null) {
- Log.d("XXX", "No context, cache miss");
- return null;
- }
- SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
- long ttl = getResponseTtl(request);
- if (ttl == 0l || (new Date().getTime() - ttl) > 0l) {
- Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime());
- return null;
- }
- return sharedPref.getString("request_" + Crypt.md5(request), null);
- }
-
- public long getResponseTtl(String request) {
- SharedPreferences sharedPref = context.getSharedPreferences(
- "http_get_cache", Context.MODE_PRIVATE);
- return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l);
- }
-
- public long getTtl() {
- return cttl > 0 ? cttl : TTL;
- }
-
- public void setTtl(long ttl) {
- this.cttl = (ttl * 1000) + new Date().getTime();
- }
-}
diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/RequestParams.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/RequestParams.java
deleted file mode 100644
index 6b66c7e474..0000000000
--- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/utils/RequestParams.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*************************************************************************/
-/* RequestParams.java */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-package org.godotengine.godot.plugin.payment.utils;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.apache.http.NameValuePair;
-import org.apache.http.message.BasicNameValuePair;
-
-/**
- *
- * @author Luis Linietsky <luis.linietsky@gmail.com>
- */
-public class RequestParams {
- private HashMap<String, String> params;
- private String url;
-
- public RequestParams() {
- params = new HashMap<String, String>();
- }
-
- public void put(String key, String value) {
- params.put(key, value);
- }
-
- public String get(String key) {
- return params.get(key);
- }
-
- public void remove(Object key) {
- params.remove(key);
- }
-
- public boolean has(String key) {
- return params.containsKey(key);
- }
-
- public List<NameValuePair> toPairsList() {
- List<NameValuePair> fields = new ArrayList<NameValuePair>();
-
- for (String key : params.keySet()) {
- fields.add(new BasicNameValuePair(key, this.get(key)));
- }
- return fields;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-}
diff --git a/platform/android/java_godot_io_wrapper.cpp b/platform/android/java_godot_io_wrapper.cpp
index 0da0bd6387..0a42adeaf2 100644
--- a/platform/android/java_godot_io_wrapper.cpp
+++ b/platform/android/java_godot_io_wrapper.cpp
@@ -53,7 +53,7 @@ GodotIOJavaWrapper::GodotIOJavaWrapper(JNIEnv *p_env, jobject p_godot_io_instanc
_get_model = p_env->GetMethodID(cls, "getModel", "()Ljava/lang/String;");
_get_screen_DPI = p_env->GetMethodID(cls, "getScreenDPI", "()I");
_get_unique_id = p_env->GetMethodID(cls, "getUniqueID", "()Ljava/lang/String;");
- _show_keyboard = p_env->GetMethodID(cls, "showKeyboard", "(Ljava/lang/String;I)V");
+ _show_keyboard = p_env->GetMethodID(cls, "showKeyboard", "(Ljava/lang/String;III)V");
_hide_keyboard = p_env->GetMethodID(cls, "hideKeyboard", "()V");
_set_screen_orientation = p_env->GetMethodID(cls, "setScreenOrientation", "(I)V");
_get_screen_orientation = p_env->GetMethodID(cls, "getScreenOrientation", "()I");
@@ -132,11 +132,11 @@ bool GodotIOJavaWrapper::has_vk() {
return (_show_keyboard != 0) && (_hide_keyboard != 0);
}
-void GodotIOJavaWrapper::show_vk(const String &p_existing, int p_max_input_length) {
+void GodotIOJavaWrapper::show_vk(const String &p_existing, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
if (_show_keyboard) {
JNIEnv *env = ThreadAndroid::get_env();
jstring jStr = env->NewStringUTF(p_existing.utf8().get_data());
- env->CallVoidMethod(godot_io_instance, _show_keyboard, jStr, p_max_input_length);
+ env->CallVoidMethod(godot_io_instance, _show_keyboard, jStr, p_max_input_length, p_cursor_start, p_cursor_end);
}
}
diff --git a/platform/android/java_godot_io_wrapper.h b/platform/android/java_godot_io_wrapper.h
index dbb3b564f6..1742021379 100644
--- a/platform/android/java_godot_io_wrapper.h
+++ b/platform/android/java_godot_io_wrapper.h
@@ -70,7 +70,7 @@ public:
int get_screen_dpi();
String get_unique_id();
bool has_vk();
- void show_vk(const String &p_existing, int p_max_input_length);
+ void show_vk(const String &p_existing, int p_max_input_length, int p_cursor_start, int p_cursor_end);
void hide_vk();
int get_vk_height();
void set_vk_height(int p_height);
diff --git a/platform/android/java_godot_lib_jni.cpp b/platform/android/java_godot_lib_jni.cpp
index 23e0d24b57..1f61c4a805 100644
--- a/platform/android/java_godot_lib_jni.cpp
+++ b/platform/android/java_godot_lib_jni.cpp
@@ -164,9 +164,20 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jc
ClassDB::register_class<JNISingleton>();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jint width, jint height) {
- if (os_android)
- os_android->set_display_size(Size2i(width, height));
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jobject p_surface, jint p_width, jint p_height) {
+ if (os_android) {
+ os_android->set_display_size(Size2i(p_width, p_height));
+
+ // No need to reset the surface during startup
+ if (step > 0) {
+ if (p_surface) {
+ ANativeWindow *native_window = ANativeWindow_fromSurface(env, p_surface);
+ os_android->set_native_window(native_window);
+
+ DisplayServerAndroid::get_singleton()->reset_window();
+ }
+ }
+ }
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface, jboolean p_32_bits) {
@@ -375,8 +386,8 @@ JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv *
return env->NewStringUTF(ProjectSettings::get_singleton()->get(js).operator String().utf8().get_data());
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jclass clazz, jint ID, jstring method, jobjectArray params) {
- Object *obj = ObjectDB::get_instance(ObjectID((uint64_t)ID));
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params) {
+ Object *obj = ObjectDB::get_instance(ObjectID(ID));
ERR_FAIL_COND(!obj);
int res = env->PushLocalFrame(16);
@@ -405,8 +416,8 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *en
env->PopLocalFrame(nullptr);
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jint ID, jstring method, jobjectArray params) {
- Object *obj = ObjectDB::get_instance(ObjectID((uint64_t)ID));
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params) {
+ Object *obj = ObjectDB::get_instance(ObjectID(ID));
ERR_FAIL_COND(!obj);
int res = env->PushLocalFrame(16);
diff --git a/platform/android/java_godot_lib_jni.h b/platform/android/java_godot_lib_jni.h
index 221d701e2b..e8be7be0d0 100644
--- a/platform/android/java_godot_lib_jni.h
+++ b/platform/android/java_godot_lib_jni.h
@@ -40,7 +40,7 @@ extern "C" {
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *env, jclass clazz, jobject activity, jobject p_asset_manager, jboolean p_use_apk_expansion);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env, jclass clazz, jobject activity);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jclass clazz, jobjectArray p_cmdline);
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jint width, jint height);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jobject p_surface, jint p_width, jint p_height);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface, jboolean p_32_bits);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jclass clazz);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jclass clazz);
@@ -61,8 +61,8 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv *env
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv *env, jclass clazz);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv *env, jclass clazz);
JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv *env, jclass clazz, jstring path);
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jclass clazz, jint ID, jstring method, jobjectArray params);
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jint ID, jstring method, jobjectArray params);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jlong ID, jstring method, jobjectArray params);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setVirtualKeyboardHeight(JNIEnv *env, jclass clazz, jint p_height);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_requestPermissionResult(JNIEnv *env, jclass clazz, jstring p_permission, jboolean p_result);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_onRendererResumed(JNIEnv *env, jclass clazz);
diff --git a/platform/android/plugin/godot_plugin_config.h b/platform/android/plugin/godot_plugin_config.h
index 9ad7de1202..5bc0fc3a58 100644
--- a/platform/android/plugin/godot_plugin_config.h
+++ b/platform/android/plugin/godot_plugin_config.h
@@ -70,6 +70,8 @@ The `dependencies` section and fields are optional and defined as follow:
struct PluginConfig {
// Set to true when the config file is properly loaded.
bool valid_config = false;
+ // Unix timestamp of last change to this plugin.
+ uint64_t last_updated = 0;
// Required config section
String name;
@@ -87,11 +89,12 @@ struct PluginConfig {
*/
static const PluginConfig GODOT_PAYMENT = {
/*.valid_config =*/true,
+ /*.last_updated =*/0,
/*.name =*/"GodotPayment",
/*.binary_type =*/"local",
/*.binary =*/"res://android/build/libs/plugins/GodotPayment.release.aar",
/*.local_dependencies =*/{},
- /*.remote_dependencies =*/{},
+ /*.remote_dependencies =*/String("com.android.billingclient:billing:2.2.1").split("|"),
/*.custom_maven_repos =*/{}
};
@@ -150,6 +153,18 @@ static inline bool is_plugin_config_valid(PluginConfig plugin_config) {
return valid_name && valid_binary && valid_binary_type && valid_local_dependencies;
}
+static inline uint64_t get_plugin_modification_time(const PluginConfig &plugin_config, const String &config_path) {
+ uint64_t last_updated = FileAccess::get_modified_time(config_path);
+ last_updated = MAX(last_updated, FileAccess::get_modified_time(plugin_config.binary));
+
+ for (int i = 0; i < plugin_config.local_dependencies.size(); i++) {
+ String binary = plugin_config.local_dependencies.get(i);
+ last_updated = MAX(last_updated, FileAccess::get_modified_time(binary));
+ }
+
+ return last_updated;
+}
+
static inline PluginConfig load_plugin_config(Ref<ConfigFile> config_file, const String &path) {
PluginConfig plugin_config = {};
@@ -177,6 +192,7 @@ static inline PluginConfig load_plugin_config(Ref<ConfigFile> config_file, const
}
plugin_config.valid_config = is_plugin_config_valid(plugin_config);
+ plugin_config.last_updated = get_plugin_modification_time(plugin_config, path);
}
}
diff --git a/platform/android/plugin/godot_plugin_jni.cpp b/platform/android/plugin/godot_plugin_jni.cpp
index 557743fa73..053a4c078e 100644
--- a/platform/android/plugin/godot_plugin_jni.cpp
+++ b/platform/android/plugin/godot_plugin_jni.cpp
@@ -114,12 +114,13 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeEmitS
String signal_name = jstring_to_string(j_signal_name, env);
int count = env->GetArrayLength(j_signal_params);
+ Variant variant_params[count];
const Variant *args[count];
for (int i = 0; i < count; i++) {
jobject j_param = env->GetObjectArrayElement(j_signal_params, i);
- Variant variant = _jobject_to_variant(env, j_param);
- args[i] = &variant;
+ variant_params[i] = _jobject_to_variant(env, j_param);
+ args[i] = &variant_params[i];
env->DeleteLocalRef(j_param);
};
diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp
index 107d142757..41dd623e69 100644
--- a/platform/iphone/os_iphone.cpp
+++ b/platform/iphone/os_iphone.cpp
@@ -441,7 +441,7 @@ extern Error _shell_open(String p_uri);
extern void _set_keep_screen_on(bool p_enabled);
extern void _vibrate();
-void OSIPhone::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_input_length) {
+void OSIPhone::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
_show_keyboard(p_existing_text);
};
diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h
index a57b8eeb5d..955eb15d57 100644
--- a/platform/iphone/os_iphone.h
+++ b/platform/iphone/os_iphone.h
@@ -170,7 +170,7 @@ public:
virtual bool can_draw() const;
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_input_length = -1);
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_input_length = -1, int p_cursor_start = -1, int p_cursor_end = -1);
virtual void hide_virtual_keyboard();
virtual int get_virtual_keyboard_height() const;
diff --git a/platform/javascript/audio_driver_javascript.cpp b/platform/javascript/audio_driver_javascript.cpp
index b52bd4ce60..b8914414e6 100644
--- a/platform/javascript/audio_driver_javascript.cpp
+++ b/platform/javascript/audio_driver_javascript.cpp
@@ -70,14 +70,14 @@ Error AudioDriverJavaScript::init() {
/* clang-format off */
_driver_id = EM_ASM_INT({
const MIX_RATE = $0;
- const LATENCY = $1;
+ const LATENCY = $1 / 1000;
return Module.IDHandler.add({
'context': new (window.AudioContext || window.webkitAudioContext)({ sampleRate: MIX_RATE, latencyHint: LATENCY}),
'input': null,
'stream': null,
'script': null
});
- });
+ }, mix_rate, latency);
/* clang-format on */
int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode());
diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp
index 7e4d17f5e7..7bd67d3726 100644
--- a/platform/uwp/os_uwp.cpp
+++ b/platform/uwp/os_uwp.cpp
@@ -698,7 +698,7 @@ bool OS_UWP::has_virtual_keyboard() const {
return UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
}
-void OS_UWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_input_length) {
+void OS_UWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
InputPane ^ pane = InputPane::GetForCurrentView();
pane->TryShow();
}
diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h
index 1cab38cabe..95359c68b0 100644
--- a/platform/uwp/os_uwp.h
+++ b/platform/uwp/os_uwp.h
@@ -234,7 +234,7 @@ public:
virtual bool has_touchscreen_ui_hint() const;
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_input_length = -1);
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_input_length = -1, int p_cursor_start = -1, int p_cursor_end = -1);
virtual void hide_virtual_keyboard();
virtual Error open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path = false);
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index 9e117dba29..9d8344fa7e 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -521,7 +521,7 @@ void DisplayServerWindows::delete_sub_window(WindowID p_window) {
}
#endif
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available && windows[p_window].wtctx) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[p_window].wtctx) {
wintab_WTClose(windows[p_window].wtctx);
windows[p_window].wtctx = 0;
}
@@ -1791,7 +1791,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
alt_mem = false;
};
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available && windows[window_id].wtctx) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
wintab_WTEnable(windows[window_id].wtctx, GET_WM_ACTIVATE_STATE(wParam, lParam));
}
@@ -1924,7 +1924,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
} break;
case WT_CSRCHANGE:
case WT_PROXIMITY: {
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available && windows[window_id].wtctx) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
AXIS pressure;
if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
windows[window_id].min_pressure = int(pressure.axMin);
@@ -1938,7 +1938,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
} break;
case WT_PACKET: {
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available && windows[window_id].wtctx) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
PACKET packet;
if (wintab_WTPacket(windows[window_id].wtctx, wParam, &packet)) {
float pressure = float(packet.pkNormalPressure - windows[window_id].min_pressure) / float(windows[window_id].max_pressure - windows[window_id].min_pressure);
@@ -2007,17 +2007,43 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
old_x = mm->get_position().x;
old_y = mm->get_position().y;
if (windows[window_id].window_has_focus)
- Input::get_singleton()->parse_input_event(mm);
+ Input::get_singleton()->accumulate_input_event(mm);
}
return 0;
}
} break;
+ case WM_POINTERENTER: {
+ if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
+ break;
+ }
+
+ if ((OS::get_singleton()->get_current_tablet_driver() != "winink") || !winink_available) {
+ break;
+ }
+
+ uint32_t pointer_id = LOWORD(wParam);
+ POINTER_INPUT_TYPE pointer_type = PT_POINTER;
+ if (!win8p_GetPointerType(pointer_id, &pointer_type)) {
+ break;
+ }
+
+ if (pointer_type != PT_PEN) {
+ break;
+ }
+
+ windows[window_id].block_mm = true;
+ return 0;
+ } break;
+ case WM_POINTERLEAVE: {
+ windows[window_id].block_mm = false;
+ return 0;
+ } break;
case WM_POINTERUPDATE: {
if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
break;
}
- if (!win8p_GetPointerType || !win8p_GetPointerPenInfo) {
+ if ((OS::get_singleton()->get_current_tablet_driver() != "winink") || !winink_available) {
break;
}
@@ -2127,12 +2153,16 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
old_x = mm->get_position().x;
old_y = mm->get_position().y;
if (windows[window_id].window_has_focus) {
- Input::get_singleton()->parse_input_event(mm);
+ Input::get_singleton()->accumulate_input_event(mm);
}
return 0; //Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event
} break;
case WM_MOUSEMOVE: {
+ if (windows[window_id].block_mm) {
+ break;
+ }
+
if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
break;
}
@@ -2177,7 +2207,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
mm->set_shift((wParam & MK_SHIFT) != 0);
mm->set_alt(alt_mem);
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available && windows[window_id].wtctx) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
// Note: WinTab sends both WT_PACKET and WM_xBUTTONDOWN/UP/MOUSEMOVE events, use mouse 1/0 pressure only when last_pressure was not update recently.
if (windows[window_id].last_pressure_update < 10) {
windows[window_id].last_pressure_update++;
@@ -2729,6 +2759,45 @@ void DisplayServerWindows::_process_key_events() {
key_event_pos = 0;
}
+void DisplayServerWindows::_update_tablet_ctx(const String &p_old_driver, const String &p_new_driver) {
+ for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
+ WindowData &wd = E->get();
+ wd.block_mm = false;
+ if ((p_old_driver == "wintab") && wintab_available && wd.wtctx) {
+ wintab_WTEnable(wd.wtctx, false);
+ wintab_WTClose(wd.wtctx);
+ wd.wtctx = 0;
+ }
+ if ((p_new_driver == "wintab") && wintab_available) {
+ wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
+ wd.wtlc.lcOptions |= CXO_MESSAGES;
+ wd.wtlc.lcPktData = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
+ wd.wtlc.lcMoveMask = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
+ wd.wtlc.lcPktMode = 0;
+ wd.wtlc.lcOutOrgX = 0;
+ wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
+ wd.wtlc.lcOutOrgY = 0;
+ wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
+ wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
+ if (wd.wtctx) {
+ wintab_WTEnable(wd.wtctx, true);
+ AXIS pressure;
+ if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
+ wd.min_pressure = int(pressure.axMin);
+ wd.max_pressure = int(pressure.axMax);
+ }
+ AXIS orientation[3];
+ if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
+ wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
+ }
+ wintab_WTEnable(wd.wtctx, true);
+ } else {
+ print_verbose("WinTab context creation failed.");
+ }
+ }
+ }
+}
+
DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect) {
DWORD dwExStyle;
DWORD dwStyle;
@@ -2785,7 +2854,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
DragAcceptFiles(wd.hWnd, true);
- if (!OS::get_singleton()->is_wintab_disabled() && wintab_available) {
+ if ((OS::get_singleton()->get_current_tablet_driver() == "wintab") && wintab_available) {
wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
wd.wtlc.lcOptions |= CXO_MESSAGES;
wd.wtlc.lcPktData = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
@@ -2844,6 +2913,7 @@ WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr;
WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr;
// Windows Ink API
+bool DisplayServerWindows::winink_available = false;
GetPointerTypePtr DisplayServerWindows::win8p_GetPointerType = nullptr;
GetPointerPenInfoPtr DisplayServerWindows::win8p_GetPointerPenInfo = nullptr;
@@ -2854,25 +2924,6 @@ typedef enum _SHC_PROCESS_DPI_AWARENESS {
} SHC_PROCESS_DPI_AWARENESS;
DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- //Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
- HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
- if (wintab_lib) {
- wintab_WTOpen = (WTOpenPtr)GetProcAddress(wintab_lib, "WTOpenW");
- wintab_WTClose = (WTClosePtr)GetProcAddress(wintab_lib, "WTClose");
- wintab_WTInfo = (WTInfoPtr)GetProcAddress(wintab_lib, "WTInfoW");
- wintab_WTPacket = (WTPacketPtr)GetProcAddress(wintab_lib, "WTPacket");
- wintab_WTEnable = (WTEnablePtr)GetProcAddress(wintab_lib, "WTEnable");
-
- wintab_available = wintab_WTOpen && wintab_WTClose && wintab_WTInfo && wintab_WTPacket && wintab_WTEnable;
- }
-
- //Note: Windows Ink API for pen input, available on Windows 8+ only.
- HMODULE user32_lib = LoadLibraryW(L"user32.dll");
- if (user32_lib) {
- win8p_GetPointerType = (GetPointerTypePtr)GetProcAddress(user32_lib, "GetPointerType");
- win8p_GetPointerPenInfo = (GetPointerPenInfoPtr)GetProcAddress(user32_lib, "GetPointerPenInfo");
- }
-
drop_events = false;
key_event_pos = 0;
@@ -3054,18 +3105,6 @@ DisplayServerWindows::~DisplayServerWindows() {
cursors_cache.clear();
-#if defined(VULKAN_ENABLED)
- if (rendering_driver == "vulkan") {
- if (rendering_device_vulkan) {
- rendering_device_vulkan->finalize();
- memdelete(rendering_device_vulkan);
- }
-
- if (context_vulkan)
- memdelete(context_vulkan);
- }
-#endif
-
if (user_proc) {
SetWindowLongPtr(windows[MAIN_WINDOW_ID].hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
};
@@ -3082,4 +3121,16 @@ DisplayServerWindows::~DisplayServerWindows() {
}
DestroyWindow(windows[MAIN_WINDOW_ID].hWnd);
}
+
+#if defined(VULKAN_ENABLED)
+ if (rendering_driver == "vulkan") {
+ if (rendering_device_vulkan) {
+ rendering_device_vulkan->finalize();
+ memdelete(rendering_device_vulkan);
+ }
+
+ if (context_vulkan)
+ memdelete(context_vulkan);
+ }
+#endif
}
diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h
index f8606bb492..caf8598dc2 100644
--- a/platform/windows/display_server_windows.h
+++ b/platform/windows/display_server_windows.h
@@ -229,6 +229,14 @@ typedef struct tagPOINTER_PEN_INFO {
#define WM_POINTERUPDATE 0x0245
#endif
+#ifndef WM_POINTERENTER
+#define WM_POINTERENTER 0x0249
+#endif
+
+#ifndef WM_POINTERLEAVE
+#define WM_POINTERLEAVE 0x024A
+#endif
+
typedef BOOL(WINAPI *GetPointerTypePtr)(uint32_t p_id, POINTER_INPUT_TYPE *p_type);
typedef BOOL(WINAPI *GetPointerPenInfoPtr)(uint32_t p_id, POINTER_PEN_INFO *p_pen_info);
@@ -256,6 +264,7 @@ class DisplayServerWindows : public DisplayServer {
_THREAD_SAFE_CLASS_
+public:
// WinTab API
static bool wintab_available;
static WTOpenPtr wintab_WTOpen;
@@ -265,9 +274,13 @@ class DisplayServerWindows : public DisplayServer {
static WTEnablePtr wintab_WTEnable;
// Windows Ink API
+ static bool winink_available;
static GetPointerTypePtr win8p_GetPointerType;
static GetPointerPenInfoPtr win8p_GetPointerPenInfo;
+ void _update_tablet_ctx(const String &p_old_driver, const String &p_new_driver);
+
+private:
void GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap);
enum {
@@ -328,6 +341,7 @@ class DisplayServerWindows : public DisplayServer {
int min_pressure;
int max_pressure;
bool tilt_supported;
+ bool block_mm = false;
int last_pressure_update;
float last_pressure;
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index 7c06e93a8a..0dab0c601a 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -415,23 +415,30 @@ uint64_t OS_Windows::get_ticks_usec() const {
return time;
}
+String OS_Windows::_quote_command_line_argument(const String &p_text) const {
+ for (int i = 0; i < p_text.size(); i++) {
+ CharType c = p_text[i];
+ if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
+ return "\"" + p_text + "\"";
+ }
+ }
+ return p_text;
+}
+
Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
if (p_blocking && r_pipe) {
- String argss;
- argss = "\"\"" + p_path + "\"";
-
+ String argss = _quote_command_line_argument(p_path);
for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
- argss += " \"" + E->get() + "\"";
+ argss += " " + _quote_command_line_argument(E->get());
}
- argss += "\"";
-
if (read_stderr) {
argss += " 2>&1"; // Read stderr too
}
+ // Note: _wpopen is calling command as "cmd.exe /c argss", instead of executing it directly, add extra quotes around full command, to prevent it from stripping quotes in the command.
+ argss = _quote_command_line_argument(argss);
FILE *f = _wpopen(argss.c_str(), L"r");
-
ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
char buf[65535];
@@ -446,19 +453,19 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments,
}
int rv = _pclose(f);
- if (r_exitcode)
+ if (r_exitcode) {
*r_exitcode = rv;
+ }
return OK;
}
- String cmdline = "\"" + p_path + "\"";
+ String cmdline = _quote_command_line_argument(p_path);
const List<String>::Element *I = p_arguments.front();
while (I) {
- cmdline += " \"" + I->get() + "\"";
-
+ cmdline += " " + _quote_command_line_argument(I->get());
I = I->next();
- };
+ }
ProcessInfo pi;
ZeroMemory(&pi.si, sizeof(pi.si));
@@ -466,17 +473,20 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments,
ZeroMemory(&pi.pi, sizeof(pi.pi));
LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
- Vector<CharType> modstr; //windows wants to change this no idea why
+ Vector<CharType> modstr; // Windows wants to change this no idea why.
modstr.resize(cmdline.size());
- for (int i = 0; i < cmdline.size(); i++)
+ for (int i = 0; i < cmdline.size(); i++) {
modstr.write[i] = cmdline[i];
+ }
+
int ret = CreateProcessW(nullptr, modstr.ptrw(), nullptr, nullptr, 0, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, nullptr, nullptr, si_w, &pi.pi);
ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
if (p_blocking) {
DWORD ret2 = WaitForSingleObject(pi.pi.hProcess, INFINITE);
- if (r_exitcode)
+ if (r_exitcode) {
*r_exitcode = ret2;
+ }
CloseHandle(pi.pi.hProcess);
CloseHandle(pi.pi.hThread);
@@ -484,9 +494,9 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments,
ProcessID pid = pi.pi.dwProcessId;
if (r_child_id) {
*r_child_id = pid;
- };
+ }
process_map->insert(pid, pi);
- };
+ }
return OK;
};
@@ -768,7 +778,72 @@ Error OS_Windows::move_to_trash(const String &p_path) {
return OK;
}
+int OS_Windows::get_tablet_driver_count() const {
+ return tablet_drivers.size();
+}
+
+String OS_Windows::get_tablet_driver_name(int p_driver) const {
+ if (p_driver < 0 || p_driver >= tablet_drivers.size()) {
+ return "";
+ } else {
+ return tablet_drivers[p_driver];
+ }
+}
+
+String OS_Windows::get_current_tablet_driver() const {
+ return tablet_driver;
+}
+
+void OS_Windows::set_current_tablet_driver(const String &p_driver) {
+ if (get_tablet_driver_count() == 0) {
+ return;
+ }
+ bool found = false;
+ for (int i = 0; i < get_tablet_driver_count(); i++) {
+ if (p_driver == get_tablet_driver_name(i)) {
+ found = true;
+ }
+ }
+ if (found) {
+ if (DisplayServerWindows::get_singleton()) {
+ ((DisplayServerWindows *)DisplayServerWindows::get_singleton())->_update_tablet_ctx(tablet_driver, p_driver);
+ }
+ tablet_driver = p_driver;
+ } else {
+ ERR_PRINT("Unknown tablet driver " + p_driver + ".");
+ }
+}
+
OS_Windows::OS_Windows(HINSTANCE _hInstance) {
+ //Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
+ HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
+ if (wintab_lib) {
+ DisplayServerWindows::wintab_WTOpen = (WTOpenPtr)GetProcAddress(wintab_lib, "WTOpenW");
+ DisplayServerWindows::wintab_WTClose = (WTClosePtr)GetProcAddress(wintab_lib, "WTClose");
+ DisplayServerWindows::wintab_WTInfo = (WTInfoPtr)GetProcAddress(wintab_lib, "WTInfoW");
+ DisplayServerWindows::wintab_WTPacket = (WTPacketPtr)GetProcAddress(wintab_lib, "WTPacket");
+ DisplayServerWindows::wintab_WTEnable = (WTEnablePtr)GetProcAddress(wintab_lib, "WTEnable");
+
+ DisplayServerWindows::wintab_available = DisplayServerWindows::wintab_WTOpen && DisplayServerWindows::wintab_WTClose && DisplayServerWindows::wintab_WTInfo && DisplayServerWindows::wintab_WTPacket && DisplayServerWindows::wintab_WTEnable;
+ }
+
+ if (DisplayServerWindows::wintab_available) {
+ tablet_drivers.push_back("wintab");
+ }
+
+ //Note: Windows Ink API for pen input, available on Windows 8+ only.
+ HMODULE user32_lib = LoadLibraryW(L"user32.dll");
+ if (user32_lib) {
+ DisplayServerWindows::win8p_GetPointerType = (GetPointerTypePtr)GetProcAddress(user32_lib, "GetPointerType");
+ DisplayServerWindows::win8p_GetPointerPenInfo = (GetPointerPenInfoPtr)GetProcAddress(user32_lib, "GetPointerPenInfo");
+
+ DisplayServerWindows::winink_available = DisplayServerWindows::win8p_GetPointerType && DisplayServerWindows::win8p_GetPointerPenInfo;
+ }
+
+ if (DisplayServerWindows::winink_available) {
+ tablet_drivers.push_back("winink");
+ }
+
force_quit = false;
hInstance = _hInstance;
diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h
index 480a9faa87..11e3533bfd 100644
--- a/platform/windows/os_windows.h
+++ b/platform/windows/os_windows.h
@@ -73,6 +73,9 @@ class OS_Windows : public OS {
HINSTANCE hInstance;
MainLoop *main_loop;
+ String tablet_driver;
+ Vector<String> tablet_drivers;
+
#ifdef WASAPI_ENABLED
AudioDriverWASAPI driver_wasapi;
#endif
@@ -99,6 +102,8 @@ protected:
virtual void finalize_core();
virtual String get_stdin_string(bool p_block);
+ String _quote_command_line_argument(const String &p_text) const;
+
struct ProcessInfo {
STARTUPINFO si;
PROCESS_INFORMATION pi;
@@ -114,6 +119,11 @@ public:
virtual String get_name() const;
+ virtual int get_tablet_driver_count() const;
+ virtual String get_tablet_driver_name(int p_driver) const;
+ virtual String get_current_tablet_driver() const;
+ virtual void set_current_tablet_driver(const String &p_driver);
+
virtual void initialize_joypads() {}
virtual Date get_date(bool utc) const;
diff --git a/scene/debugger/scene_debugger.cpp b/scene/debugger/scene_debugger.cpp
index 0222585948..f57c8e58db 100644
--- a/scene/debugger/scene_debugger.cpp
+++ b/scene/debugger/scene_debugger.cpp
@@ -361,15 +361,6 @@ void SceneDebuggerObject::serialize(Array &r_arr, int p_max_size) {
RES res = var;
- if (var.get_type() == Variant::OBJECT && var.is_ref()) {
- REF r = var;
- if (r.is_valid()) {
- res = *r;
- } else {
- res = RES();
- }
- }
-
Array prop;
prop.push_back(pi.name);
prop.push_back(pi.type);
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 88710289c7..84170a65d1 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -66,7 +66,7 @@ void ColorPicker::_notification(int p_what) {
} break;
case NOTIFICATION_PARENTED: {
for (int i = 0; i < 4; i++) {
- set_margin((Margin)i, get_theme_constant("margin"));
+ set_margin((Margin)i, get_margin((Margin)i) + get_theme_constant("margin"));
}
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
diff --git a/scene/gui/container.cpp b/scene/gui/container.cpp
index 18a84ce348..a89eef6209 100644
--- a/scene/gui/container.cpp
+++ b/scene/gui/container.cpp
@@ -140,7 +140,7 @@ void Container::queue_sort() {
return;
}
- MessageQueue::get_singleton()->push_call(this, "_sort_children");
+ MessageQueue::get_singleton()->push_callable(callable_mp(this, &Container::_sort_children));
pending_sort = true;
}
@@ -177,8 +177,6 @@ String Container::get_configuration_warning() const {
}
void Container::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_sort_children"), &Container::_sort_children);
-
ClassDB::bind_method(D_METHOD("queue_sort"), &Container::queue_sort);
ClassDB::bind_method(D_METHOD("fit_child_in_rect", "child", "rect"), &Container::fit_child_in_rect);
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index e3c75491f7..fbacb3ed9e 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -119,7 +119,11 @@ void LineEdit::_gui_input(Ref<InputEvent> p_event) {
selection.doubleclick = false;
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD)) {
- DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length);
+ if (selection.enabled) {
+ DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length, selection.begin, selection.end);
+ } else {
+ DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length, cursor_pos);
+ }
}
}
@@ -918,7 +922,11 @@ void LineEdit::_notification(int p_what) {
}
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD)) {
- DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length);
+ if (selection.enabled) {
+ DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length, selection.begin, selection.end);
+ } else {
+ DisplayServer::get_singleton()->virtual_keyboard_show(text, get_global_rect(), max_length, cursor_pos);
+ }
}
} break;
diff --git a/scene/gui/tab_container.cpp b/scene/gui/tab_container.cpp
index 97b8362214..8c4d9a5ece 100644
--- a/scene/gui/tab_container.cpp
+++ b/scene/gui/tab_container.cpp
@@ -278,7 +278,7 @@ void TabContainer::_notification(int p_what) {
Color font_color_bg = get_theme_color("font_color_bg");
Color font_color_disabled = get_theme_color("font_color_disabled");
int side_margin = get_theme_constant("side_margin");
- int icon_text_distance = get_theme_constant("hseparation");
+ int icon_text_distance = get_theme_constant("icon_separation");
// Find out start and width of the header area.
int header_x = side_margin;
@@ -465,7 +465,7 @@ int TabContainer::_get_tab_width(int p_index) const {
if (icon.is_valid()) {
width += icon->get_width();
if (text != "") {
- width += get_theme_constant("hseparation");
+ width += get_theme_constant("icon_separation");
}
}
}
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 932dda2f9d..e050b3f174 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -5447,17 +5447,16 @@ int TextEdit::_get_column_pos_of_word(const String &p_key, const String &p_searc
return col;
}
-Vector<int> TextEdit::_search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const {
+Dictionary TextEdit::_search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const {
int col, line;
if (search(p_key, p_search_flags, p_from_line, p_from_column, line, col)) {
- Vector<int> result;
- result.resize(2);
- result.set(SEARCH_RESULT_COLUMN, col);
- result.set(SEARCH_RESULT_LINE, line);
+ Dictionary result;
+ result["line"] = line;
+ result["column"] = col;
return result;
} else {
- return Vector<int>();
+ return Dictionary();
}
}
@@ -6980,9 +6979,6 @@ void TextEdit::_bind_methods() {
BIND_ENUM_CONSTANT(SEARCH_WHOLE_WORDS);
BIND_ENUM_CONSTANT(SEARCH_BACKWARDS);
- BIND_ENUM_CONSTANT(SEARCH_RESULT_COLUMN);
- BIND_ENUM_CONSTANT(SEARCH_RESULT_LINE);
-
/*
ClassDB::bind_method(D_METHOD("delete_char"),&TextEdit::delete_char);
ClassDB::bind_method(D_METHOD("delete_line"),&TextEdit::delete_line);
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 689199b6c2..ab78f77d94 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -508,7 +508,7 @@ private:
int _get_column_pos_of_word(const String &p_key, const String &p_search, uint32_t p_search_flags, int p_from_column);
- Vector<int> _search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const;
+ Dictionary _search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const;
PopupMenu *menu;
@@ -561,11 +561,6 @@ public:
SEARCH_BACKWARDS = 4
};
- enum SearchResult {
- SEARCH_RESULT_COLUMN,
- SEARCH_RESULT_LINE,
- };
-
virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const;
void _get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) const;
@@ -826,7 +821,6 @@ public:
VARIANT_ENUM_CAST(TextEdit::MenuItems);
VARIANT_ENUM_CAST(TextEdit::SearchFlags);
-VARIANT_ENUM_CAST(TextEdit::SearchResult);
class SyntaxHighlighter {
protected:
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index f5b987e8df..de39fac627 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -681,7 +681,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
theme->set_color("font_color_disabled", "TabContainer", control_font_color_disabled);
theme->set_constant("side_margin", "TabContainer", 8 * scale);
- theme->set_constant("hseparation", "TabContainer", 4 * scale);
+ theme->set_constant("icon_separation", "TabContainer", 4 * scale);
// Tabs
diff --git a/servers/display_server.cpp b/servers/display_server.cpp
index ffb05588cc..cc818cbe04 100644
--- a/servers/display_server.cpp
+++ b/servers/display_server.cpp
@@ -213,7 +213,7 @@ bool DisplayServer::is_console_visible() const {
return false;
}
-void DisplayServer::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_legth) {
+void DisplayServer::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_length, int p_cursor_start, int p_cursor_end) {
WARN_PRINT("Virtual keyboard not supported by this display server.");
}
@@ -439,7 +439,7 @@ void DisplayServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("console_set_visible", "console_visible"), &DisplayServer::console_set_visible);
ClassDB::bind_method(D_METHOD("is_console_visible"), &DisplayServer::is_console_visible);
- ClassDB::bind_method(D_METHOD("virtual_keyboard_show", "existing_text", "position", "max_length"), &DisplayServer::virtual_keyboard_show, DEFVAL(Rect2i()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("virtual_keyboard_show", "existing_text", "position", "max_length", "cursor_start", "cursor_end"), &DisplayServer::virtual_keyboard_show, DEFVAL(Rect2i()), DEFVAL(-1), DEFVAL(-1), DEFVAL(-1));
ClassDB::bind_method(D_METHOD("virtual_keyboard_hide"), &DisplayServer::virtual_keyboard_hide);
ClassDB::bind_method(D_METHOD("virtual_keyboard_get_height"), &DisplayServer::virtual_keyboard_get_height);
diff --git a/servers/display_server.h b/servers/display_server.h
index f6ba26fc6f..b25b1931c8 100644
--- a/servers/display_server.h
+++ b/servers/display_server.h
@@ -280,7 +280,7 @@ public:
virtual void console_set_visible(bool p_enabled);
virtual bool is_console_visible() const;
- virtual void virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_legth = -1);
+ virtual void virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_length = -1, int p_cursor_start = -1, int p_cursor_end = -1);
virtual void virtual_keyboard_hide();
// returns height of the currently shown virtual keyboard (0 if keyboard is hidden)
diff --git a/thirdparty/README.md b/thirdparty/README.md
index 5b24d2b96d..64c2ce336d 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -616,7 +616,7 @@ File extracted from upstream release tarball:
## xatlas
- Upstream: https://github.com/jpcy/xatlas
-- Version: git (e12ea82, 2019)
+- Version: git (470576d3516f7e6d8b4554e7c941194a935969fd, 2020)
- License: MIT
Files extracted from upstream source:
diff --git a/thirdparty/xatlas/LICENSE b/thirdparty/xatlas/LICENSE
index 9e61e15fb7..7af8b33238 100644
--- a/thirdparty/xatlas/LICENSE
+++ b/thirdparty/xatlas/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2018-2019 Jonathan Young
+Copyright (c) 2018-2020 Jonathan Young
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/thirdparty/xatlas/xatlas.cpp b/thirdparty/xatlas/xatlas.cpp
index b1cbeb980f..43aec33a9f 100644
--- a/thirdparty/xatlas/xatlas.cpp
+++ b/thirdparty/xatlas/xatlas.cpp
@@ -1,7 +1,7 @@
/*
MIT License
-Copyright (c) 2018-2019 Jonathan Young
+Copyright (c) 2018-2020 Jonathan Young
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -33,19 +33,19 @@ https://github.com/brandonpelfrey/Fast-BVH
MIT License
Copyright (c) 2012 Brandon Pelfrey
*/
-#include <assert.h>
-#include <float.h> // FLT_MAX
-#include <limits.h>
-#include <math.h>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
+#include <assert.h>
+#include <float.h> // FLT_MAX
+#include <limits.h>
+#include <math.h>
#define __STDC_LIMIT_MACROS
-#include "xatlas.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
+#include "xatlas.h"
#ifndef XA_DEBUG
#ifdef NDEBUG
@@ -70,10 +70,7 @@ Copyright (c) 2012 Brandon Pelfrey
#define XA_XSTR(x) XA_STR(x)
#ifndef XA_ASSERT
-#define XA_ASSERT(exp) \
- if (!(exp)) { \
- XA_PRINT_WARNING("\rASSERT: %s %s %d\n", XA_XSTR(exp), __FILE__, __LINE__); \
- }
+#define XA_ASSERT(exp) if (!(exp)) { XA_PRINT_WARNING("\rASSERT: %s %s %d\n", XA_XSTR(exp), __FILE__, __LINE__); }
#endif
#ifndef XA_DEBUG_ASSERT
@@ -81,20 +78,20 @@ Copyright (c) 2012 Brandon Pelfrey
#endif
#ifndef XA_PRINT
-#define XA_PRINT(...) \
+#define XA_PRINT(...) \
if (xatlas::internal::s_print && xatlas::internal::s_printVerbose) \
xatlas::internal::s_print(__VA_ARGS__);
#endif
#ifndef XA_PRINT_WARNING
-#define XA_PRINT_WARNING(...) \
+#define XA_PRINT_WARNING(...) \
if (xatlas::internal::s_print) \
xatlas::internal::s_print(__VA_ARGS__);
#endif
#define XA_ALLOC(tag, type) (type *)internal::Realloc(nullptr, sizeof(type), tag, __FILE__, __LINE__)
-#define XA_ALLOC_ARRAY(tag, type, num) (type *)internal::Realloc(nullptr, sizeof(type) * num, tag, __FILE__, __LINE__)
-#define XA_REALLOC(tag, ptr, type, num) (type *)internal::Realloc(ptr, sizeof(type) * num, tag, __FILE__, __LINE__)
+#define XA_ALLOC_ARRAY(tag, type, num) (type *)internal::Realloc(nullptr, sizeof(type) * (num), tag, __FILE__, __LINE__)
+#define XA_REALLOC(tag, ptr, type, num) (type *)internal::Realloc(ptr, sizeof(type) * (num), tag, __FILE__, __LINE__)
#define XA_REALLOC_SIZE(tag, ptr, size) (uint8_t *)internal::Realloc(ptr, size, tag, __FILE__, __LINE__)
#define XA_FREE(ptr) internal::Realloc(ptr, 0, internal::MemTag::Default, __FILE__, __LINE__)
#define XA_NEW(tag, type) new (XA_ALLOC(tag, type)) type()
@@ -125,11 +122,12 @@ Copyright (c) 2012 Brandon Pelfrey
#define XA_DEBUG_HEAP 0
#define XA_DEBUG_SINGLE_CHART 0
+#define XA_DEBUG_ALL_CHARTS_INVALID 0
#define XA_DEBUG_EXPORT_ATLAS_IMAGES 0
#define XA_DEBUG_EXPORT_ATLAS_IMAGES_PER_CHART 0 // Export an atlas image after each chart is added.
#define XA_DEBUG_EXPORT_BOUNDARY_GRID 0
#define XA_DEBUG_EXPORT_TGA (XA_DEBUG_EXPORT_ATLAS_IMAGES || XA_DEBUG_EXPORT_BOUNDARY_GRID)
-#define XA_DEBUG_EXPORT_OBJ_SOURCE_MESHES 0
+#define XA_DEBUG_EXPORT_OBJ_FACE_GROUPS 0
#define XA_DEBUG_EXPORT_OBJ_CHART_GROUPS 0
#define XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS 0
#define XA_DEBUG_EXPORT_OBJ_CHARTS 0
@@ -139,13 +137,19 @@ Copyright (c) 2012 Brandon Pelfrey
#define XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION 0
#define XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS 0
-#define XA_DEBUG_EXPORT_OBJ (0 || XA_DEBUG_EXPORT_OBJ_SOURCE_MESHES || XA_DEBUG_EXPORT_OBJ_CHART_GROUPS || XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS || XA_DEBUG_EXPORT_OBJ_CHARTS || XA_DEBUG_EXPORT_OBJ_BEFORE_FIX_TJUNCTION || XA_DEBUG_EXPORT_OBJ_CLOSE_HOLES_ERROR || XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION || XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION || XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS)
+#define XA_DEBUG_EXPORT_OBJ (0 \
+ || XA_DEBUG_EXPORT_OBJ_FACE_GROUPS \
+ || XA_DEBUG_EXPORT_OBJ_CHART_GROUPS \
+ || XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS \
+ || XA_DEBUG_EXPORT_OBJ_CHARTS \
+ || XA_DEBUG_EXPORT_OBJ_BEFORE_FIX_TJUNCTION \
+ || XA_DEBUG_EXPORT_OBJ_CLOSE_HOLES_ERROR \
+ || XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION \
+ || XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION \
+ || XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS)
#ifdef _MSC_VER
-#define XA_FOPEN(_file, _filename, _mode) \
- { \
- if (fopen_s(&_file, _filename, _mode) != 0) _file = NULL; \
- }
+#define XA_FOPEN(_file, _filename, _mode) { if (fopen_s(&_file, _filename, _mode) != 0) _file = NULL; }
#define XA_SPRINTF(_buffer, _size, _format, ...) sprintf_s(_buffer, _size, _format, __VA_ARGS__)
#else
#define XA_FOPEN(_file, _filename, _mode) _file = fopen(_filename, _mode)
@@ -160,12 +164,90 @@ static FreeFunc s_free = free;
static PrintFunc s_print = printf;
static bool s_printVerbose = false;
-struct MemTag {
- enum {
+#if XA_PROFILE
+#define XA_PROFILE_START(var) const clock_t var##Start = clock();
+#define XA_PROFILE_END(var) internal::s_profile.var += clock() - var##Start;
+#define XA_PROFILE_PRINT_AND_RESET(label, var) XA_PRINT("%s%.2f seconds (%g ms)\n", label, internal::clockToSeconds(internal::s_profile.var), internal::clockToMs(internal::s_profile.var)); internal::s_profile.var = 0;
+#define XA_PROFILE_ALLOC 0
+
+struct ProfileData
+{
+#if XA_PROFILE_ALLOC
+ std::atomic<clock_t> alloc;
+#endif
+ clock_t addMeshReal;
+ clock_t addMeshCopyData;
+ std::atomic<clock_t> addMeshThread;
+ std::atomic<clock_t> addMeshCreateColocals;
+ clock_t computeChartsReal;
+ std::atomic<clock_t> computeChartsThread;
+ std::atomic<clock_t> createFaceGroups;
+ std::atomic<clock_t> extractInvalidMeshGeometry;
+ std::atomic<clock_t> chartGroupComputeChartsReal;
+ std::atomic<clock_t> chartGroupComputeChartsThread;
+ std::atomic<clock_t> createChartGroupMesh;
+ std::atomic<clock_t> createChartGroupMeshColocals;
+ std::atomic<clock_t> createChartGroupMeshBoundaries;
+ std::atomic<clock_t> buildAtlas;
+ std::atomic<clock_t> buildAtlasInit;
+ std::atomic<clock_t> planarCharts;
+ std::atomic<clock_t> clusteredCharts;
+ std::atomic<clock_t> clusteredChartsPlaceSeeds;
+ std::atomic<clock_t> clusteredChartsPlaceSeedsBoundaryIntersection;
+ std::atomic<clock_t> clusteredChartsRelocateSeeds;
+ std::atomic<clock_t> clusteredChartsReset;
+ std::atomic<clock_t> clusteredChartsGrow;
+ std::atomic<clock_t> clusteredChartsGrowBoundaryIntersection;
+ std::atomic<clock_t> clusteredChartsMerge;
+ std::atomic<clock_t> clusteredChartsFillHoles;
+ std::atomic<clock_t> copyChartFaces;
+ clock_t parameterizeChartsReal;
+ std::atomic<clock_t> parameterizeChartsThread;
+ std::atomic<clock_t> createChartMesh;
+ std::atomic<clock_t> fixChartMeshTJunctions;
+ std::atomic<clock_t> closeChartMeshHoles;
+ std::atomic<clock_t> parameterizeChartsOrthogonal;
+ std::atomic<clock_t> parameterizeChartsLSCM;
+ std::atomic<clock_t> parameterizeChartsRecompute;
+ std::atomic<clock_t> parameterizeChartsPiecewise;
+ std::atomic<clock_t> parameterizeChartsPiecewiseBoundaryIntersection;
+ std::atomic<clock_t> parameterizeChartsEvaluateQuality;
+ clock_t packCharts;
+ clock_t packChartsAddCharts;
+ std::atomic<clock_t> packChartsAddChartsThread;
+ std::atomic<clock_t> packChartsAddChartsRestoreTexcoords;
+ clock_t packChartsRasterize;
+ clock_t packChartsDilate;
+ clock_t packChartsFindLocation;
+ clock_t packChartsBlit;
+ clock_t buildOutputMeshes;
+};
+
+static ProfileData s_profile;
+
+static double clockToMs(clock_t c)
+{
+ return c * 1000.0 / CLOCKS_PER_SEC;
+}
+
+static double clockToSeconds(clock_t c)
+{
+ return c / (double)CLOCKS_PER_SEC;
+}
+#else
+#define XA_PROFILE_START(var)
+#define XA_PROFILE_END(var)
+#define XA_PROFILE_PRINT_AND_RESET(label, var)
+#define XA_PROFILE_ALLOC 0
+#endif
+
+struct MemTag
+{
+ enum
+ {
Default,
BitImage,
BVH,
- FullVector,
Matrix,
Mesh,
MeshBoundaries,
@@ -175,6 +257,7 @@ struct MemTag {
MeshNormals,
MeshPositions,
MeshTexcoords,
+ OpenNL,
SegmentAtlasChartCandidates,
SegmentAtlasChartFaces,
SegmentAtlasMeshData,
@@ -184,7 +267,8 @@ struct MemTag {
};
#if XA_DEBUG_HEAP
-struct AllocHeader {
+struct AllocHeader
+{
size_t size;
const char *file;
int line;
@@ -197,10 +281,11 @@ struct AllocHeader {
static std::mutex s_allocMutex;
static AllocHeader *s_allocRoot = nullptr;
static size_t s_allocTotalCount = 0, s_allocTotalSize = 0, s_allocPeakSize = 0, s_allocCount[MemTag::Count] = { 0 }, s_allocTotalTagSize[MemTag::Count] = { 0 }, s_allocPeakTagSize[MemTag::Count] = { 0 };
-static uint32_t s_allocId = 0;
+static uint32_t s_allocId =0 ;
static constexpr uint32_t kAllocRedzone = 0x12345678;
-static void *Realloc(void *ptr, size_t size, int tag, const char *file, int line) {
+static void *Realloc(void *ptr, size_t size, int tag, const char *file, int line)
+{
std::unique_lock<std::mutex> lock(s_allocMutex);
if (!size && !ptr)
return nullptr;
@@ -261,7 +346,8 @@ static void *Realloc(void *ptr, size_t size, int tag, const char *file, int line
return newPtr + sizeof(AllocHeader);
}
-static void ReportLeaks() {
+static void ReportLeaks()
+{
printf("Checking for memory leaks...\n");
bool anyLeaks = false;
AllocHeader *header = s_allocRoot;
@@ -289,14 +375,14 @@ static void ReportLeaks() {
s_allocTotalTagSize[i] = s_allocPeakTagSize[i] = 0;
}
-static void PrintMemoryUsage() {
+static void PrintMemoryUsage()
+{
XA_PRINT("Total allocations: %zu\n", s_allocTotalCount);
XA_PRINT("Memory usage: %0.2fMB current, %0.2fMB peak\n", internal::s_allocTotalSize / 1024.0f / 1024.0f, internal::s_allocPeakSize / 1024.0f / 1024.0f);
static const char *labels[] = { // Sync with MemTag
"Default",
"BitImage",
"BVH",
- "FullVector",
"Matrix",
"Mesh",
"MeshBoundaries",
@@ -306,6 +392,7 @@ static void PrintMemoryUsage() {
"MeshNormals",
"MeshPositions",
"MeshTexcoords",
+ "OpenNL",
"SegmentAtlasChartCandidates",
"SegmentAtlasChartFaces",
"SegmentAtlasMeshData",
@@ -318,158 +405,116 @@ static void PrintMemoryUsage() {
#define XA_PRINT_MEM_USAGE internal::PrintMemoryUsage();
#else
-static void *Realloc(void *ptr, size_t size, int /*tag*/, const char * /*file*/, int /*line*/) {
+static void *Realloc(void *ptr, size_t size, int /*tag*/, const char * /*file*/, int /*line*/)
+{
if (size == 0 && !ptr)
return nullptr;
if (size == 0 && s_free) {
s_free(ptr);
return nullptr;
}
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_START(alloc)
+#endif
void *mem = s_realloc(ptr, size);
- if (size > 0) {
- XA_DEBUG_ASSERT(mem);
- }
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_END(alloc)
+#endif
+ XA_DEBUG_ASSERT(size <= 0 || (size > 0 && mem));
return mem;
}
#define XA_PRINT_MEM_USAGE
#endif
-#if XA_PROFILE
-#define XA_PROFILE_START(var) const clock_t var##Start = clock();
-#define XA_PROFILE_END(var) internal::s_profile.var += clock() - var##Start;
-#define XA_PROFILE_PRINT_AND_RESET(label, var) \
- XA_PRINT("%s%.2f seconds (%g ms)\n", label, internal::clockToSeconds(internal::s_profile.var), internal::clockToMs(internal::s_profile.var)); \
- internal::s_profile.var = 0;
-
-struct ProfileData {
- clock_t addMeshReal;
- clock_t addMeshCopyData;
- std::atomic<clock_t> addMeshThread;
- std::atomic<clock_t> addMeshCreateColocals;
- std::atomic<clock_t> addMeshCreateFaceGroups;
- std::atomic<clock_t> addMeshCreateChartGroupsReal;
- std::atomic<clock_t> addMeshCreateChartGroupsThread;
- clock_t computeChartsReal;
- std::atomic<clock_t> computeChartsThread;
- std::atomic<clock_t> buildAtlas;
- std::atomic<clock_t> buildAtlasInit;
- std::atomic<clock_t> buildAtlasPlaceSeeds;
- std::atomic<clock_t> buildAtlasRelocateSeeds;
- std::atomic<clock_t> buildAtlasResetCharts;
- std::atomic<clock_t> buildAtlasGrowCharts;
- std::atomic<clock_t> buildAtlasMergeCharts;
- std::atomic<clock_t> buildAtlasFillHoles;
- std::atomic<clock_t> createChartMeshesReal;
- std::atomic<clock_t> createChartMeshesThread;
- std::atomic<clock_t> fixChartMeshTJunctions;
- std::atomic<clock_t> closeChartMeshHoles;
- clock_t parameterizeChartsReal;
- std::atomic<clock_t> parameterizeChartsThread;
- std::atomic<clock_t> parameterizeChartsOrthogonal;
- std::atomic<clock_t> parameterizeChartsLSCM;
- std::atomic<clock_t> parameterizeChartsEvaluateQuality;
- clock_t packCharts;
- clock_t packChartsAddCharts;
- std::atomic<clock_t> packChartsAddChartsThread;
- std::atomic<clock_t> packChartsAddChartsRestoreTexcoords;
- clock_t packChartsRasterize;
- clock_t packChartsDilate;
- clock_t packChartsFindLocation;
- clock_t packChartsBlit;
- clock_t buildOutputMeshes;
-};
-
-static ProfileData s_profile;
-
-static double clockToMs(clock_t c) {
- return c * 1000.0 / CLOCKS_PER_SEC;
-}
-
-static double clockToSeconds(clock_t c) {
- return c / (double)CLOCKS_PER_SEC;
-}
-#else
-#define XA_PROFILE_START(var)
-#define XA_PROFILE_END(var)
-#define XA_PROFILE_PRINT_AND_RESET(label, var)
-#endif
-
static constexpr float kPi = 3.14159265358979323846f;
static constexpr float kPi2 = 6.28318530717958647692f;
-static constexpr float kPi4 = 12.56637061435917295384f;
static constexpr float kEpsilon = 0.0001f;
static constexpr float kAreaEpsilon = FLT_EPSILON;
static constexpr float kNormalEpsilon = 0.001f;
-static int align(int x, int a) {
+static int align(int x, int a)
+{
return (x + a - 1) & ~(a - 1);
}
template <typename T>
-static T max(const T &a, const T &b) {
+static T max(const T &a, const T &b)
+{
return a > b ? a : b;
}
template <typename T>
-static T min(const T &a, const T &b) {
+static T min(const T &a, const T &b)
+{
return a < b ? a : b;
}
template <typename T>
-static T max3(const T &a, const T &b, const T &c) {
+static T max3(const T &a, const T &b, const T &c)
+{
return max(a, max(b, c));
}
/// Return the maximum of the three arguments.
template <typename T>
-static T min3(const T &a, const T &b, const T &c) {
+static T min3(const T &a, const T &b, const T &c)
+{
return min(a, min(b, c));
}
/// Clamp between two values.
template <typename T>
-static T clamp(const T &x, const T &a, const T &b) {
+static T clamp(const T &x, const T &a, const T &b)
+{
return min(max(x, a), b);
}
template <typename T>
-static void swap(T &a, T &b) {
+static void swap(T &a, T &b)
+{
T temp = a;
a = b;
b = temp;
}
-union FloatUint32 {
+union FloatUint32
+{
float f;
uint32_t u;
};
-static bool isFinite(float f) {
+static bool isFinite(float f)
+{
FloatUint32 fu;
fu.f = f;
return fu.u != 0x7F800000u && fu.u != 0x7F800001u;
}
-static bool isNan(float f) {
+static bool isNan(float f)
+{
return f != f;
}
// Robust floating point comparisons:
// http://realtimecollisiondetection.net/blog/?p=89
-static bool equal(const float f0, const float f1, const float epsilon) {
+static bool equal(const float f0, const float f1, const float epsilon)
+{
//return fabs(f0-f1) <= epsilon;
return fabs(f0 - f1) <= epsilon * max3(1.0f, fabsf(f0), fabsf(f1));
}
-static int ftoi_ceil(float val) {
+static int ftoi_ceil(float val)
+{
return (int)ceilf(val);
}
-static bool isZero(const float f, const float epsilon) {
+static bool isZero(const float f, const float epsilon)
+{
return fabs(f) <= epsilon;
}
-static float square(float f) {
+static float square(float f)
+{
return f * f;
}
@@ -479,8 +524,9 @@ static float square(float f) {
* @note isPowerOfTwo(x) == true -> nextPowerOfTwo(x) == x
* @note nextPowerOfTwo(x) = 2 << log2(x-1)
*/
-static uint32_t nextPowerOfTwo(uint32_t x) {
- XA_DEBUG_ASSERT(x != 0);
+static uint32_t nextPowerOfTwo(uint32_t x)
+{
+ XA_DEBUG_ASSERT( x != 0 );
// On modern CPUs this is supposed to be as fast as using the bsr instruction.
x--;
x |= x >> 1;
@@ -491,59 +537,38 @@ static uint32_t nextPowerOfTwo(uint32_t x) {
return x + 1;
}
-static uint32_t sdbmHash(const void *data_in, uint32_t size, uint32_t h = 5381) {
- const uint8_t *data = (const uint8_t *)data_in;
- uint32_t i = 0;
- while (i < size) {
- h = (h << 16) + (h << 6) - h + (uint32_t)data[i++];
- }
- return h;
-}
-
-template <typename T>
-static uint32_t hash(const T &t, uint32_t h = 5381) {
- return sdbmHash(&t, sizeof(T), h);
-}
-
-// Functors for hash table:
-template <typename Key>
-struct Hash {
- uint32_t operator()(const Key &k) const { return hash(k); }
-};
-
-template <typename Key>
-struct Equal {
- bool operator()(const Key &k0, const Key &k1) const { return k0 == k1; }
-};
-
-class Vector2 {
+class Vector2
+{
public:
Vector2() {}
- explicit Vector2(float f) :
- x(f), y(f) {}
- Vector2(float x, float y) :
- x(x), y(y) {}
+ explicit Vector2(float f) : x(f), y(f) {}
+ Vector2(float x, float y): x(x), y(y) {}
- Vector2 operator-() const {
+ Vector2 operator-() const
+ {
return Vector2(-x, -y);
}
- void operator+=(const Vector2 &v) {
+ void operator+=(const Vector2 &v)
+ {
x += v.x;
y += v.y;
}
- void operator-=(const Vector2 &v) {
+ void operator-=(const Vector2 &v)
+ {
x -= v.x;
y -= v.y;
}
- void operator*=(float s) {
+ void operator*=(float s)
+ {
x *= s;
y *= s;
}
- void operator*=(const Vector2 &v) {
+ void operator*=(const Vector2 &v)
+ {
x *= v.x;
y *= v.y;
}
@@ -551,11 +576,13 @@ public:
float x, y;
};
-static bool operator==(const Vector2 &a, const Vector2 &b) {
+static bool operator==(const Vector2 &a, const Vector2 &b)
+{
return a.x == b.x && a.y == b.y;
}
-static bool operator!=(const Vector2 &a, const Vector2 &b) {
+static bool operator!=(const Vector2 &a, const Vector2 &b)
+{
return a.x != b.x || a.y != b.y;
}
@@ -564,33 +591,40 @@ static bool operator!=(const Vector2 &a, const Vector2 &b) {
return Vector2(a.x + b.x, a.y + b.y);
}*/
-static Vector2 operator-(const Vector2 &a, const Vector2 &b) {
+static Vector2 operator-(const Vector2 &a, const Vector2 &b)
+{
return Vector2(a.x - b.x, a.y - b.y);
}
-static Vector2 operator*(const Vector2 &v, float s) {
+static Vector2 operator*(const Vector2 &v, float s)
+{
return Vector2(v.x * s, v.y * s);
}
-static float dot(const Vector2 &a, const Vector2 &b) {
+static float dot(const Vector2 &a, const Vector2 &b)
+{
return a.x * b.x + a.y * b.y;
}
-static float lengthSquared(const Vector2 &v) {
+static float lengthSquared(const Vector2 &v)
+{
return v.x * v.x + v.y * v.y;
}
-static float length(const Vector2 &v) {
+static float length(const Vector2 &v)
+{
return sqrtf(lengthSquared(v));
}
#if XA_DEBUG
-static bool isNormalized(const Vector2 &v, float epsilon = kNormalEpsilon) {
+static bool isNormalized(const Vector2 &v, float epsilon = kNormalEpsilon)
+{
return equal(length(v), 1, epsilon);
}
#endif
-static Vector2 normalize(const Vector2 &v, float epsilon) {
+static Vector2 normalize(const Vector2 &v, float epsilon)
+{
float l = length(v);
XA_DEBUG_ASSERT(!isZero(l, epsilon));
XA_UNUSED(epsilon);
@@ -599,30 +633,36 @@ static Vector2 normalize(const Vector2 &v, float epsilon) {
return n;
}
-static Vector2 normalizeSafe(const Vector2 &v, const Vector2 &fallback, float epsilon) {
+static Vector2 normalizeSafe(const Vector2 &v, const Vector2 &fallback, float epsilon)
+{
float l = length(v);
if (isZero(l, epsilon))
return fallback;
return v * (1.0f / l);
}
-static bool equal(const Vector2 &v1, const Vector2 &v2, float epsilon) {
+static bool equal(const Vector2 &v1, const Vector2 &v2, float epsilon)
+{
return equal(v1.x, v2.x, epsilon) && equal(v1.y, v2.y, epsilon);
}
-static Vector2 min(const Vector2 &a, const Vector2 &b) {
+static Vector2 min(const Vector2 &a, const Vector2 &b)
+{
return Vector2(min(a.x, b.x), min(a.y, b.y));
}
-static Vector2 max(const Vector2 &a, const Vector2 &b) {
+static Vector2 max(const Vector2 &a, const Vector2 &b)
+{
return Vector2(max(a.x, b.x), max(a.y, b.y));
}
-static bool isFinite(const Vector2 &v) {
+static bool isFinite(const Vector2 &v)
+{
return isFinite(v.x) && isFinite(v.y);
}
-static float triangleArea(const Vector2 &a, const Vector2 &b, const Vector2 &c) {
+static float triangleArea(const Vector2 &a, const Vector2 &b, const Vector2 &c)
+{
// IC: While it may be appealing to use the following expression:
//return (c.x * a.y + a.x * b.y + b.x * c.y - b.x * a.y - c.x * b.y - a.x * c.y) * 0.5f;
// That's actually a terrible idea. Small triangles far from the origin can end up producing fairly large floating point
@@ -636,7 +676,8 @@ static float triangleArea(const Vector2 &a, const Vector2 &b, const Vector2 &c)
return (v0.x * v1.y - v0.y * v1.x) * 0.5f;
}
-static bool linesIntersect(const Vector2 &a1, const Vector2 &a2, const Vector2 &b1, const Vector2 &b2, float epsilon) {
+static bool linesIntersect(const Vector2 &a1, const Vector2 &a2, const Vector2 &b1, const Vector2 &b2, float epsilon)
+{
const Vector2 v0 = a2 - a1;
const Vector2 v1 = b2 - b1;
const float denom = -v1.x * v0.y + v0.x * v1.y;
@@ -644,70 +685,76 @@ static bool linesIntersect(const Vector2 &a1, const Vector2 &a2, const Vector2 &
return false;
const float s = (-v0.y * (a1.x - b1.x) + v0.x * (a1.y - b1.y)) / denom;
if (s > epsilon && s < 1.0f - epsilon) {
- const float t = (v1.x * (a1.y - b1.y) - v1.y * (a1.x - b1.x)) / denom;
+ const float t = ( v1.x * (a1.y - b1.y) - v1.y * (a1.x - b1.x)) / denom;
return t > epsilon && t < 1.0f - epsilon;
}
return false;
}
-struct Vector2i {
+struct Vector2i
+{
Vector2i() {}
- Vector2i(int32_t x, int32_t y) :
- x(x), y(y) {}
+ Vector2i(int32_t x, int32_t y) : x(x), y(y) {}
int32_t x, y;
};
-class Vector3 {
+class Vector3
+{
public:
Vector3() {}
- explicit Vector3(float f) :
- x(f), y(f), z(f) {}
- Vector3(float x, float y, float z) :
- x(x), y(y), z(z) {}
- Vector3(const Vector2 &v, float z) :
- x(v.x), y(v.y), z(z) {}
-
- Vector2 xy() const {
+ explicit Vector3(float f) : x(f), y(f), z(f) {}
+ Vector3(float x, float y, float z) : x(x), y(y), z(z) {}
+ Vector3(const Vector2 &v, float z) : x(v.x), y(v.y), z(z) {}
+
+ Vector2 xy() const
+ {
return Vector2(x, y);
}
- Vector3 operator-() const {
+ Vector3 operator-() const
+ {
return Vector3(-x, -y, -z);
}
- void operator+=(const Vector3 &v) {
+ void operator+=(const Vector3 &v)
+ {
x += v.x;
y += v.y;
z += v.z;
}
- void operator-=(const Vector3 &v) {
+ void operator-=(const Vector3 &v)
+ {
x -= v.x;
y -= v.y;
z -= v.z;
}
- void operator*=(float s) {
+ void operator*=(float s)
+ {
x *= s;
y *= s;
z *= s;
}
- void operator/=(float s) {
+ void operator/=(float s)
+ {
float is = 1.0f / s;
x *= is;
y *= is;
z *= is;
}
- void operator*=(const Vector3 &v) {
+ void operator*=(const Vector3 &v)
+ {
x *= v.x;
y *= v.y;
z *= v.z;
}
- void operator/=(const Vector3 &v) {
+ void operator/=(const Vector3 &v)
+ {
x /= v.x;
y /= v.y;
z /= v.z;
@@ -716,43 +763,53 @@ public:
float x, y, z;
};
-static Vector3 operator+(const Vector3 &a, const Vector3 &b) {
+static Vector3 operator+(const Vector3 &a, const Vector3 &b)
+{
return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
-static Vector3 operator-(const Vector3 &a, const Vector3 &b) {
+static Vector3 operator-(const Vector3 &a, const Vector3 &b)
+{
return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
-static Vector3 cross(const Vector3 &a, const Vector3 &b) {
+static Vector3 cross(const Vector3 &a, const Vector3 &b)
+{
return Vector3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
}
-static Vector3 operator*(const Vector3 &v, float s) {
+static Vector3 operator*(const Vector3 &v, float s)
+{
return Vector3(v.x * s, v.y * s, v.z * s);
}
-static Vector3 operator/(const Vector3 &v, float s) {
+static Vector3 operator/(const Vector3 &v, float s)
+{
return v * (1.0f / s);
}
-static float dot(const Vector3 &a, const Vector3 &b) {
+static float dot(const Vector3 &a, const Vector3 &b)
+{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
-static float lengthSquared(const Vector3 &v) {
+static float lengthSquared(const Vector3 &v)
+{
return v.x * v.x + v.y * v.y + v.z * v.z;
}
-static float length(const Vector3 &v) {
+static float length(const Vector3 &v)
+{
return sqrtf(lengthSquared(v));
}
-static bool isNormalized(const Vector3 &v, float epsilon = kNormalEpsilon) {
+static bool isNormalized(const Vector3 &v, float epsilon = kNormalEpsilon)
+{
return equal(length(v), 1, epsilon);
}
-static Vector3 normalize(const Vector3 &v, float epsilon) {
+static Vector3 normalize(const Vector3 &v, float epsilon)
+{
float l = length(v);
XA_DEBUG_ASSERT(!isZero(l, epsilon));
XA_UNUSED(epsilon);
@@ -761,7 +818,8 @@ static Vector3 normalize(const Vector3 &v, float epsilon) {
return n;
}
-static Vector3 normalizeSafe(const Vector3 &v, const Vector3 &fallback, float epsilon) {
+static Vector3 normalizeSafe(const Vector3 &v, const Vector3 &fallback, float epsilon)
+{
float l = length(v);
if (isZero(l, epsilon)) {
return fallback;
@@ -769,59 +827,80 @@ static Vector3 normalizeSafe(const Vector3 &v, const Vector3 &fallback, float ep
return v * (1.0f / l);
}
-static bool equal(const Vector3 &v0, const Vector3 &v1, float epsilon) {
+static bool equal(const Vector3 &v0, const Vector3 &v1, float epsilon)
+{
return fabs(v0.x - v1.x) <= epsilon && fabs(v0.y - v1.y) <= epsilon && fabs(v0.z - v1.z) <= epsilon;
}
-static Vector3 min(const Vector3 &a, const Vector3 &b) {
+static Vector3 min(const Vector3 &a, const Vector3 &b)
+{
return Vector3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
}
-static Vector3 max(const Vector3 &a, const Vector3 &b) {
+static Vector3 max(const Vector3 &a, const Vector3 &b)
+{
return Vector3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
}
#if XA_DEBUG
-bool isFinite(const Vector3 &v) {
+bool isFinite(const Vector3 &v)
+{
return isFinite(v.x) && isFinite(v.y) && isFinite(v.z);
}
#endif
-struct Extents2 {
+struct Extents2
+{
Vector2 min, max;
- void reset() {
+ Extents2() {}
+
+ Extents2(Vector2 p1, Vector2 p2)
+ {
+ min = xatlas::internal::min(p1, p2);
+ max = xatlas::internal::max(p1, p2);
+ }
+
+ void reset()
+ {
min.x = min.y = FLT_MAX;
max.x = max.y = -FLT_MAX;
}
- void add(Vector2 p) {
+ void add(Vector2 p)
+ {
min = xatlas::internal::min(min, p);
max = xatlas::internal::max(max, p);
}
- Vector2 midpoint() const {
+ Vector2 midpoint() const
+ {
return Vector2(min.x + (max.x - min.x) * 0.5f, min.y + (max.y - min.y) * 0.5f);
}
- static bool intersect(Extents2 e1, Extents2 e2) {
+ static bool intersect(const Extents2 &e1, const Extents2 &e2)
+ {
return e1.min.x <= e2.max.x && e1.max.x >= e2.min.x && e1.min.y <= e2.max.y && e1.max.y >= e2.min.y;
}
};
-struct Plane {
+struct Plane
+{
Plane() = default;
-
- Plane(const Vector3 &p1, const Vector3 &p2, const Vector3 &p3) {
+
+ Plane(const Vector3 &p1, const Vector3 &p2, const Vector3 &p3)
+ {
normal = cross(p2 - p1, p3 - p1);
dist = dot(normal, p1);
}
- float distance(const Vector3 &p) const {
+ float distance(const Vector3 &p) const
+ {
return dot(normal, p) - dist;
}
- void normalize() {
+ void normalize()
+ {
const float len = length(normal);
if (len > 0.0f) {
const float il = 1.0f / len;
@@ -834,7 +913,8 @@ struct Plane {
float dist;
};
-static bool lineIntersectsPoint(const Vector3 &point, const Vector3 &lineStart, const Vector3 &lineEnd, float *t, float epsilon) {
+static bool lineIntersectsPoint(const Vector3 &point, const Vector3 &lineStart, const Vector3 &lineEnd, float *t, float epsilon)
+{
float tt;
if (!t)
t = &tt;
@@ -851,19 +931,22 @@ static bool lineIntersectsPoint(const Vector3 &point, const Vector3 &lineStart,
return *t > kEpsilon && *t < 1.0f - kEpsilon;
}
-static bool sameSide(const Vector3 &p1, const Vector3 &p2, const Vector3 &a, const Vector3 &b) {
+static bool sameSide(const Vector3 &p1, const Vector3 &p2, const Vector3 &a, const Vector3 &b)
+{
const Vector3 &ab = b - a;
return dot(cross(ab, p1 - a), cross(ab, p2 - a)) >= 0.0f;
}
// http://blackpawn.com/texts/pointinpoly/default.html
-static bool pointInTriangle(const Vector3 &p, const Vector3 &a, const Vector3 &b, const Vector3 &c) {
+static bool pointInTriangle(const Vector3 &p, const Vector3 &a, const Vector3 &b, const Vector3 &c)
+{
return sameSide(p, a, b, c) && sameSide(p, b, a, c) && sameSide(p, c, a, b);
}
#if XA_CLOSE_HOLES_CHECK_EDGE_INTERSECTION
// https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
-static bool rayIntersectsTriangle(const Vector3 &rayOrigin, const Vector3 &rayDir, const Vector3 *tri, float *t) {
+static bool rayIntersectsTriangle(const Vector3 &rayOrigin, const Vector3 &rayDir, const Vector3 *tri, float *t)
+{
*t = 0.0f;
const Vector3 &edge1 = tri[1] - tri[0];
const Vector3 &edge2 = tri[2] - tri[0];
@@ -890,47 +973,50 @@ static bool rayIntersectsTriangle(const Vector3 &rayOrigin, const Vector3 &rayDi
#endif
// From Fast-BVH
-struct AABB {
- AABB() :
- min(FLT_MAX, FLT_MAX, FLT_MAX), max(-FLT_MAX, -FLT_MAX, -FLT_MAX) {}
- AABB(const Vector3 &min, const Vector3 &max) :
- min(min), max(max) {}
- AABB(const Vector3 &p, float radius = 0.0f) :
- min(p), max(p) {
- if (radius > 0.0f) expand(radius);
- }
+struct AABB
+{
+ AABB() : min(FLT_MAX, FLT_MAX, FLT_MAX), max(-FLT_MAX, -FLT_MAX, -FLT_MAX) {}
+ AABB(const Vector3 &min, const Vector3 &max) : min(min), max(max) { }
+ AABB(const Vector3 &p, float radius = 0.0f) : min(p), max(p) { if (radius > 0.0f) expand(radius); }
- bool intersect(const AABB &other) const {
+ bool intersect(const AABB &other) const
+ {
return min.x <= other.max.x && max.x >= other.min.x && min.y <= other.max.y && max.y >= other.min.y && min.z <= other.max.z && max.z >= other.min.z;
}
- void expandToInclude(const Vector3 &p) {
+ void expandToInclude(const Vector3 &p)
+ {
min = internal::min(min, p);
max = internal::max(max, p);
}
- void expandToInclude(const AABB &aabb) {
+ void expandToInclude(const AABB &aabb)
+ {
min = internal::min(min, aabb.min);
max = internal::max(max, aabb.max);
}
- void expand(float amount) {
+ void expand(float amount)
+ {
min -= Vector3(amount);
max += Vector3(amount);
}
- Vector3 centroid() const {
+ Vector3 centroid() const
+ {
return min + (max - min) * 0.5f;
}
- uint32_t maxDimension() const {
+ uint32_t maxDimension() const
+ {
const Vector3 extent = max - min;
uint32_t result = 0;
if (extent.y > extent.x) {
result = 1;
if (extent.z > extent.y)
result = 2;
- } else if (extent.z > extent.x)
+ }
+ else if(extent.z > extent.x)
result = 2;
return result;
}
@@ -938,9 +1024,10 @@ struct AABB {
Vector3 min, max;
};
-struct ArrayBase {
- ArrayBase(uint32_t elementSize, int memTag = MemTag::Default) :
- buffer(nullptr), elementSize(elementSize), size(0), capacity(0) {
+struct ArrayBase
+{
+ ArrayBase(uint32_t elementSize, int memTag = MemTag::Default) : buffer(nullptr), elementSize(elementSize), size(0), capacity(0)
+ {
#if XA_DEBUG_HEAP
this->memTag = memTag;
#else
@@ -948,26 +1035,31 @@ struct ArrayBase {
#endif
}
- ~ArrayBase() {
+ ~ArrayBase()
+ {
XA_FREE(buffer);
}
- XA_INLINE void clear() {
+ XA_INLINE void clear()
+ {
size = 0;
}
- void copyFrom(const uint8_t *data, uint32_t length) {
+ void copyFrom(const uint8_t *data, uint32_t length)
+ {
resize(length, true);
memcpy(buffer, data, length * elementSize);
}
- void copyTo(ArrayBase &other) const {
+ void copyTo(ArrayBase &other) const
+ {
XA_DEBUG_ASSERT(elementSize == other.elementSize);
other.resize(size, true);
memcpy(other.buffer, buffer, size * elementSize);
}
- void destroy() {
+ void destroy()
+ {
size = 0;
XA_FREE(buffer);
buffer = nullptr;
@@ -976,7 +1068,8 @@ struct ArrayBase {
}
// Insert the given element at the given index shifting all the elements up.
- void insertAt(uint32_t index, const uint8_t *value) {
+ void insertAt(uint32_t index, const uint8_t *value)
+ {
XA_DEBUG_ASSERT(index >= 0 && index <= size);
resize(size + 1, false);
if (index < size - 1)
@@ -984,7 +1077,8 @@ struct ArrayBase {
memcpy(&buffer[index * elementSize], value, elementSize);
}
- void moveTo(ArrayBase &other) {
+ void moveTo(ArrayBase &other)
+ {
XA_DEBUG_ASSERT(elementSize == other.elementSize);
other.destroy();
other.buffer = buffer;
@@ -998,18 +1092,21 @@ struct ArrayBase {
elementSize = size = capacity = 0;
}
- void pop_back() {
+ void pop_back()
+ {
XA_DEBUG_ASSERT(size > 0);
resize(size - 1, false);
}
- void push_back(const uint8_t *value) {
+ void push_back(const uint8_t *value)
+ {
XA_DEBUG_ASSERT(value < buffer || value >= buffer + size);
resize(size + 1, false);
memcpy(&buffer[(size - 1) * elementSize], value, elementSize);
}
- void push_back(const ArrayBase &other) {
+ void push_back(const ArrayBase &other)
+ {
XA_DEBUG_ASSERT(elementSize == other.elementSize);
if (other.size == 0)
return;
@@ -1019,19 +1116,31 @@ struct ArrayBase {
}
// Remove the element at the given index. This is an expensive operation!
- void removeAt(uint32_t index) {
+ void removeAt(uint32_t index)
+ {
XA_DEBUG_ASSERT(index >= 0 && index < size);
if (size != 1)
memmove(buffer + elementSize * index, buffer + elementSize * (index + 1), elementSize * (size - 1 - index));
size--;
}
- void reserve(uint32_t desiredSize) {
+ // Element at index is swapped with the last element, then the array length is decremented.
+ void removeAtFast(uint32_t index)
+ {
+ XA_DEBUG_ASSERT(index >= 0 && index < size);
+ if (size != 1 && index != size - 1)
+ memcpy(buffer + elementSize * index, buffer + elementSize * (size - 1), elementSize);
+ size--;
+ }
+
+ void reserve(uint32_t desiredSize)
+ {
if (desiredSize > capacity)
setArrayCapacity(desiredSize);
}
- void resize(uint32_t newSize, bool exact) {
+ void resize(uint32_t newSize, bool exact)
+ {
size = newSize;
if (size > capacity) {
// First allocation is always exact. Otherwise, following allocations grow array to 150% of desired size.
@@ -1044,7 +1153,8 @@ struct ArrayBase {
}
}
- void setArrayCapacity(uint32_t newCapacity) {
+ void setArrayCapacity(uint32_t newCapacity)
+ {
XA_DEBUG_ASSERT(newCapacity >= size);
if (newCapacity == 0) {
// free the buffer.
@@ -1064,8 +1174,9 @@ struct ArrayBase {
}
#if XA_DEBUG_HEAP
- void setMemTag(int memTag) {
- this->memTag = memTag;
+ void setMemTag(int _memTag)
+ {
+ this->memTag = _memTag;
}
#endif
@@ -1078,25 +1189,28 @@ struct ArrayBase {
#endif
};
-template <typename T>
-class Array {
+template<typename T>
+class Array
+{
public:
- Array(int memTag = MemTag::Default) :
- m_base(sizeof(T), memTag) {}
- Array(const Array &) = delete;
+ Array(int memTag = MemTag::Default) : m_base(sizeof(T), memTag) {}
+ Array(const Array&) = delete;
Array &operator=(const Array &) = delete;
- XA_INLINE const T &operator[](uint32_t index) const {
+ XA_INLINE const T &operator[](uint32_t index) const
+ {
XA_DEBUG_ASSERT(index < m_base.size);
return ((const T *)m_base.buffer)[index];
}
- XA_INLINE T &operator[](uint32_t index) {
+ XA_INLINE T &operator[](uint32_t index)
+ {
XA_DEBUG_ASSERT(index < m_base.size);
return ((T *)m_base.buffer)[index];
}
- XA_INLINE const T &back() const {
+ XA_INLINE const T &back() const
+ {
XA_DEBUG_ASSERT(!isEmpty());
return ((const T *)m_base.buffer)[m_base.size - 1];
}
@@ -1104,7 +1218,8 @@ public:
XA_INLINE T *begin() { return (T *)m_base.buffer; }
XA_INLINE void clear() { m_base.clear(); }
- bool contains(const T &value) const {
+ bool contains(const T &value) const
+ {
for (uint32_t i = 0; i < m_base.size; i++) {
if (((const T *)m_base.buffer)[i] == value)
return true;
@@ -1116,6 +1231,7 @@ public:
void copyTo(Array &other) const { m_base.copyTo(other.m_base); }
XA_INLINE const T *data() const { return (const T *)m_base.buffer; }
XA_INLINE T *data() { return (T *)m_base.buffer; }
+ void destroy() { m_base.destroy(); }
XA_INLINE T *end() { return (T *)m_base.buffer + m_base.size; }
XA_INLINE bool isEmpty() const { return m_base.size == 0; }
void insertAt(uint32_t index, const T &value) { m_base.insertAt(index, (const uint8_t *)&value); }
@@ -1124,25 +1240,34 @@ public:
void push_back(const Array &other) { m_base.push_back(other.m_base); }
void pop_back() { m_base.pop_back(); }
void removeAt(uint32_t index) { m_base.removeAt(index); }
+ void removeAtFast(uint32_t index) { m_base.removeAtFast(index); }
void reserve(uint32_t desiredSize) { m_base.reserve(desiredSize); }
void resize(uint32_t newSize) { m_base.resize(newSize, true); }
- void runCtors() {
+ void runCtors()
+ {
for (uint32_t i = 0; i < m_base.size; i++)
new (&((T *)m_base.buffer)[i]) T;
}
- void runDtors() {
+ void runDtors()
+ {
for (uint32_t i = 0; i < m_base.size; i++)
((T *)m_base.buffer)[i].~T();
}
- void setAll(const T &value) {
+ void fill(const T &value)
+ {
auto buffer = (T *)m_base.buffer;
for (uint32_t i = 0; i < m_base.size; i++)
buffer[i] = value;
}
+ void fillBytes(uint8_t value)
+ {
+ memset(m_base.buffer, (int)value, m_base.size * m_base.elementSize);
+ }
+
#if XA_DEBUG_HEAP
void setMemTag(int memTag) { m_base.setMemTag(memTag); }
#endif
@@ -1154,47 +1279,35 @@ private:
ArrayBase m_base;
};
-template <typename T>
-struct ArrayView {
- ArrayView(Array<T> &a) :
- data(a.data()), length(a.size()) {}
- ArrayView(T *data, uint32_t length) :
- data(data), length(length) {}
- ArrayView &operator=(Array<T> &a) {
- data = a.data();
- length = a.size();
- return *this;
- }
- XA_INLINE const T &operator[](uint32_t index) const {
- XA_DEBUG_ASSERT(index < length);
- return data[index];
- }
+template<typename T>
+struct ArrayView
+{
+ ArrayView() : data(nullptr), length(0) {}
+ ArrayView(Array<T> &a) : data(a.data()), length(a.size()) {}
+ ArrayView(T *data, uint32_t length) : data(data), length(length) {}
+ ArrayView &operator=(Array<T> &a) { data = a.data(); length = a.size(); return *this; }
+ XA_INLINE const T &operator[](uint32_t index) const { XA_DEBUG_ASSERT(index < length); return data[index]; }
T *data;
uint32_t length;
};
-template <typename T>
-struct ConstArrayView {
- ConstArrayView(const Array<T> &a) :
- data(a.data()), length(a.size()) {}
- ConstArrayView(const T *data, uint32_t length) :
- data(data), length(length) {}
- ConstArrayView &operator=(const Array<T> &a) {
- data = a.data();
- length = a.size();
- return *this;
- }
- XA_INLINE const T &operator[](uint32_t index) const {
- XA_DEBUG_ASSERT(index < length);
- return data[index];
- }
+template<typename T>
+struct ConstArrayView
+{
+ ConstArrayView() : data(nullptr), length(0) {}
+ ConstArrayView(const Array<T> &a) : data(a.data()), length(a.size()) {}
+ ConstArrayView(const T *data, uint32_t length) : data(data), length(length) {}
+ ConstArrayView &operator=(const Array<T> &a) { data = a.data(); length = a.size(); return *this; }
+ XA_INLINE const T &operator[](uint32_t index) const { XA_DEBUG_ASSERT(index < length); return data[index]; }
const T *data;
uint32_t length;
};
/// Basis class to compute tangent space basis, ortogonalizations and to transform vectors from one space to another.
-struct Basis {
- XA_NODISCARD static Vector3 computeTangent(const Vector3 &normal) {
+struct Basis
+{
+ XA_NODISCARD static Vector3 computeTangent(const Vector3 &normal)
+ {
XA_ASSERT(isNormalized(normal));
// Choose minimum axis.
Vector3 tangent;
@@ -1210,7 +1323,8 @@ struct Basis {
return tangent;
}
- XA_NODISCARD static Vector3 computeBitangent(const Vector3 &normal, const Vector3 &tangent) {
+ XA_NODISCARD static Vector3 computeBitangent(const Vector3 &normal, const Vector3 &tangent)
+ {
return cross(normal, tangent);
}
@@ -1220,31 +1334,42 @@ struct Basis {
};
// Simple bit array.
-class BitArray {
+class BitArray
+{
public:
- BitArray() :
- m_size(0) {}
+ BitArray() : m_size(0) {}
- BitArray(uint32_t sz) {
+ BitArray(uint32_t sz)
+ {
resize(sz);
}
- void resize(uint32_t new_size) {
+ void resize(uint32_t new_size)
+ {
m_size = new_size;
m_wordArray.resize((m_size + 31) >> 5);
}
- bool get(uint32_t index) const {
+ bool get(uint32_t index) const
+ {
XA_DEBUG_ASSERT(index < m_size);
return (m_wordArray[index >> 5] & (1 << (index & 31))) != 0;
}
- void set(uint32_t index) {
+ void set(uint32_t index)
+ {
XA_DEBUG_ASSERT(index < m_size);
m_wordArray[index >> 5] |= (1 << (index & 31));
}
- void zeroOutMemory() {
+ void unset(uint32_t index)
+ {
+ XA_DEBUG_ASSERT(index < m_size);
+ m_wordArray[index >> 5] &= ~(1 << (index & 31));
+ }
+
+ void zeroOutMemory()
+ {
m_wordArray.zeroOutMemory();
}
@@ -1253,13 +1378,13 @@ private:
Array<uint32_t> m_wordArray;
};
-class BitImage {
+class BitImage
+{
public:
- BitImage() :
- m_width(0), m_height(0), m_rowStride(0), m_data(MemTag::BitImage) {}
+ BitImage() : m_width(0), m_height(0), m_rowStride(0), m_data(MemTag::BitImage) {}
- BitImage(uint32_t w, uint32_t h) :
- m_width(w), m_height(h), m_data(MemTag::BitImage) {
+ BitImage(uint32_t w, uint32_t h) : m_width(w), m_height(h), m_data(MemTag::BitImage)
+ {
m_rowStride = (m_width + 63) >> 6;
m_data.resize(m_rowStride * m_height);
m_data.zeroOutMemory();
@@ -1270,14 +1395,16 @@ public:
uint32_t width() const { return m_width; }
uint32_t height() const { return m_height; }
- void copyTo(BitImage &other) {
+ void copyTo(BitImage &other)
+ {
other.m_width = m_width;
other.m_height = m_height;
other.m_rowStride = m_rowStride;
m_data.copyTo(other.m_data);
}
- void resize(uint32_t w, uint32_t h, bool discard) {
+ void resize(uint32_t w, uint32_t h, bool discard)
+ {
const uint32_t rowStride = (w + 63) >> 6;
if (discard) {
m_data.resize(rowStride * h);
@@ -1301,24 +1428,28 @@ public:
m_rowStride = rowStride;
}
- bool get(uint32_t x, uint32_t y) const {
+ bool get(uint32_t x, uint32_t y) const
+ {
XA_DEBUG_ASSERT(x < m_width && y < m_height);
const uint32_t index = (x >> 6) + y * m_rowStride;
return (m_data[index] & (UINT64_C(1) << (uint64_t(x) & UINT64_C(63)))) != 0;
}
- void set(uint32_t x, uint32_t y) {
+ void set(uint32_t x, uint32_t y)
+ {
XA_DEBUG_ASSERT(x < m_width && y < m_height);
const uint32_t index = (x >> 6) + y * m_rowStride;
m_data[index] |= UINT64_C(1) << (uint64_t(x) & UINT64_C(63));
XA_DEBUG_ASSERT(get(x, y));
}
- void zeroOutMemory() {
+ void zeroOutMemory()
+ {
m_data.zeroOutMemory();
}
- bool canBlit(const BitImage &image, uint32_t offsetX, uint32_t offsetY) const {
+ bool canBlit(const BitImage &image, uint32_t offsetX, uint32_t offsetY) const
+ {
for (uint32_t y = 0; y < image.m_height; y++) {
const uint32_t thisY = y + offsetY;
if (thisY >= m_height)
@@ -1342,7 +1473,8 @@ public:
return true;
}
- void dilate(uint32_t padding) {
+ void dilate(uint32_t padding)
+ {
BitImage tmp(m_width, m_height);
for (uint32_t p = 0; p < padding; p++) {
tmp.zeroOutMemory();
@@ -1379,10 +1511,11 @@ private:
};
// From Fast-BVH
-class BVH {
+class BVH
+{
public:
- BVH(const Array<AABB> &objectAabbs, uint32_t leafSize = 4) :
- m_objectIds(MemTag::BVH), m_nodes(MemTag::BVH) {
+ BVH(const Array<AABB> &objectAabbs, uint32_t leafSize = 4) : m_objectIds(MemTag::BVH), m_nodes(MemTag::BVH)
+ {
m_objectAabbs = &objectAabbs;
if (m_objectAabbs->isEmpty())
return;
@@ -1402,7 +1535,7 @@ public:
Node node;
m_nodes.reserve(objectAabbs.size() * 2);
uint32_t nNodes = 0;
- while (stackptr > 0) {
+ while(stackptr > 0) {
// Pop the next item off of the stack
const BuildEntry &bnode = todo[--stackptr];
const uint32_t start = bnode.start;
@@ -1415,7 +1548,7 @@ public:
// Calculate the bounding box for this node
AABB bb(objectAabbs[m_objectIds[start]]);
AABB bc(objectAabbs[m_objectIds[start]].centroid());
- for (uint32_t p = start + 1; p < end; ++p) {
+ for(uint32_t p = start + 1; p < end; ++p) {
bb.expandToInclude(objectAabbs[m_objectIds[p]]);
bc.expandToInclude(objectAabbs[m_objectIds[p]].centroid());
}
@@ -1431,7 +1564,7 @@ public:
m_nodes[bnode.parent].rightOffset--;
// When this is the second touch, this is the right child.
// The right child sets up the offset for the flat tree.
- if (m_nodes[bnode.parent].rightOffset == kTouchedTwice)
+ if (m_nodes[bnode.parent].rightOffset == kTouchedTwice )
m_nodes[bnode.parent].rightOffset = nNodes - 1 - bnode.parent;
}
// If this is a leaf, no need to subdivide.
@@ -1466,20 +1599,21 @@ public:
}
}
- void query(const AABB &queryAabb, Array<uint32_t> &result) const {
+ void query(const AABB &queryAabb, Array<uint32_t> &result) const
+ {
result.clear();
// Working set
uint32_t todo[64];
int32_t stackptr = 0;
// "Push" on the root node to the working set
todo[stackptr] = 0;
- while (stackptr >= 0) {
+ while(stackptr >= 0) {
// Pop off the next node to work on.
const int ni = todo[stackptr--];
const Node &node = m_nodes[ni];
// Is leaf -> Intersect
if (node.rightOffset == 0) {
- for (uint32_t o = 0; o < node.nPrims; ++o) {
+ for(uint32_t o = 0; o < node.nPrims; ++o) {
const uint32_t obj = node.start + o;
if (queryAabb.intersect((*m_objectAabbs)[m_objectIds[obj]]))
result.push_back(m_objectIds[obj]);
@@ -1496,12 +1630,14 @@ public:
}
private:
- struct BuildEntry {
+ struct BuildEntry
+ {
uint32_t parent; // If non-zero then this is the index of the parent. (used in offsets)
uint32_t start, end; // The range of objects in the object list covered by this node.
};
- struct Node {
+ struct Node
+ {
AABB aabb;
uint32_t start, nPrims, rightOffset;
};
@@ -1511,8 +1647,10 @@ private:
Array<Node> m_nodes;
};
-struct Fit {
- static bool computeBasis(const Vector3 *points, uint32_t pointsCount, Basis *basis) {
+struct Fit
+{
+ static bool computeBasis(const Vector3 *points, uint32_t pointsCount, Basis *basis)
+ {
if (computeLeastSquaresNormal(points, pointsCount, &basis->normal)) {
basis->tangent = Basis::computeTangent(basis->normal);
basis->bitangent = Basis::computeBitangent(basis->normal, basis->tangent);
@@ -1526,7 +1664,8 @@ private:
// Fast, and accurate to within a few degrees.
// Returns None if the points do not span a plane.
// https://www.ilikebigbits.com/2015_03_04_plane_from_points.html
- static bool computeLeastSquaresNormal(const Vector3 *points, uint32_t pointsCount, Vector3 *normal) {
+ static bool computeLeastSquaresNormal(const Vector3 *points, uint32_t pointsCount, Vector3 *normal)
+ {
XA_DEBUG_ASSERT(pointsCount >= 3);
if (pointsCount == 3) {
*normal = normalize(cross(points[2] - points[0], points[1] - points[0]), kEpsilon);
@@ -1591,7 +1730,7 @@ private:
// Pick path with best conditioning:
Vector3 dir(0.0f);
if (det_max == det_x)
- dir = Vector3(det_x, xz * yz - xy * zz, xy * yz - xz * yy);
+ dir = Vector3(det_x,xz * yz - xy * zz,xy * yz - xz * yy);
else if (det_max == det_y)
dir = Vector3(xz * yz - xy * zz, det_y, xy * xz - yz * xx);
else if (det_max == det_z)
@@ -1604,7 +1743,8 @@ private:
return isNormalized(*normal);
}
- static bool computeEigen(const Vector3 *points, uint32_t pointsCount, Basis *basis) {
+ static bool computeEigen(const Vector3 *points, uint32_t pointsCount, Basis *basis)
+ {
float matrix[6];
computeCovariance(pointsCount, points, matrix);
if (matrix[0] == 0 && matrix[3] == 0 && matrix[5] == 0)
@@ -1619,7 +1759,8 @@ private:
return true;
}
- static Vector3 computeCentroid(int n, const Vector3 *points) {
+ static Vector3 computeCentroid(int n, const Vector3 * points)
+ {
Vector3 centroid(0.0f);
for (int i = 0; i < n; i++) {
centroid += points[i];
@@ -1628,7 +1769,8 @@ private:
return centroid;
}
- static Vector3 computeCovariance(int n, const Vector3 *points, float *covariance) {
+ static Vector3 computeCovariance(int n, const Vector3 * points, float * covariance)
+ {
// compute the centroid
Vector3 centroid = computeCentroid(n, points);
// compute covariance matrix
@@ -1650,7 +1792,8 @@ private:
// Tridiagonal solver from Charles Bloom.
// Householder transforms followed by QL decomposition.
// Seems to be based on the code from Numerical Recipes in C.
- static bool eigenSolveSymmetric3(const float matrix[6], float eigenValues[3], Vector3 eigenVectors[3]) {
+ static bool eigenSolveSymmetric3(const float matrix[6], float eigenValues[3], Vector3 eigenVectors[3])
+ {
XA_DEBUG_ASSERT(matrix != nullptr && eigenValues != nullptr && eigenVectors != nullptr);
float subd[3];
float diag[3];
@@ -1675,7 +1818,7 @@ private:
// eigenvectors are the columns; make them the rows :
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
- (&eigenVectors[j].x)[i] = (float)work[i][j];
+ (&eigenVectors[j].x)[i] = (float) work[i][j];
}
}
// shuffle to sort by singular value :
@@ -1697,7 +1840,8 @@ private:
}
private:
- static void EigenSolver3_Tridiagonal(float mat[3][3], float *diag, float *subd) {
+ static void EigenSolver3_Tridiagonal(float mat[3][3], float *diag, float *subd)
+ {
// Householder reduction T = Q^t M Q
// Input:
// mat, symmetric 3x3 matrix M
@@ -1749,7 +1893,8 @@ private:
}
}
- static bool EigenSolver3_QLAlgorithm(float mat[3][3], float *diag, float *subd) {
+ static bool EigenSolver3_QLAlgorithm(float mat[3][3], float *diag, float *subd)
+ {
// QL iteration with implicit shifting to reduce matrix from tridiagonal
// to diagonal
const int maxiter = 32;
@@ -1759,21 +1904,21 @@ private:
int m;
for (m = ell; m <= 1; m++) {
float dd = fabsf(diag[m]) + fabsf(diag[m + 1]);
- if (fabsf(subd[m]) + dd == dd)
+ if ( fabsf(subd[m]) + dd == dd )
break;
}
- if (m == ell)
+ if ( m == ell )
break;
float g = (diag[ell + 1] - diag[ell]) / (2 * subd[ell]);
float r = sqrtf(g * g + 1);
- if (g < 0)
+ if ( g < 0 )
g = diag[m] - diag[ell] + subd[ell] / (g - r);
else
g = diag[m] - diag[ell] + subd[ell] / (g + r);
float s = 1, c = 1, p = 0;
for (int i = m - 1; i >= ell; i--) {
float f = s * subd[i], b = c * subd[i];
- if (fabsf(f) >= fabsf(g)) {
+ if ( fabsf(f) >= fabsf(g) ) {
c = g / f;
r = sqrtf(c * c + 1);
subd[i + 1] = f * r;
@@ -1799,7 +1944,7 @@ private:
subd[ell] = g;
subd[m] = 0;
}
- if (iter == maxiter)
+ if ( iter == maxiter )
// should not get here under normal circumstances
return false;
}
@@ -1807,50 +1952,77 @@ private:
}
};
-/// Fixed size vector class.
-class FullVector {
-public:
- FullVector(uint32_t dim) :
- m_array(MemTag::FullVector) { m_array.resize(dim); }
- FullVector(const FullVector &v) :
- m_array(MemTag::FullVector) { v.m_array.copyTo(m_array); }
- FullVector &operator=(const FullVector &v) = delete;
- XA_INLINE uint32_t dimension() const { return m_array.size(); }
- XA_INLINE const float &operator[](uint32_t index) const { return m_array[index]; }
- XA_INLINE float &operator[](uint32_t index) { return m_array[index]; }
-
- void fill(float f) {
- const uint32_t dim = dimension();
- for (uint32_t i = 0; i < dim; i++)
- m_array[i] = f;
+static uint32_t sdbmHash(const void *data_in, uint32_t size, uint32_t h = 5381)
+{
+ const uint8_t *data = (const uint8_t *) data_in;
+ uint32_t i = 0;
+ while (i < size) {
+ h = (h << 16) + (h << 6) - h + (uint32_t ) data[i++];
}
+ return h;
+}
-private:
- Array<float> m_array;
+template <typename T>
+static uint32_t hash(const T &t, uint32_t h = 5381)
+{
+ return sdbmHash(&t, sizeof(T), h);
+}
+
+template <typename Key>
+struct Hash
+{
+ uint32_t operator()(const Key &k) const { return hash(k); }
};
-template <typename Key, typename H = Hash<Key>, typename E = Equal<Key>>
-class HashMap {
+template <typename Key>
+struct PassthroughHash
+{
+ uint32_t operator()(const Key &k) const { return (uint32_t)k; }
+};
+
+template <typename Key>
+struct Equal
+{
+ bool operator()(const Key &k0, const Key &k1) const { return k0 == k1; }
+};
+
+template<typename Key, typename H = Hash<Key>, typename E = Equal<Key> >
+class HashMap
+{
public:
- HashMap(int memTag, uint32_t size) :
- m_memTag(memTag), m_size(size), m_numSlots(0), m_slots(nullptr), m_keys(memTag), m_next(memTag) {
+ HashMap(int memTag, uint32_t size) : m_memTag(memTag), m_size(size), m_numSlots(0), m_slots(nullptr), m_keys(memTag), m_next(memTag)
+ {
}
- ~HashMap() {
+ ~HashMap()
+ {
if (m_slots)
XA_FREE(m_slots);
}
- void add(const Key &key) {
+ void destroy()
+ {
+ if (m_slots) {
+ XA_FREE(m_slots);
+ m_slots = nullptr;
+ }
+ m_keys.destroy();
+ m_next.destroy();
+ }
+
+ uint32_t add(const Key &key)
+ {
if (!m_slots)
alloc();
const uint32_t hash = computeHash(key);
m_keys.push_back(key);
m_next.push_back(m_slots[hash]);
m_slots[hash] = m_next.size() - 1;
+ return m_keys.size() - 1;
}
- uint32_t get(const Key &key) const {
+ uint32_t get(const Key &key) const
+ {
if (!m_slots)
return UINT32_MAX;
const uint32_t hash = computeHash(key);
@@ -1864,7 +2036,8 @@ public:
return UINT32_MAX;
}
- uint32_t getNext(uint32_t current) const {
+ uint32_t getNext(uint32_t current) const
+ {
uint32_t i = m_next[current];
E equal;
while (i != UINT32_MAX) {
@@ -1876,7 +2049,8 @@ public:
}
private:
- void alloc() {
+ void alloc()
+ {
XA_DEBUG_ASSERT(m_size > 0);
m_numSlots = nextPowerOfTwo(m_size);
auto minNumSlots = uint32_t(m_size * 1.3);
@@ -1889,7 +2063,8 @@ private:
m_next.reserve(m_size);
}
- uint32_t computeHash(const Key &key) const {
+ uint32_t computeHash(const Key &key) const
+ {
H hash;
return hash(key) & (m_numSlots - 1);
}
@@ -1902,8 +2077,9 @@ private:
Array<uint32_t> m_next;
};
-template <typename T>
-static void insertionSort(T *data, uint32_t length) {
+template<typename T>
+static void insertionSort(T *data, uint32_t length)
+{
for (int32_t i = 1; i < (int32_t)length; i++) {
T x = data[i];
int32_t j = i - 1;
@@ -1915,18 +2091,21 @@ static void insertionSort(T *data, uint32_t length) {
}
}
-class KISSRng {
+class KISSRng
+{
public:
KISSRng() { reset(); }
- void reset() {
+ void reset()
+ {
x = 123456789;
y = 362436000;
z = 521288629;
c = 7654321;
}
- uint32_t getRange(uint32_t range) {
+ uint32_t getRange(uint32_t range)
+ {
if (range == 0)
return 0;
x = 69069 * x + 12345;
@@ -1935,7 +2114,7 @@ public:
y ^= (y << 5);
uint64_t t = 698769069ULL * z + c;
c = (t >> 32);
- return (x + y + (z = (uint32_t)t)) % range;
+ return (x + y + (z = (uint32_t)t)) % (range + 1);
}
private:
@@ -1945,76 +2124,70 @@ private:
// Based on Pierre Terdiman's and Michael Herf's source code.
// http://www.codercorner.com/RadixSortRevisited.htm
// http://www.stereopsis.com/radix.html
-class RadixSort {
+class RadixSort
+{
public:
- RadixSort() :
- m_size(0), m_ranks(nullptr), m_ranks2(nullptr), m_validRanks(false) {}
-
- ~RadixSort() {
- // Release everything
- XA_FREE(m_ranks2);
- XA_FREE(m_ranks);
- }
-
- RadixSort &sort(const float *input, uint32_t count) {
- if (input == nullptr || count == 0) return *this;
- // Resize lists if needed
- if (count != m_size) {
- if (count > m_size) {
- m_ranks2 = XA_REALLOC(MemTag::Default, m_ranks2, uint32_t, count);
- m_ranks = XA_REALLOC(MemTag::Default, m_ranks, uint32_t, count);
- }
- m_size = count;
- m_validRanks = false;
+ void sort(const float *input, uint32_t count)
+ {
+ if (input == nullptr || count == 0) {
+ m_buffer1.clear();
+ m_buffer2.clear();
+ m_ranks = m_buffer1.data();
+ m_ranks2 = m_buffer2.data();
+ return;
}
- if (count < 32) {
+ // Resize lists if needed
+ m_buffer1.resize(count);
+ m_buffer2.resize(count);
+ m_ranks = m_buffer1.data();
+ m_ranks2 = m_buffer2.data();
+ m_validRanks = false;
+ if (count < 32)
insertionSort(input, count);
- } else {
+ else {
// @@ Avoid touching the input multiple times.
for (uint32_t i = 0; i < count; i++) {
- FloatFlip((uint32_t &)input[i]);
+ floatFlip((uint32_t &)input[i]);
}
radixSort<uint32_t>((const uint32_t *)input, count);
for (uint32_t i = 0; i < count; i++) {
- IFloatFlip((uint32_t &)input[i]);
+ ifloatFlip((uint32_t &)input[i]);
}
}
- return *this;
}
- RadixSort &sort(const Array<float> &input) {
- return sort(input.data(), input.size());
+ void sort(const Array<float> &input)
+ {
+ sort(input.data(), input.size());
}
// Access to results. m_ranks is a list of indices in sorted order, i.e. in the order you may further process your data
- const uint32_t *ranks() const {
- XA_DEBUG_ASSERT(m_validRanks);
- return m_ranks;
- }
-
- uint32_t *ranks() {
+ const uint32_t *ranks() const
+ {
XA_DEBUG_ASSERT(m_validRanks);
return m_ranks;
}
private:
- uint32_t m_size;
- uint32_t *m_ranks;
- uint32_t *m_ranks2;
+ uint32_t *m_ranks, *m_ranks2;
+ Array<uint32_t> m_buffer1, m_buffer2;
bool m_validRanks;
- void FloatFlip(uint32_t &f) {
+ void floatFlip(uint32_t &f)
+ {
int32_t mask = (int32_t(f) >> 31) | 0x80000000; // Warren Hunt, Manchor Ko.
f ^= mask;
}
- void IFloatFlip(uint32_t &f) {
+ void ifloatFlip(uint32_t &f)
+ {
uint32_t mask = ((f >> 31) - 1) | 0x80000000; // Michael Herf.
f ^= mask;
}
- template <typename T>
- void createHistograms(const T *buffer, uint32_t count, uint32_t *histogram) {
+ template<typename T>
+ void createHistograms(const T *buffer, uint32_t count, uint32_t *histogram)
+ {
const uint32_t bucketCount = sizeof(T); // (8 * sizeof(T)) / log2(radix)
// Init bucket pointers.
uint32_t *h[bucketCount];
@@ -2022,10 +2195,10 @@ private:
h[i] = histogram + 256 * i;
}
// Clear histograms.
- memset(histogram, 0, 256 * bucketCount * sizeof(uint32_t));
+ memset(histogram, 0, 256 * bucketCount * sizeof(uint32_t ));
// @@ Add support for signed integers.
// Build histograms.
- const uint8_t *p = (const uint8_t *)buffer; // @@ Does this break aliasing rules?
+ const uint8_t *p = (const uint8_t *)buffer; // @@ Does this break aliasing rules?
const uint8_t *pe = p + count * sizeof(T);
while (p != pe) {
h[0][*p++]++, h[1][*p++]++, h[2][*p++]++, h[3][*p++]++;
@@ -2041,7 +2214,8 @@ private:
}
template <typename T>
- void insertionSort(const T *input, uint32_t count) {
+ void insertionSort(const T *input, uint32_t count)
+ {
if (!m_validRanks) {
m_ranks[0] = 0;
for (uint32_t i = 1; i != count; ++i) {
@@ -2072,7 +2246,8 @@ private:
}
template <typename T>
- void radixSort(const T *input, uint32_t count) {
+ void radixSort(const T *input, uint32_t count)
+ {
const uint32_t P = sizeof(T); // pass count
// Allocate histograms & offsets on the stack
uint32_t histogram[256 * P];
@@ -2090,8 +2265,7 @@ private:
}
// Create offsets
link[0] = m_ranks2;
- for (uint32_t i = 1; i < 256; i++)
- link[i] = link[i - 1] + h[i - 1];
+ for (uint32_t i = 1; i < 256; i++) link[i] = link[i - 1] + h[i - 1];
// Perform Radix Sort
if (!m_validRanks) {
for (uint32_t i = 0; i < count; i++) {
@@ -2109,30 +2283,33 @@ private:
}
// All values were equal, generate linear ranks.
if (!m_validRanks) {
- for (uint32_t i = 0; i < count; i++) {
+ for (uint32_t i = 0; i < count; i++)
m_ranks[i] = i;
- }
m_validRanks = true;
}
}
};
// Wrapping this in a class allows temporary arrays to be re-used.
-class BoundingBox2D {
+class BoundingBox2D
+{
public:
Vector2 majorAxis, minorAxis, minCorner, maxCorner;
- void clear() {
+ void clear()
+ {
m_boundaryVertices.clear();
}
- void appendBoundaryVertex(Vector2 v) {
+ void appendBoundaryVertex(Vector2 v)
+ {
m_boundaryVertices.push_back(v);
}
// This should compute convex hull and use rotating calipers to find the best box. Currently it uses a brute force method.
// If vertices is null or vertexCount is 0, the boundary vertices are used.
- void compute(const Vector2 *vertices = nullptr, uint32_t vertexCount = 0) {
+ void compute(const Vector2 *vertices = nullptr, uint32_t vertexCount = 0)
+ {
if (!vertices || vertexCount == 0) {
vertices = m_boundaryVertices.data();
vertexCount = m_boundaryVertices.size();
@@ -2180,13 +2357,13 @@ public:
private:
// Compute the convex hull using Graham Scan.
- void convexHull(const Vector2 *input, uint32_t inputCount, Array<Vector2> &output, float epsilon) {
+ void convexHull(const Vector2 *input, uint32_t inputCount, Array<Vector2> &output, float epsilon)
+ {
m_coords.resize(inputCount);
for (uint32_t i = 0; i < inputCount; i++)
m_coords[i] = input[i].x;
- RadixSort radix;
- radix.sort(m_coords);
- const uint32_t *ranks = radix.ranks();
+ m_radix.sort(m_coords);
+ const uint32_t *ranks = m_radix.ranks();
m_top.clear();
m_bottom.clear();
m_top.reserve(inputCount);
@@ -2210,7 +2387,7 @@ private:
XA_DEBUG_ASSERT(m_top.size() >= 2);
output.push_back(m_top[0]);
output.push_back(m_top[1]);
- for (uint32_t i = 2; i < m_top.size();) {
+ for (uint32_t i = 2; i < m_top.size(); ) {
Vector2 a = output[output.size() - 2];
Vector2 b = output[output.size() - 1];
Vector2 c = m_top[i];
@@ -2226,7 +2403,7 @@ private:
XA_DEBUG_ASSERT(m_bottom.size() >= 2);
output.push_back(m_bottom[1]);
// Filter bottom list.
- for (uint32_t i = 2; i < m_bottom.size();) {
+ for (uint32_t i = 2; i < m_bottom.size(); ) {
Vector2 a = output[output.size() - 2];
Vector2 b = output[output.size() - 1];
Vector2 c = m_bottom[i];
@@ -2246,51 +2423,49 @@ private:
Array<Vector2> m_boundaryVertices;
Array<float> m_coords;
Array<Vector2> m_top, m_bottom, m_hull;
+ RadixSort m_radix;
};
-static uint32_t meshEdgeFace(uint32_t edge) {
- return edge / 3;
-}
-static uint32_t meshEdgeIndex0(uint32_t edge) {
- return edge;
-}
+static uint32_t meshEdgeFace(uint32_t edge) { return edge / 3; }
+static uint32_t meshEdgeIndex0(uint32_t edge) { return edge; }
-static uint32_t meshEdgeIndex1(uint32_t edge) {
+static uint32_t meshEdgeIndex1(uint32_t edge)
+{
const uint32_t faceFirstEdge = edge / 3 * 3;
return faceFirstEdge + (edge - faceFirstEdge + 1) % 3;
}
-struct MeshFlags {
- enum {
- HasFaceGroups = 1 << 0,
- HasIgnoredFaces = 1 << 1,
- HasNormals = 1 << 2
+struct MeshFlags
+{
+ enum
+ {
+ HasIgnoredFaces = 1<<0,
+ HasNormals = 1<<1
};
};
class Mesh;
static void meshGetBoundaryLoops(const Mesh &mesh, Array<uint32_t> &boundaryLoops);
-class Mesh {
+class Mesh
+{
public:
- Mesh(float epsilon, uint32_t approxVertexCount, uint32_t approxFaceCount, uint32_t flags = 0, uint32_t id = UINT32_MAX) :
- m_epsilon(epsilon), m_flags(flags), m_id(id), m_faceIgnore(MemTag::Mesh), m_ignoredFaceCount(0), m_indices(MemTag::MeshIndices), m_positions(MemTag::MeshPositions), m_normals(MemTag::MeshNormals), m_texcoords(MemTag::MeshTexcoords), m_faceGroups(MemTag::Mesh), m_faceGroupFirstFace(MemTag::Mesh), m_faceGroupNextFace(MemTag::Mesh), m_faceGroupFaceCounts(MemTag::Mesh), m_colocalVertexCount(0), m_nextColocalVertex(MemTag::MeshColocals), m_boundaryEdges(MemTag::MeshBoundaries), m_oppositeEdges(MemTag::MeshBoundaries), m_nextBoundaryEdges(MemTag::MeshBoundaries), m_edgeMap(MemTag::MeshEdgeMap, approxFaceCount * 3) {
+ Mesh(float epsilon, uint32_t approxVertexCount, uint32_t approxFaceCount, uint32_t flags = 0, uint32_t id = UINT32_MAX) : m_epsilon(epsilon), m_flags(flags), m_id(id), m_faceIgnore(MemTag::Mesh), m_indices(MemTag::MeshIndices), m_positions(MemTag::MeshPositions), m_normals(MemTag::MeshNormals), m_texcoords(MemTag::MeshTexcoords), m_nextColocalVertex(MemTag::MeshColocals), m_boundaryEdges(MemTag::MeshBoundaries), m_oppositeEdges(MemTag::MeshBoundaries), m_nextBoundaryEdges(MemTag::MeshBoundaries), m_edgeMap(MemTag::MeshEdgeMap, approxFaceCount * 3)
+ {
m_indices.reserve(approxFaceCount * 3);
m_positions.reserve(approxVertexCount);
m_texcoords.reserve(approxVertexCount);
- if (m_flags & MeshFlags::HasFaceGroups)
- m_faceGroups.reserve(approxFaceCount);
if (m_flags & MeshFlags::HasIgnoredFaces)
m_faceIgnore.reserve(approxFaceCount);
if (m_flags & MeshFlags::HasNormals)
m_normals.reserve(approxVertexCount);
}
- static constexpr uint16_t kInvalidFaceGroup = UINT16_MAX;
uint32_t flags() const { return m_flags; }
uint32_t id() const { return m_id; }
- void addVertex(const Vector3 &pos, const Vector3 &normal = Vector3(0.0f), const Vector2 &texcoord = Vector2(0.0f)) {
+ void addVertex(const Vector3 &pos, const Vector3 &normal = Vector3(0.0f), const Vector2 &texcoord = Vector2(0.0f))
+ {
XA_DEBUG_ASSERT(isFinite(pos));
m_positions.push_back(pos);
if (m_flags & MeshFlags::HasNormals)
@@ -2298,47 +2473,45 @@ public:
m_texcoords.push_back(texcoord);
}
- struct AddFaceResult {
- enum Enum {
+ struct AddFaceResult
+ {
+ enum Enum
+ {
OK,
DuplicateEdge = 1
};
};
- AddFaceResult::Enum addFace(uint32_t v0, uint32_t v1, uint32_t v2, bool ignore = false, bool hashEdge = true) {
+ AddFaceResult::Enum addFace(uint32_t v0, uint32_t v1, uint32_t v2, bool ignore = false)
+ {
uint32_t indexArray[3];
indexArray[0] = v0;
indexArray[1] = v1;
indexArray[2] = v2;
- return addFace(indexArray, ignore, hashEdge);
+ return addFace(indexArray, ignore);
}
- AddFaceResult::Enum addFace(const uint32_t *indices, bool ignore = false, bool hashEdge = true) {
+ AddFaceResult::Enum addFace(const uint32_t *indices, bool ignore = false)
+ {
AddFaceResult::Enum result = AddFaceResult::OK;
- if (m_flags & MeshFlags::HasFaceGroups)
- m_faceGroups.push_back(kInvalidFaceGroup);
- if (m_flags & MeshFlags::HasIgnoredFaces) {
+ if (m_flags & MeshFlags::HasIgnoredFaces)
m_faceIgnore.push_back(ignore);
- if (ignore)
- m_ignoredFaceCount++;
- }
const uint32_t firstIndex = m_indices.size();
for (uint32_t i = 0; i < 3; i++)
m_indices.push_back(indices[i]);
- if (hashEdge) {
- for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex0 = m_indices[firstIndex + i];
- const uint32_t vertex1 = m_indices[firstIndex + (i + 1) % 3];
- const EdgeKey key(vertex0, vertex1);
- if (m_edgeMap.get(key) != UINT32_MAX)
- result = AddFaceResult::DuplicateEdge;
- m_edgeMap.add(key);
- }
+ for (uint32_t i = 0; i < 3; i++) {
+ const uint32_t vertex0 = m_indices[firstIndex + i];
+ const uint32_t vertex1 = m_indices[firstIndex + (i + 1) % 3];
+ const EdgeKey key(vertex0, vertex1);
+ if (m_edgeMap.get(key) != UINT32_MAX)
+ result = AddFaceResult::DuplicateEdge;
+ m_edgeMap.add(key);
}
return result;
}
- void createColocals() {
+ void createColocals()
+ {
const uint32_t vertexCount = m_positions.size();
Array<AABB> aabbs(MemTag::BVH);
aabbs.resize(vertexCount);
@@ -2347,10 +2520,8 @@ public:
BVH bvh(aabbs);
Array<uint32_t> colocals(MemTag::MeshColocals);
Array<uint32_t> potential(MemTag::MeshColocals);
- m_colocalVertexCount = 0;
m_nextColocalVertex.resize(vertexCount);
- for (uint32_t i = 0; i < vertexCount; i++)
- m_nextColocalVertex[i] = UINT32_MAX;
+ m_nextColocalVertex.fillBytes(0xff);
for (uint32_t i = 0; i < vertexCount; i++) {
if (m_nextColocalVertex[i] != UINT32_MAX)
continue; // Already linked.
@@ -2366,9 +2537,8 @@ public:
if (colocals.size() == 1) {
// No colocals for this vertex.
m_nextColocalVertex[i] = i;
- continue;
+ continue;
}
- m_colocalVertexCount += colocals.size();
// Link in ascending order.
insertionSort(colocals.data(), colocals.size());
for (uint32_t j = 0; j < colocals.size(); j++)
@@ -2377,98 +2547,8 @@ public:
}
}
- // Check if the face duplicates any edges of any face already in the group.
- bool faceDuplicatesGroupEdge(uint16_t group, uint32_t face) const {
- for (FaceEdgeIterator edgeIt(this, face); !edgeIt.isDone(); edgeIt.advance()) {
- for (ColocalEdgeIterator colocalEdgeIt(this, edgeIt.vertex0(), edgeIt.vertex1()); !colocalEdgeIt.isDone(); colocalEdgeIt.advance()) {
- if (m_faceGroups[meshEdgeFace(colocalEdgeIt.edge())] == group)
- return true;
- }
- }
- return false;
- }
-
- void createFaceGroups() {
- uint32_t firstUnassignedFace = 0;
- uint16_t group = 0;
- Array<uint32_t> growFaces;
- const uint32_t n = faceCount();
- m_faceGroupNextFace.resize(n);
- for (;;) {
- // Find an unassigned face.
- uint32_t face = UINT32_MAX;
- for (uint32_t f = firstUnassignedFace; f < n; f++) {
- if (m_faceGroups[f] == kInvalidFaceGroup && !isFaceIgnored(f)) {
- face = f;
- firstUnassignedFace = f + 1;
- break;
- }
- }
- if (face == UINT32_MAX)
- break; // All faces assigned to a group (except ignored faces).
- m_faceGroups[face] = group;
- m_faceGroupNextFace[face] = UINT32_MAX;
- m_faceGroupFirstFace.push_back(face);
- growFaces.clear();
- growFaces.push_back(face);
- uint32_t prevFace = face, groupFaceCount = 1;
- // Find faces connected to the face and assign them to the same group as the face, unless they are already assigned to another group.
- for (;;) {
- if (growFaces.isEmpty())
- break;
- const uint32_t f = growFaces.back();
- growFaces.pop_back();
- for (FaceEdgeIterator edgeIt(this, f); !edgeIt.isDone(); edgeIt.advance()) {
- // Iterate opposite edges. There may be more than one - non-manifold geometry can have duplicate edges.
- // Prioritize the one with exact vertex match, not just colocal.
- // If *any* of the opposite edges are already assigned to this group, don't do anything.
- bool alreadyAssignedToThisGroup = false;
- uint32_t bestConnectedFace = UINT32_MAX;
- for (ColocalEdgeIterator oppositeEdgeIt(this, edgeIt.vertex1(), edgeIt.vertex0()); !oppositeEdgeIt.isDone(); oppositeEdgeIt.advance()) {
- const uint32_t oppositeEdge = oppositeEdgeIt.edge();
- const uint32_t oppositeFace = meshEdgeFace(oppositeEdge);
- if (isFaceIgnored(oppositeFace))
- continue; // Don't add ignored faces to group.
- if (m_faceGroups[oppositeFace] == group) {
- alreadyAssignedToThisGroup = true;
- break;
- }
- if (m_faceGroups[oppositeFace] != kInvalidFaceGroup)
- continue; // Connected face is already assigned to another group.
- if (faceDuplicatesGroupEdge(group, oppositeFace))
- continue; // Don't want duplicate edges in a group.
- const uint32_t oppositeVertex0 = m_indices[meshEdgeIndex0(oppositeEdge)];
- const uint32_t oppositeVertex1 = m_indices[meshEdgeIndex1(oppositeEdge)];
- if (bestConnectedFace == UINT32_MAX || (oppositeVertex0 == edgeIt.vertex1() && oppositeVertex1 == edgeIt.vertex0()))
- bestConnectedFace = oppositeFace;
-#if 0
- else {
- // Choose the opposite face with the smallest dihedral angle.
- const float d1 = 1.0f - dot(computeFaceNormal(f), computeFaceNormal(bestConnectedFace));
- const float d2 = 1.0f - dot(computeFaceNormal(f), computeFaceNormal(oppositeFace));
- if (d2 < d1)
- bestConnectedFace = oppositeFace;
- }
-#endif
- }
- if (!alreadyAssignedToThisGroup && bestConnectedFace != UINT32_MAX) {
- m_faceGroups[bestConnectedFace] = group;
- m_faceGroupNextFace[bestConnectedFace] = UINT32_MAX;
- if (prevFace != UINT32_MAX)
- m_faceGroupNextFace[prevFace] = bestConnectedFace;
- prevFace = bestConnectedFace;
- groupFaceCount++;
- growFaces.push_back(bestConnectedFace);
- }
- }
- }
- m_faceGroupFaceCounts.push_back(groupFaceCount);
- group++;
- XA_ASSERT(group < kInvalidFaceGroup);
- }
- }
-
- void createBoundaries() {
+ void createBoundaries()
+ {
const uint32_t edgeCount = m_indices.size();
const uint32_t vertexCount = m_positions.size();
m_oppositeEdges.resize(edgeCount);
@@ -2498,7 +2578,8 @@ public:
}
}
- void linkBoundaries() {
+ void linkBoundaries()
+ {
const uint32_t edgeCount = m_indices.size();
HashMap<uint32_t> vertexToEdgeMap(MemTag::Mesh, edgeCount); // Edge is index / 2
for (uint32_t i = 0; i < edgeCount; i++) {
@@ -2591,7 +2672,8 @@ public:
}
/// Find edge, test all colocals.
- uint32_t findEdge(uint32_t vertex0, uint32_t vertex1) const {
+ uint32_t findEdge(uint32_t vertex0, uint32_t vertex1) const
+ {
uint32_t result = UINT32_MAX;
if (m_nextColocalVertex.isEmpty()) {
EdgeKey key(vertex0, vertex1);
@@ -2629,8 +2711,18 @@ public:
return result;
}
+ // Edge map can be destroyed when no longer used to reduce memory usage. It's used by:
+ // * Mesh::createBoundaries()
+ // * Mesh::ColocalEdgeIterator (used by MeshFaceGroups)
+ // * meshCloseHole()
+ void destroyEdgeMap()
+ {
+ m_edgeMap.destroy();
+ }
+
#if XA_DEBUG_EXPORT_OBJ
- void writeObjVertices(FILE *file) const {
+ void writeObjVertices(FILE *file) const
+ {
for (uint32_t i = 0; i < m_positions.size(); i++)
fprintf(file, "v %g %g %g\n", m_positions[i].x, m_positions[i].y, m_positions[i].z);
if (m_flags & MeshFlags::HasNormals) {
@@ -2641,15 +2733,17 @@ public:
fprintf(file, "vt %g %g\n", m_texcoords[i].x, m_texcoords[i].y);
}
- void writeObjFace(FILE *file, uint32_t face) const {
+ void writeObjFace(FILE *file, uint32_t face, uint32_t offset = 0) const
+ {
fprintf(file, "f ");
for (uint32_t j = 0; j < 3; j++) {
- const uint32_t index = m_indices[face * 3 + j] + 1; // 1-indexed
+ const uint32_t index = m_indices[face * 3 + j] + 1 + offset; // 1-indexed
fprintf(file, "%d/%d/%d%c", index, index, index, j == 2 ? '\n' : ' ');
}
}
- void writeObjBoundaryEges(FILE *file) const {
+ void writeObjBoundaryEges(FILE *file) const
+ {
if (m_oppositeEdges.isEmpty())
return; // Boundaries haven't been created.
fprintf(file, "o boundary_edges\n");
@@ -2660,7 +2754,8 @@ public:
}
}
- void writeObjLinkedBoundaries(FILE *file) const {
+ void writeObjLinkedBoundaries(FILE *file) const
+ {
if (m_oppositeEdges.isEmpty() || m_nextBoundaryEdges.isEmpty())
return; // Boundaries haven't been created and/or linked.
Array<uint32_t> boundaryLoops;
@@ -2682,7 +2777,8 @@ public:
}
}
- void writeObjFile(const char *filename) const {
+ void writeObjFile(const char *filename) const
+ {
FILE *file;
XA_FOPEN(file, filename, "w");
if (!file)
@@ -2698,7 +2794,8 @@ public:
}
#endif
- float computeSurfaceArea() const {
+ float computeSurfaceArea() const
+ {
float area = 0;
for (uint32_t f = 0; f < faceCount(); f++)
area += computeFaceArea(f);
@@ -2706,21 +2803,25 @@ public:
return area;
}
- float computeParametricArea() const {
+ // Returned value is always positive, even if some triangles are flipped.
+ float computeParametricArea() const
+ {
float area = 0;
for (uint32_t f = 0; f < faceCount(); f++)
- area += computeFaceParametricArea(f);
- return fabsf(area); // May be negative, depends on texcoord winding.
+ area += fabsf(computeFaceParametricArea(f)); // May be negative, depends on texcoord winding.
+ return area;
}
- float computeFaceArea(uint32_t face) const {
+ float computeFaceArea(uint32_t face) const
+ {
const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
return length(cross(p1 - p0, p2 - p0)) * 0.5f;
}
- Vector3 computeFaceCentroid(uint32_t face) const {
+ Vector3 computeFaceCentroid(uint32_t face) const
+ {
Vector3 sum(0.0f);
for (uint32_t i = 0; i < 3; i++)
sum += m_positions[m_indices[face * 3 + i]];
@@ -2729,7 +2830,8 @@ public:
// Average of the edge midpoints weighted by the edge length.
// I want a point inside the triangle, but closer to the cirumcenter.
- Vector3 computeFaceCenter(uint32_t face) const {
+ Vector3 computeFaceCenter(uint32_t face) const
+ {
const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
@@ -2742,7 +2844,8 @@ public:
return m0 + m1 + m2;
}
- Vector3 computeFaceNormal(uint32_t face) const {
+ Vector3 computeFaceNormal(uint32_t face) const
+ {
const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
@@ -2752,15 +2855,17 @@ public:
return normalizeSafe(normalAreaScaled, Vector3(0, 0, 1), 0.0f);
}
- float computeFaceParametricArea(uint32_t face) const {
+ float computeFaceParametricArea(uint32_t face) const
+ {
const Vector2 &t0 = m_texcoords[m_indices[face * 3 + 0]];
const Vector2 &t1 = m_texcoords[m_indices[face * 3 + 1]];
const Vector2 &t2 = m_texcoords[m_indices[face * 3 + 2]];
return triangleArea(t0, t1, t2);
}
-
+
// @@ This is not exactly accurate, we should compare the texture coordinates...
- bool isSeam(uint32_t edge) const {
+ bool isSeam(uint32_t edge) const
+ {
const uint32_t oppositeEdge = m_oppositeEdges[edge];
if (oppositeEdge == UINT32_MAX)
return false; // boundary edge
@@ -2771,7 +2876,8 @@ public:
return m_indices[e0] != m_indices[oe1] || m_indices[e1] != m_indices[oe0];
}
- bool isTextureSeam(uint32_t edge) const {
+ bool isTextureSeam(uint32_t edge) const
+ {
const uint32_t oppositeEdge = m_oppositeEdges[edge];
if (oppositeEdge == UINT32_MAX)
return false; // boundary edge
@@ -2782,7 +2888,8 @@ public:
return m_texcoords[m_indices[e0]] != m_texcoords[m_indices[oe1]] || m_texcoords[m_indices[e1]] != m_texcoords[m_indices[oe0]];
}
- uint32_t firstColocal(uint32_t vertex) const {
+ uint32_t firstColocal(uint32_t vertex) const
+ {
for (ColocalVertexIterator it(this, vertex); !it.isDone(); it.advance()) {
if (it.vertex() < vertex)
vertex = it.vertex();
@@ -2790,7 +2897,8 @@ public:
return vertex;
}
- bool areColocal(uint32_t vertex0, uint32_t vertex1) const {
+ bool areColocal(uint32_t vertex0, uint32_t vertex1) const
+ {
if (vertex0 == vertex1)
return true;
if (m_nextColocalVertex.isEmpty())
@@ -2808,60 +2916,32 @@ public:
XA_INLINE bool isBoundaryEdge(uint32_t edge) const { return m_oppositeEdges[edge] == UINT32_MAX; }
XA_INLINE const Array<uint32_t> &boundaryEdges() const { return m_boundaryEdges; }
XA_INLINE bool isBoundaryVertex(uint32_t vertex) const { return m_isBoundaryVertex.get(vertex); }
- XA_INLINE uint32_t colocalVertexCount() const { return m_colocalVertexCount; }
XA_INLINE uint32_t vertexCount() const { return m_positions.size(); }
XA_INLINE uint32_t vertexAt(uint32_t i) const { return m_indices[i]; }
XA_INLINE const Vector3 &position(uint32_t vertex) const { return m_positions[vertex]; }
- XA_INLINE const Vector3 &normal(uint32_t vertex) const {
- XA_DEBUG_ASSERT(m_flags & MeshFlags::HasNormals);
- return m_normals[vertex];
- }
+ XA_INLINE const Vector3 *positions() const { return m_positions.data(); }
+ XA_INLINE const Vector3 &normal(uint32_t vertex) const { XA_DEBUG_ASSERT(m_flags & MeshFlags::HasNormals); return m_normals[vertex]; }
XA_INLINE const Vector2 &texcoord(uint32_t vertex) const { return m_texcoords[vertex]; }
XA_INLINE Vector2 &texcoord(uint32_t vertex) { return m_texcoords[vertex]; }
XA_INLINE const Vector2 *texcoords() const { return m_texcoords.data(); }
XA_INLINE Vector2 *texcoords() { return m_texcoords.data(); }
- XA_INLINE uint32_t ignoredFaceCount() const { return m_ignoredFaceCount; }
XA_INLINE uint32_t faceCount() const { return m_indices.size() / 3; }
- XA_INLINE uint16_t faceGroupAt(uint32_t face) const {
- XA_DEBUG_ASSERT(m_flags & MeshFlags::HasFaceGroups);
- return m_faceGroups[face];
- }
- XA_INLINE uint32_t faceGroupCount() const {
- XA_DEBUG_ASSERT(m_flags & MeshFlags::HasFaceGroups);
- return m_faceGroupFaceCounts.size();
- }
- XA_INLINE uint32_t faceGroupNextFace(uint32_t face) const {
- XA_DEBUG_ASSERT(m_flags & MeshFlags::HasFaceGroups);
- return m_faceGroupNextFace[face];
- }
- XA_INLINE uint32_t faceGroupFaceCount(uint32_t group) const {
- XA_DEBUG_ASSERT(m_flags & MeshFlags::HasFaceGroups);
- return m_faceGroupFaceCounts[group];
- }
XA_INLINE const uint32_t *indices() const { return m_indices.data(); }
XA_INLINE uint32_t indexCount() const { return m_indices.size(); }
+ XA_INLINE bool isFaceIgnored(uint32_t face) const { return (m_flags & MeshFlags::HasIgnoredFaces) && m_faceIgnore[face]; }
private:
- bool isFaceIgnored(uint32_t face) const { return (m_flags & MeshFlags::HasIgnoredFaces) && m_faceIgnore[face]; }
float m_epsilon;
uint32_t m_flags;
uint32_t m_id;
Array<bool> m_faceIgnore;
- uint32_t m_ignoredFaceCount;
Array<uint32_t> m_indices;
Array<Vector3> m_positions;
Array<Vector3> m_normals;
Array<Vector2> m_texcoords;
- // Populated by createFaceGroups
- Array<uint16_t> m_faceGroups;
- Array<uint32_t> m_faceGroupFirstFace;
- Array<uint32_t> m_faceGroupNextFace; // In: face. Out: the next face in the same group.
- Array<uint32_t> m_faceGroupFaceCounts; // In: face group. Out: number of faces in the group.
-
// Populated by createColocals
- uint32_t m_colocalVertexCount;
Array<uint32_t> m_nextColocalVertex; // In: vertex index. Out: the vertex index of the next colocal position.
// Populated by createBoundaries
@@ -2872,45 +2952,48 @@ private:
// Populated by linkBoundaries
Array<uint32_t> m_nextBoundaryEdges; // The index of the next boundary edge. UINT32_MAX if the edge is not a boundary edge.
- struct EdgeKey {
- EdgeKey() {}
- EdgeKey(const EdgeKey &k) :
- v0(k.v0), v1(k.v1) {}
- EdgeKey(uint32_t v0, uint32_t v1) :
- v0(v0), v1(v1) {}
+ struct EdgeKey
+ {
+ EdgeKey(const EdgeKey &k) : v0(k.v0), v1(k.v1) {}
+ EdgeKey(uint32_t v0, uint32_t v1) : v0(v0), v1(v1) {}
bool operator==(const EdgeKey &k) const { return v0 == k.v0 && v1 == k.v1; }
uint32_t v0;
uint32_t v1;
};
- struct EdgeHash {
+ struct EdgeHash
+ {
uint32_t operator()(const EdgeKey &k) const { return k.v0 * 32768u + k.v1; }
};
HashMap<EdgeKey, EdgeHash> m_edgeMap;
public:
- class BoundaryLoopEdgeIterator {
+ class BoundaryLoopEdgeIterator
+ {
public:
- BoundaryLoopEdgeIterator(const Mesh *mesh, uint32_t edge) :
- m_mesh(mesh), m_first(UINT32_MAX), m_current(edge) {}
+ BoundaryLoopEdgeIterator(const Mesh *mesh, uint32_t edge) : m_mesh(mesh), m_first(UINT32_MAX), m_current(edge) {}
- void advance() {
+ void advance()
+ {
if (m_first == UINT32_MAX)
m_first = m_current;
m_current = m_mesh->m_nextBoundaryEdges[m_current];
}
- bool isDone() const {
+ bool isDone() const
+ {
return m_first == m_current || m_current == UINT32_MAX;
}
- uint32_t edge() const {
+ uint32_t edge() const
+ {
return m_current;
}
- uint32_t nextEdge() const {
+ uint32_t nextEdge() const
+ {
return m_mesh->m_nextBoundaryEdges[m_current];
}
@@ -2920,27 +3003,31 @@ public:
uint32_t m_current;
};
- class ColocalVertexIterator {
+ class ColocalVertexIterator
+ {
public:
- ColocalVertexIterator(const Mesh *mesh, uint32_t v) :
- m_mesh(mesh), m_first(UINT32_MAX), m_current(v) {}
+ ColocalVertexIterator(const Mesh *mesh, uint32_t v) : m_mesh(mesh), m_first(UINT32_MAX), m_current(v) {}
- void advance() {
+ void advance()
+ {
if (m_first == UINT32_MAX)
m_first = m_current;
if (!m_mesh->m_nextColocalVertex.isEmpty())
m_current = m_mesh->m_nextColocalVertex[m_current];
}
- bool isDone() const {
+ bool isDone() const
+ {
return m_first == m_current;
}
- uint32_t vertex() const {
+ uint32_t vertex() const
+ {
return m_current;
}
- const Vector3 *pos() const {
+ const Vector3 *pos() const
+ {
return &m_mesh->m_positions[m_current];
}
@@ -2950,33 +3037,39 @@ public:
uint32_t m_current;
};
- class ColocalEdgeIterator {
+ class ColocalEdgeIterator
+ {
public:
- ColocalEdgeIterator(const Mesh *mesh, uint32_t vertex0, uint32_t vertex1) :
- m_mesh(mesh), m_vertex0It(mesh, vertex0), m_vertex1It(mesh, vertex1), m_vertex1(vertex1) {
+ ColocalEdgeIterator(const Mesh *mesh, uint32_t vertex0, uint32_t vertex1) : m_mesh(mesh), m_vertex0It(mesh, vertex0), m_vertex1It(mesh, vertex1), m_vertex1(vertex1)
+ {
do {
if (!resetElement()) {
advanceVertex1();
- } else {
+ }
+ else {
break;
}
} while (!isDone());
}
- void advance() {
+ void advance()
+ {
advanceElement();
}
- bool isDone() const {
+ bool isDone() const
+ {
return m_vertex0It.isDone() && m_vertex1It.isDone() && m_edge == UINT32_MAX;
}
- uint32_t edge() const {
+ uint32_t edge() const
+ {
return m_edge;
}
private:
- bool resetElement() {
+ bool resetElement()
+ {
m_edge = m_mesh->m_edgeMap.get(Mesh::EdgeKey(m_vertex0It.vertex(), m_vertex1It.vertex()));
while (m_edge != UINT32_MAX) {
if (!isIgnoredFace())
@@ -2989,7 +3082,8 @@ public:
return true;
}
- void advanceElement() {
+ void advanceElement()
+ {
for (;;) {
m_edge = m_mesh->m_edgeMap.getNext(m_edge);
if (m_edge == UINT32_MAX)
@@ -3001,15 +3095,17 @@ public:
advanceVertex1();
}
- void advanceVertex1() {
+ void advanceVertex1()
+ {
auto successful = false;
- while (!successful) {
+ while (!successful) {
m_vertex1It.advance();
if (m_vertex1It.isDone()) {
if (!m_vertex0It.isDone()) {
m_vertex0It.advance();
m_vertex1It = ColocalVertexIterator(m_mesh, m_vertex1);
- } else {
+ }
+ else {
return;
}
}
@@ -3017,7 +3113,8 @@ public:
}
}
- bool isIgnoredFace() const {
+ bool isIgnoredFace() const
+ {
return m_mesh->m_faceIgnore[meshEdgeFace(m_edge)];
}
@@ -3027,21 +3124,24 @@ public:
uint32_t m_edge;
};
- class FaceEdgeIterator {
+ class FaceEdgeIterator
+ {
public:
- FaceEdgeIterator(const Mesh *mesh, uint32_t face) :
- m_mesh(mesh), m_face(face), m_relativeEdge(0) {
+ FaceEdgeIterator (const Mesh *mesh, uint32_t face) : m_mesh(mesh), m_face(face), m_relativeEdge(0)
+ {
m_edge = m_face * 3;
}
- void advance() {
+ void advance()
+ {
if (m_relativeEdge < 3) {
m_edge++;
m_relativeEdge++;
}
}
- bool isDone() const {
+ bool isDone() const
+ {
return m_relativeEdge == 3;
}
@@ -3052,8 +3152,9 @@ public:
uint32_t relativeEdge() const { return m_relativeEdge; }
uint32_t face() const { return m_face; }
uint32_t oppositeEdge() const { return m_mesh->m_oppositeEdges[m_edge]; }
-
- uint32_t oppositeFace() const {
+
+ uint32_t oppositeFace() const
+ {
const uint32_t oedge = m_mesh->m_oppositeEdges[m_edge];
if (oedge == UINT32_MAX)
return UINT32_MAX;
@@ -3075,36 +3176,164 @@ public:
uint32_t m_edge;
uint32_t m_relativeEdge;
};
+};
+
+struct MeshFaceGroups
+{
+ typedef uint32_t Handle;
+ static constexpr Handle kInvalid = UINT32_MAX;
+
+ MeshFaceGroups(const Mesh *mesh) : m_mesh(mesh), m_groups(MemTag::Mesh), m_firstFace(MemTag::Mesh), m_nextFace(MemTag::Mesh), m_faceCount(MemTag::Mesh) {}
+ XA_INLINE Handle groupAt(uint32_t face) const { return m_groups[face]; }
+ XA_INLINE uint32_t groupCount() const { return m_faceCount.size(); }
+ XA_INLINE uint32_t nextFace(uint32_t face) const { return m_nextFace[face]; }
+ XA_INLINE uint32_t faceCount(uint32_t group) const { return m_faceCount[group]; }
+
+ void compute()
+ {
+ m_groups.resize(m_mesh->faceCount());
+ m_groups.fillBytes(0xff); // Set all faces to kInvalid
+ uint32_t firstUnassignedFace = 0;
+ Handle group = 0;
+ Array<uint32_t> growFaces;
+ const uint32_t n = m_mesh->faceCount();
+ m_nextFace.resize(n);
+ for (;;) {
+ // Find an unassigned face.
+ uint32_t face = UINT32_MAX;
+ for (uint32_t f = firstUnassignedFace; f < n; f++) {
+ if (m_groups[f] == kInvalid && !m_mesh->isFaceIgnored(f)) {
+ face = f;
+ firstUnassignedFace = f + 1;
+ break;
+ }
+ }
+ if (face == UINT32_MAX)
+ break; // All faces assigned to a group (except ignored faces).
+ m_groups[face] = group;
+ m_nextFace[face] = UINT32_MAX;
+ m_firstFace.push_back(face);
+ growFaces.clear();
+ growFaces.push_back(face);
+ uint32_t prevFace = face, groupFaceCount = 1;
+ // Find faces connected to the face and assign them to the same group as the face, unless they are already assigned to another group.
+ for (;;) {
+ if (growFaces.isEmpty())
+ break;
+ const uint32_t f = growFaces.back();
+ growFaces.pop_back();
+ for (Mesh::FaceEdgeIterator edgeIt(m_mesh, f); !edgeIt.isDone(); edgeIt.advance()) {
+ // Iterate opposite edges. There may be more than one - non-manifold geometry can have duplicate edges.
+ // Prioritize the one with exact vertex match, not just colocal.
+ // If *any* of the opposite edges are already assigned to this group, don't do anything.
+ bool alreadyAssignedToThisGroup = false;
+ uint32_t bestConnectedFace = UINT32_MAX;
+ for (Mesh::ColocalEdgeIterator oppositeEdgeIt(m_mesh, edgeIt.vertex1(), edgeIt.vertex0()); !oppositeEdgeIt.isDone(); oppositeEdgeIt.advance()) {
+ const uint32_t oppositeEdge = oppositeEdgeIt.edge();
+ const uint32_t oppositeFace = meshEdgeFace(oppositeEdge);
+#if 0
+ // Reject opposite face if dihedral angle >= 90 degrees.
+ {
+ Vector3 a = m_mesh->computeFaceNormal(f);
+ Vector3 b = m_mesh->computeFaceNormal(oppositeFace);
+ if (dot(a, b) <= 0.0f)
+ continue;
+ }
+#endif
+ if (m_mesh->isFaceIgnored(oppositeFace))
+ continue; // Don't add ignored faces to group.
+ if (m_groups[oppositeFace] == group) {
+ alreadyAssignedToThisGroup = true;
+ break;
+ }
+ if (m_groups[oppositeFace] != kInvalid)
+ continue; // Connected face is already assigned to another group.
+ if (faceDuplicatesGroupEdge(group, oppositeFace))
+ continue; // Don't want duplicate edges in a group.
+ const uint32_t oppositeVertex0 = m_mesh->vertexAt(meshEdgeIndex0(oppositeEdge));
+ const uint32_t oppositeVertex1 = m_mesh->vertexAt(meshEdgeIndex1(oppositeEdge));
+ if (bestConnectedFace == UINT32_MAX || (oppositeVertex0 == edgeIt.vertex1() && oppositeVertex1 == edgeIt.vertex0()))
+ bestConnectedFace = oppositeFace;
+#if 0
+ else {
+ // Choose the opposite face with the smallest dihedral angle.
+ const float d1 = 1.0f - dot(computeFaceNormal(f), computeFaceNormal(bestConnectedFace));
+ const float d2 = 1.0f - dot(computeFaceNormal(f), computeFaceNormal(oppositeFace));
+ if (d2 < d1)
+ bestConnectedFace = oppositeFace;
+ }
+#endif
+ }
+ if (!alreadyAssignedToThisGroup && bestConnectedFace != UINT32_MAX) {
+ m_groups[bestConnectedFace] = group;
+ m_nextFace[bestConnectedFace] = UINT32_MAX;
+ if (prevFace != UINT32_MAX)
+ m_nextFace[prevFace] = bestConnectedFace;
+ prevFace = bestConnectedFace;
+ groupFaceCount++;
+ growFaces.push_back(bestConnectedFace);
+ }
+ }
+ }
+ m_faceCount.push_back(groupFaceCount);
+ group++;
+ XA_ASSERT(group < kInvalid);
+ }
+ }
- class GroupFaceIterator {
+ class Iterator
+ {
public:
- GroupFaceIterator(const Mesh *mesh, uint32_t group) :
- m_mesh(mesh) {
- XA_DEBUG_ASSERT(group != UINT32_MAX);
- m_current = mesh->m_faceGroupFirstFace[group];
+ Iterator(const MeshFaceGroups *meshFaceGroups, Handle group) : m_meshFaceGroups(meshFaceGroups)
+ {
+ XA_DEBUG_ASSERT(group != kInvalid);
+ m_current = m_meshFaceGroups->m_firstFace[group];
}
- void advance() {
- m_current = m_mesh->m_faceGroupNextFace[m_current];
+ void advance()
+ {
+ m_current = m_meshFaceGroups->m_nextFace[m_current];
}
- bool isDone() const {
+ bool isDone() const
+ {
return m_current == UINT32_MAX;
}
- uint32_t face() const {
+ uint32_t face() const
+ {
return m_current;
}
private:
- const Mesh *m_mesh;
+ const MeshFaceGroups *m_meshFaceGroups;
uint32_t m_current;
};
+
+private:
+ // Check if the face duplicates any edges of any face already in the group.
+ bool faceDuplicatesGroupEdge(Handle group, uint32_t face) const
+ {
+ for (Mesh::FaceEdgeIterator edgeIt(m_mesh, face); !edgeIt.isDone(); edgeIt.advance()) {
+ for (Mesh::ColocalEdgeIterator colocalEdgeIt(m_mesh, edgeIt.vertex0(), edgeIt.vertex1()); !colocalEdgeIt.isDone(); colocalEdgeIt.advance()) {
+ if (m_groups[meshEdgeFace(colocalEdgeIt.edge())] == group)
+ return true;
+ }
+ }
+ return false;
+ }
+
+ const Mesh *m_mesh;
+ Array<Handle> m_groups;
+ Array<uint32_t> m_firstFace;
+ Array<uint32_t> m_nextFace; // In: face. Out: the next face in the same group.
+ Array<uint32_t> m_faceCount; // In: face group. Out: number of faces in the group.
};
-constexpr uint16_t Mesh::kInvalidFaceGroup;
+constexpr MeshFaceGroups::Handle MeshFaceGroups::kInvalid;
-static bool meshCloseHole(Mesh *mesh, const Array<uint32_t> &holeVertices, const Vector3 &normal) {
+static bool meshCloseHole(Mesh *mesh, const Array<uint32_t> &holeVertices, const Vector3 &normal)
+{
#if XA_CLOSE_HOLES_CHECK_EDGE_INTERSECTION
const uint32_t faceCount = mesh->faceCount();
#endif
@@ -3230,7 +3459,8 @@ static bool meshCloseHole(Mesh *mesh, const Array<uint32_t> &holeVertices, const
return true;
}
-static bool meshCloseHoles(Mesh *mesh, const Array<uint32_t> &boundaryLoops, const Vector3 &normal, uint32_t *holeCount, Array<uint32_t> *holeFaceCounts) {
+static bool meshCloseHoles(Mesh *mesh, const Array<uint32_t> &boundaryLoops, const Vector3 &normal, uint32_t *holeCount, Array<uint32_t> *holeFaceCounts)
+{
if (holeFaceCounts)
holeFaceCounts->clear();
// Compute lengths.
@@ -3286,7 +3516,8 @@ static bool meshCloseHoles(Mesh *mesh, const Array<uint32_t> &boundaryLoops, con
return result;
}
-static bool meshIsPlanar(const Mesh &mesh) {
+static bool meshIsPlanar(const Mesh &mesh)
+{
const Vector3 p1 = mesh.position(mesh.vertexAt(0));
const Vector3 p2 = mesh.position(mesh.vertexAt(1));
const Vector3 p3 = mesh.position(mesh.vertexAt(2));
@@ -3312,12 +3543,14 @@ Fixing T-junctions.
- Split edge.
*/
-struct SplitEdge {
+struct SplitEdge
+{
uint32_t edge;
float t;
uint32_t vertex;
- bool operator<(const SplitEdge &other) const {
+ bool operator<(const SplitEdge &other) const
+ {
if (edge < other.edge)
return true;
else if (edge == other.edge) {
@@ -3329,7 +3562,8 @@ struct SplitEdge {
};
// Returns nullptr if there were no t-junctions to fix.
-static Mesh *meshFixTJunctions(const Mesh &inputMesh, bool *duplicatedEdge, bool *failed, uint32_t *fixedTJunctionsCount) {
+static Mesh *meshFixTJunctions(const Mesh &inputMesh, bool *duplicatedEdge, bool *failed, uint32_t *fixedTJunctionsCount)
+{
if (duplicatedEdge)
*duplicatedEdge = false;
if (failed)
@@ -3404,7 +3638,8 @@ static Mesh *meshFixTJunctions(const Mesh &inputMesh, bool *duplicatedEdge, bool
}
// boundaryLoops are the first edges for each boundary loop.
-static void meshGetBoundaryLoops(const Mesh &mesh, Array<uint32_t> &boundaryLoops) {
+static void meshGetBoundaryLoops(const Mesh &mesh, Array<uint32_t> &boundaryLoops)
+{
const uint32_t edgeCount = mesh.edgeCount();
BitArray bitFlags(edgeCount);
bitFlags.zeroOutMemory();
@@ -3419,23 +3654,26 @@ static void meshGetBoundaryLoops(const Mesh &mesh, Array<uint32_t> &boundaryLoop
}
}
-struct Progress {
- Progress(ProgressCategory::Enum category, ProgressFunc func, void *userData, uint32_t maxValue) :
- value(0), cancel(false), m_category(category), m_func(func), m_userData(userData), m_maxValue(maxValue), m_progress(0) {
+struct Progress
+{
+ Progress(ProgressCategory::Enum category, ProgressFunc func, void *userData, uint32_t maxValue) : value(0), cancel(false), m_category(category), m_func(func), m_userData(userData), m_maxValue(maxValue), m_progress(0)
+ {
if (m_func) {
if (!m_func(category, 0, userData))
cancel = true;
}
}
- ~Progress() {
+ ~Progress()
+ {
if (m_func) {
if (!m_func(m_category, 100, m_userData))
cancel = true;
}
}
- void update() {
+ void update()
+ {
if (!m_func)
return;
m_mutex.lock();
@@ -3448,7 +3686,8 @@ struct Progress {
m_mutex.unlock();
}
- void setMaxValue(uint32_t maxValue) {
+ void setMaxValue(uint32_t maxValue)
+ {
m_mutex.lock();
m_maxValue = maxValue;
m_mutex.unlock();
@@ -3466,31 +3705,32 @@ private:
std::mutex m_mutex;
};
-struct Spinlock {
- void lock() {
- while (m_lock.test_and_set(std::memory_order_acquire)) {
- }
- }
+struct Spinlock
+{
+ void lock() { while(m_lock.test_and_set(std::memory_order_acquire)) {} }
void unlock() { m_lock.clear(std::memory_order_release); }
private:
std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
};
-struct TaskGroupHandle {
+struct TaskGroupHandle
+{
uint32_t value = UINT32_MAX;
};
-struct Task {
+struct Task
+{
void (*func)(void *userData);
void *userData;
};
#if XA_MULTITHREADED
-class TaskScheduler {
+class TaskScheduler
+{
public:
- TaskScheduler() :
- m_shutdown(false) {
+ TaskScheduler() : m_shutdown(false)
+ {
m_threadIndex = 0;
// Max with current task scheduler usage is 1 per thread + 1 deep nesting, but allow for some slop.
m_maxGroups = std::thread::hardware_concurrency() * 4;
@@ -3508,7 +3748,8 @@ public:
}
}
- ~TaskScheduler() {
+ ~TaskScheduler()
+ {
m_shutdown = true;
for (uint32_t i = 0; i < m_workers.size(); i++) {
Worker &worker = m_workers[i];
@@ -3526,11 +3767,13 @@ public:
XA_FREE(m_groups);
}
- uint32_t threadCount() const {
+ uint32_t threadCount() const
+ {
return max(1u, std::thread::hardware_concurrency()); // Including the main thread.
}
- TaskGroupHandle createTaskGroup(uint32_t reserveSize = 0) {
+ TaskGroupHandle createTaskGroup(uint32_t reserveSize = 0)
+ {
// Claim the first free group.
for (uint32_t i = 0; i < m_maxGroups; i++) {
TaskGroup &group = m_groups[i];
@@ -3552,7 +3795,8 @@ public:
return handle;
}
- void run(TaskGroupHandle handle, Task task) {
+ void run(TaskGroupHandle handle, const Task &task)
+ {
XA_DEBUG_ASSERT(handle.value != UINT32_MAX);
TaskGroup &group = m_groups[handle.value];
group.queueLock.lock();
@@ -3566,7 +3810,8 @@ public:
}
}
- void wait(TaskGroupHandle *handle) {
+ void wait(TaskGroupHandle *handle)
+ {
if (handle->value == UINT32_MAX) {
XA_DEBUG_ASSERT(false);
return;
@@ -3594,7 +3839,8 @@ public:
static uint32_t currentThreadIndex() { return m_threadIndex; }
private:
- struct TaskGroup {
+ struct TaskGroup
+ {
std::atomic<bool> free;
Array<Task> queue; // Items are never removed. queueHead is incremented to pop items.
uint32_t queueHead = 0;
@@ -3602,7 +3848,8 @@ private:
std::atomic<uint32_t> ref; // Increment when a task is enqueued, decrement when a task finishes.
};
- struct Worker {
+ struct Worker
+ {
std::thread *thread = nullptr;
std::mutex mutex;
std::condition_variable cv;
@@ -3610,16 +3857,17 @@ private:
};
TaskGroup *m_groups;
- uint32_t m_maxGroups;
Array<Worker> m_workers;
std::atomic<bool> m_shutdown;
+ uint32_t m_maxGroups;
static thread_local uint32_t m_threadIndex;
- static void workerThread(TaskScheduler *scheduler, Worker *worker, uint32_t threadIndex) {
+ static void workerThread(TaskScheduler *scheduler, Worker *worker, uint32_t threadIndex)
+ {
m_threadIndex = threadIndex;
std::unique_lock<std::mutex> lock(worker->mutex);
for (;;) {
- worker->cv.wait(lock, [=] { return worker->wakeup.load(); });
+ worker->cv.wait(lock, [=]{ return worker->wakeup.load(); });
worker->wakeup = false;
for (;;) {
if (scheduler->m_shutdown)
@@ -3650,18 +3898,22 @@ private:
thread_local uint32_t TaskScheduler::m_threadIndex;
#else
-class TaskScheduler {
+class TaskScheduler
+{
public:
- ~TaskScheduler() {
+ ~TaskScheduler()
+ {
for (uint32_t i = 0; i < m_groups.size(); i++)
destroyGroup({ i });
}
- uint32_t threadCount() const {
+ uint32_t threadCount() const
+ {
return 1;
}
- TaskGroupHandle createTaskGroup(uint32_t reserveSize = 0) {
+ TaskGroupHandle createTaskGroup(uint32_t reserveSize = 0)
+ {
TaskGroup *group = XA_NEW(MemTag::Default, TaskGroup);
group->queue.reserve(reserveSize);
m_groups.push_back(group);
@@ -3670,11 +3922,13 @@ public:
return handle;
}
- void run(TaskGroupHandle handle, Task task) {
+ void run(TaskGroupHandle handle, Task task)
+ {
m_groups[handle.value]->queue.push_back(task);
}
- void wait(TaskGroupHandle *handle) {
+ void wait(TaskGroupHandle *handle)
+ {
if (handle->value == UINT32_MAX) {
XA_DEBUG_ASSERT(false);
return;
@@ -3690,7 +3944,8 @@ public:
static uint32_t currentThreadIndex() { return 0; }
private:
- void destroyGroup(TaskGroupHandle handle) {
+ void destroyGroup(TaskGroupHandle handle)
+ {
TaskGroup *group = m_groups[handle.value];
if (group) {
group->~TaskGroup();
@@ -3699,7 +3954,8 @@ private:
}
}
- struct TaskGroup {
+ struct TaskGroup
+ {
Array<Task> queue;
};
@@ -3712,7 +3968,8 @@ const uint8_t TGA_TYPE_RGB = 2;
const uint8_t TGA_ORIGIN_UPPER = 0x20;
#pragma pack(push, 1)
-struct TgaHeader {
+struct TgaHeader
+{
uint8_t id_length;
uint8_t colormap_type;
uint8_t image_type;
@@ -3729,7 +3986,8 @@ struct TgaHeader {
};
#pragma pack(pop)
-static void WriteTga(const char *filename, const uint8_t *data, uint32_t width, uint32_t height) {
+static void WriteTga(const char *filename, const uint8_t *data, uint32_t width, uint32_t height)
+{
XA_DEBUG_ASSERT(sizeof(TgaHeader) == TgaHeader::Size);
FILE *f;
XA_FOPEN(f, filename, "wb");
@@ -3754,10 +4012,12 @@ static void WriteTga(const char *filename, const uint8_t *data, uint32_t width,
}
#endif
-template <typename T>
-class ThreadLocal {
+template<typename T>
+class ThreadLocal
+{
public:
- ThreadLocal() {
+ ThreadLocal()
+ {
#if XA_MULTITHREADED
const uint32_t n = std::thread::hardware_concurrency();
#else
@@ -3768,7 +4028,8 @@ public:
new (&m_array[i]) T;
}
- ~ThreadLocal() {
+ ~ThreadLocal()
+ {
#if XA_MULTITHREADED
const uint32_t n = std::thread::hardware_concurrency();
#else
@@ -3779,7 +4040,8 @@ public:
XA_FREE(m_array);
}
- T &get() const {
+ T &get() const
+ {
return m_array[TaskScheduler::currentThreadIndex()];
}
@@ -3787,9 +4049,11 @@ private:
T *m_array;
};
-class UniformGrid2 {
+class UniformGrid2
+{
public:
- void reset(const Vector2 *positions, const uint32_t *indices = nullptr, uint32_t reserveEdgeCount = 0) {
+ void reset(const Vector2 *positions, const uint32_t *indices = nullptr, uint32_t reserveEdgeCount = 0)
+ {
m_edges.clear();
if (reserveEdgeCount > 0)
m_edges.reserve(reserveEdgeCount);
@@ -3798,14 +4062,16 @@ public:
m_cellDataOffsets.clear();
}
- void append(uint32_t edge) {
+ void append(uint32_t edge)
+ {
XA_DEBUG_ASSERT(m_cellDataOffsets.isEmpty());
m_edges.push_back(edge);
}
- bool intersect(Vector2 v1, Vector2 v2, float epsilon) {
+ bool intersect(Vector2 v1, Vector2 v2, float epsilon)
+ {
const uint32_t edgeCount = m_edges.size();
- bool bruteForce = edgeCount <= 64;
+ bool bruteForce = edgeCount <= 20;
if (!bruteForce && m_cellDataOffsets.isEmpty())
bruteForce = !createGrid();
if (bruteForce) {
@@ -3829,37 +4095,80 @@ public:
return false;
}
- bool intersectSelf(float epsilon) {
- const uint32_t edgeCount = m_edges.size();
- bool bruteForce = edgeCount <= 64;
+ // If edges is empty, checks for intersection with all edges in the grid.
+ bool intersect(float epsilon, ConstArrayView<uint32_t> edges = ConstArrayView<uint32_t>(), ConstArrayView<uint32_t> ignoreEdges = ConstArrayView<uint32_t>())
+ {
+ bool bruteForce = m_edges.size() <= 20;
if (!bruteForce && m_cellDataOffsets.isEmpty())
bruteForce = !createGrid();
- for (uint32_t i = 0; i < edgeCount; i++) {
- const uint32_t edge1 = m_edges[i];
+ const uint32_t *edges1, *edges2 = nullptr;
+ uint32_t edges1Count, edges2Count = 0;
+ if (edges.length == 0) {
+ edges1 = m_edges.data();
+ edges1Count = m_edges.size();
+ } else {
+ edges1 = edges.data;
+ edges1Count = edges.length;
+ }
+ if (bruteForce) {
+ edges2 = m_edges.data();
+ edges2Count = m_edges.size();
+ }
+ for (uint32_t i = 0; i < edges1Count; i++) {
+ const uint32_t edge1 = edges1[i];
+ const uint32_t edge1Vertex[2] = { vertexAt(meshEdgeIndex0(edge1)), vertexAt(meshEdgeIndex1(edge1)) };
+ const Vector2 &edge1Position1 = m_positions[edge1Vertex[0]];
+ const Vector2 &edge1Position2 = m_positions[edge1Vertex[1]];
+ const Extents2 edge1Extents(edge1Position1, edge1Position2);
+ uint32_t j = 0;
if (bruteForce) {
- for (uint32_t j = 0; j < edgeCount; j++) {
- const uint32_t edge2 = m_edges[j];
- if (edgesIntersect(edge1, edge2, epsilon))
- return true;
+ // If checking against self, test each edge pair only once.
+ if (edges.length == 0) {
+ j = i + 1;
+ if (j == edges1Count)
+ break;
}
} else {
computePotentialEdges(edgePosition0(edge1), edgePosition1(edge1));
- uint32_t prevEdge = UINT32_MAX;
- for (uint32_t j = 0; j < m_potentialEdges.size(); j++) {
- const uint32_t edge2 = m_potentialEdges[j];
- if (edge2 == prevEdge)
- continue;
- if (edgesIntersect(edge1, edge2, epsilon))
- return true;
- prevEdge = edge2;
+ edges2 = m_potentialEdges.data();
+ edges2Count = m_potentialEdges.size();
+ }
+ uint32_t prevEdge = UINT32_MAX; // Handle potential edges duplicates.
+ for (; j < edges2Count; j++) {
+ const uint32_t edge2 = edges2[j];
+ if (edge1 == edge2)
+ continue;
+ if (edge2 == prevEdge)
+ continue;
+ prevEdge = edge2;
+ // Check if edge2 is ignored.
+ bool ignore = false;
+ for (uint32_t k = 0; k < ignoreEdges.length; k++) {
+ if (edge2 == ignoreEdges[k]) {
+ ignore = true;
+ break;
+ }
}
+ if (ignore)
+ continue;
+ const uint32_t edge2Vertex[2] = { vertexAt(meshEdgeIndex0(edge2)), vertexAt(meshEdgeIndex1(edge2)) };
+ // Ignore connected edges, since they can't intersect (only overlap), and may be detected as false positives.
+ if (edge1Vertex[0] == edge2Vertex[0] || edge1Vertex[0] == edge2Vertex[1] || edge1Vertex[1] == edge2Vertex[0] || edge1Vertex[1] == edge2Vertex[1])
+ continue;
+ const Vector2 &edge2Position1 = m_positions[edge2Vertex[0]];
+ const Vector2 &edge2Position2 = m_positions[edge2Vertex[1]];
+ if (!Extents2::intersect(edge1Extents, Extents2(edge2Position1, edge2Position2)))
+ continue;
+ if (linesIntersect(edge1Position1, edge1Position2, edge2Position1, edge2Position2, epsilon))
+ return true;
}
}
return false;
}
#if XA_DEBUG_EXPORT_BOUNDARY_GRID
- void debugExport(const char *filename) {
+ void debugExport(const char *filename)
+ {
Array<uint8_t> image;
image.resize(m_gridWidth * m_gridHeight * 3);
for (uint32_t y = 0; y < m_gridHeight; y++) {
@@ -3881,7 +4190,8 @@ public:
#endif
private:
- bool createGrid() {
+ bool createGrid()
+ {
// Compute edge extents. Min will be the grid origin.
const uint32_t edgeCount = m_edges.size();
Extents2 edgeExtents;
@@ -3933,7 +4243,8 @@ private:
return true;
}
- void computePotentialEdges(Vector2 p1, Vector2 p2) {
+ void computePotentialEdges(Vector2 p1, Vector2 p2)
+ {
m_potentialEdges.clear();
traverse(p1, p2);
for (uint32_t j = 0; j < m_traversedCellOffsets.size(); j++) {
@@ -3951,7 +4262,8 @@ private:
}
// "A Fast Voxel Traversal Algorithm for Ray Tracing"
- void traverse(Vector2 p1, Vector2 p2) {
+ void traverse(Vector2 p1, Vector2 p2)
+ {
const Vector2 dir = p2 - p1;
const Vector2 normal = normalizeSafe(dir, Vector2(0.0f), kEpsilon);
const int stepX = dir.x >= 0 ? 1 : -1;
@@ -3972,12 +4284,14 @@ private:
if (normal.x > kEpsilon || normal.x < -kEpsilon) {
tMaxX = (distToNextCellX * stepX) / normal.x;
tDeltaX = (m_cellSize * stepX) / normal.x;
- } else
+ }
+ else
tMaxX = tDeltaX = FLT_MAX;
if (normal.y > kEpsilon || normal.y < -kEpsilon) {
tMaxY = (distToNextCellY * stepY) / normal.y;
tDeltaY = (m_cellSize * stepY) / normal.y;
- } else
+ }
+ else
tMaxY = tDeltaY = FLT_MAX;
m_traversedCellOffsets.clear();
m_traversedCellOffsets.push_back(firstCell[0] + firstCell[1] * m_gridWidth);
@@ -3992,11 +4306,11 @@ private:
}
if (currentCell[0] >= m_gridWidth || currentCell[1] >= m_gridHeight)
break;
- if (stepX == 0 && currentCell[0] < lastCell[0])
+ if (stepX == -1 && currentCell[0] < lastCell[0])
break;
if (stepX == 1 && currentCell[0] > lastCell[0])
break;
- if (stepY == 0 && currentCell[1] < lastCell[1])
+ if (stepY == -1 && currentCell[1] < lastCell[1])
break;
if (stepY == 1 && currentCell[1] > lastCell[1])
break;
@@ -4004,34 +4318,28 @@ private:
}
}
- bool edgesIntersect(uint32_t edge1, uint32_t edge2, float epsilon) const {
- if (edge1 == edge2)
- return false;
- const uint32_t ai[2] = { vertexAt(meshEdgeIndex0(edge1)), vertexAt(meshEdgeIndex1(edge1)) };
- const uint32_t bi[2] = { vertexAt(meshEdgeIndex0(edge2)), vertexAt(meshEdgeIndex1(edge2)) };
- // Ignore connected edges, since they can't intersect (only overlap), and may be detected as false positives.
- if (ai[0] == bi[0] || ai[0] == bi[1] || ai[1] == bi[0] || ai[1] == bi[1])
- return false;
- return linesIntersect(m_positions[ai[0]], m_positions[ai[1]], m_positions[bi[0]], m_positions[bi[1]], epsilon);
- }
-
- uint32_t cellX(float x) const {
+ uint32_t cellX(float x) const
+ {
return min((uint32_t)max(0.0f, (x - m_gridOrigin.x) / m_cellSize), m_gridWidth - 1u);
}
- uint32_t cellY(float y) const {
+ uint32_t cellY(float y) const
+ {
return min((uint32_t)max(0.0f, (y - m_gridOrigin.y) / m_cellSize), m_gridHeight - 1u);
}
- Vector2 edgePosition0(uint32_t edge) const {
+ Vector2 edgePosition0(uint32_t edge) const
+ {
return m_positions[vertexAt(meshEdgeIndex0(edge))];
}
- Vector2 edgePosition1(uint32_t edge) const {
+ Vector2 edgePosition1(uint32_t edge) const
+ {
return m_positions[vertexAt(meshEdgeIndex1(edge))];
}
- uint32_t vertexAt(uint32_t index) const {
+ uint32_t vertexAt(uint32_t index) const
+ {
return m_indices ? m_indices[index] : index;
}
@@ -4047,29 +4355,835 @@ private:
Array<uint32_t> m_traversedCellOffsets;
};
-struct UvMeshChart {
+struct UvMeshChart
+{
Array<uint32_t> faces;
Array<uint32_t> indices;
uint32_t material;
};
-struct UvMesh {
+struct UvMesh
+{
UvMeshDecl decl;
Array<uint32_t> indices;
Array<UvMeshChart *> charts;
Array<uint32_t> vertexToChartMap;
};
-struct UvMeshInstance {
+struct UvMeshInstance
+{
UvMesh *mesh;
Array<Vector2> texcoords;
bool rotateCharts;
};
+/*
+ * Copyright (c) 2004-2010, Bruno Levy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * * Neither the name of the ALICE Project-Team nor the names of its
+ * contributors may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * If you modify this software, you should include a notice giving the
+ * name of the person performing the modification, the date of modification,
+ * and the reason for such modification.
+ *
+ * Contact: Bruno Levy
+ *
+ * levy@loria.fr
+ *
+ * ALICE Project
+ * LORIA, INRIA Lorraine,
+ * Campus Scientifique, BP 239
+ * 54506 VANDOEUVRE LES NANCY CEDEX
+ * FRANCE
+ */
+namespace opennl {
+#define NL_NEW(T) XA_ALLOC(MemTag::OpenNL, T)
+#define NL_NEW_ARRAY(T,NB) XA_ALLOC_ARRAY(MemTag::OpenNL, T, NB)
+#define NL_RENEW_ARRAY(T,x,NB) XA_REALLOC(MemTag::OpenNL, x, T, NB)
+#define NL_DELETE(x) XA_FREE(x); x = nullptr
+#define NL_DELETE_ARRAY(x) XA_FREE(x); x = nullptr
+#define NL_CLEAR(x, T) memset(x, 0, sizeof(T));
+#define NL_CLEAR_ARRAY(T,x,NB) memset(x, 0, (size_t)(NB)*sizeof(T))
+#define NL_NEW_VECTOR(dim) XA_ALLOC_ARRAY(MemTag::OpenNL, double, dim)
+#define NL_DELETE_VECTOR(ptr) XA_FREE(ptr)
+
+struct NLMatrixStruct;
+typedef NLMatrixStruct * NLMatrix;
+typedef void (*NLDestroyMatrixFunc)(NLMatrix M);
+typedef void (*NLMultMatrixVectorFunc)(NLMatrix M, const double* x, double* y);
+
+#define NL_MATRIX_SPARSE_DYNAMIC 0x1001
+#define NL_MATRIX_CRS 0x1002
+#define NL_MATRIX_OTHER 0x1006
+
+struct NLMatrixStruct
+{
+ uint32_t m;
+ uint32_t n;
+ uint32_t type;
+ NLDestroyMatrixFunc destroy_func;
+ NLMultMatrixVectorFunc mult_func;
+};
+
+/* Dynamic arrays for sparse row/columns */
+
+struct NLCoeff
+{
+ uint32_t index;
+ double value;
+};
+
+struct NLRowColumn
+{
+ uint32_t size;
+ uint32_t capacity;
+ NLCoeff* coeff;
+};
+
+/* Compressed Row Storage */
+
+struct NLCRSMatrix
+{
+ uint32_t m;
+ uint32_t n;
+ uint32_t type;
+ NLDestroyMatrixFunc destroy_func;
+ NLMultMatrixVectorFunc mult_func;
+ double* val;
+ uint32_t* rowptr;
+ uint32_t* colind;
+ uint32_t nslices;
+ uint32_t* sliceptr;
+};
+
+/* SparseMatrix data structure */
+
+struct NLSparseMatrix
+{
+ uint32_t m;
+ uint32_t n;
+ uint32_t type;
+ NLDestroyMatrixFunc destroy_func;
+ NLMultMatrixVectorFunc mult_func;
+ uint32_t diag_size;
+ uint32_t diag_capacity;
+ NLRowColumn* row;
+ NLRowColumn* column;
+ double* diag;
+ uint32_t row_capacity;
+ uint32_t column_capacity;
+};
+
+/* NLContext data structure */
+
+struct NLBufferBinding
+{
+ void* base_address;
+ uint32_t stride;
+};
+
+#define NL_BUFFER_ITEM(B,i) *(double*)((void*)((char*)((B).base_address)+((i)*(B).stride)))
+
+struct NLContext
+{
+ NLBufferBinding *variable_buffer;
+ double *variable_value;
+ bool *variable_is_locked;
+ uint32_t *variable_index;
+ uint32_t n;
+ NLMatrix M;
+ NLMatrix P;
+ NLMatrix B;
+ NLRowColumn af;
+ NLRowColumn al;
+ double *x;
+ double *b;
+ uint32_t nb_variables;
+ uint32_t nb_systems;
+ uint32_t current_row;
+ uint32_t max_iterations;
+ bool max_iterations_defined;
+ double threshold;
+ double omega;
+ uint32_t used_iterations;
+ double error;
+};
+
+static void nlDeleteMatrix(NLMatrix M)
+{
+ if (!M)
+ return;
+ M->destroy_func(M);
+ NL_DELETE(M);
+}
+
+static void nlMultMatrixVector(NLMatrix M, const double* x, double* y)
+{
+ M->mult_func(M, x, y);
+}
+
+static void nlRowColumnConstruct(NLRowColumn* c)
+{
+ c->size = 0;
+ c->capacity = 0;
+ c->coeff = nullptr;
+}
+
+static void nlRowColumnDestroy(NLRowColumn* c)
+{
+ NL_DELETE_ARRAY(c->coeff);
+ c->size = 0;
+ c->capacity = 0;
+}
+
+static void nlRowColumnGrow(NLRowColumn* c)
+{
+ if (c->capacity != 0) {
+ c->capacity = 2 * c->capacity;
+ c->coeff = NL_RENEW_ARRAY(NLCoeff, c->coeff, c->capacity);
+ } else {
+ c->capacity = 4;
+ c->coeff = NL_NEW_ARRAY(NLCoeff, c->capacity);
+ NL_CLEAR_ARRAY(NLCoeff, c->coeff, c->capacity);
+ }
+}
+
+static void nlRowColumnAdd(NLRowColumn* c, uint32_t index, double value)
+{
+ for (uint32_t i = 0; i < c->size; i++) {
+ if (c->coeff[i].index == index) {
+ c->coeff[i].value += value;
+ return;
+ }
+ }
+ if (c->size == c->capacity)
+ nlRowColumnGrow(c);
+ c->coeff[c->size].index = index;
+ c->coeff[c->size].value = value;
+ c->size++;
+}
+
+/* Does not check whether the index already exists */
+static void nlRowColumnAppend(NLRowColumn* c, uint32_t index, double value)
+{
+ if (c->size == c->capacity)
+ nlRowColumnGrow(c);
+ c->coeff[c->size].index = index;
+ c->coeff[c->size].value = value;
+ c->size++;
+}
+
+static void nlRowColumnZero(NLRowColumn* c)
+{
+ c->size = 0;
+}
+
+static void nlRowColumnClear(NLRowColumn* c)
+{
+ c->size = 0;
+ c->capacity = 0;
+ NL_DELETE_ARRAY(c->coeff);
+}
+
+static int nlCoeffCompare(const void* p1, const void* p2)
+{
+ return (((NLCoeff*)(p2))->index < ((NLCoeff*)(p1))->index);
+}
+
+static void nlRowColumnSort(NLRowColumn* c)
+{
+ qsort(c->coeff, c->size, sizeof(NLCoeff), nlCoeffCompare);
+}
+
+/* CRSMatrix data structure */
+
+static void nlCRSMatrixDestroy(NLCRSMatrix* M)
+{
+ NL_DELETE_ARRAY(M->val);
+ NL_DELETE_ARRAY(M->rowptr);
+ NL_DELETE_ARRAY(M->colind);
+ NL_DELETE_ARRAY(M->sliceptr);
+ M->m = 0;
+ M->n = 0;
+ M->nslices = 0;
+}
+
+static void nlCRSMatrixMultSlice(NLCRSMatrix* M, const double* x, double* y, uint32_t Ibegin, uint32_t Iend)
+{
+ for (uint32_t i = Ibegin; i < Iend; ++i) {
+ double sum = 0.0;
+ for (uint32_t j = M->rowptr[i]; j < M->rowptr[i + 1]; ++j)
+ sum += M->val[j] * x[M->colind[j]];
+ y[i] = sum;
+ }
+}
+
+static void nlCRSMatrixMult(NLCRSMatrix* M, const double* x, double* y)
+{
+ int nslices = (int)(M->nslices);
+ for (int slice = 0; slice < nslices; ++slice)
+ nlCRSMatrixMultSlice(M, x, y, M->sliceptr[slice], M->sliceptr[slice + 1]);
+}
+
+static void nlCRSMatrixConstruct(NLCRSMatrix* M, uint32_t m, uint32_t n, uint32_t nnz, uint32_t nslices)
+{
+ M->m = m;
+ M->n = n;
+ M->type = NL_MATRIX_CRS;
+ M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy;
+ M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult;
+ M->nslices = nslices;
+ M->val = NL_NEW_ARRAY(double, nnz);
+ NL_CLEAR_ARRAY(double, M->val, nnz);
+ M->rowptr = NL_NEW_ARRAY(uint32_t, m + 1);
+ NL_CLEAR_ARRAY(uint32_t, M->rowptr, m + 1);
+ M->colind = NL_NEW_ARRAY(uint32_t, nnz);
+ NL_CLEAR_ARRAY(uint32_t, M->colind, nnz);
+ M->sliceptr = NL_NEW_ARRAY(uint32_t, nslices + 1);
+ NL_CLEAR_ARRAY(uint32_t, M->sliceptr, nslices + 1);
+}
+
+/* SparseMatrix data structure */
+
+static void nlSparseMatrixDestroyRowColumns(NLSparseMatrix* M)
+{
+ for (uint32_t i = 0; i < M->m; i++)
+ nlRowColumnDestroy(&(M->row[i]));
+ NL_DELETE_ARRAY(M->row);
+}
+
+static void nlSparseMatrixDestroy(NLSparseMatrix* M)
+{
+ XA_DEBUG_ASSERT(M->type == NL_MATRIX_SPARSE_DYNAMIC);
+ nlSparseMatrixDestroyRowColumns(M);
+ NL_DELETE_ARRAY(M->diag);
+}
+
+static void nlSparseMatrixAdd(NLSparseMatrix* M, uint32_t i, uint32_t j, double value)
+{
+ XA_DEBUG_ASSERT(i >= 0 && i <= M->m - 1);
+ XA_DEBUG_ASSERT(j >= 0 && j <= M->n - 1);
+ if (i == j)
+ M->diag[i] += value;
+ nlRowColumnAdd(&(M->row[i]), j, value);
+}
+
+/* Returns the number of non-zero coefficients */
+static uint32_t nlSparseMatrixNNZ(NLSparseMatrix* M)
+{
+ uint32_t nnz = 0;
+ for (uint32_t i = 0; i < M->m; i++)
+ nnz += M->row[i].size;
+ return nnz;
+}
+
+static void nlSparseMatrixSort(NLSparseMatrix* M)
+{
+ for (uint32_t i = 0; i < M->m; i++)
+ nlRowColumnSort(&(M->row[i]));
+}
+
+/* SparseMatrix x Vector routines, internal helper routines */
+
+static void nlSparseMatrix_mult_rows(NLSparseMatrix* A, const double* x, double* y)
+{
+ /*
+ * Note: OpenMP does not like unsigned ints
+ * (causes some floating point exceptions),
+ * therefore I use here signed ints for all
+ * indices.
+ */
+ int m = (int)(A->m);
+ NLCoeff* c = nullptr;
+ NLRowColumn* Ri = nullptr;
+ for (int i = 0; i < m; i++) {
+ Ri = &(A->row[i]);
+ y[i] = 0;
+ for (int ij = 0; ij < (int)(Ri->size); ij++) {
+ c = &(Ri->coeff[ij]);
+ y[i] += c->value * x[c->index];
+ }
+ }
+}
+
+static void nlSparseMatrixMult(NLSparseMatrix* A, const double* x, double* y)
+{
+ XA_DEBUG_ASSERT(A->type == NL_MATRIX_SPARSE_DYNAMIC);
+ nlSparseMatrix_mult_rows(A, x, y);
+}
+
+static void nlSparseMatrixConstruct(NLSparseMatrix* M, uint32_t m, uint32_t n)
+{
+ M->m = m;
+ M->n = n;
+ M->type = NL_MATRIX_SPARSE_DYNAMIC;
+ M->destroy_func = (NLDestroyMatrixFunc)nlSparseMatrixDestroy;
+ M->mult_func = (NLMultMatrixVectorFunc)nlSparseMatrixMult;
+ M->row = NL_NEW_ARRAY(NLRowColumn, m);
+ NL_CLEAR_ARRAY(NLRowColumn, M->row, m);
+ M->row_capacity = m;
+ for (uint32_t i = 0; i < n; i++)
+ nlRowColumnConstruct(&(M->row[i]));
+ M->row_capacity = 0;
+ M->column = nullptr;
+ M->column_capacity = 0;
+ M->diag_size = min(m, n);
+ M->diag_capacity = M->diag_size;
+ M->diag = NL_NEW_ARRAY(double, M->diag_size);
+ NL_CLEAR_ARRAY(double, M->diag, M->diag_size);
+}
+
+static NLMatrix nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M)
+{
+ uint32_t nnz = nlSparseMatrixNNZ(M);
+ uint32_t nslices = 8; /* TODO: get number of cores */
+ uint32_t slice, cur_bound, cur_NNZ, cur_row;
+ uint32_t k;
+ uint32_t slice_size = nnz / nslices;
+ NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix);
+ NL_CLEAR(CRS, NLCRSMatrix);
+ nlCRSMatrixConstruct(CRS, M->m, M->n, nnz, nslices);
+ nlSparseMatrixSort(M);
+ /* Convert matrix to CRS format */
+ k = 0;
+ for (uint32_t i = 0; i < M->m; ++i) {
+ NLRowColumn* Ri = &(M->row[i]);
+ CRS->rowptr[i] = k;
+ for (uint32_t ij = 0; ij < Ri->size; ij++) {
+ NLCoeff* c = &(Ri->coeff[ij]);
+ CRS->val[k] = c->value;
+ CRS->colind[k] = c->index;
+ ++k;
+ }
+ }
+ CRS->rowptr[M->m] = k;
+ /* Create "slices" to be used by parallel sparse matrix vector product */
+ if (CRS->sliceptr) {
+ cur_bound = slice_size;
+ cur_NNZ = 0;
+ cur_row = 0;
+ CRS->sliceptr[0] = 0;
+ for (slice = 1; slice < nslices; ++slice) {
+ while (cur_NNZ < cur_bound && cur_row < M->m) {
+ ++cur_row;
+ cur_NNZ += CRS->rowptr[cur_row + 1] - CRS->rowptr[cur_row];
+ }
+ CRS->sliceptr[slice] = cur_row;
+ cur_bound += slice_size;
+ }
+ CRS->sliceptr[nslices] = M->m;
+ }
+ return (NLMatrix)CRS;
+}
+
+static void nlMatrixCompress(NLMatrix* M)
+{
+ NLMatrix CRS = nullptr;
+ if ((*M)->type != NL_MATRIX_SPARSE_DYNAMIC)
+ return;
+ CRS = nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)*M);
+ nlDeleteMatrix(*M);
+ *M = CRS;
+}
+
+static NLContext *nlNewContext()
+{
+ NLContext* result = NL_NEW(NLContext);
+ NL_CLEAR(result, NLContext);
+ result->max_iterations = 100;
+ result->threshold = 1e-6;
+ result->omega = 1.5;
+ result->nb_systems = 1;
+ return result;
+}
+
+static void nlDeleteContext(NLContext *context)
+{
+ nlDeleteMatrix(context->M);
+ context->M = nullptr;
+ nlDeleteMatrix(context->P);
+ context->P = nullptr;
+ nlDeleteMatrix(context->B);
+ context->B = nullptr;
+ nlRowColumnDestroy(&context->af);
+ nlRowColumnDestroy(&context->al);
+ NL_DELETE_ARRAY(context->variable_value);
+ NL_DELETE_ARRAY(context->variable_buffer);
+ NL_DELETE_ARRAY(context->variable_is_locked);
+ NL_DELETE_ARRAY(context->variable_index);
+ NL_DELETE_ARRAY(context->x);
+ NL_DELETE_ARRAY(context->b);
+ NL_DELETE(context);
+}
+
+static double ddot(int n, const double *x, const double *y)
+{
+ double sum = 0.0;
+ for (int i = 0; i < n; i++)
+ sum += x[i] * y[i];
+ return sum;
+}
+
+static void daxpy(int n, double a, const double *x, double *y)
+{
+ for (int i = 0; i < n; i++)
+ y[i] = a * x[i] + y[i];
+}
+
+static void dscal(int n, double a, double *x)
+{
+ for (int i = 0; i < n; i++)
+ x[i] *= a;
+}
+
+/*
+ * The implementation of the solvers is inspired by
+ * the lsolver library, by Christian Badura, available from:
+ * http://www.mathematik.uni-freiburg.de
+ * /IAM/Research/projectskr/lin_solver/
+ *
+ * About the Conjugate Gradient, details can be found in:
+ * Ashby, Manteuffel, Saylor
+ * A taxononmy for conjugate gradient methods
+ * SIAM J Numer Anal 27, 1542-1568 (1990)
+ *
+ * This version is completely abstract, the same code can be used for
+ * CPU/GPU, dense matrix / sparse matrix etc...
+ * Abstraction is realized through:
+ * - Abstract matrix interface (NLMatrix), that can implement different
+ * versions of matrix x vector product (CPU/GPU, sparse/dense ...)
+ */
+
+static uint32_t nlSolveSystem_PRE_CG(NLMatrix M, NLMatrix P, double* b, double* x, double eps, uint32_t max_iter, double *sq_bnorm, double *sq_rnorm)
+{
+ int N = (int)M->n;
+ double* r = NL_NEW_VECTOR(N);
+ double* d = NL_NEW_VECTOR(N);
+ double* h = NL_NEW_VECTOR(N);
+ double *Ad = h;
+ uint32_t its = 0;
+ double rh, alpha, beta;
+ double b_square = ddot(N, b, b);
+ double err = eps * eps*b_square;
+ double curr_err;
+ nlMultMatrixVector(M, x, r);
+ daxpy(N, -1., b, r);
+ nlMultMatrixVector(P, r, d);
+ memcpy(h, d, N * sizeof(double));
+ rh = ddot(N, r, h);
+ curr_err = ddot(N, r, r);
+ while (curr_err > err && its < max_iter) {
+ nlMultMatrixVector(M, d, Ad);
+ alpha = rh / ddot(N, d, Ad);
+ daxpy(N, -alpha, d, x);
+ daxpy(N, -alpha, Ad, r);
+ nlMultMatrixVector(P, r, h);
+ beta = 1. / rh;
+ rh = ddot(N, r, h);
+ beta *= rh;
+ dscal(N, beta, d);
+ daxpy(N, 1., h, d);
+ ++its;
+ curr_err = ddot(N, r, r);
+ }
+ NL_DELETE_VECTOR(r);
+ NL_DELETE_VECTOR(d);
+ NL_DELETE_VECTOR(h);
+ *sq_bnorm = b_square;
+ *sq_rnorm = curr_err;
+ return its;
+}
+
+static uint32_t nlSolveSystemIterative(NLContext *context, NLMatrix M, NLMatrix P, double* b_in, double* x_in, double eps, uint32_t max_iter)
+{
+ uint32_t result = 0;
+ double rnorm = 0.0;
+ double bnorm = 0.0;
+ double* b = b_in;
+ double* x = x_in;
+ XA_DEBUG_ASSERT(M->m == M->n);
+ double sq_bnorm, sq_rnorm;
+ result = nlSolveSystem_PRE_CG(M, P, b, x, eps, max_iter, &sq_bnorm, &sq_rnorm);
+ /* Get residual norm and rhs norm */
+ bnorm = sqrt(sq_bnorm);
+ rnorm = sqrt(sq_rnorm);
+ if (bnorm == 0.0)
+ context->error = rnorm;
+ else
+ context->error = rnorm / bnorm;
+ context->used_iterations = result;
+ return result;
+}
+
+static bool nlSolveIterative(NLContext *context)
+{
+ double* b = context->b;
+ double* x = context->x;
+ uint32_t n = context->n;
+ NLMatrix M = context->M;
+ NLMatrix P = context->P;
+ for (uint32_t k = 0; k < context->nb_systems; ++k) {
+ nlSolveSystemIterative(context, M, P, b, x, context->threshold, context->max_iterations);
+ b += n;
+ x += n;
+ }
+ return true;
+}
+
+struct NLJacobiPreconditioner
+{
+ uint32_t m;
+ uint32_t n;
+ uint32_t type;
+ NLDestroyMatrixFunc destroy_func;
+ NLMultMatrixVectorFunc mult_func;
+ double* diag_inv;
+};
+
+static void nlJacobiPreconditionerDestroy(NLJacobiPreconditioner* M)
+{
+ NL_DELETE_ARRAY(M->diag_inv);
+}
+
+static void nlJacobiPreconditionerMult(NLJacobiPreconditioner* M, const double* x, double* y)
+{
+ for (uint32_t i = 0; i < M->n; ++i)
+ y[i] = x[i] * M->diag_inv[i];
+}
+
+static NLMatrix nlNewJacobiPreconditioner(NLMatrix M_in)
+{
+ NLSparseMatrix* M = nullptr;
+ NLJacobiPreconditioner* result = nullptr;
+ XA_DEBUG_ASSERT(M_in->type == NL_MATRIX_SPARSE_DYNAMIC);
+ XA_DEBUG_ASSERT(M_in->m == M_in->n);
+ M = (NLSparseMatrix*)M_in;
+ result = NL_NEW(NLJacobiPreconditioner);
+ NL_CLEAR(result, NLJacobiPreconditioner);
+ result->m = M->m;
+ result->n = M->n;
+ result->type = NL_MATRIX_OTHER;
+ result->destroy_func = (NLDestroyMatrixFunc)nlJacobiPreconditionerDestroy;
+ result->mult_func = (NLMultMatrixVectorFunc)nlJacobiPreconditionerMult;
+ result->diag_inv = NL_NEW_ARRAY(double, M->n);
+ NL_CLEAR_ARRAY(double, result->diag_inv, M->n);
+ for (uint32_t i = 0; i < M->n; ++i)
+ result->diag_inv[i] = (M->diag[i] == 0.0) ? 1.0 : 1.0 / M->diag[i];
+ return (NLMatrix)result;
+}
+
+#define NL_NB_VARIABLES 0x101
+#define NL_MAX_ITERATIONS 0x103
+
+static void nlSolverParameteri(NLContext *context, uint32_t pname, int param)
+{
+ if (pname == NL_NB_VARIABLES) {
+ XA_DEBUG_ASSERT(param > 0);
+ context->nb_variables = (uint32_t)param;
+ } else if (pname == NL_MAX_ITERATIONS) {
+ XA_DEBUG_ASSERT(param > 0);
+ context->max_iterations = (uint32_t)param;
+ context->max_iterations_defined = true;
+ }
+}
+
+static void nlSetVariable(NLContext *context, uint32_t index, double value)
+{
+ XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
+ NL_BUFFER_ITEM(context->variable_buffer[0], index) = value;
+}
+
+static double nlGetVariable(NLContext *context, uint32_t index)
+{
+ XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
+ return NL_BUFFER_ITEM(context->variable_buffer[0], index);
+}
+
+static void nlLockVariable(NLContext *context, uint32_t index)
+{
+ XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
+ context->variable_is_locked[index] = true;
+}
+
+static void nlVariablesToVector(NLContext *context)
+{
+ uint32_t n = context->n;
+ XA_DEBUG_ASSERT(context->x);
+ for (uint32_t k = 0; k < context->nb_systems; ++k) {
+ for (uint32_t i = 0; i < context->nb_variables; ++i) {
+ if (!context->variable_is_locked[i]) {
+ uint32_t index = context->variable_index[i];
+ XA_DEBUG_ASSERT(index < context->n);
+ double value = NL_BUFFER_ITEM(context->variable_buffer[k], i);
+ context->x[index + k * n] = value;
+ }
+ }
+ }
+}
+
+static void nlVectorToVariables(NLContext *context)
+{
+ uint32_t n = context->n;
+ XA_DEBUG_ASSERT(context->x);
+ for (uint32_t k = 0; k < context->nb_systems; ++k) {
+ for (uint32_t i = 0; i < context->nb_variables; ++i) {
+ if (!context->variable_is_locked[i]) {
+ uint32_t index = context->variable_index[i];
+ XA_DEBUG_ASSERT(index < context->n);
+ double value = context->x[index + k * n];
+ NL_BUFFER_ITEM(context->variable_buffer[k], i) = value;
+ }
+ }
+ }
+}
+
+static void nlCoefficient(NLContext *context, uint32_t index, double value)
+{
+ XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
+ if (context->variable_is_locked[index]) {
+ /*
+ * Note: in al, indices are NLvariable indices,
+ * within [0..nb_variables-1]
+ */
+ nlRowColumnAppend(&(context->al), index, value);
+ } else {
+ /*
+ * Note: in af, indices are system indices,
+ * within [0..n-1]
+ */
+ nlRowColumnAppend(&(context->af), context->variable_index[index], value);
+ }
+}
+
+#define NL_SYSTEM 0x0
+#define NL_MATRIX 0x1
+#define NL_ROW 0x2
+
+static void nlBegin(NLContext *context, uint32_t prim)
+{
+ if (prim == NL_SYSTEM) {
+ XA_DEBUG_ASSERT(context->nb_variables > 0);
+ context->variable_buffer = NL_NEW_ARRAY(NLBufferBinding, context->nb_systems);
+ NL_CLEAR_ARRAY(NLBufferBinding, context->variable_buffer, context->nb_systems);
+ context->variable_value = NL_NEW_ARRAY(double, context->nb_variables * context->nb_systems);
+ NL_CLEAR_ARRAY(double, context->variable_value, context->nb_variables * context->nb_systems);
+ for (uint32_t k = 0; k < context->nb_systems; ++k) {
+ context->variable_buffer[k].base_address =
+ context->variable_value +
+ k * context->nb_variables;
+ context->variable_buffer[k].stride = sizeof(double);
+ }
+ context->variable_is_locked = NL_NEW_ARRAY(bool, context->nb_variables);
+ NL_CLEAR_ARRAY(bool, context->variable_is_locked, context->nb_variables);
+ context->variable_index = NL_NEW_ARRAY(uint32_t, context->nb_variables);
+ NL_CLEAR_ARRAY(uint32_t, context->variable_index, context->nb_variables);
+ } else if (prim == NL_MATRIX) {
+ if (context->M)
+ return;
+ uint32_t n = 0;
+ for (uint32_t i = 0; i < context->nb_variables; i++) {
+ if (!context->variable_is_locked[i]) {
+ context->variable_index[i] = n;
+ n++;
+ } else
+ context->variable_index[i] = (uint32_t)~0;
+ }
+ context->n = n;
+ if (!context->max_iterations_defined)
+ context->max_iterations = n * 5;
+ context->M = (NLMatrix)(NL_NEW(NLSparseMatrix));
+ NL_CLEAR(context->M, NLSparseMatrix);
+ nlSparseMatrixConstruct((NLSparseMatrix*)(context->M), n, n);
+ context->x = NL_NEW_ARRAY(double, n*context->nb_systems);
+ NL_CLEAR_ARRAY(double, context->x, n*context->nb_systems);
+ context->b = NL_NEW_ARRAY(double, n*context->nb_systems);
+ NL_CLEAR_ARRAY(double, context->b, n*context->nb_systems);
+ nlVariablesToVector(context);
+ nlRowColumnConstruct(&context->af);
+ nlRowColumnConstruct(&context->al);
+ context->current_row = 0;
+ } else if (prim == NL_ROW) {
+ nlRowColumnZero(&context->af);
+ nlRowColumnZero(&context->al);
+ }
+}
+
+static void nlEnd(NLContext *context, uint32_t prim)
+{
+ if (prim == NL_MATRIX) {
+ nlRowColumnClear(&context->af);
+ nlRowColumnClear(&context->al);
+ } else if (prim == NL_ROW) {
+ NLRowColumn* af = &context->af;
+ NLRowColumn* al = &context->al;
+ NLSparseMatrix* M = (NLSparseMatrix*)context->M;
+ double* b = context->b;
+ uint32_t nf = af->size;
+ uint32_t nl = al->size;
+ uint32_t n = context->n;
+ double S;
+ /*
+ * least_squares : we want to solve
+ * A'A x = A'b
+ */
+ for (uint32_t i = 0; i < nf; i++) {
+ for (uint32_t j = 0; j < nf; j++) {
+ nlSparseMatrixAdd(M, af->coeff[i].index, af->coeff[j].index, af->coeff[i].value * af->coeff[j].value);
+ }
+ }
+ for (uint32_t k = 0; k < context->nb_systems; ++k) {
+ S = 0.0;
+ for (uint32_t jj = 0; jj < nl; ++jj) {
+ uint32_t j = al->coeff[jj].index;
+ S += al->coeff[jj].value * NL_BUFFER_ITEM(context->variable_buffer[k], j);
+ }
+ for (uint32_t jj = 0; jj < nf; jj++)
+ b[k*n + af->coeff[jj].index] -= af->coeff[jj].value * S;
+ }
+ context->current_row++;
+ }
+}
+
+static bool nlSolve(NLContext *context)
+{
+ nlDeleteMatrix(context->P);
+ context->P = nlNewJacobiPreconditioner(context->M);
+ nlMatrixCompress(&context->M);
+ bool result = nlSolveIterative(context);
+ nlVectorToVariables(context);
+ return result;
+}
+} // namespace opennl
+
namespace raster {
-class ClippedTriangle {
+class ClippedTriangle
+{
public:
- ClippedTriangle(const Vector2 &a, const Vector2 &b, const Vector2 &c) {
+ ClippedTriangle(const Vector2 &a, const Vector2 &b, const Vector2 &c)
+ {
m_numVertices = 3;
m_activeVertexBuffer = 0;
m_verticesA[0] = a;
@@ -4077,21 +5191,23 @@ public:
m_verticesA[2] = c;
m_vertexBuffers[0] = m_verticesA;
m_vertexBuffers[1] = m_verticesB;
+ m_area = 0;
}
- void clipHorizontalPlane(float offset, float clipdirection) {
- Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
+ void clipHorizontalPlane(float offset, float clipdirection)
+ {
+ Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
m_activeVertexBuffer ^= 1;
Vector2 *v2 = m_vertexBuffers[m_activeVertexBuffer];
v[m_numVertices] = v[0];
- float dy2, dy1 = offset - v[0].y;
- int dy2in, dy1in = clipdirection * dy1 >= 0;
- uint32_t p = 0;
+ float dy2, dy1 = offset - v[0].y;
+ int dy2in, dy1in = clipdirection * dy1 >= 0;
+ uint32_t p = 0;
for (uint32_t k = 0; k < m_numVertices; k++) {
- dy2 = offset - v[k + 1].y;
+ dy2 = offset - v[k + 1].y;
dy2in = clipdirection * dy2 >= 0;
if (dy1in) v2[p++] = v[k];
- if (dy1in + dy2in == 1) { // not both in/out
+ if ( dy1in + dy2in == 1 ) { // not both in/out
float dx = v[k + 1].x - v[k].x;
float dy = v[k + 1].y - v[k].y;
v2[p++] = Vector2(v[k].x + dy1 * (dx / dy), offset);
@@ -4102,19 +5218,20 @@ public:
m_numVertices = p;
}
- void clipVerticalPlane(float offset, float clipdirection) {
- Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
+ void clipVerticalPlane(float offset, float clipdirection)
+ {
+ Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
m_activeVertexBuffer ^= 1;
Vector2 *v2 = m_vertexBuffers[m_activeVertexBuffer];
v[m_numVertices] = v[0];
- float dx2, dx1 = offset - v[0].x;
- int dx2in, dx1in = clipdirection * dx1 >= 0;
- uint32_t p = 0;
+ float dx2, dx1 = offset - v[0].x;
+ int dx2in, dx1in = clipdirection * dx1 >= 0;
+ uint32_t p = 0;
for (uint32_t k = 0; k < m_numVertices; k++) {
dx2 = offset - v[k + 1].x;
dx2in = clipdirection * dx2 >= 0;
if (dx1in) v2[p++] = v[k];
- if (dx1in + dx2in == 1) { // not both in/out
+ if ( dx1in + dx2in == 1 ) { // not both in/out
float dx = v[k + 1].x - v[k].x;
float dy = v[k + 1].y - v[k].y;
v2[p++] = Vector2(offset, v[k].y + dx1 * (dy / dx));
@@ -4125,8 +5242,9 @@ public:
m_numVertices = p;
}
- void computeArea() {
- Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
+ void computeArea()
+ {
+ Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
v[m_numVertices] = v[0];
m_area = 0;
float centroidx = 0, centroidy = 0;
@@ -4140,7 +5258,8 @@ public:
m_area = 0.5f * fabsf(m_area);
}
- void clipAABox(float x0, float y0, float x1, float y1) {
+ void clipAABox(float x0, float y0, float x1, float y1)
+ {
clipVerticalPlane(x0, -1);
clipHorizontalPlane(y0, -1);
clipVerticalPlane(x1, 1);
@@ -4148,7 +5267,8 @@ public:
computeArea();
}
- float area() const {
+ float area() const
+ {
return m_area;
}
@@ -4165,12 +5285,10 @@ private:
typedef bool (*SamplingCallback)(void *param, int x, int y);
/// A triangle for rasterization.
-struct Triangle {
- Triangle(const Vector2 &v0, const Vector2 &v1, const Vector2 &v2) {
- // Init vertices.
- this->v1 = v0;
- this->v2 = v2;
- this->v3 = v1;
+struct Triangle
+{
+ Triangle(const Vector2 &_v0, const Vector2 &_v1, const Vector2 &_v2) : v1(_v0), v2(_v2), v3(_v1)
+ {
// make sure every triangle is front facing.
flipBackface();
// Compute deltas.
@@ -4178,7 +5296,8 @@ struct Triangle {
computeUnitInwardNormals();
}
- bool isValid() {
+ bool isValid()
+ {
const Vector2 e0 = v3 - v1;
const Vector2 e1 = v2 - v1;
const float area = e0.y * e1.x - e1.y * e0.x;
@@ -4186,17 +5305,18 @@ struct Triangle {
}
// extents has to be multiple of BK_SIZE!!
- bool drawAA(const Vector2 &extents, SamplingCallback cb, void *param) {
- const float PX_INSIDE = 1.0f / sqrtf(2.0f);
- const float PX_OUTSIDE = -1.0f / sqrtf(2.0f);
+ bool drawAA(const Vector2 &extents, SamplingCallback cb, void *param)
+ {
+ const float PX_INSIDE = 1.0f/sqrtf(2.0f);
+ const float PX_OUTSIDE = -1.0f/sqrtf(2.0f);
const float BK_SIZE = 8;
- const float BK_INSIDE = sqrtf(BK_SIZE * BK_SIZE / 2.0f);
- const float BK_OUTSIDE = -sqrtf(BK_SIZE * BK_SIZE / 2.0f);
+ const float BK_INSIDE = sqrtf(BK_SIZE*BK_SIZE/2.0f);
+ const float BK_OUTSIDE = -sqrtf(BK_SIZE*BK_SIZE/2.0f);
// Bounding rectangle
float minx = floorf(max(min3(v1.x, v2.x, v3.x), 0.0f));
float miny = floorf(max(min3(v1.y, v2.y, v3.y), 0.0f));
- float maxx = ceilf(min(max3(v1.x, v2.x, v3.x), extents.x - 1.0f));
- float maxy = ceilf(min(max3(v1.y, v2.y, v3.y), extents.y - 1.0f));
+ float maxx = ceilf( min(max3(v1.x, v2.x, v3.x), extents.x - 1.0f));
+ float maxy = ceilf( min(max3(v1.y, v2.y, v3.y), extents.y - 1.0f));
// There's no reason to align the blocks to the viewport, instead we align them to the origin of the triangle bounds.
minx = floorf(minx);
miny = floorf(miny);
@@ -4221,9 +5341,9 @@ struct Triangle {
float bC = C2 + n2.x * xc + n2.y * yc;
float cC = C3 + n3.x * xc + n3.y * yc;
// Skip block when outside an edge
- if ((aC <= BK_OUTSIDE) || (bC <= BK_OUTSIDE) || (cC <= BK_OUTSIDE)) continue;
+ if ( (aC <= BK_OUTSIDE) || (bC <= BK_OUTSIDE) || (cC <= BK_OUTSIDE) ) continue;
// Accept whole block when totally covered
- if ((aC >= BK_INSIDE) && (bC >= BK_INSIDE) && (cC >= BK_INSIDE)) {
+ if ( (aC >= BK_INSIDE) && (bC >= BK_INSIDE) && (cC >= BK_INSIDE) ) {
for (float y = y0; y < y0 + BK_SIZE; y++) {
for (float x = x0; x < x0 + BK_SIZE; x++) {
if (!cb(param, (int)x, (int)y))
@@ -4266,9 +5386,10 @@ struct Triangle {
}
private:
- void flipBackface() {
+ void flipBackface()
+ {
// check if triangle is backfacing, if so, swap two vertices
- if (((v3.x - v1.x) * (v2.y - v1.y) - (v3.y - v1.y) * (v2.x - v1.x)) < 0) {
+ if ( ((v3.x - v1.x) * (v2.y - v1.y) - (v3.y - v1.y) * (v2.x - v1.x)) < 0 ) {
Vector2 hv = v1;
v1 = v2;
v2 = hv; // swap pos
@@ -4276,7 +5397,8 @@ private:
}
// compute unit inward normals for each edge.
- void computeUnitInwardNormals() {
+ void computeUnitInwardNormals()
+ {
n1 = v1 - v2;
n1 = Vector2(-n1.y, n1.x);
n1 = n1 * (1.0f / sqrtf(dot(n1, n1)));
@@ -4294,7 +5416,8 @@ private:
};
// Process the given triangle. Returns false if rasterization was interrupted by the callback.
-static bool drawTriangle(const Vector2 &extents, const Vector2 v[3], SamplingCallback cb, void *param) {
+static bool drawTriangle(const Vector2 &extents, const Vector2 v[3], SamplingCallback cb, void *param)
+{
Triangle tri(v[0], v[1], v[2]);
// @@ It would be nice to have a conservative drawing mode that enlarges the triangle extents by one texel and is able to handle degenerate triangles.
// @@ Maybe the simplest thing to do would be raster triangle edges.
@@ -4305,251 +5428,26 @@ static bool drawTriangle(const Vector2 &extents, const Vector2 v[3], SamplingCal
} // namespace raster
-// Full and sparse vector and matrix classes. BLAS subset.
-// Pseudo-BLAS interface.
-namespace sparse {
-
-/**
-* Sparse matrix class. The matrix is assumed to be sparse and to have
-* very few non-zero elements, for this reason it's stored in indexed
-* format. To multiply column vectors efficiently, the matrix stores
-* the elements in indexed-column order, there is a list of indexed
-* elements for each row of the matrix. As with the FullVector the
-* dimension of the matrix is constant.
-**/
-class Matrix {
-public:
- // An element of the sparse array.
- struct Coefficient {
- uint32_t x; // column
- float v; // value
- };
-
- Matrix(uint32_t d) :
- m_width(d), m_array(MemTag::Matrix) {
- m_array.resize(d);
- m_array.runCtors();
-#if XA_DEBUG_HEAP
- for (uint32_t i = 0; i < d; i++)
- m_array[i].setMemTag(MemTag::Matrix);
-#endif
- }
-
- Matrix(uint32_t w, uint32_t h) :
- m_width(w), m_array(MemTag::Matrix) {
- m_array.resize(h);
- m_array.runCtors();
-#if XA_DEBUG_HEAP
- for (uint32_t i = 0; i < h; i++)
- m_array[i].setMemTag(MemTag::Matrix);
-#endif
- }
-
- ~Matrix() {
- m_array.runDtors();
- }
-
- Matrix(const Matrix &m) = delete;
- Matrix &operator=(const Matrix &m) = delete;
- uint32_t width() const { return m_width; }
- uint32_t height() const { return m_array.size(); }
- bool isSquare() const { return width() == height(); }
-
- // x is column, y is row
- float getCoefficient(uint32_t x, uint32_t y) const {
- XA_DEBUG_ASSERT(x < width());
- XA_DEBUG_ASSERT(y < height());
- const uint32_t count = m_array[y].size();
- for (uint32_t i = 0; i < count; i++) {
- if (m_array[y][i].x == x) return m_array[y][i].v;
- }
- return 0.0f;
- }
-
- void setCoefficient(uint32_t x, uint32_t y, float f) {
- XA_DEBUG_ASSERT(x < width());
- XA_DEBUG_ASSERT(y < height());
- const uint32_t count = m_array[y].size();
- for (uint32_t i = 0; i < count; i++) {
- if (m_array[y][i].x == x) {
- m_array[y][i].v = f;
- return;
- }
- }
- if (f != 0.0f) {
- Coefficient c = { x, f };
- m_array[y].push_back(c);
- }
- }
-
- float dotRow(uint32_t y, const FullVector &v) const {
- XA_DEBUG_ASSERT(y < height());
- const uint32_t count = m_array[y].size();
- float sum = 0;
- for (uint32_t i = 0; i < count; i++) {
- sum += m_array[y][i].v * v[m_array[y][i].x];
- }
- return sum;
- }
-
- void madRow(uint32_t y, float alpha, FullVector &v) const {
- XA_DEBUG_ASSERT(y < height());
- const uint32_t count = m_array[y].size();
- for (uint32_t i = 0; i < count; i++) {
- v[m_array[y][i].x] += alpha * m_array[y][i].v;
- }
- }
-
- void clearRow(uint32_t y) {
- XA_DEBUG_ASSERT(y < height());
- m_array[y].clear();
- }
-
- const Array<Coefficient> &getRow(uint32_t y) const { return m_array[y]; }
-
-private:
- /// Number of columns.
- const uint32_t m_width;
-
- /// Array of matrix elements.
- Array<Array<Coefficient>> m_array;
-};
-
-// y = a * x + y
-static void saxpy(float a, const FullVector &x, FullVector &y) {
- XA_DEBUG_ASSERT(x.dimension() == y.dimension());
- const uint32_t dim = x.dimension();
- for (uint32_t i = 0; i < dim; i++) {
- y[i] += a * x[i];
- }
-}
-
-static void copy(const FullVector &x, FullVector &y) {
- XA_DEBUG_ASSERT(x.dimension() == y.dimension());
- const uint32_t dim = x.dimension();
- for (uint32_t i = 0; i < dim; i++) {
- y[i] = x[i];
- }
-}
-
-static void scal(float a, FullVector &x) {
- const uint32_t dim = x.dimension();
- for (uint32_t i = 0; i < dim; i++) {
- x[i] *= a;
- }
-}
-
-static float dot(const FullVector &x, const FullVector &y) {
- XA_DEBUG_ASSERT(x.dimension() == y.dimension());
- const uint32_t dim = x.dimension();
- float sum = 0;
- for (uint32_t i = 0; i < dim; i++) {
- sum += x[i] * y[i];
- }
- return sum;
-}
-
-// y = M * x
-static void mult(const Matrix &M, const FullVector &x, FullVector &y) {
- uint32_t w = M.width();
- uint32_t h = M.height();
- XA_DEBUG_ASSERT(w == x.dimension());
- XA_UNUSED(w);
- XA_DEBUG_ASSERT(h == y.dimension());
- for (uint32_t i = 0; i < h; i++)
- y[i] = M.dotRow(i, x);
-}
-
-// y = alpha*A*x + beta*y
-static void sgemv(float alpha, const Matrix &A, const FullVector &x, float beta, FullVector &y) {
- const uint32_t w = A.width();
- const uint32_t h = A.height();
- XA_DEBUG_ASSERT(w == x.dimension());
- XA_DEBUG_ASSERT(h == y.dimension());
- XA_UNUSED(w);
- XA_UNUSED(h);
- for (uint32_t i = 0; i < h; i++)
- y[i] = alpha * A.dotRow(i, x) + beta * y[i];
-}
-
-// dot y-row of A by x-column of B
-static float dotRowColumn(int y, const Matrix &A, int x, const Matrix &B) {
- const Array<Matrix::Coefficient> &row = A.getRow(y);
- const uint32_t count = row.size();
- float sum = 0.0f;
- for (uint32_t i = 0; i < count; i++) {
- const Matrix::Coefficient &c = row[i];
- sum += c.v * B.getCoefficient(x, c.x);
- }
- return sum;
-}
-
-static void transpose(const Matrix &A, Matrix &B) {
- XA_DEBUG_ASSERT(A.width() == B.height());
- XA_DEBUG_ASSERT(B.width() == A.height());
- const uint32_t w = A.width();
- for (uint32_t x = 0; x < w; x++) {
- B.clearRow(x);
- }
- const uint32_t h = A.height();
- for (uint32_t y = 0; y < h; y++) {
- const Array<Matrix::Coefficient> &row = A.getRow(y);
- const uint32_t count = row.size();
- for (uint32_t i = 0; i < count; i++) {
- const Matrix::Coefficient &c = row[i];
- XA_DEBUG_ASSERT(c.x < w);
- B.setCoefficient(y, c.x, c.v);
- }
- }
-}
-
-static void sgemm(float alpha, const Matrix &A, const Matrix &B, float beta, Matrix &C) {
- const uint32_t w = C.width();
- const uint32_t h = C.height();
-#if XA_DEBUG
- const uint32_t aw = A.width();
- const uint32_t ah = A.height();
- const uint32_t bw = B.width();
- const uint32_t bh = B.height();
- XA_DEBUG_ASSERT(aw == bh);
- XA_DEBUG_ASSERT(bw == ah);
- XA_DEBUG_ASSERT(w == bw);
- XA_DEBUG_ASSERT(h == ah);
-#endif
- for (uint32_t y = 0; y < h; y++) {
- for (uint32_t x = 0; x < w; x++) {
- float c = beta * C.getCoefficient(x, y);
- // dot y-row of A by x-column of B.
- c += alpha * dotRowColumn(y, A, x, B);
- C.setCoefficient(x, y, c);
- }
- }
-}
-
-// C = A * B
-static void mult(const Matrix &A, const Matrix &B, Matrix &C) {
- sgemm(1.0f, A, B, 0.0f, C);
-}
-
-} // namespace sparse
-
namespace segment {
// - Insertion is o(n)
// - Smallest element goes at the end, so that popping it is o(1).
-struct CostQueue {
- CostQueue(uint32_t size = UINT32_MAX) :
- m_maxSize(size), m_pairs(MemTag::SegmentAtlasChartCandidates) {}
+struct CostQueue
+{
+ CostQueue(uint32_t size = UINT32_MAX) : m_maxSize(size), m_pairs(MemTag::SegmentAtlasChartCandidates) {}
- float peekCost() const {
+ float peekCost() const
+ {
return m_pairs.back().cost;
}
- uint32_t peekFace() const {
+ uint32_t peekFace() const
+ {
return m_pairs.back().face;
}
- void push(float cost, uint32_t face) {
+ void push(float cost, uint32_t face)
+ {
const Pair p = { cost, face };
if (m_pairs.isEmpty() || cost < peekCost())
m_pairs.push_back(p);
@@ -4566,25 +5464,29 @@ struct CostQueue {
}
}
- uint32_t pop() {
+ uint32_t pop()
+ {
XA_DEBUG_ASSERT(!m_pairs.isEmpty());
uint32_t f = m_pairs.back().face;
m_pairs.pop_back();
return f;
}
- XA_INLINE void clear() {
+ XA_INLINE void clear()
+ {
m_pairs.clear();
}
- XA_INLINE uint32_t count() const {
+ XA_INLINE uint32_t count() const
+ {
return m_pairs.size();
}
private:
const uint32_t m_maxSize;
- struct Pair {
+ struct Pair
+ {
float cost;
uint32_t face;
};
@@ -4592,86 +5494,92 @@ private:
Array<Pair> m_pairs;
};
-struct Chart {
- Chart() :
- faces(MemTag::SegmentAtlasChartFaces) {}
-
- int id = -1;
- Basis basis; // Best fit normal.
- float area = 0.0f;
- float boundaryLength = 0.0f;
- Vector3 centroidSum = Vector3(0.0f); // Sum of chart face centroids.
- Vector3 centroid = Vector3(0.0f); // Average centroid of chart faces.
- Array<uint32_t> seeds;
- Array<uint32_t> faces;
- Array<uint32_t> failedPlanarRegions;
- CostQueue candidates;
-};
-
-struct Atlas {
- Atlas() :
- m_edgeLengths(MemTag::SegmentAtlasMeshData), m_faceAreas(MemTag::SegmentAtlasMeshData), m_faceNormals(MemTag::SegmentAtlasMeshData), m_texcoords(MemTag::SegmentAtlasMeshData), m_bestTriangles(10), m_nextPlanarRegionFace(MemTag::SegmentAtlasPlanarRegions), m_facePlanarRegionId(MemTag::SegmentAtlasPlanarRegions) {}
-
- ~Atlas() {
- const uint32_t chartCount = m_charts.size();
- for (uint32_t i = 0; i < chartCount; i++) {
- m_charts[i]->~Chart();
- XA_FREE(m_charts[i]);
- }
- }
+struct AtlasData
+{
+ ChartOptions options;
+ const Mesh *mesh = nullptr;
+ Array<float> edgeDihedralAngles;
+ Array<float> edgeLengths;
+ Array<float> faceAreas;
+ Array<Vector3> faceNormals;
+ BitArray isFaceInChart;
- uint32_t facesLeft() const { return m_facesLeft; }
- uint32_t chartCount() const { return m_charts.size(); }
- const Array<uint32_t> &chartFaces(uint32_t i) const { return m_charts[i]->faces; }
- const Basis &chartBasis(uint32_t chartIndex) const { return m_charts[chartIndex]->basis; }
+ AtlasData() : edgeDihedralAngles(MemTag::SegmentAtlasMeshData), edgeLengths(MemTag::SegmentAtlasMeshData), faceAreas(MemTag::SegmentAtlasMeshData), faceNormals(MemTag::SegmentAtlasMeshData) {}
- void reset(uint32_t meshId, uint32_t chartGroupId, const Mesh *mesh, const ChartOptions &options) {
- XA_UNUSED(meshId);
- XA_UNUSED(chartGroupId);
- XA_PROFILE_START(buildAtlasInit)
- m_mesh = mesh;
- const uint32_t faceCount = m_mesh->faceCount();
- m_facesLeft = faceCount;
- m_options = options;
- m_rand.reset();
- const uint32_t chartCount = m_charts.size();
- for (uint32_t i = 0; i < chartCount; i++) {
- m_charts[i]->~Chart();
- XA_FREE(m_charts[i]);
- }
- m_charts.clear();
- m_faceCharts.resize(faceCount);
- m_faceCharts.setAll(-1);
- m_texcoords.resize(faceCount * 3);
- // Precompute edge lengths and face areas.
- const uint32_t edgeCount = m_mesh->edgeCount();
- m_edgeLengths.resize(edgeCount);
- m_faceAreas.resize(faceCount);
- m_faceNormals.resize(faceCount);
+ void compute()
+ {
+ const uint32_t faceCount = mesh->faceCount();
+ const uint32_t edgeCount = mesh->edgeCount();
+ edgeDihedralAngles.resize(edgeCount);
+ edgeLengths.resize(edgeCount);
+ faceAreas.resize(faceCount);
+ faceNormals.resize(faceCount);
+ isFaceInChart.resize(faceCount);
+ isFaceInChart.zeroOutMemory();
for (uint32_t f = 0; f < faceCount; f++) {
for (uint32_t i = 0; i < 3; i++) {
const uint32_t edge = f * 3 + i;
- const Vector3 &p0 = mesh->position(m_mesh->vertexAt(meshEdgeIndex0(edge)));
- const Vector3 &p1 = mesh->position(m_mesh->vertexAt(meshEdgeIndex1(edge)));
- m_edgeLengths[edge] = length(p1 - p0);
- XA_DEBUG_ASSERT(m_edgeLengths[edge] > 0.0f);
+ const Vector3 &p0 = mesh->position(mesh->vertexAt(meshEdgeIndex0(edge)));
+ const Vector3 &p1 = mesh->position(mesh->vertexAt(meshEdgeIndex1(edge)));
+ edgeLengths[edge] = length(p1 - p0);
+ XA_DEBUG_ASSERT(edgeLengths[edge] > 0.0f);
+ }
+ faceAreas[f] = mesh->computeFaceArea(f);
+ XA_DEBUG_ASSERT(faceAreas[f] > 0.0f);
+ faceNormals[f] = mesh->computeFaceNormal(f);
+ }
+ for (uint32_t face = 0; face < faceCount; face++) {
+ for (uint32_t i = 0; i < 3; i++) {
+ const uint32_t edge = face * 3 + i;
+ const uint32_t oedge = mesh->oppositeEdge(edge);
+ if (oedge == UINT32_MAX)
+ edgeDihedralAngles[edge] = FLT_MAX;
+ else {
+ const uint32_t oface = meshEdgeFace(oedge);
+ edgeDihedralAngles[edge] = edgeDihedralAngles[oedge] = dot(faceNormals[face], faceNormals[oface]);
+ }
}
- m_faceAreas[f] = m_mesh->computeFaceArea(f);
- XA_DEBUG_ASSERT(m_faceAreas[f] > 0.0f);
- m_faceNormals[f] = m_mesh->computeFaceNormal(f);
}
+ }
+};
+
+#if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
+static uint32_t s_planarRegionsCurrentRegion;
+static uint32_t s_planarRegionsCurrentVertex;
+#endif
+
+struct PlanarCharts
+{
+ PlanarCharts(AtlasData &data) : m_data(data), m_nextRegionFace(MemTag::SegmentAtlasPlanarRegions), m_faceToRegionId(MemTag::SegmentAtlasPlanarRegions) {}
+ const Basis &chartBasis(uint32_t chartIndex) const { return m_chartBasis[chartIndex]; }
+ uint32_t chartCount() const { return m_charts.size(); }
+
+ ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const
+ {
+ const Chart &chart = m_charts[chartIndex];
+ return ConstArrayView<uint32_t>(&m_chartFaces[chart.firstFace], chart.faceCount);
+ }
+
+ uint32_t regionIdFromFace(uint32_t face) const { return m_faceToRegionId[face]; }
+ uint32_t nextRegionFace(uint32_t face) const { return m_nextRegionFace[face]; }
+ float regionArea(uint32_t region) const { return m_regionAreas[region]; }
+
+ void compute()
+ {
+ const uint32_t faceCount = m_data.mesh->faceCount();
// Precompute regions of coplanar incident faces.
- m_nextPlanarRegionFace.resize(faceCount);
- m_facePlanarRegionId.resize(faceCount);
+ m_regionFirstFace.clear();
+ m_nextRegionFace.resize(faceCount);
+ m_faceToRegionId.resize(faceCount);
for (uint32_t f = 0; f < faceCount; f++) {
- m_nextPlanarRegionFace[f] = f;
- m_facePlanarRegionId[f] = UINT32_MAX;
+ m_nextRegionFace[f] = f;
+ m_faceToRegionId[f] = UINT32_MAX;
}
Array<uint32_t> faceStack;
faceStack.reserve(min(faceCount, 16u));
- uint32_t planarRegionCount = 0;
+ uint32_t regionCount = 0;
for (uint32_t f = 0; f < faceCount; f++) {
- if (m_nextPlanarRegionFace[f] != f)
+ if (m_nextRegionFace[f] != f)
continue; // Already assigned.
faceStack.clear();
faceStack.push_back(f);
@@ -4679,48 +5587,207 @@ struct Atlas {
if (faceStack.isEmpty())
break;
const uint32_t face = faceStack.back();
- m_facePlanarRegionId[face] = planarRegionCount;
+ m_faceToRegionId[face] = regionCount;
faceStack.pop_back();
- for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
const uint32_t oface = it.oppositeFace();
if (it.isBoundary())
continue;
- if (m_nextPlanarRegionFace[oface] != oface)
+ if (m_nextRegionFace[oface] != oface)
continue; // Already assigned.
- if (!equal(dot(m_faceNormals[face], m_faceNormals[oface]), 1.0f, kEpsilon))
+ if (!equal(dot(m_data.faceNormals[face], m_data.faceNormals[oface]), 1.0f, kEpsilon))
continue; // Not coplanar.
- const uint32_t next = m_nextPlanarRegionFace[face];
- m_nextPlanarRegionFace[face] = oface;
- m_nextPlanarRegionFace[oface] = next;
- m_facePlanarRegionId[oface] = planarRegionCount;
+ const uint32_t next = m_nextRegionFace[face];
+ m_nextRegionFace[face] = oface;
+ m_nextRegionFace[oface] = next;
+ m_faceToRegionId[oface] = regionCount;
faceStack.push_back(oface);
}
}
- planarRegionCount++;
+ m_regionFirstFace.push_back(f);
+ regionCount++;
}
#if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
- char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_planar_regions.obj", meshId, chartGroupId);
- FILE *file;
- XA_FOPEN(file, filename, "w");
- if (file) {
- m_mesh->writeObjVertices(file);
- fprintf(file, "s off\n");
- for (uint32_t i = 0; i < planarRegionCount; i++) {
- fprintf(file, "o region%u\n", i);
- for (uint32_t j = 0; j < faceCount; j++) {
- if (m_facePlanarRegionId[j] == i)
- m_mesh->writeObjFace(file, j);
+ static std::mutex s_mutex;
+ {
+ std::lock_guard<std::mutex> lock(s_mutex);
+ FILE *file;
+ XA_FOPEN(file, "debug_mesh_planar_regions.obj", s_planarRegionsCurrentRegion == 0 ? "w" : "a");
+ if (file) {
+ m_data.mesh->writeObjVertices(file);
+ fprintf(file, "s off\n");
+ for (uint32_t i = 0; i < regionCount; i++) {
+ fprintf(file, "o region%u\n", s_planarRegionsCurrentRegion);
+ for (uint32_t j = 0; j < faceCount; j++) {
+ if (m_faceToRegionId[j] == i)
+ m_data.mesh->writeObjFace(file, j, s_planarRegionsCurrentVertex);
+ }
+ s_planarRegionsCurrentRegion++;
}
+ s_planarRegionsCurrentVertex += m_data.mesh->vertexCount();
+ fclose(file);
}
- fclose(file);
}
#endif
- XA_PROFILE_END(buildAtlasInit)
+ // Precompute planar region areas.
+ m_regionAreas.resize(regionCount);
+ m_regionAreas.zeroOutMemory();
+ for (uint32_t f = 0; f < faceCount; f++)
+ m_regionAreas[m_faceToRegionId[f]] += m_data.faceAreas[f];
+ // Create charts from suitable planar regions.
+ // The dihedral angle of all boundary edges must be >= 90 degrees.
+ m_charts.clear();
+ m_chartFaces.clear();
+ for (uint32_t region = 0; region < regionCount; region++) {
+ const uint32_t firstRegionFace = m_regionFirstFace[region];
+ uint32_t face = firstRegionFace;
+ bool createChart = true;
+ do {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
+ if (it.isBoundary())
+ continue; // Ignore mesh boundary edges.
+ const uint32_t oface = it.oppositeFace();
+ if (m_faceToRegionId[oface] == region)
+ continue; // Ignore internal edges.
+ const float angle = m_data.edgeDihedralAngles[it.edge()];
+ if (angle > 0.0f && angle < FLT_MAX) { // FLT_MAX on boundaries.
+ createChart = false;
+ break;
+ }
+ }
+ if (!createChart)
+ break;
+ face = m_nextRegionFace[face];
+ }
+ while (face != firstRegionFace);
+ // Create a chart.
+ if (createChart) {
+ Chart chart;
+ chart.firstFace = m_chartFaces.size();
+ chart.faceCount = 0;
+ face = firstRegionFace;
+ do {
+ m_data.isFaceInChart.set(face);
+ m_chartFaces.push_back(face);
+ chart.faceCount++;
+ face = m_nextRegionFace[face];
+ }
+ while (face != firstRegionFace);
+ m_charts.push_back(chart);
+ }
+ }
+ // Compute basis for each chart using the first face normal (all faces have the same normal).
+ m_chartBasis.resize(m_charts.size());
+ for (uint32_t c = 0; c < m_charts.size(); c++)
+ {
+ const uint32_t face = m_chartFaces[m_charts[c].firstFace];
+ Basis &basis = m_chartBasis[c];
+ basis.normal = m_data.faceNormals[face];
+ basis.tangent = Basis::computeTangent(basis.normal);
+ basis.bitangent = Basis::computeBitangent(basis.normal, basis.tangent);
+ }
+ }
+
+private:
+ struct Chart
+ {
+ uint32_t firstFace, faceCount;
+ };
+
+ AtlasData &m_data;
+ Array<uint32_t> m_regionFirstFace;
+ Array<uint32_t> m_nextRegionFace;
+ Array<uint32_t> m_faceToRegionId;
+ Array<float> m_regionAreas;
+ Array<Chart> m_charts;
+ Array<uint32_t> m_chartFaces;
+ Array<Basis> m_chartBasis;
+};
+
+struct ClusteredCharts
+{
+ ClusteredCharts(AtlasData &data, const PlanarCharts &planarCharts) : m_data(data), m_planarCharts(planarCharts), m_texcoords(MemTag::SegmentAtlasMeshData), m_bestTriangles(10), m_placingSeeds(false) {}
+
+ ~ClusteredCharts()
+ {
+ const uint32_t chartCount = m_charts.size();
+ for (uint32_t i = 0; i < chartCount; i++) {
+ m_charts[i]->~Chart();
+ XA_FREE(m_charts[i]);
+ }
}
- void placeSeeds(float threshold) {
- XA_PROFILE_START(buildAtlasPlaceSeeds)
+ uint32_t chartCount() const { return m_charts.size(); }
+ ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const { return m_charts[chartIndex]->faces; }
+ const Basis &chartBasis(uint32_t chartIndex) const { return m_charts[chartIndex]->basis; }
+
+ void compute()
+ {
+ const uint32_t faceCount = m_data.mesh->faceCount();
+ m_facesLeft = 0;
+ for (uint32_t i = 0; i < faceCount; i++) {
+ if (!m_data.isFaceInChart.get(i))
+ m_facesLeft++;
+ }
+ const uint32_t chartCount = m_charts.size();
+ for (uint32_t i = 0; i < chartCount; i++) {
+ m_charts[i]->~Chart();
+ XA_FREE(m_charts[i]);
+ }
+ m_charts.clear();
+ m_faceCharts.resize(faceCount);
+ m_faceCharts.fill(-1);
+ m_texcoords.resize(faceCount * 3);
+ if (m_facesLeft == 0)
+ return;
+ // Create initial charts greedely.
+ placeSeeds(m_data.options.maxCost * 0.5f);
+ if (m_data.options.maxIterations == 0) {
+ XA_DEBUG_ASSERT(m_facesLeft == 0);
+ return;
+ }
+ relocateSeeds();
+ resetCharts();
+ // Restart process growing charts in parallel.
+ uint32_t iteration = 0;
+ for (;;) {
+ growCharts(m_data.options.maxCost);
+ // When charts cannot grow more: fill holes, merge charts, relocate seeds and start new iteration.
+ fillHoles(m_data.options.maxCost * 0.5f);
+#if XA_MERGE_CHARTS
+ mergeCharts();
+#endif
+ if (++iteration == m_data.options.maxIterations)
+ break;
+ if (!relocateSeeds())
+ break;
+ resetCharts();
+ }
+ // Make sure no holes are left!
+ XA_DEBUG_ASSERT(m_facesLeft == 0);
+ }
+
+private:
+ struct Chart
+ {
+ Chart() : faces(MemTag::SegmentAtlasChartFaces) {}
+
+ int id = -1;
+ Basis basis; // Best fit normal.
+ float area = 0.0f;
+ float boundaryLength = 0.0f;
+ Vector3 centroidSum = Vector3(0.0f); // Sum of chart face centroids.
+ Vector3 centroid = Vector3(0.0f); // Average centroid of chart faces.
+ Array<uint32_t> faces;
+ Array<uint32_t> failedPlanarRegions;
+ CostQueue candidates;
+ uint32_t seed;
+ };
+
+ void placeSeeds(float threshold)
+ {
+ XA_PROFILE_START(clusteredChartsPlaceSeeds)
+ m_placingSeeds = true;
// Instead of using a predefiened number of seeds:
// - Add seeds one by one, growing chart until a certain treshold.
// - Undo charts and restart growing process.
@@ -4728,13 +5795,15 @@ struct Atlas {
// - those points can be found using a simple flood filling algorithm.
// - how do we weight the probabilities?
while (m_facesLeft > 0)
- createRandomChart(threshold);
- XA_PROFILE_END(buildAtlasPlaceSeeds)
+ createChart(threshold);
+ m_placingSeeds = false;
+ XA_PROFILE_END(clusteredChartsPlaceSeeds)
}
// Returns true if any of the charts can grow more.
- void growCharts(float threshold) {
- XA_PROFILE_START(buildAtlasGrowCharts)
+ void growCharts(float threshold)
+ {
+ XA_PROFILE_START(clusteredChartsGrow)
for (;;) {
if (m_facesLeft == 0)
break;
@@ -4752,7 +5821,7 @@ struct Atlas {
break;
cost = chart->candidates.peekCost();
face = chart->candidates.peekFace();
- if (m_faceCharts[face] == -1)
+ if (!m_data.isFaceInChart.get(face))
break;
else {
// Face belongs to another chart. Pop from queue so the next best candidate can be retrieved.
@@ -4774,21 +5843,28 @@ struct Atlas {
Chart *chart = m_charts[bestChart];
chart->candidates.pop(); // Pop the selected candidate from the queue.
if (!addFaceToChart(chart, bestFace))
- chart->failedPlanarRegions.push_back(m_facePlanarRegionId[bestFace]);
+ chart->failedPlanarRegions.push_back(m_planarCharts.regionIdFromFace(bestFace));
}
- XA_PROFILE_END(buildAtlasGrowCharts)
+ XA_PROFILE_END(clusteredChartsGrow)
}
- void resetCharts() {
- XA_PROFILE_START(buildAtlasResetCharts)
- const uint32_t faceCount = m_mesh->faceCount();
- for (uint32_t i = 0; i < faceCount; i++)
+ void resetCharts()
+ {
+ XA_PROFILE_START(clusteredChartsReset)
+ const uint32_t faceCount = m_data.mesh->faceCount();
+ for (uint32_t i = 0; i < faceCount; i++) {
+ if (m_faceCharts[i] != -1)
+ m_data.isFaceInChart.unset(i);
m_faceCharts[i] = -1;
- m_facesLeft = faceCount;
+ }
+ m_facesLeft = 0;
+ for (uint32_t i = 0; i < faceCount; i++) {
+ if (!m_data.isFaceInChart.get(i))
+ m_facesLeft++;
+ }
const uint32_t chartCount = m_charts.size();
for (uint32_t i = 0; i < chartCount; i++) {
Chart *chart = m_charts[i];
- const uint32_t seed = chart->seeds.back();
chart->area = 0.0f;
chart->boundaryLength = 0.0f;
chart->basis.normal = Vector3(0.0f);
@@ -4799,13 +5875,14 @@ struct Atlas {
chart->faces.clear();
chart->candidates.clear();
chart->failedPlanarRegions.clear();
- addFaceToChart(chart, seed);
+ addFaceToChart(chart, chart->seed);
}
- XA_PROFILE_END(buildAtlasResetCharts)
+ XA_PROFILE_END(clusteredChartsReset)
}
- bool relocateSeeds() {
- XA_PROFILE_START(buildAtlasRelocateSeeds)
+ bool relocateSeeds()
+ {
+ XA_PROFILE_START(clusteredChartsRelocateSeeds)
bool anySeedChanged = false;
const uint32_t chartCount = m_charts.size();
for (uint32_t i = 0; i < chartCount; i++) {
@@ -4813,20 +5890,22 @@ struct Atlas {
anySeedChanged = true;
}
}
- XA_PROFILE_END(buildAtlasRelocateSeeds)
+ XA_PROFILE_END(clusteredChartsRelocateSeeds)
return anySeedChanged;
}
- void fillHoles(float threshold) {
- XA_PROFILE_START(buildAtlasFillHoles)
+ void fillHoles(float threshold)
+ {
+ XA_PROFILE_START(clusteredChartsFillHoles)
while (m_facesLeft > 0)
- createRandomChart(threshold);
- XA_PROFILE_END(buildAtlasFillHoles)
+ createChart(threshold);
+ XA_PROFILE_END(clusteredChartsFillHoles)
}
#if XA_MERGE_CHARTS
- void mergeCharts() {
- XA_PROFILE_START(buildAtlasMergeCharts)
+ void mergeCharts()
+ {
+ XA_PROFILE_START(clusteredChartsMerge)
const uint32_t chartCount = m_charts.size();
// Merge charts progressively until there's none left to merge.
for (;;) {
@@ -4845,13 +5924,15 @@ struct Atlas {
const uint32_t faceCount = chart->faces.size();
for (uint32_t i = 0; i < faceCount; i++) {
const uint32_t f = chart->faces[i];
- for (Mesh::FaceEdgeIterator it(m_mesh, f); !it.isDone(); it.advance()) {
- const float l = m_edgeLengths[it.edge()];
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, f); !it.isDone(); it.advance()) {
+ const float l = m_data.edgeLengths[it.edge()];
if (it.isBoundary()) {
externalBoundaryLength += l;
} else {
const int neighborChart = m_faceCharts[it.oppositeFace()];
- if (m_charts[neighborChart] != chart) {
+ if (neighborChart == -1)
+ externalBoundaryLength += l;
+ else if (m_charts[neighborChart] != chart) {
if ((it.isSeam() && (isNormalSeam(it.edge()) || it.isTextureSeam()))) {
externalBoundaryLength += l;
} else {
@@ -4876,14 +5957,14 @@ struct Atlas {
if (dot(chart2->basis.normal, chart->basis.normal) < XA_MERGE_CHARTS_MIN_NORMAL_DEVIATION)
continue;
// Obey max chart area and boundary length.
- if (m_options.maxChartArea > 0.0f && chart->area + chart2->area > m_options.maxChartArea)
+ if (m_data.options.maxChartArea > 0.0f && chart->area + chart2->area > m_data.options.maxChartArea)
continue;
- if (m_options.maxBoundaryLength > 0.0f && chart->boundaryLength + chart2->boundaryLength - m_sharedBoundaryLengthsNoSeams[cc] > m_options.maxBoundaryLength)
+ if (m_data.options.maxBoundaryLength > 0.0f && chart->boundaryLength + chart2->boundaryLength - m_sharedBoundaryLengthsNoSeams[cc] > m_data.options.maxBoundaryLength)
continue;
// Merge if chart2 has a single face.
// chart1 must have more than 1 face.
// chart2 area must be <= 10% of chart1 area.
- if (m_sharedBoundaryLengthsNoSeams[cc] > 0.0f && chart->faces.size() > 1 && chart2->faces.size() == 1 && chart2->area <= chart->area * 0.1f)
+ if (m_sharedBoundaryLengthsNoSeams[cc] > 0.0f && chart->faces.size() > 1 && chart2->faces.size() == 1 && chart2->area <= chart->area * 0.1f)
goto merge;
// Merge if chart2 has two faces (probably a quad), and chart1 bounds at least 2 of its edges.
if (chart2->faces.size() == 2 && m_sharedBoundaryEdgeCountNoSeams[cc] >= 2)
@@ -4891,8 +5972,8 @@ struct Atlas {
// Merge if chart2 is wholely inside chart1, ignoring seams.
if (m_sharedBoundaryLengthsNoSeams[cc] > 0.0f && equal(m_sharedBoundaryLengthsNoSeams[cc], chart2->boundaryLength, kEpsilon))
goto merge;
- if (m_sharedBoundaryLengths[cc] > 0.2f * max(0.0f, chart->boundaryLength - externalBoundaryLength) ||
- m_sharedBoundaryLengths[cc] > 0.75f * chart2->boundaryLength)
+ if (m_sharedBoundaryLengths[cc] > 0.2f * max(0.0f, chart->boundaryLength - externalBoundaryLength) ||
+ m_sharedBoundaryLengths[cc] > 0.75f * chart2->boundaryLength)
goto merge;
continue;
merge:
@@ -4925,55 +6006,64 @@ struct Atlas {
c++;
}
}
- XA_PROFILE_END(buildAtlasMergeCharts)
+ XA_PROFILE_END(clusteredChartsMerge)
}
#endif
private:
- void createRandomChart(float threshold) {
+ void createChart(float threshold)
+ {
Chart *chart = XA_NEW(MemTag::Default, Chart);
chart->id = (int)m_charts.size();
m_charts.push_back(chart);
- // Pick random face that is not used by any chart yet.
- uint32_t face = m_rand.getRange(m_mesh->faceCount() - 1);
- while (m_faceCharts[face] != -1) {
- if (++face >= m_mesh->faceCount())
- face = 0;
- }
- chart->seeds.push_back(face);
- addFaceToChart(chart, face);
+ // Pick a face not used by any chart yet, belonging to the largest planar region.
+ chart->seed = 0;
+ float largestArea = 0.0f;
+ for (uint32_t f = 0; f < m_data.mesh->faceCount(); f++) {
+ if (m_data.isFaceInChart.get(f))
+ continue;
+ const float area = m_planarCharts.regionArea(m_planarCharts.regionIdFromFace(f));
+ if (area > largestArea) {
+ largestArea = area;
+ chart->seed = f;
+ }
+ }
+ addFaceToChart(chart, chart->seed);
// Grow the chart as much as possible within the given threshold.
for (;;) {
if (chart->candidates.count() == 0 || chart->candidates.peekCost() > threshold)
break;
const uint32_t f = chart->candidates.pop();
- if (m_faceCharts[f] != -1)
+ if (m_data.isFaceInChart.get(f))
continue;
if (!addFaceToChart(chart, f)) {
- chart->failedPlanarRegions.push_back(m_facePlanarRegionId[f]);
+ chart->failedPlanarRegions.push_back(m_planarCharts.regionIdFromFace(f));
continue;
}
}
}
- bool isChartBoundaryEdge(const Chart *chart, uint32_t edge) const {
- const uint32_t oppositeEdge = m_mesh->oppositeEdge(edge);
+ bool isChartBoundaryEdge(const Chart *chart, uint32_t edge) const
+ {
+ const uint32_t oppositeEdge = m_data.mesh->oppositeEdge(edge);
const uint32_t oppositeFace = meshEdgeFace(oppositeEdge);
return oppositeEdge == UINT32_MAX || m_faceCharts[oppositeFace] != chart->id;
}
- bool computeChartBasis(Chart *chart, Basis *basis) {
+ bool computeChartBasis(Chart *chart, Basis *basis)
+ {
const uint32_t faceCount = chart->faces.size();
m_tempPoints.resize(chart->faces.size() * 3);
for (uint32_t i = 0; i < faceCount; i++) {
const uint32_t f = chart->faces[i];
for (uint32_t j = 0; j < 3; j++)
- m_tempPoints[i * 3 + j] = m_mesh->position(m_mesh->vertexAt(f * 3 + j));
+ m_tempPoints[i * 3 + j] = m_data.mesh->position(m_data.mesh->vertexAt(f * 3 + j));
}
return Fit::computeBasis(m_tempPoints.data(), m_tempPoints.size(), basis);
}
- bool isFaceFlipped(uint32_t face) const {
+ bool isFaceFlipped(uint32_t face) const
+ {
const Vector2 &v1 = m_texcoords[face * 3 + 0];
const Vector2 &v2 = m_texcoords[face * 3 + 1];
const Vector2 &v3 = m_texcoords[face * 3 + 2];
@@ -4981,20 +6071,22 @@ private:
return parametricArea < 0.0f;
}
- void parameterizeChart(const Chart *chart) {
+ void parameterizeChart(const Chart *chart)
+ {
const uint32_t faceCount = chart->faces.size();
for (uint32_t i = 0; i < faceCount; i++) {
const uint32_t face = chart->faces[i];
for (uint32_t j = 0; j < 3; j++) {
const uint32_t offset = face * 3 + j;
- const Vector3 &pos = m_mesh->position(m_mesh->vertexAt(offset));
+ const Vector3 &pos = m_data.mesh->position(m_data.mesh->vertexAt(offset));
m_texcoords[offset] = Vector2(dot(chart->basis.tangent, pos), dot(chart->basis.bitangent, pos));
}
}
}
// m_faceCharts for the chart faces must be set to the chart ID. Needed to compute boundary edges.
- bool isChartParameterizationValid(const Chart *chart) {
+ bool isChartParameterizationValid(const Chart *chart)
+ {
const uint32_t faceCount = chart->faces.size();
// Check for flipped faces in the parameterization. OK if all are flipped.
uint32_t flippedFaceCount = 0;
@@ -5005,6 +6097,8 @@ private:
if (flippedFaceCount != 0 && flippedFaceCount != faceCount)
return false;
// Check for boundary intersection in the parameterization.
+ XA_PROFILE_START(clusteredChartsPlaceSeedsBoundaryIntersection)
+ XA_PROFILE_START(clusteredChartsGrowBoundaryIntersection)
m_boundaryGrid.reset(m_texcoords.data());
for (uint32_t i = 0; i < faceCount; i++) {
const uint32_t f = chart->faces[i];
@@ -5014,22 +6108,30 @@ private:
m_boundaryGrid.append(edge);
}
}
- if (m_boundaryGrid.intersectSelf(m_mesh->epsilon()))
+ const bool intersection = m_boundaryGrid.intersect(m_data.mesh->epsilon());
+#if XA_PROFILE
+ if (m_placingSeeds)
+ XA_PROFILE_END(clusteredChartsPlaceSeedsBoundaryIntersection)
+ else
+ XA_PROFILE_END(clusteredChartsGrowBoundaryIntersection)
+#endif
+ if (intersection)
return false;
return true;
}
- bool addFaceToChart(Chart *chart, uint32_t face) {
- XA_DEBUG_ASSERT(m_faceCharts[face] == -1);
+ bool addFaceToChart(Chart *chart, uint32_t face)
+ {
+ XA_DEBUG_ASSERT(!m_data.isFaceInChart.get(face));
const uint32_t oldFaceCount = chart->faces.size();
const bool firstFace = oldFaceCount == 0;
// Append the face and any coplanar connected faces to the chart faces array.
chart->faces.push_back(face);
- uint32_t coplanarFace = m_nextPlanarRegionFace[face];
- while (coplanarFace != face) {
- XA_DEBUG_ASSERT(m_faceCharts[coplanarFace] == -1);
+ uint32_t coplanarFace = m_planarCharts.nextRegionFace(face);
+ while (coplanarFace != face) {
+ XA_DEBUG_ASSERT(!m_data.isFaceInChart.get(coplanarFace));
chart->faces.push_back(coplanarFace);
- coplanarFace = m_nextPlanarRegionFace[coplanarFace];
+ coplanarFace = m_planarCharts.nextRegionFace(coplanarFace);
}
const uint32_t faceCount = chart->faces.size();
// Compute basis.
@@ -5037,8 +6139,8 @@ private:
if (firstFace) {
// Use the first face normal.
// Use any edge as the tangent vector.
- basis.normal = m_faceNormals[face];
- basis.tangent = normalize(m_mesh->position(m_mesh->vertexAt(face * 3 + 0)) - m_mesh->position(m_mesh->vertexAt(face * 3 + 1)), 0);
+ basis.normal = m_data.faceNormals[face];
+ basis.tangent = normalize(m_data.mesh->position(m_data.mesh->vertexAt(face * 3 + 0)) - m_data.mesh->position(m_data.mesh->vertexAt(face * 3 + 1)), kEpsilon);
basis.bitangent = cross(basis.normal, basis.tangent);
} else {
// Use best fit normal.
@@ -5046,7 +6148,7 @@ private:
chart->faces.resize(oldFaceCount);
return false;
}
- if (dot(basis.normal, m_faceNormals[face]) < 0.0f) // Flip normal if oriented in the wrong direction.
+ if (dot(basis.normal, m_data.faceNormals[face]) < 0.0f) // Flip normal if oriented in the wrong direction.
basis.normal = -basis.normal;
}
if (!firstFace) {
@@ -5069,7 +6171,8 @@ private:
const uint32_t f = chart->faces[i];
m_faceCharts[f] = chart->id;
m_facesLeft--;
- chart->centroidSum += m_mesh->computeFaceCenter(f);
+ m_data.isFaceInChart.set(f);
+ chart->centroidSum += m_data.mesh->computeFaceCenter(f);
}
chart->centroid = chart->centroidSum / float(chart->faces.size());
// Refresh candidates.
@@ -5079,15 +6182,15 @@ private:
const uint32_t f = chart->faces[i];
for (uint32_t j = 0; j < 3; j++) {
const uint32_t edge = f * 3 + j;
- const uint32_t oedge = m_mesh->oppositeEdge(edge);
+ const uint32_t oedge = m_data.mesh->oppositeEdge(edge);
if (oedge == UINT32_MAX)
continue; // Boundary edge.
const uint32_t oface = meshEdgeFace(oedge);
- if (m_faceCharts[oface] != -1)
+ if (m_data.isFaceInChart.get(oface))
continue; // Face belongs to another chart.
- if (chart->failedPlanarRegions.contains(m_facePlanarRegionId[oface]))
+ if (chart->failedPlanarRegions.contains(m_planarCharts.regionIdFromFace(oface)))
continue; // Failed to add this faces planar region to the chart before.
- const float cost = evaluateCost(chart, oface);
+ const float cost = computeCost(chart, oface);
if (cost < FLT_MAX)
chart->candidates.push(cost, oface);
}
@@ -5096,76 +6199,62 @@ private:
}
// Returns true if the seed has changed.
- bool relocateSeed(Chart *chart) {
+ bool relocateSeed(Chart *chart)
+ {
// Find the first N triangles that fit the proxy best.
const uint32_t faceCount = chart->faces.size();
m_bestTriangles.clear();
for (uint32_t i = 0; i < faceCount; i++) {
- const float cost = evaluateProxyFitMetric(chart, chart->faces[i]);
+ const float cost = computeNormalDeviationMetric(chart, chart->faces[i]);
m_bestTriangles.push(cost, chart->faces[i]);
}
- // Of those, choose the least central triangle.
- uint32_t leastCentral = 0;
- float maxDistance = -1;
+ // Of those, choose the most central triangle.
+ uint32_t mostCentral = 0;
+ float minDistance = FLT_MAX;
for (;;) {
if (m_bestTriangles.count() == 0)
break;
const uint32_t face = m_bestTriangles.pop();
- Vector3 faceCentroid = m_mesh->computeFaceCenter(face);
+ Vector3 faceCentroid = m_data.mesh->computeFaceCenter(face);
const float distance = length(chart->centroid - faceCentroid);
- if (distance > maxDistance) {
- maxDistance = distance;
- leastCentral = face;
- }
- }
- XA_DEBUG_ASSERT(maxDistance >= 0);
- // In order to prevent k-means cyles we record all the previously chosen seeds.
- for (uint32_t i = 0; i < chart->seeds.size(); i++) {
- // Treat seeds belong to the same planar region as equal.
- if (chart->seeds[i] == leastCentral || m_facePlanarRegionId[chart->seeds[i]] == m_facePlanarRegionId[leastCentral]) {
- // Move new seed to the end of the seed array.
- uint32_t last = chart->seeds.size() - 1;
- swap(chart->seeds[i], chart->seeds[last]);
- return false;
+ if (distance < minDistance) {
+ minDistance = distance;
+ mostCentral = face;
}
}
- // Append new seed.
- chart->seeds.push_back(leastCentral);
+ XA_DEBUG_ASSERT(minDistance < FLT_MAX);
+ if (mostCentral == chart->seed)
+ return false;
+ chart->seed = mostCentral;
return true;
}
- // Evaluate combined metric.
- float evaluateCost(Chart *chart, uint32_t face) const {
- if (dot(m_faceNormals[face], chart->basis.normal) <= 0.26f) // ~75 degrees
- return FLT_MAX;
+ // Cost is combined metrics * weights.
+ float computeCost(Chart *chart, uint32_t face) const
+ {
// Estimate boundary length and area:
- float newChartArea = 0.0f, newBoundaryLength = 0.0f;
- if (m_options.maxChartArea > 0.0f || m_options.roundnessMetricWeight > 0.0f)
- newChartArea = computeArea(chart, face);
- if (m_options.maxBoundaryLength > 0.0f || m_options.roundnessMetricWeight > 0.0f)
- newBoundaryLength = computeBoundaryLength(chart, face);
+ const float newChartArea = computeArea(chart, face);
+ const float newBoundaryLength = computeBoundaryLength(chart, face);
// Enforce limits strictly:
- if (m_options.maxChartArea > 0.0f && newChartArea > m_options.maxChartArea)
+ if (m_data.options.maxChartArea > 0.0f && newChartArea > m_data.options.maxChartArea)
return FLT_MAX;
- if (m_options.maxBoundaryLength > 0.0f && newBoundaryLength > m_options.maxBoundaryLength)
+ if (m_data.options.maxBoundaryLength > 0.0f && newBoundaryLength > m_data.options.maxBoundaryLength)
return FLT_MAX;
+ // Compute metrics.
float cost = 0.0f;
- if (m_options.normalSeamMetricWeight > 0.0f) {
- // Penalize faces that cross seams, reward faces that close seams or reach boundaries.
- // Make sure normal seams are fully respected:
- const float N = evaluateNormalSeamMetric(chart, face);
- if (m_options.normalSeamMetricWeight >= 1000.0f && N > 0.0f)
- return FLT_MAX;
- cost += m_options.normalSeamMetricWeight * N;
- }
- if (m_options.proxyFitMetricWeight > 0.0f)
- cost += m_options.proxyFitMetricWeight * evaluateProxyFitMetric(chart, face);
- if (m_options.roundnessMetricWeight > 0.0f)
- cost += m_options.roundnessMetricWeight * evaluateRoundnessMetric(chart, newBoundaryLength, newChartArea);
- if (m_options.straightnessMetricWeight > 0.0f)
- cost += m_options.straightnessMetricWeight * evaluateStraightnessMetric(chart, face);
- if (m_options.textureSeamMetricWeight > 0.0f)
- cost += m_options.textureSeamMetricWeight * evaluateTextureSeamMetric(chart, face);
+ const float normalDeviation = computeNormalDeviationMetric(chart, face);
+ if (normalDeviation >= 0.707f) // ~75 degrees
+ return FLT_MAX;
+ cost += m_data.options.normalDeviationWeight * normalDeviation;
+ // Penalize faces that cross seams, reward faces that close seams or reach boundaries.
+ // Make sure normal seams are fully respected:
+ const float normalSeam = computeNormalSeamMetric(chart, face);
+ if (m_data.options.normalSeamWeight >= 1000.0f && normalSeam > 0.0f)
+ return FLT_MAX;
+ cost += m_data.options.normalSeamWeight * normalSeam;
+ cost += m_data.options.roundnessWeight * computeRoundnessMetric(chart, newBoundaryLength, newChartArea);
+ cost += m_data.options.straightnessWeight * computeStraightnessMetric(chart, face);
+ cost += m_data.options.textureSeamWeight * computeTextureSeamMetric(chart, face);
//float R = evaluateCompletenessMetric(chart, face);
//float D = evaluateDihedralAngleMetric(chart, face);
// @@ Add a metric based on local dihedral angle.
@@ -5176,100 +6265,108 @@ private:
}
// Returns a value in [0-1].
- float evaluateProxyFitMetric(Chart *chart, uint32_t face) const {
+ // 0 if face normal is coplanar to the chart's best fit normal.
+ // 1 if face normal is perpendicular.
+ float computeNormalDeviationMetric(Chart *chart, uint32_t face) const
+ {
// All faces in coplanar regions have the same normal, can use any face.
- const Vector3 faceNormal = m_faceNormals[face];
+ const Vector3 faceNormal = m_data.faceNormals[face];
// Use plane fitting metric for now:
- return 1 - dot(faceNormal, chart->basis.normal); // @@ normal deviations should be weighted by face area
+ return min(1.0f - dot(faceNormal, chart->basis.normal), 1.0f); // @@ normal deviations should be weighted by face area
}
- float evaluateRoundnessMetric(Chart *chart, float newBoundaryLength, float newChartArea) const {
- const float roundness = square(chart->boundaryLength) / chart->area;
- const float newBoundaryLengthSq = square(newBoundaryLength);
- const float newRoundness = newBoundaryLengthSq / newChartArea;
- if (newRoundness > roundness)
- return newBoundaryLengthSq / (newChartArea * kPi4);
- // Offer no impedance to faces that improve roundness.
- return 0;
+ float computeRoundnessMetric(Chart *chart, float newBoundaryLength, float newChartArea) const
+ {
+ const float oldRoundness = square(chart->boundaryLength) / chart->area;
+ const float newRoundness = square(newBoundaryLength) / newChartArea;
+ return 1.0f - oldRoundness / newRoundness;
}
- float evaluateStraightnessMetric(Chart *chart, uint32_t firstFace) const {
- float l_out = 0.0f, l_in = 0.0f;
- const uint32_t planarRegionId = m_facePlanarRegionId[firstFace];
+ float computeStraightnessMetric(Chart *chart, uint32_t firstFace) const
+ {
+ float l_out = 0.0f; // Length of firstFace planar region boundary that doesn't border the chart.
+ float l_in = 0.0f; // Length that does border the chart.
+ const uint32_t planarRegionId = m_planarCharts.regionIdFromFace(firstFace);
uint32_t face = firstFace;
- for (;;) {
- for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
- const float l = m_edgeLengths[it.edge()];
+ for (;;) {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
+ const float l = m_data.edgeLengths[it.edge()];
if (it.isBoundary()) {
l_out += l;
- } else if (m_facePlanarRegionId[it.oppositeFace()] != planarRegionId) {
+ } else if (m_planarCharts.regionIdFromFace(it.oppositeFace()) != planarRegionId) {
if (m_faceCharts[it.oppositeFace()] != chart->id)
l_out += l;
else
l_in += l;
}
}
- face = m_nextPlanarRegionFace[face];
+ face = m_planarCharts.nextRegionFace(face);
if (face == firstFace)
break;
}
+#if 1
XA_DEBUG_ASSERT(l_in != 0.0f); // Candidate face must be adjacent to chart. @@ This is not true if the input mesh has zero-length edges.
float ratio = (l_out - l_in) / (l_out + l_in);
return min(ratio, 0.0f); // Only use the straightness metric to close gaps.
+#else
+ return 1.0f - l_in / l_out;
+#endif
}
- bool isNormalSeam(uint32_t edge) const {
- const uint32_t oppositeEdge = m_mesh->oppositeEdge(edge);
+ bool isNormalSeam(uint32_t edge) const
+ {
+ const uint32_t oppositeEdge = m_data.mesh->oppositeEdge(edge);
if (oppositeEdge == UINT32_MAX)
return false; // boundary edge
- if (m_mesh->flags() & MeshFlags::HasNormals) {
- const uint32_t v0 = m_mesh->vertexAt(meshEdgeIndex0(edge));
- const uint32_t v1 = m_mesh->vertexAt(meshEdgeIndex1(edge));
- const uint32_t ov0 = m_mesh->vertexAt(meshEdgeIndex0(oppositeEdge));
- const uint32_t ov1 = m_mesh->vertexAt(meshEdgeIndex1(oppositeEdge));
+ if (m_data.mesh->flags() & MeshFlags::HasNormals) {
+ const uint32_t v0 = m_data.mesh->vertexAt(meshEdgeIndex0(edge));
+ const uint32_t v1 = m_data.mesh->vertexAt(meshEdgeIndex1(edge));
+ const uint32_t ov0 = m_data.mesh->vertexAt(meshEdgeIndex0(oppositeEdge));
+ const uint32_t ov1 = m_data.mesh->vertexAt(meshEdgeIndex1(oppositeEdge));
if (v0 == ov1 && v1 == ov0)
return false;
- return !equal(m_mesh->normal(v0), m_mesh->normal(ov1), kNormalEpsilon) || !equal(m_mesh->normal(v1), m_mesh->normal(ov0), kNormalEpsilon);
+ return !equal(m_data.mesh->normal(v0), m_data.mesh->normal(ov1), kNormalEpsilon) || !equal(m_data.mesh->normal(v1), m_data.mesh->normal(ov0), kNormalEpsilon);
}
const uint32_t f0 = meshEdgeFace(edge);
const uint32_t f1 = meshEdgeFace(oppositeEdge);
- if (m_facePlanarRegionId[f0] == m_facePlanarRegionId[f1])
+ if (m_planarCharts.regionIdFromFace(f0) == m_planarCharts.regionIdFromFace(f1))
return false;
- return !equal(m_faceNormals[f0], m_faceNormals[f1], kNormalEpsilon);
+ return !equal(m_data.faceNormals[f0], m_data.faceNormals[f1], kNormalEpsilon);
}
- float evaluateNormalSeamMetric(Chart *chart, uint32_t firstFace) const {
+ float computeNormalSeamMetric(Chart *chart, uint32_t firstFace) const
+ {
float seamFactor = 0.0f, totalLength = 0.0f;
uint32_t face = firstFace;
- for (;;) {
- for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
+ for (;;) {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
if (it.isBoundary())
continue;
if (m_faceCharts[it.oppositeFace()] != chart->id)
continue;
- float l = m_edgeLengths[it.edge()];
+ float l = m_data.edgeLengths[it.edge()];
totalLength += l;
if (!it.isSeam())
continue;
// Make sure it's a normal seam.
if (isNormalSeam(it.edge())) {
float d;
- if (m_mesh->flags() & MeshFlags::HasNormals) {
- const Vector3 &n0 = m_mesh->normal(it.vertex0());
- const Vector3 &n1 = m_mesh->normal(it.vertex1());
- const Vector3 &on0 = m_mesh->normal(m_mesh->vertexAt(meshEdgeIndex0(it.oppositeEdge())));
- const Vector3 &on1 = m_mesh->normal(m_mesh->vertexAt(meshEdgeIndex1(it.oppositeEdge())));
+ if (m_data.mesh->flags() & MeshFlags::HasNormals) {
+ const Vector3 &n0 = m_data.mesh->normal(it.vertex0());
+ const Vector3 &n1 = m_data.mesh->normal(it.vertex1());
+ const Vector3 &on0 = m_data.mesh->normal(m_data.mesh->vertexAt(meshEdgeIndex0(it.oppositeEdge())));
+ const Vector3 &on1 = m_data.mesh->normal(m_data.mesh->vertexAt(meshEdgeIndex1(it.oppositeEdge())));
const float d0 = clamp(dot(n0, on1), 0.0f, 1.0f);
const float d1 = clamp(dot(n1, on0), 0.0f, 1.0f);
d = (d0 + d1) * 0.5f;
} else {
- d = clamp(dot(m_faceNormals[face], m_faceNormals[meshEdgeFace(it.oppositeEdge())]), 0.0f, 1.0f);
+ d = clamp(dot(m_data.faceNormals[face], m_data.faceNormals[meshEdgeFace(it.oppositeEdge())]), 0.0f, 1.0f);
}
l *= 1 - d;
seamFactor += l;
}
}
- face = m_nextPlanarRegionFace[face];
+ face = m_planarCharts.nextRegionFace(face);
if (face == firstFace)
break;
}
@@ -5278,16 +6375,17 @@ private:
return seamFactor / totalLength;
}
- float evaluateTextureSeamMetric(Chart *chart, uint32_t firstFace) const {
+ float computeTextureSeamMetric(Chart *chart, uint32_t firstFace) const
+ {
float seamLength = 0.0f, totalLength = 0.0f;
uint32_t face = firstFace;
- for (;;) {
- for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
+ for (;;) {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
if (it.isBoundary())
continue;
if (m_faceCharts[it.oppositeFace()] != chart->id)
continue;
- float l = m_edgeLengths[it.edge()];
+ float l = m_data.edgeLengths[it.edge()];
totalLength += l;
if (!it.isSeam())
continue;
@@ -5295,7 +6393,7 @@ private:
if (it.isTextureSeam())
seamLength += l;
}
- face = m_nextPlanarRegionFace[face];
+ face = m_planarCharts.nextRegionFace(face);
if (face == firstFace)
break;
}
@@ -5304,43 +6402,46 @@ private:
return seamLength / totalLength;
}
- float computeArea(Chart *chart, uint32_t firstFace) const {
+ float computeArea(Chart *chart, uint32_t firstFace) const
+ {
float area = chart->area;
uint32_t face = firstFace;
- for (;;) {
- area += m_faceAreas[face];
- face = m_nextPlanarRegionFace[face];
+ for (;;) {
+ area += m_data.faceAreas[face];
+ face = m_planarCharts.nextRegionFace(face);
if (face == firstFace)
break;
}
return area;
}
- float computeBoundaryLength(Chart *chart, uint32_t firstFace) const {
+ float computeBoundaryLength(Chart *chart, uint32_t firstFace) const
+ {
float boundaryLength = chart->boundaryLength;
// Add new edges, subtract edges shared with the chart.
- const uint32_t planarRegionId = m_facePlanarRegionId[firstFace];
+ const uint32_t planarRegionId = m_planarCharts.regionIdFromFace(firstFace);
uint32_t face = firstFace;
- for (;;) {
- for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
- const float edgeLength = m_edgeLengths[it.edge()];
+ for (;;) {
+ for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
+ const float edgeLength = m_data.edgeLengths[it.edge()];
if (it.isBoundary()) {
boundaryLength += edgeLength;
- } else if (m_facePlanarRegionId[it.oppositeFace()] != planarRegionId) {
+ } else if (m_planarCharts.regionIdFromFace(it.oppositeFace()) != planarRegionId) {
if (m_faceCharts[it.oppositeFace()] != chart->id)
boundaryLength += edgeLength;
else
boundaryLength -= edgeLength;
}
}
- face = m_nextPlanarRegionFace[face];
+ face = m_planarCharts.nextRegionFace(face);
if (face == firstFace)
break;
}
- return max(0.0f, boundaryLength); // @@ Hack!
+ return max(0.0f, boundaryLength); // @@ Hack!
}
- bool mergeChart(Chart *owner, Chart *chart, float sharedBoundaryLength) {
+ bool mergeChart(Chart *owner, Chart *chart, float sharedBoundaryLength)
+ {
const uint32_t oldOwnerFaceCount = owner->faces.size();
const uint32_t chartFaceCount = chart->faces.size();
owner->faces.push_back(chart->faces);
@@ -5356,7 +6457,7 @@ private:
m_faceCharts[chart->faces[i]] = chart->id;
return false;
}
- if (dot(basis.normal, m_faceNormals[owner->faces[0]]) < 0.0f) // Flip normal if oriented in the wrong direction.
+ if (dot(basis.normal, m_data.faceNormals[owner->faces[0]]) < 0.0f) // Flip normal if oriented in the wrong direction.
basis.normal = -basis.normal;
// Compute orthogonal parameterization and check that it is valid.
parameterizeChart(owner);
@@ -5379,19 +6480,14 @@ private:
return true;
}
- const Mesh *m_mesh;
- Array<float> m_edgeLengths;
- Array<float> m_faceAreas;
- Array<Vector3> m_faceNormals;
+private:
+ AtlasData &m_data;
+ const PlanarCharts &m_planarCharts;
Array<Vector2> m_texcoords;
uint32_t m_facesLeft;
Array<int> m_faceCharts;
Array<Chart *> m_charts;
CostQueue m_bestTriangles;
- KISSRng m_rand;
- ChartOptions m_options;
- Array<uint32_t> m_nextPlanarRegionFace;
- Array<uint32_t> m_facePlanarRegionId;
Array<Vector3> m_tempPoints;
UniformGrid2 m_boundaryGrid;
#if XA_MERGE_CHARTS
@@ -5400,226 +6496,66 @@ private:
Array<float> m_sharedBoundaryLengthsNoSeams;
Array<uint32_t> m_sharedBoundaryEdgeCountNoSeams;
#endif
+ bool m_placingSeeds;
};
-} // namespace segment
-
-namespace param {
+struct Atlas
+{
+ Atlas() : m_planarCharts(m_data), m_clusteredCharts(m_data, m_planarCharts) {}
-class JacobiPreconditioner {
-public:
- JacobiPreconditioner(const sparse::Matrix &M, bool symmetric) :
- m_inverseDiagonal(M.width()) {
- XA_ASSERT(M.isSquare());
- for (uint32_t x = 0; x < M.width(); x++) {
- float elem = M.getCoefficient(x, x);
- //XA_DEBUG_ASSERT( elem != 0.0f ); // This can be zero in the presence of zero area triangles.
- if (symmetric) {
- m_inverseDiagonal[x] = (elem != 0) ? 1.0f / sqrtf(fabsf(elem)) : 1.0f;
- } else {
- m_inverseDiagonal[x] = (elem != 0) ? 1.0f / elem : 1.0f;
- }
- }
+ uint32_t chartCount() const
+ {
+ return m_planarCharts.chartCount() + m_clusteredCharts.chartCount();
}
- void apply(const FullVector &x, FullVector &y) const {
- XA_DEBUG_ASSERT(x.dimension() == m_inverseDiagonal.dimension());
- XA_DEBUG_ASSERT(y.dimension() == m_inverseDiagonal.dimension());
- // @@ Wrap vector component-wise product into a separate function.
- const uint32_t D = x.dimension();
- for (uint32_t i = 0; i < D; i++) {
- y[i] = m_inverseDiagonal[i] * x[i];
- }
+ ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const
+ {
+ if (chartIndex < m_planarCharts.chartCount())
+ return m_planarCharts.chartFaces(chartIndex);
+ chartIndex -= m_planarCharts.chartCount();
+ return m_clusteredCharts.chartFaces(chartIndex);
}
-private:
- FullVector m_inverseDiagonal;
-};
-
-// Linear solvers.
-class Solver {
-public:
- // Solve the symmetric system: At·A·x = At·b
- static bool LeastSquaresSolver(const sparse::Matrix &A, const FullVector &b, FullVector &x, float epsilon = 1e-5f) {
- XA_DEBUG_ASSERT(A.width() == x.dimension());
- XA_DEBUG_ASSERT(A.height() == b.dimension());
- XA_DEBUG_ASSERT(A.height() >= A.width()); // @@ If height == width we could solve it directly...
- const uint32_t D = A.width();
- sparse::Matrix At(A.height(), A.width());
- sparse::transpose(A, At);
- FullVector Atb(D);
- sparse::mult(At, b, Atb);
- sparse::Matrix AtA(D);
- sparse::mult(At, A, AtA);
- return SymmetricSolver(AtA, Atb, x, epsilon);
- }
-
- // See section 10.4.3 in: Mesh Parameterization: Theory and Practice, Siggraph Course Notes, August 2007
- static bool LeastSquaresSolver(const sparse::Matrix &A, const FullVector &b, FullVector &x, const uint32_t *lockedParameters, uint32_t lockedCount, float epsilon = 1e-5f) {
- XA_DEBUG_ASSERT(A.width() == x.dimension());
- XA_DEBUG_ASSERT(A.height() == b.dimension());
- XA_DEBUG_ASSERT(A.height() >= A.width() - lockedCount);
- // @@ This is not the most efficient way of building a system with reduced degrees of freedom. It would be faster to do it on the fly.
- const uint32_t D = A.width() - lockedCount;
- XA_DEBUG_ASSERT(D > 0);
- // Compute: b - Al * xl
- FullVector b_Alxl(b);
- for (uint32_t y = 0; y < A.height(); y++) {
- const uint32_t count = A.getRow(y).size();
- for (uint32_t e = 0; e < count; e++) {
- uint32_t column = A.getRow(y)[e].x;
- bool isFree = true;
- for (uint32_t i = 0; i < lockedCount; i++) {
- isFree &= (lockedParameters[i] != column);
- }
- if (!isFree) {
- b_Alxl[y] -= x[column] * A.getRow(y)[e].v;
- }
- }
- }
- // Remove locked columns from A.
- sparse::Matrix Af(D, A.height());
- for (uint32_t y = 0; y < A.height(); y++) {
- const uint32_t count = A.getRow(y).size();
- for (uint32_t e = 0; e < count; e++) {
- uint32_t column = A.getRow(y)[e].x;
- uint32_t ix = column;
- bool isFree = true;
- for (uint32_t i = 0; i < lockedCount; i++) {
- isFree &= (lockedParameters[i] != column);
- if (column > lockedParameters[i]) ix--; // shift columns
- }
- if (isFree) {
- Af.setCoefficient(ix, y, A.getRow(y)[e].v);
- }
- }
- }
- // Remove elements from x
- FullVector xf(D);
- for (uint32_t i = 0, j = 0; i < A.width(); i++) {
- bool isFree = true;
- for (uint32_t l = 0; l < lockedCount; l++) {
- isFree &= (lockedParameters[l] != i);
- }
- if (isFree) {
- xf[j++] = x[i];
- }
- }
- // Solve reduced system.
- bool result = LeastSquaresSolver(Af, b_Alxl, xf, epsilon);
- // Copy results back to x.
- for (uint32_t i = 0, j = 0; i < A.width(); i++) {
- bool isFree = true;
- for (uint32_t l = 0; l < lockedCount; l++) {
- isFree &= (lockedParameters[l] != i);
- }
- if (isFree) {
- x[i] = xf[j++];
- }
- }
- return result;
+ const Basis &chartBasis(uint32_t chartIndex) const
+ {
+ if (chartIndex < m_planarCharts.chartCount())
+ return m_planarCharts.chartBasis(chartIndex);
+ chartIndex -= m_planarCharts.chartCount();
+ return m_clusteredCharts.chartBasis(chartIndex);
}
-private:
- /**
- * Compute the solution of the sparse linear system Ab=x using the Conjugate
- * Gradient method.
- *
- * Solving sparse linear systems:
- * (1) A·x = b
- *
- * The conjugate gradient algorithm solves (1) only in the case that A is
- * symmetric and positive definite. It is based on the idea of minimizing the
- * function
- *
- * (2) f(x) = 1/2·x·A·x - b·x
- *
- * This function is minimized when its gradient
- *
- * (3) df = A·x - b
- *
- * is zero, which is equivalent to (1). The minimization is carried out by
- * generating a succession of search directions p.k and improved minimizers x.k.
- * At each stage a quantity alfa.k is found that minimizes f(x.k + alfa.k·p.k),
- * and x.k+1 is set equal to the new point x.k + alfa.k·p.k. The p.k and x.k are
- * built up in such a way that x.k+1 is also the minimizer of f over the whole
- * vector space of directions already taken, {p.1, p.2, . . . , p.k}. After N
- * iterations you arrive at the minimizer over the entire vector space, i.e., the
- * solution to (1).
- *
- * For a really good explanation of the method see:
- *
- * "An Introduction to the Conjugate Gradient Method Without the Agonizing Pain",
- * Jonhathan Richard Shewchuk.
- *
- **/
- // Conjugate gradient with preconditioner.
- static bool ConjugateGradientSolver(const JacobiPreconditioner &preconditioner, const sparse::Matrix &A, const FullVector &b, FullVector &x, float epsilon) {
- XA_DEBUG_ASSERT(A.isSquare());
- XA_DEBUG_ASSERT(A.width() == b.dimension());
- XA_DEBUG_ASSERT(A.width() == x.dimension());
- int i = 0;
- const int D = A.width();
- const int i_max = 4 * D; // Convergence should be linear, but in some cases, it's not.
- FullVector r(D); // residual
- FullVector p(D); // search direction
- FullVector q(D); //
- FullVector s(D); // preconditioned
- float delta_0;
- float delta_old;
- float delta_new;
- float alpha;
- float beta;
- // r = b - A·x
- sparse::copy(b, r);
- sparse::sgemv(-1, A, x, 1, r);
- // p = M^-1 · r
- preconditioner.apply(r, p);
- delta_new = sparse::dot(r, p);
- delta_0 = delta_new;
- while (i < i_max && delta_new > epsilon * epsilon * delta_0) {
- i++;
- // q = A·p
- sparse::mult(A, p, q);
- // alpha = delta_new / p·q
- const float pdotq = sparse::dot(p, q);
- if (!isFinite(pdotq) || isNan(pdotq))
- alpha = 0.0f;
- else
- alpha = delta_new / pdotq;
- // x = alfa·p + x
- sparse::saxpy(alpha, p, x);
- if ((i & 31) == 0) { // recompute r after 32 steps
- // r = b - A·x
- sparse::copy(b, r);
- sparse::sgemv(-1, A, x, 1, r);
- } else {
- // r = r - alfa·q
- sparse::saxpy(-alpha, q, r);
- }
- // s = M^-1 · r
- preconditioner.apply(r, s);
- delta_old = delta_new;
- delta_new = sparse::dot(r, s);
- beta = delta_new / delta_old;
- // p = s + beta·p
- sparse::scal(beta, p);
- sparse::saxpy(1, s, p);
- }
- return delta_new <= epsilon * epsilon * delta_0;
+ void reset(const Mesh *mesh, const ChartOptions &options)
+ {
+ XA_PROFILE_START(buildAtlasInit)
+ m_data.options = options;
+ m_data.mesh = mesh;
+ m_data.compute();
+ XA_PROFILE_END(buildAtlasInit)
}
- static bool SymmetricSolver(const sparse::Matrix &A, const FullVector &b, FullVector &x, float epsilon = 1e-5f) {
- XA_DEBUG_ASSERT(A.height() == A.width());
- XA_DEBUG_ASSERT(A.height() == b.dimension());
- XA_DEBUG_ASSERT(b.dimension() == x.dimension());
- JacobiPreconditioner jacobi(A, true);
- return ConjugateGradientSolver(jacobi, A, b, x, epsilon);
+ void compute()
+ {
+ XA_PROFILE_START(planarCharts)
+ m_planarCharts.compute();
+ XA_PROFILE_END(planarCharts)
+ XA_PROFILE_START(clusteredCharts)
+ m_clusteredCharts.compute();
+ XA_PROFILE_END(clusteredCharts)
}
+
+private:
+ AtlasData m_data;
+ PlanarCharts m_planarCharts;
+ ClusteredCharts m_clusteredCharts;
};
+} // namespace segment
+
+namespace param {
+
// Fast sweep in 3 directions
-static bool findApproximateDiameterVertices(Mesh *mesh, uint32_t *a, uint32_t *b) {
+static bool findApproximateDiameterVertices(Mesh *mesh, uint32_t *a, uint32_t *b)
+{
XA_DEBUG_ASSERT(a != nullptr);
XA_DEBUG_ASSERT(b != nullptr);
const uint32_t vertexCount = mesh->vertexCount();
@@ -5674,165 +6610,136 @@ static bool findApproximateDiameterVertices(Mesh *mesh, uint32_t *a, uint32_t *b
return true;
}
-// Conformal relations from Brecht Van Lommel (based on ABF):
-
-static float vec_angle_cos(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3) {
- Vector3 d1 = v1 - v2;
- Vector3 d2 = v3 - v2;
- return clamp(dot(d1, d2) / (length(d1) * length(d2)), -1.0f, 1.0f);
-}
-
-static float vec_angle(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3) {
- float dot = vec_angle_cos(v1, v2, v3);
- return acosf(dot);
-}
-
-static void triangle_angles(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, float *a1, float *a2, float *a3) {
- *a1 = vec_angle(v3, v1, v2);
- *a2 = vec_angle(v1, v2, v3);
- *a3 = kPi - *a2 - *a1;
-}
-
-static void setup_abf_relations(sparse::Matrix &A, int row, int id0, int id1, int id2, const Vector3 &p0, const Vector3 &p1, const Vector3 &p2) {
- // @@ IC: Wouldn't it be more accurate to return cos and compute 1-cos^2?
- // It does indeed seem to be a little bit more robust.
- // @@ Need to revisit this more carefully!
- float a0, a1, a2;
- triangle_angles(p0, p1, p2, &a0, &a1, &a2);
- float s0 = sinf(a0);
- float s1 = sinf(a1);
- float s2 = sinf(a2);
- if (s1 > s0 && s1 > s2) {
- swap(s1, s2);
- swap(s0, s1);
- swap(a1, a2);
- swap(a0, a1);
- swap(id1, id2);
- swap(id0, id1);
- } else if (s0 > s1 && s0 > s2) {
- swap(s0, s2);
- swap(s0, s1);
- swap(a0, a2);
- swap(a0, a1);
- swap(id0, id2);
- swap(id0, id1);
- }
- float c0 = cosf(a0);
- float ratio = (s2 == 0.0f) ? 1.0f : s1 / s2;
- float cosine = c0 * ratio;
- float sine = s0 * ratio;
- // Note : 2*id + 0 --> u
- // 2*id + 1 --> v
- int u0_id = 2 * id0 + 0;
- int v0_id = 2 * id0 + 1;
- int u1_id = 2 * id1 + 0;
- int v1_id = 2 * id1 + 1;
- int u2_id = 2 * id2 + 0;
- int v2_id = 2 * id2 + 1;
- // Real part
- A.setCoefficient(u0_id, 2 * row + 0, cosine - 1.0f);
- A.setCoefficient(v0_id, 2 * row + 0, -sine);
- A.setCoefficient(u1_id, 2 * row + 0, -cosine);
- A.setCoefficient(v1_id, 2 * row + 0, sine);
- A.setCoefficient(u2_id, 2 * row + 0, 1);
- // Imaginary part
- A.setCoefficient(u0_id, 2 * row + 1, sine);
- A.setCoefficient(v0_id, 2 * row + 1, cosine - 1.0f);
- A.setCoefficient(u1_id, 2 * row + 1, -sine);
- A.setCoefficient(v1_id, 2 * row + 1, -cosine);
- A.setCoefficient(v2_id, 2 * row + 1, 1);
-}
-
-static bool computeLeastSquaresConformalMap(Mesh *mesh) {
- // For this to work properly, mesh should not have colocals that have the same
- // attributes, unless you want the vertices to actually have different texcoords.
- const uint32_t vertexCount = mesh->vertexCount();
- const uint32_t D = 2 * vertexCount;
- const uint32_t N = 2 * mesh->faceCount();
- // N is the number of equations (one per triangle)
- // D is the number of variables (one per vertex; there are 2 pinned vertices).
- if (N < D - 4) {
- return false;
- }
- sparse::Matrix A(D, N);
- FullVector b(N);
- FullVector x(D);
- // Fill b:
- b.fill(0.0f);
- // Fill x:
- uint32_t v0, v1;
- if (!findApproximateDiameterVertices(mesh, &v0, &v1)) {
+// From OpenNL LSCM example.
+// Computes the coordinates of the vertices of a triangle in a local 2D orthonormal basis of the triangle's plane.
+static void projectTriangle(Vector3 p0, Vector3 p1, Vector3 p2, Vector2 *z0, Vector2 *z1, Vector2 *z2, float epsilon)
+{
+ Vector3 X = normalize(p1 - p0, epsilon);
+ Vector3 Z = normalize(cross(X, p2 - p0), epsilon);
+ Vector3 Y = cross(Z, X);
+ Vector3 &O = p0;
+ *z0 = Vector2(0, 0);
+ *z1 = Vector2(length(p1 - O), 0);
+ *z2 = Vector2(dot(p2 - O, X), dot(p2 - O, Y));
+}
+
+static bool computeLeastSquaresConformalMap(Mesh *mesh)
+{
+ uint32_t lockedVertex0, lockedVertex1;
+ if (!findApproximateDiameterVertices(mesh, &lockedVertex0, &lockedVertex1)) {
// Mesh has no boundaries.
return false;
}
- if (mesh->texcoord(v0) == mesh->texcoord(v1)) {
- // LSCM expects an existing parameterization.
+ const uint32_t vertexCount = mesh->vertexCount();
+ opennl::NLContext *context = opennl::nlNewContext();
+ opennl::nlSolverParameteri(context, NL_NB_VARIABLES, int(2 * vertexCount));
+ opennl::nlSolverParameteri(context, NL_MAX_ITERATIONS, int(5 * vertexCount));
+ opennl::nlBegin(context, NL_SYSTEM);
+ const Vector2 *texcoords = mesh->texcoords();
+ for (uint32_t i = 0; i < vertexCount; i++) {
+ opennl::nlSetVariable(context, 2 * i, texcoords[i].x);
+ opennl::nlSetVariable(context, 2 * i + 1, texcoords[i].y);
+ if (i == lockedVertex0 || i == lockedVertex1) {
+ opennl::nlLockVariable(context, 2 * i);
+ opennl::nlLockVariable(context, 2 * i + 1);
+ }
+ }
+ opennl::nlBegin(context, NL_MATRIX);
+ const uint32_t faceCount = mesh->faceCount();
+ const Vector3 *positions = mesh->positions();
+ const uint32_t *indices = mesh->indices();
+ for (uint32_t f = 0; f < faceCount; f++) {
+ const uint32_t v0 = indices[f * 3 + 0];
+ const uint32_t v1 = indices[f * 3 + 1];
+ const uint32_t v2 = indices[f * 3 + 2];
+ Vector2 z0, z1, z2;
+ projectTriangle(positions[v0], positions[v1], positions[v2], &z0, &z1, &z2, mesh->epsilon());
+ double a = z1.x - z0.x;
+ double b = z1.y - z0.y;
+ double c = z2.x - z0.x;
+ double d = z2.y - z0.y;
+ XA_DEBUG_ASSERT(b == 0.0);
+ // Note : 2*id + 0 --> u
+ // 2*id + 1 --> v
+ uint32_t u0_id = 2 * v0;
+ uint32_t v0_id = 2 * v0 + 1;
+ uint32_t u1_id = 2 * v1;
+ uint32_t v1_id = 2 * v1 + 1;
+ uint32_t u2_id = 2 * v2;
+ uint32_t v2_id = 2 * v2 + 1;
+ // Note : b = 0
+ // Real part
+ opennl::nlBegin(context, NL_ROW);
+ opennl::nlCoefficient(context, u0_id, -a+c) ;
+ opennl::nlCoefficient(context, v0_id, b-d) ;
+ opennl::nlCoefficient(context, u1_id, -c) ;
+ opennl::nlCoefficient(context, v1_id, d) ;
+ opennl::nlCoefficient(context, u2_id, a);
+ opennl::nlEnd(context, NL_ROW);
+ // Imaginary part
+ opennl::nlBegin(context, NL_ROW);
+ opennl::nlCoefficient(context, u0_id, -b+d);
+ opennl::nlCoefficient(context, v0_id, -a+c);
+ opennl::nlCoefficient(context, u1_id, -d);
+ opennl::nlCoefficient(context, v1_id, -c);
+ opennl::nlCoefficient(context, v2_id, a);
+ opennl::nlEnd(context, NL_ROW);
+ }
+ opennl::nlEnd(context, NL_MATRIX);
+ opennl::nlEnd(context, NL_SYSTEM);
+ if (!opennl::nlSolve(context)) {
+ opennl::nlDeleteContext(context);
return false;
}
- for (uint32_t v = 0; v < vertexCount; v++) {
- // Initial solution.
- x[2 * v + 0] = mesh->texcoord(v).x;
- x[2 * v + 1] = mesh->texcoord(v).y;
- }
- // Fill A:
- const uint32_t faceCount = mesh->faceCount();
- for (uint32_t f = 0, t = 0; f < faceCount; f++) {
- const uint32_t vertex0 = mesh->vertexAt(f * 3 + 0);
- const uint32_t vertex1 = mesh->vertexAt(f * 3 + 1);
- const uint32_t vertex2 = mesh->vertexAt(f * 3 + 2);
- setup_abf_relations(A, t, vertex0, vertex1, vertex2, mesh->position(vertex0), mesh->position(vertex1), mesh->position(vertex2));
- t++;
- }
- const uint32_t lockedParameters[] = {
- 2 * v0 + 0,
- 2 * v0 + 1,
- 2 * v1 + 0,
- 2 * v1 + 1
- };
- // Solve
- Solver::LeastSquaresSolver(A, b, x, lockedParameters, 4, 0.000001f);
- // Map x back to texcoords:
- for (uint32_t v = 0; v < vertexCount; v++) {
- mesh->texcoord(v) = Vector2(x[2 * v + 0], x[2 * v + 1]);
- XA_DEBUG_ASSERT(!isNan(mesh->texcoord(v).x));
- XA_DEBUG_ASSERT(!isNan(mesh->texcoord(v).y));
+ for (uint32_t i = 0; i < vertexCount; i++) {
+ const double u = opennl::nlGetVariable(context, 2 * i);
+ const double v = opennl::nlGetVariable(context, 2 * i + 1);
+ mesh->texcoord(i) = Vector2((float)u, (float)v);
+ XA_DEBUG_ASSERT(!isNan(mesh->texcoord(i).x));
+ XA_DEBUG_ASSERT(!isNan(mesh->texcoord(i).y));
}
+ opennl::nlDeleteContext(context);
return true;
}
#if XA_RECOMPUTE_CHARTS
-struct PiecewiseParam {
- void reset(const Mesh *mesh, uint32_t faceCount) {
+struct PiecewiseParam
+{
+ void reset(const Mesh *mesh, uint32_t faceCount)
+ {
m_mesh = mesh;
m_faceCount = faceCount;
const uint32_t vertexCount = m_mesh->vertexCount();
m_texcoords.resize(vertexCount);
m_patch.reserve(m_faceCount);
- m_faceAssigned.resize(m_faceCount);
- m_faceAssigned.zeroOutMemory();
+ m_candidates.reserve(m_faceCount);
+ m_faceInAnyPatch.resize(m_faceCount);
+ m_faceInAnyPatch.zeroOutMemory();
m_faceInvalid.resize(m_faceCount);
m_faceInPatch.resize(m_faceCount);
m_vertexInPatch.resize(vertexCount);
- m_faceInCandidates.resize(m_faceCount);
+ m_faceToCandidate.resize(m_faceCount);
}
ConstArrayView<uint32_t> chartFaces() const { return m_patch; }
const Vector2 *texcoords() const { return m_texcoords.data(); }
- bool computeChart() {
+ bool computeChart()
+ {
+ // Clear per-patch state.
m_patch.clear();
+ m_candidates.clear();
+ m_faceToCandidate.zeroOutMemory();
m_faceInvalid.zeroOutMemory();
m_faceInPatch.zeroOutMemory();
m_vertexInPatch.zeroOutMemory();
// Add the seed face (first unassigned face) to the patch.
uint32_t seed = UINT32_MAX;
for (uint32_t f = 0; f < m_faceCount; f++) {
- if (m_faceAssigned.get(f))
+ if (m_faceInAnyPatch.get(f))
continue;
seed = f;
- m_patch.push_back(seed);
- m_faceInPatch.set(seed);
- m_faceAssigned.set(seed);
+ // Add all 3 vertices.
Vector2 texcoords[3];
orthoProjectFace(seed, texcoords);
for (uint32_t i = 0; i < 3; i++) {
@@ -5840,95 +6747,104 @@ struct PiecewiseParam {
m_vertexInPatch.set(vertex);
m_texcoords[vertex] = texcoords[i];
}
+ addFaceToPatch(seed);
+ // Initialize the boundary grid.
+ m_boundaryGrid.reset(m_texcoords.data(), m_mesh->indices());
+ for (Mesh::FaceEdgeIterator it(m_mesh, seed); !it.isDone(); it.advance())
+ m_boundaryGrid.append(it.edge());
break;
}
if (seed == UINT32_MAX)
return false;
for (;;) {
- findCandidates();
- if (m_candidates.isEmpty())
- break;
- for (;;) {
- // Find the candidate with the lowest cost.
- float lowestCost = FLT_MAX;
- uint32_t bestCandidate = UINT32_MAX;
- for (uint32_t i = 0; i < m_candidates.size(); i++) {
- const Candidate &candidate = m_candidates[i];
- if (m_faceInvalid.get(candidate.face)) // A candidate face may be invalidated after is was added.
- continue;
- if (candidate.maxCost < lowestCost) {
- lowestCost = candidate.maxCost;
- bestCandidate = i;
- }
+ // Find the candidate with the lowest cost.
+ float lowestCost = FLT_MAX;
+ Candidate *bestCandidate = nullptr;
+ for (uint32_t i = 0; i < m_candidates.size(); i++) {
+ Candidate *candidate = m_candidates[i];
+ if (candidate->maxCost < lowestCost) {
+ lowestCost = candidate->maxCost;
+ bestCandidate = candidate;
}
- if (bestCandidate == UINT32_MAX)
+ }
+ if (!bestCandidate)
+ break;
+ XA_DEBUG_ASSERT(!bestCandidate->prev); // Must be head of linked candidates.
+ // Compute the position by averaging linked candidates (candidates that share the same free vertex).
+ Vector2 position(0.0f);
+ uint32_t n = 0;
+ for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance()) {
+ position += it.current()->position;
+ n++;
+ }
+ position *= 1.0f / (float)n;
+ const uint32_t freeVertex = bestCandidate->vertex;
+ XA_DEBUG_ASSERT(!isNan(position.x));
+ XA_DEBUG_ASSERT(!isNan(position.y));
+ m_texcoords[freeVertex] = position;
+ // Check for flipped faces. This is also done when candidates are first added, but the averaged position of the free vertex is different now, so check again.
+ bool invalid = false;
+ for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance()) {
+ const uint32_t vertex0 = m_mesh->vertexAt(meshEdgeIndex0(it.current()->patchEdge));
+ const uint32_t vertex1 = m_mesh->vertexAt(meshEdgeIndex1(it.current()->patchEdge));
+ const float freeVertexOrient = orientToEdge(m_texcoords[vertex0], m_texcoords[vertex1], position);
+ if ((it.current()->patchVertexOrient < 0.0f && freeVertexOrient < 0.0f) || (it.current()->patchVertexOrient > 0.0f && freeVertexOrient > 0.0f)) {
+ invalid = true;
break;
- // Compute the position by averaging linked candidates (candidates that share the same free vertex).
- Vector2 position(0.0f);
- uint32_t n = 0;
- for (CandidateIterator it(m_candidates, bestCandidate); !it.isDone(); it.advance()) {
- position += it.current().position;
- n++;
}
- position *= 1.0f / (float)n;
- const uint32_t freeVertex = m_candidates[bestCandidate].vertex;
- XA_DEBUG_ASSERT(!isNan(position.x));
- XA_DEBUG_ASSERT(!isNan(position.y));
- m_texcoords[freeVertex] = position;
- // Check for flipped faces. This is also done when candidates are first added, but the averaged position of the free vertex is different now, so check again.
- bool invalid = false;
- for (CandidateIterator it(m_candidates, bestCandidate); !it.isDone(); it.advance()) {
- const uint32_t vertex0 = m_mesh->vertexAt(meshEdgeIndex0(it.current().patchEdge));
- const uint32_t vertex1 = m_mesh->vertexAt(meshEdgeIndex1(it.current().patchEdge));
- const float freeVertexOrient = orientToEdge(m_texcoords[vertex0], m_texcoords[vertex1], position);
- if ((it.current().patchVertexOrient < 0.0f && freeVertexOrient < 0.0f) || (it.current().patchVertexOrient > 0.0f && freeVertexOrient > 0.0f)) {
- invalid = true;
- break;
- }
- }
- // Check for boundary intersection.
- if (!invalid) {
- m_boundaryGrid.reset(m_texcoords.data(), m_mesh->indices());
- // Add edges on the patch boundary to the grid.
- // Temporarily adding candidate faces to the patch makes it simpler to detect which edges are on the boundary.
- const uint32_t oldPatchSize = m_patch.size();
- for (CandidateIterator it(m_candidates, bestCandidate); !it.isDone(); it.advance())
- m_patch.push_back(it.current().face);
- for (uint32_t i = 0; i < m_patch.size(); i++) {
- for (Mesh::FaceEdgeIterator it(m_mesh, m_patch[i]); !it.isDone(); it.advance()) {
- const uint32_t oface = it.oppositeFace();
- if (oface == UINT32_MAX || oface >= m_faceCount || !m_faceInPatch.get(oface))
- m_boundaryGrid.append(it.edge());
- }
+ }
+ // Check for boundary intersection.
+ if (!invalid) {
+ XA_PROFILE_START(parameterizeChartsPiecewiseBoundaryIntersection)
+ // Test candidate edges that would form part of the new patch boundary.
+ // Ignore boundary edges that would become internal if the candidate faces were added to the patch.
+ Array<uint32_t> newBoundaryEdges, ignoreEdges;
+ for (CandidateIterator candidateIt(bestCandidate); !candidateIt.isDone(); candidateIt.advance()) {
+ for (Mesh::FaceEdgeIterator it(m_mesh, candidateIt.current()->face); !it.isDone(); it.advance()) {
+ const uint32_t oface = it.oppositeFace();
+ if (oface == UINT32_MAX || oface >= m_faceCount || !m_faceInPatch.get(oface))
+ newBoundaryEdges.push_back(it.edge());
+ if (oface != UINT32_MAX && oface < m_faceCount && m_faceInPatch.get(oface))
+ ignoreEdges.push_back(it.oppositeEdge());
}
- invalid = m_boundaryGrid.intersectSelf(m_mesh->epsilon());
- m_patch.resize(oldPatchSize);
- }
- if (invalid) {
- // Mark all faces of linked candidates as invalid.
- for (CandidateIterator it(m_candidates, bestCandidate); !it.isDone(); it.advance())
- m_faceInvalid.set(it.current().face);
- continue;
- }
- // Add faces to the patch.
- for (CandidateIterator it(m_candidates, bestCandidate); !it.isDone(); it.advance()) {
- m_patch.push_back(it.current().face);
- m_faceInPatch.set(it.current().face);
- m_faceAssigned.set(it.current().face);
}
+ invalid = m_boundaryGrid.intersect(m_mesh->epsilon(), newBoundaryEdges, ignoreEdges);
+ XA_PROFILE_END(parameterizeChartsPiecewiseBoundaryIntersection)
+ }
+ if (invalid) {
+ // Mark all faces of linked candidates as invalid.
+ for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance())
+ m_faceInvalid.set(it.current()->face);
+ removeLinkedCandidates(bestCandidate);
+ } else {
// Add vertex to the patch.
m_vertexInPatch.set(freeVertex);
+ // Add faces to the patch.
+ for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance())
+ addFaceToPatch(it.current()->face);
// Successfully added candidate face(s) to patch.
- break;
+ removeLinkedCandidates(bestCandidate);
+ // Reset the grid with all edges on the patch boundary.
+ XA_PROFILE_START(parameterizeChartsPiecewiseBoundaryIntersection)
+ m_boundaryGrid.reset(m_texcoords.data(), m_mesh->indices());
+ for (uint32_t i = 0; i < m_patch.size(); i++) {
+ for (Mesh::FaceEdgeIterator it(m_mesh, m_patch[i]); !it.isDone(); it.advance()) {
+ const uint32_t oface = it.oppositeFace();
+ if (oface == UINT32_MAX || oface >= m_faceCount || !m_faceInPatch.get(oface))
+ m_boundaryGrid.append(it.edge());
+ }
+ }
+ XA_PROFILE_END(parameterizeChartsPiecewiseBoundaryIntersection)
}
}
return true;
}
private:
- struct Candidate {
+ struct Candidate
+ {
uint32_t face, vertex;
- uint32_t next; // The next candidate with the same vertex.
+ Candidate *prev, *next; // The previous/next candidate with the same vertex.
Vector2 position;
float cost;
float maxCost; // Of all linked candidates.
@@ -5936,90 +6852,70 @@ private:
float patchVertexOrient;
};
- struct CandidateIterator {
- CandidateIterator(Array<Candidate> &candidates, uint32_t first) :
- m_candidates(candidates), m_current(first) {}
- void advance() {
- if (m_current != UINT32_MAX) m_current = m_candidates[m_current].next;
- }
- bool isDone() const { return m_current == UINT32_MAX; }
- Candidate &current() { return m_candidates[m_current]; }
+ struct CandidateIterator
+ {
+ CandidateIterator(Candidate *head) : m_current(head) { XA_DEBUG_ASSERT(!head->prev); }
+ void advance() { if (m_current != nullptr) { m_current = m_current->next; } }
+ bool isDone() const { return !m_current; }
+ Candidate *current() { return m_current; }
private:
- Array<Candidate> &m_candidates;
- uint32_t m_current;
+ Candidate *m_current;
};
const Mesh *m_mesh;
uint32_t m_faceCount;
Array<Vector2> m_texcoords;
- Array<Candidate> m_candidates;
- BitArray m_faceInCandidates;
- Array<uint32_t> m_patch;
- BitArray m_faceAssigned; // Face is assigned to a previous chart or the current patch.
- BitArray m_faceInPatch, m_vertexInPatch;
+ BitArray m_faceInAnyPatch; // Face is in a previous chart patch or the current patch.
+ Array<Candidate *> m_candidates; // Incident faces to the patch.
+ Array<Candidate *> m_faceToCandidate;
+ Array<uint32_t> m_patch; // The current chart patch.
+ BitArray m_faceInPatch, m_vertexInPatch; // Face/vertex is in the current patch.
BitArray m_faceInvalid; // Face cannot be added to the patch - flipped, cost too high or causes boundary intersection.
UniformGrid2 m_boundaryGrid;
- // Find candidate faces on the patch front.
- void findCandidates() {
- m_candidates.clear();
- m_faceInCandidates.zeroOutMemory();
- for (uint32_t i = 0; i < m_patch.size(); i++) {
- for (Mesh::FaceEdgeIterator it(m_mesh, m_patch[i]); !it.isDone(); it.advance()) {
- const uint32_t oface = it.oppositeFace();
- if (oface == UINT32_MAX || oface >= m_faceCount || m_faceAssigned.get(oface) || m_faceInCandidates.get(oface))
- continue;
- // Found an active edge on the patch front.
- // Find the free vertex (the vertex that isn't on the active edge).
- // Compute the orientation of the other patch face vertex to the active edge.
- uint32_t freeVertex = UINT32_MAX;
- float orient = 0.0f;
- for (uint32_t j = 0; j < 3; j++) {
- const uint32_t vertex = m_mesh->vertexAt(oface * 3 + j);
- if (vertex != it.vertex0() && vertex != it.vertex1()) {
- freeVertex = vertex;
- orient = orientToEdge(m_texcoords[it.vertex0()], m_texcoords[it.vertex1()], m_texcoords[m_mesh->vertexAt(m_patch[i] * 3 + j)]);
- break;
- }
- }
- XA_DEBUG_ASSERT(freeVertex != UINT32_MAX);
- // If the free vertex is already in the patch, the face is enclosed by the patch. Add the face to the patch - don't need to assign texcoords.
- if (m_vertexInPatch.get(freeVertex)) {
- freeVertex = UINT32_MAX;
- m_patch.push_back(oface);
- m_faceAssigned.set(oface);
- continue;
- }
- // Check this here rather than above so faces enclosed by the patch are always added.
- if (m_faceInvalid.get(oface))
- continue;
- addCandidateFace(it.edge(), orient, oface, it.oppositeEdge(), freeVertex);
- }
- }
- // Link candidates that share the same vertex.
- for (uint32_t i = 0; i < m_candidates.size(); i++) {
- if (m_candidates[i].next != UINT32_MAX)
+ void addFaceToPatch(uint32_t face)
+ {
+ XA_DEBUG_ASSERT(!m_faceInPatch.get(face));
+ XA_DEBUG_ASSERT(!m_faceInAnyPatch.get(face));
+ m_patch.push_back(face);
+ m_faceInPatch.set(face);
+ m_faceInAnyPatch.set(face);
+ // Find new candidate faces on the patch incident to the newly added face.
+ for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
+ const uint32_t oface = it.oppositeFace();
+ if (oface == UINT32_MAX || oface >= m_faceCount || m_faceInAnyPatch.get(oface) || m_faceToCandidate[oface])
continue;
- uint32_t current = i;
- for (uint32_t j = i + 1; j < m_candidates.size(); j++) {
- if (m_candidates[j].vertex == m_candidates[current].vertex) {
- m_candidates[current].next = j;
- current = j;
+ // Found an active edge on the patch front.
+ // Find the free vertex (the vertex that isn't on the active edge).
+ // Compute the orientation of the other patch face vertex to the active edge.
+ uint32_t freeVertex = UINT32_MAX;
+ float orient = 0.0f;
+ for (uint32_t j = 0; j < 3; j++) {
+ const uint32_t vertex = m_mesh->vertexAt(oface * 3 + j);
+ if (vertex != it.vertex0() && vertex != it.vertex1()) {
+ freeVertex = vertex;
+ orient = orientToEdge(m_texcoords[it.vertex0()], m_texcoords[it.vertex1()], m_texcoords[m_mesh->vertexAt(face * 3 + j)]);
+ break;
}
}
- }
- // Set max cost for linked candidates.
- for (uint32_t i = 0; i < m_candidates.size(); i++) {
- float maxCost = 0.0f;
- for (CandidateIterator it(m_candidates, i); !it.isDone(); it.advance())
- maxCost = max(maxCost, it.current().cost);
- for (CandidateIterator it(m_candidates, i); !it.isDone(); it.advance())
- it.current().maxCost = maxCost;
+ XA_DEBUG_ASSERT(freeVertex != UINT32_MAX);
+ // If the free vertex is already in the patch, the face is enclosed by the patch. Add the face to the patch - don't need to assign texcoords.
+ /*if (m_vertexInPatch.get(freeVertex)) {
+ freeVertex = UINT32_MAX;
+ addFaceToPatch(oface, false);
+ continue;
+ }*/
+ // Check this here rather than above so faces enclosed by the patch are always added.
+ if (m_faceInvalid.get(oface))
+ continue;
+ addCandidateFace(it.edge(), orient, oface, it.oppositeEdge(), freeVertex);
}
}
- void addCandidateFace(uint32_t patchEdge, float patchVertexOrient, uint32_t face, uint32_t edge, uint32_t freeVertex) {
+ void addCandidateFace(uint32_t patchEdge, float patchVertexOrient, uint32_t face, uint32_t edge, uint32_t freeVertex)
+ {
+ XA_DEBUG_ASSERT(!m_faceToCandidate[face]);
Vector2 texcoords[3];
orthoProjectFace(face, texcoords);
// Find corresponding vertices between the patch edge and candidate edge.
@@ -6040,8 +6936,9 @@ private:
const Vector2 localEdgeVec = texcoords[localVertex1] - texcoords[localVertex0];
const float len1 = length(patchEdgeVec);
const float len2 = length(localEdgeVec);
+ if (len1 <= 0.0f || len2 <= 0.0f)
+ return; // Zero length edge.
const float scale = len1 / len2;
- XA_ASSERT(scale > 0.0f);
for (uint32_t i = 0; i < 3; i++)
texcoords[i] *= scale;
// Translate to the first vertex on the patch edge.
@@ -6063,6 +6960,8 @@ private:
uv.x = x + texcoords[localVertex0].x;
uv.y = y + texcoords[localVertex0].y;
}
+ if (isNan(texcoords[localFreeVertex].x) || isNan(texcoords[localFreeVertex].y))
+ return;
// Check for local overlap (flipped triangle).
// The patch face vertex that isn't on the active edge and the free vertex should be oriented on opposite sides to the active edge.
const float freeVertexOrient = orientToEdge(m_texcoords[vertex0], m_texcoords[vertex1], texcoords[localFreeVertex]);
@@ -6083,19 +6982,72 @@ private:
}
#endif
// Add the candidate.
- Candidate candidate;
- candidate.face = face;
- candidate.vertex = freeVertex;
- candidate.position = texcoords[localFreeVertex];
- candidate.next = UINT32_MAX;
- candidate.cost = cost;
- candidate.patchEdge = patchEdge;
- candidate.patchVertexOrient = patchVertexOrient;
+ Candidate *candidate = XA_ALLOC(MemTag::Default, Candidate);
+ candidate->face = face;
+ candidate->vertex = freeVertex;
+ candidate->position = texcoords[localFreeVertex];
+ candidate->prev = candidate->next = nullptr;
+ candidate->cost = candidate->maxCost = cost;
+ candidate->patchEdge = patchEdge;
+ candidate->patchVertexOrient = patchVertexOrient;
m_candidates.push_back(candidate);
- m_faceInCandidates.set(face);
+ m_faceToCandidate[face] = candidate;
+ // Link with candidates that share the same vertex. Append to tail.
+ for (uint32_t i = 0; i < m_candidates.size() - 1; i++) {
+ if (m_candidates[i]->vertex == candidate->vertex) {
+ Candidate *tail = m_candidates[i];
+ for (;;) {
+ if (tail->next)
+ tail = tail->next;
+ else
+ break;
+ }
+ candidate->prev = tail;
+ candidate->next = nullptr;
+ tail->next = candidate;
+ break;
+ }
+ }
+ // Set max cost for linked candidates.
+ Candidate *head = linkedCandidateHead(candidate);
+ float maxCost = 0.0f;
+ for (CandidateIterator it(head); !it.isDone(); it.advance())
+ maxCost = max(maxCost, it.current()->cost);
+ for (CandidateIterator it(head); !it.isDone(); it.advance())
+ it.current()->maxCost = maxCost;
+ }
+
+ Candidate *linkedCandidateHead(Candidate *candidate)
+ {
+ Candidate *current = candidate;
+ for (;;) {
+ if (!current->prev)
+ break;
+ current = current->prev;
+ }
+ return current;
}
- void orthoProjectFace(uint32_t face, Vector2 *texcoords) const {
+ void removeLinkedCandidates(Candidate *head)
+ {
+ XA_DEBUG_ASSERT(!head->prev);
+ Candidate *current = head;
+ while (current) {
+ Candidate *next = current->next;
+ m_faceToCandidate[current->face] = nullptr;
+ for (uint32_t i = 0; i < m_candidates.size(); i++) {
+ if (m_candidates[i] == current) {
+ m_candidates.removeAt(i);
+ break;
+ }
+ }
+ XA_FREE(current);
+ current = next;
+ }
+ }
+
+ void orthoProjectFace(uint32_t face, Vector2 *texcoords) const
+ {
const Vector3 normal = m_mesh->computeFaceNormal(face);
const Vector3 tangent = normalize(m_mesh->position(m_mesh->vertexAt(face * 3 + 1)) - m_mesh->position(m_mesh->vertexAt(face * 3 + 0)), kEpsilon);
const Vector3 bitangent = cross(normal, tangent);
@@ -6105,14 +7057,16 @@ private:
}
}
- float parametricArea(const Vector2 *texcoords) const {
+ float parametricArea(const Vector2 *texcoords) const
+ {
const Vector2 &v1 = texcoords[0];
const Vector2 &v2 = texcoords[1];
const Vector2 &v3 = texcoords[2];
return ((v2.x - v1.x) * (v3.y - v1.y) - (v3.x - v1.x) * (v2.y - v1.y)) * 0.5f;
}
- float computeStretch(Vector3 p1, Vector3 p2, Vector3 p3, Vector2 t1, Vector2 t2, Vector2 t3) const {
+ float computeStretch(Vector3 p1, Vector3 p2, Vector3 p3, Vector2 t1, Vector2 t2, Vector2 t3) const
+ {
float parametricArea = ((t2.y - t1.y) * (t3.x - t1.x) - (t3.y - t1.y) * (t2.x - t1.x)) * 0.5f;
if (isZero(parametricArea, kAreaEpsilon))
return FLT_MAX;
@@ -6126,14 +7080,16 @@ private:
}
// Return value is positive if the point is one side of the edge, negative if on the other side.
- float orientToEdge(Vector2 edgeVertex0, Vector2 edgeVertex1, Vector2 point) const {
+ float orientToEdge(Vector2 edgeVertex0, Vector2 edgeVertex1, Vector2 point) const
+ {
return (edgeVertex0.x - point.x) * (edgeVertex1.y - point.y) - (edgeVertex0.y - point.y) * (edgeVertex1.x - point.x);
}
};
#endif
// Estimate quality of existing parameterization.
-struct Quality {
+struct Quality
+{
// computeBoundaryIntersection
bool boundaryIntersection = false;
@@ -6150,13 +7106,14 @@ struct Quality {
float conformalMetric = 0.0f;
float authalicMetric = 0.0f;
- void computeBoundaryIntersection(const Mesh *mesh, UniformGrid2 &boundaryGrid) {
+ void computeBoundaryIntersection(const Mesh *mesh, UniformGrid2 &boundaryGrid)
+ {
const Array<uint32_t> &boundaryEdges = mesh->boundaryEdges();
const uint32_t boundaryEdgeCount = boundaryEdges.size();
boundaryGrid.reset(mesh->texcoords(), mesh->indices(), boundaryEdgeCount);
for (uint32_t i = 0; i < boundaryEdgeCount; i++)
boundaryGrid.append(boundaryEdges[i]);
- boundaryIntersection = boundaryGrid.intersectSelf(mesh->epsilon());
+ boundaryIntersection = boundaryGrid.intersect(mesh->epsilon());
#if XA_DEBUG_EXPORT_BOUNDARY_GRID
static int exportIndex = 0;
char filename[256];
@@ -6166,7 +7123,8 @@ struct Quality {
#endif
}
- void computeFlippedFaces(const Mesh *mesh, uint32_t faceCount, Array<uint32_t> *flippedFaces) {
+ void computeFlippedFaces(const Mesh *mesh, uint32_t faceCount, Array<uint32_t> *flippedFaces)
+ {
totalTriangleCount = flippedTriangleCount = zeroAreaTriangleCount = 0;
if (flippedFaces)
flippedFaces->clear();
@@ -6201,7 +7159,8 @@ struct Quality {
flippedFaces->clear();
flippedTriangleCount = 0;
}
- if (flippedTriangleCount > totalTriangleCount / 2) {
+ if (flippedTriangleCount > totalTriangleCount / 2)
+ {
// If more than half the triangles are flipped, reverse the flipped / not flipped classification.
flippedTriangleCount = totalTriangleCount - flippedTriangleCount;
if (flippedFaces) {
@@ -6223,7 +7182,8 @@ struct Quality {
}
}
- void computeMetrics(const Mesh *mesh, uint32_t faceCount) {
+ void computeMetrics(const Mesh *mesh, uint32_t faceCount)
+ {
totalGeometricArea = totalParametricArea = 0.0f;
stretchMetric = maxStretchMetric = conformalMetric = authalicMetric = 0.0f;
for (uint32_t f = 0; f < faceCount; f++) {
@@ -6254,7 +7214,7 @@ struct Quality {
const float a = dot(Ss, Ss); // E
const float b = dot(Ss, St); // F
const float c = dot(St, St); // G
- // Compute eigen-values of the first fundamental form:
+ // Compute eigen-values of the first fundamental form:
const float sigma1 = sqrtf(0.5f * max(0.0f, a + c - sqrtf(square(a - c) + 4 * square(b)))); // gamma uppercase, min eigenvalue.
const float sigma2 = sqrtf(0.5f * max(0.0f, a + c + sqrtf(square(a - c) + 4 * square(b)))); // gamma lowercase, max eigenvalue.
XA_ASSERT(sigma2 > sigma1 || equal(sigma1, sigma2, kEpsilon));
@@ -6285,62 +7245,59 @@ struct Quality {
if (totalGeometricArea > 0.0f) {
const float normFactor = sqrtf(totalParametricArea / totalGeometricArea);
stretchMetric = sqrtf(stretchMetric / totalGeometricArea) * normFactor;
- maxStretchMetric *= normFactor;
+ maxStretchMetric *= normFactor;
conformalMetric = sqrtf(conformalMetric / totalGeometricArea);
authalicMetric = sqrtf(authalicMetric / totalGeometricArea);
}
}
};
-struct ChartWarningFlags {
- enum Enum {
- CloseHolesFailed = 1 << 1,
- FixTJunctionsDuplicatedEdge = 1 << 2,
- FixTJunctionsFailed = 1 << 3,
- TriangulateDuplicatedEdge = 1 << 4,
+struct ChartWarningFlags
+{
+ enum Enum
+ {
+ CloseHolesFailed = 1<<1,
+ FixTJunctionsDuplicatedEdge = 1<<2,
+ FixTJunctionsFailed = 1<<3,
+ TriangulateDuplicatedEdge = 1<<4,
};
};
-struct ChartCtorBuffers {
+struct ChartCtorBuffers
+{
Array<uint32_t> chartMeshIndices;
Array<uint32_t> unifiedMeshIndices;
Array<uint32_t> boundaryLoops;
};
-/// A chart is a connected set of faces with a certain topology (usually a disk).
-class Chart {
+class Chart
+{
public:
- Chart(ChartCtorBuffers &buffers, const Basis &basis, ConstArrayView<uint32_t> faces, const Mesh *originalMesh, uint32_t meshId, uint32_t chartGroupId, uint32_t chartId) :
- m_basis(basis), m_mesh(nullptr), m_unifiedMesh(nullptr), m_unmodifiedUnifiedMesh(nullptr), m_type(ChartType::LSCM), m_warningFlags(0), m_closedHolesCount(0), m_fixedTJunctionsCount(0) {
- XA_UNUSED(meshId);
+ Chart(ChartCtorBuffers &buffers, const ParameterizeOptions &options, const Basis &basis, ConstArrayView<uint32_t> faces, const Mesh *sourceMesh, uint32_t chartGroupId, uint32_t chartId) : m_basis(basis), m_mesh(nullptr), m_unifiedMesh(nullptr), m_unmodifiedUnifiedMesh(nullptr), m_type(ChartType::LSCM), m_warningFlags(0), m_closedHolesCount(0), m_fixedTJunctionsCount(0), m_isInvalid(false)
+ {
XA_UNUSED(chartGroupId);
XA_UNUSED(chartId);
- m_faceArray.copyFrom(faces.data, faces.length);
- // Copy face indices.
- m_mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, originalMesh->epsilon(), m_faceArray.size() * 3, m_faceArray.size());
- m_unifiedMesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, originalMesh->epsilon(), m_faceArray.size() * 3, m_faceArray.size());
- Array<uint32_t> &chartMeshIndices = buffers.chartMeshIndices;
- chartMeshIndices.resize(originalMesh->vertexCount());
- chartMeshIndices.setAll(UINT32_MAX);
- Array<uint32_t> &unifiedMeshIndices = buffers.unifiedMeshIndices;
- unifiedMeshIndices.resize(originalMesh->vertexCount());
- unifiedMeshIndices.setAll(UINT32_MAX);
+ m_faceToSourceFaceMap.copyFrom(faces.data, faces.length);
+ const uint32_t approxVertexCount = min(faces.length * 3, sourceMesh->vertexCount());
+ m_mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), approxVertexCount, faces.length);
+ m_unifiedMesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), approxVertexCount, faces.length);
+ HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToUnifiedVertexMap(MemTag::Mesh, approxVertexCount), sourceVertexToChartVertexMap(MemTag::Mesh, approxVertexCount);
// Add vertices.
- const uint32_t faceCount = m_initialFaceCount = m_faceArray.size();
+ const uint32_t faceCount = m_initialFaceCount = faces.length;
for (uint32_t f = 0; f < faceCount; f++) {
for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = originalMesh->vertexAt(m_faceArray[f] * 3 + i);
- const uint32_t unifiedVertex = originalMesh->firstColocal(vertex);
- if (unifiedMeshIndices[unifiedVertex] == (uint32_t)~0) {
- unifiedMeshIndices[unifiedVertex] = m_unifiedMesh->vertexCount();
- XA_DEBUG_ASSERT(equal(originalMesh->position(vertex), originalMesh->position(unifiedVertex), originalMesh->epsilon()));
- m_unifiedMesh->addVertex(originalMesh->position(vertex));
+ const uint32_t sourceVertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
+ const uint32_t sourceUnifiedVertex = sourceMesh->firstColocal(sourceVertex);
+ uint32_t unifiedVertex = sourceVertexToUnifiedVertexMap.get(sourceUnifiedVertex);
+ if (unifiedVertex == UINT32_MAX) {
+ unifiedVertex = sourceVertexToUnifiedVertexMap.add(sourceUnifiedVertex);
+ m_unifiedMesh->addVertex(sourceMesh->position(sourceVertex));
}
- if (chartMeshIndices[vertex] == (uint32_t)~0) {
- chartMeshIndices[vertex] = m_mesh->vertexCount();
- m_chartToOriginalMap.push_back(vertex);
- m_chartToUnifiedMap.push_back(unifiedMeshIndices[unifiedVertex]);
- m_mesh->addVertex(originalMesh->position(vertex), Vector3(0.0f), originalMesh->texcoord(vertex));
+ if (sourceVertexToChartVertexMap.get(sourceVertex) == UINT32_MAX) {
+ sourceVertexToChartVertexMap.add(sourceVertex);
+ m_vertexToSourceVertexMap.push_back(sourceVertex);
+ m_chartVertexToUnifiedVertexMap.push_back(unifiedVertex);
+ m_mesh->addVertex(sourceMesh->position(sourceVertex), Vector3(0.0f), sourceMesh->texcoord(sourceVertex));
}
}
}
@@ -6348,9 +7305,12 @@ public:
for (uint32_t f = 0; f < faceCount; f++) {
uint32_t indices[3], unifiedIndices[3];
for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = originalMesh->vertexAt(m_faceArray[f] * 3 + i);
- indices[i] = chartMeshIndices[vertex];
- unifiedIndices[i] = unifiedMeshIndices[originalMesh->firstColocal(vertex)];
+ const uint32_t sourceVertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
+ const uint32_t sourceUnifiedVertex = sourceMesh->firstColocal(sourceVertex);
+ indices[i] = sourceVertexToChartVertexMap.get(sourceVertex);
+ XA_DEBUG_ASSERT(indices[i] != UINT32_MAX);
+ unifiedIndices[i] = sourceVertexToUnifiedVertexMap.get(sourceUnifiedVertex);
+ XA_DEBUG_ASSERT(unifiedIndices[i] != UINT32_MAX);
}
Mesh::AddFaceResult::Enum result = m_mesh->addFace(indices);
XA_UNUSED(result);
@@ -6368,15 +7328,18 @@ public:
XA_DEBUG_ASSERT(result == Mesh::AddFaceResult::OK);
}
m_mesh->createBoundaries(); // For AtlasPacker::computeBoundingBox
+ m_mesh->destroyEdgeMap(); // Only needed it for createBoundaries.
m_unifiedMesh->createBoundaries();
- if (meshIsPlanar(*m_unifiedMesh))
+ if (meshIsPlanar(*m_unifiedMesh)) {
m_type = ChartType::Planar;
- else {
- m_unifiedMesh->linkBoundaries();
+ return;
+ }
+ m_unifiedMesh->linkBoundaries();
#if XA_DEBUG_EXPORT_OBJ_BEFORE_FIX_TJUNCTION
- m_unifiedMesh->writeObjFile("debug_before_fix_tjunction.obj");
+ m_unifiedMesh->writeObjFile("debug_before_fix_tjunction.obj");
#endif
- bool duplicatedEdge = false, failed = false;
+ bool duplicatedEdge = false, failed = false;
+ if (options.fixTJunctions) {
XA_PROFILE_START(fixChartMeshTJunctions)
Mesh *fixedUnifiedMesh = meshFixTJunctions(*m_unifiedMesh, &duplicatedEdge, &failed, &m_fixedTJunctionsCount);
XA_PROFILE_END(fixChartMeshTJunctions)
@@ -6391,6 +7354,8 @@ public:
m_unifiedMesh->linkBoundaries();
m_initialFaceCount = m_unifiedMesh->faceCount(); // Fixing t-junctions rewrites faces.
}
+ }
+ if (options.closeHoles) {
// See if there are any holes that need closing.
Array<uint32_t> &boundaryLoops = buffers.boundaryLoops;
meshGetBoundaryLoops(*m_unifiedMesh, boundaryLoops);
@@ -6421,7 +7386,7 @@ public:
#if XA_DEBUG_EXPORT_OBJ_CLOSE_HOLES_ERROR
if (m_warningFlags & ChartWarningFlags::CloseHolesFailed) {
char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_chart_%03u_close_holes_error.obj", meshId, chartGroupId, chartId);
+ XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_chart_%03u_close_holes_error.obj", sourceMesh->id(), chartGroupId, chartId);
FILE *file;
XA_FOPEN(file, filename, "w");
if (file) {
@@ -6450,88 +7415,57 @@ public:
}
#if XA_RECOMPUTE_CHARTS
- Chart(ChartCtorBuffers &buffers, const Chart *parent, const Mesh *parentMesh, ConstArrayView<uint32_t> faces, const Vector2 *texcoords, const Mesh *originalMesh, uint32_t meshId, uint32_t chartGroupId, uint32_t chartId) :
- m_mesh(nullptr), m_unifiedMesh(nullptr), m_unmodifiedUnifiedMesh(nullptr), m_type(ChartType::Piecewise), m_warningFlags(0), m_closedHolesCount(0), m_fixedTJunctionsCount(0) {
- XA_UNUSED(meshId);
- XA_UNUSED(chartGroupId);
- XA_UNUSED(chartId);
+ Chart(ChartCtorBuffers &buffers, const Chart *parent, const Mesh *parentMesh, ConstArrayView<uint32_t> faces, const Vector2 *texcoords, const Mesh *sourceMesh) : m_mesh(nullptr), m_unifiedMesh(nullptr), m_unmodifiedUnifiedMesh(nullptr), m_type(ChartType::Piecewise), m_warningFlags(0), m_closedHolesCount(0), m_fixedTJunctionsCount(0), m_isInvalid(false)
+ {
const uint32_t faceCount = m_initialFaceCount = faces.length;
- m_faceArray.resize(faceCount);
+ m_faceToSourceFaceMap.resize(faceCount);
for (uint32_t i = 0; i < faceCount; i++)
- m_faceArray[i] = parent->m_faceArray[faces[i]]; // Map faces to parent chart original mesh.
+ m_faceToSourceFaceMap[i] = parent->m_faceToSourceFaceMap[faces[i]]; // Map faces to parent chart source mesh.
// Copy face indices.
- m_mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, originalMesh->epsilon(), m_faceArray.size() * 3, m_faceArray.size());
- m_unifiedMesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, originalMesh->epsilon(), m_faceArray.size() * 3, m_faceArray.size());
+ m_mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), m_faceToSourceFaceMap.size() * 3, m_faceToSourceFaceMap.size());
Array<uint32_t> &chartMeshIndices = buffers.chartMeshIndices;
- chartMeshIndices.resize(originalMesh->vertexCount());
- chartMeshIndices.setAll(UINT32_MAX);
- Array<uint32_t> &unifiedMeshIndices = buffers.unifiedMeshIndices;
- unifiedMeshIndices.resize(originalMesh->vertexCount());
- unifiedMeshIndices.setAll(UINT32_MAX);
+ chartMeshIndices.resize(sourceMesh->vertexCount());
+ chartMeshIndices.fillBytes(0xff);
// Add vertices.
for (uint32_t f = 0; f < faceCount; f++) {
for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = originalMesh->vertexAt(m_faceArray[f] * 3 + i);
- const uint32_t unifiedVertex = originalMesh->firstColocal(vertex);
+ const uint32_t vertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
const uint32_t parentVertex = parentMesh->vertexAt(faces[f] * 3 + i);
- if (unifiedMeshIndices[unifiedVertex] == (uint32_t)~0) {
- unifiedMeshIndices[unifiedVertex] = m_unifiedMesh->vertexCount();
- XA_DEBUG_ASSERT(equal(originalMesh->position(vertex), originalMesh->position(unifiedVertex), originalMesh->epsilon()));
- m_unifiedMesh->addVertex(originalMesh->position(vertex), Vector3(0.0f), texcoords[parentVertex]);
- }
if (chartMeshIndices[vertex] == (uint32_t)~0) {
chartMeshIndices[vertex] = m_mesh->vertexCount();
- m_chartToOriginalMap.push_back(vertex);
- m_chartToUnifiedMap.push_back(unifiedMeshIndices[unifiedVertex]);
- m_mesh->addVertex(originalMesh->position(vertex), Vector3(0.0f), texcoords[parentVertex]);
+ m_vertexToSourceVertexMap.push_back(vertex);
+ m_mesh->addVertex(sourceMesh->position(vertex), Vector3(0.0f), texcoords[parentVertex]);
}
}
}
// Add faces.
for (uint32_t f = 0; f < faceCount; f++) {
- uint32_t indices[3], unifiedIndices[3];
+ uint32_t indices[3];
for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = originalMesh->vertexAt(m_faceArray[f] * 3 + i);
+ const uint32_t vertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
indices[i] = chartMeshIndices[vertex];
- unifiedIndices[i] = unifiedMeshIndices[originalMesh->firstColocal(vertex)];
}
Mesh::AddFaceResult::Enum result = m_mesh->addFace(indices);
XA_UNUSED(result);
XA_DEBUG_ASSERT(result == Mesh::AddFaceResult::OK);
-#if XA_DEBUG
- // Unifying colocals may create degenerate edges. e.g. if two triangle vertices are colocal.
- for (int i = 0; i < 3; i++) {
- const uint32_t index1 = unifiedIndices[i];
- const uint32_t index2 = unifiedIndices[(i + 1) % 3];
- XA_DEBUG_ASSERT(index1 != index2);
- }
-#endif
- result = m_unifiedMesh->addFace(unifiedIndices);
- XA_UNUSED(result);
- XA_DEBUG_ASSERT(result == Mesh::AddFaceResult::OK);
}
m_mesh->createBoundaries(); // For AtlasPacker::computeBoundingBox
- m_unifiedMesh->createBoundaries();
- m_unifiedMesh->linkBoundaries();
+ m_mesh->destroyEdgeMap(); // Only needed it for createBoundaries.
+ // Need to store texcoords for backup/restore so packing can be run multiple times.
+ backupTexcoords();
}
#endif
- ~Chart() {
+ ~Chart()
+ {
if (m_mesh) {
m_mesh->~Mesh();
XA_FREE(m_mesh);
}
- if (m_unifiedMesh) {
- m_unifiedMesh->~Mesh();
- XA_FREE(m_unifiedMesh);
- }
- if (m_unmodifiedUnifiedMesh) {
- m_unmodifiedUnifiedMesh->~Mesh();
- XA_FREE(m_unmodifiedUnifiedMesh);
- }
+ destroyUnifiedMesh();
}
- const Basis &basis() const { return m_basis; }
+ bool isInvalid() const { return m_isInvalid; }
ChartType::Enum type() const { return m_type; }
uint32_t warningFlags() const { return m_warningFlags; }
uint32_t closedHolesCount() const { return m_closedHolesCount; }
@@ -6541,45 +7475,71 @@ public:
#if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
const Array<uint32_t> &paramFlippedFaces() const { return m_paramFlippedFaces; }
#endif
- uint32_t mapFaceToSourceFace(uint32_t i) const { return m_faceArray[i]; }
+ uint32_t mapFaceToSourceFace(uint32_t i) const { return m_faceToSourceFaceMap[i]; }
+ uint32_t mapChartVertexToSourceVertex(uint32_t i) const { return m_vertexToSourceVertexMap[i]; }
const Mesh *mesh() const { return m_mesh; }
Mesh *mesh() { return m_mesh; }
const Mesh *unifiedMesh() const { return m_unifiedMesh; }
- Mesh *unifiedMesh() { return m_unifiedMesh; }
const Mesh *unmodifiedUnifiedMesh() const { return m_unmodifiedUnifiedMesh; }
- uint32_t mapChartVertexToOriginalVertex(uint32_t i) const { return m_chartToOriginalMap[i]; }
-
- void evaluateOrthoQuality(UniformGrid2 &boundaryGrid) {
- XA_PROFILE_START(parameterizeChartsEvaluateQuality)
- m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
- m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, nullptr);
- m_quality.computeMetrics(m_unifiedMesh, m_initialFaceCount);
- XA_PROFILE_END(parameterizeChartsEvaluateQuality)
- // Use orthogonal parameterization if quality is acceptable.
- if (!m_quality.boundaryIntersection && m_quality.totalGeometricArea > 0.0f && m_quality.stretchMetric <= 1.1f && m_quality.maxStretchMetric <= 1.25f)
- m_type = ChartType::Ortho;
- }
-
- void evaluateQuality(UniformGrid2 &boundaryGrid) {
- XA_PROFILE_START(parameterizeChartsEvaluateQuality)
- m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
+
+ void parameterize(const ParameterizeOptions &options, UniformGrid2 &boundaryGrid)
+ {
+ XA_PROFILE_START(parameterizeChartsOrthogonal)
+ {
+ // Project vertices to plane.
+ const uint32_t vertexCount = m_unifiedMesh->vertexCount();
+ for (uint32_t i = 0; i < vertexCount; i++)
+ m_unifiedMesh->texcoord(i) = Vector2(dot(m_basis.tangent, m_unifiedMesh->position(i)), dot(m_basis.bitangent, m_unifiedMesh->position(i)));
+ }
+ XA_PROFILE_END(parameterizeChartsOrthogonal)
+ // Computing charts checks for flipped triangles and boundary intersection. Don't need to do that again here if chart is planar.
+ if (m_type != ChartType::Planar) {
+ XA_PROFILE_START(parameterizeChartsEvaluateQuality)
+ m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
+ m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, nullptr);
+ m_quality.computeMetrics(m_unifiedMesh, m_initialFaceCount);
+ XA_PROFILE_END(parameterizeChartsEvaluateQuality)
+ // Use orthogonal parameterization if quality is acceptable.
+ if (!m_quality.boundaryIntersection && m_quality.flippedTriangleCount == 0 && m_quality.totalGeometricArea > 0.0f && m_quality.stretchMetric <= 1.1f && m_quality.maxStretchMetric <= 1.25f)
+ m_type = ChartType::Ortho;
+ }
+ if (m_type == ChartType::LSCM) {
+ XA_PROFILE_START(parameterizeChartsLSCM)
+ if (options.func) {
+ options.func(&m_unifiedMesh->position(0).x, &m_unifiedMesh->texcoord(0).x, m_unifiedMesh->vertexCount(), m_unifiedMesh->indices(), m_unifiedMesh->indexCount());
+ }
+ else
+ computeLeastSquaresConformalMap(m_unifiedMesh);
+ XA_PROFILE_END(parameterizeChartsLSCM)
+ XA_PROFILE_START(parameterizeChartsEvaluateQuality)
+ m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
#if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
- m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, &m_paramFlippedFaces);
+ m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, &m_paramFlippedFaces);
#else
- m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, nullptr);
+ m_quality.computeFlippedFaces(m_unifiedMesh, m_initialFaceCount, nullptr);
#endif
- // Don't need to call computeMetrics here, that's only used in evaluateOrthoQuality to determine if quality is acceptable enough to use ortho projection.
- XA_PROFILE_END(parameterizeChartsEvaluateQuality)
- }
-
- // Transfer parameterization from unified mesh to chart mesh.
- void transferParameterization() {
+ // Don't need to call computeMetrics here, that's only used in evaluateOrthoQuality to determine if quality is acceptable enough to use ortho projection.
+ if (m_quality.boundaryIntersection || m_quality.flippedTriangleCount > 0)
+ m_isInvalid = true;
+ XA_PROFILE_END(parameterizeChartsEvaluateQuality)
+ }
+#if XA_DEBUG_ALL_CHARTS_INVALID
+ m_isInvalid = true;
+#endif
+ // Transfer parameterization from unified mesh to chart mesh.
const uint32_t vertexCount = m_mesh->vertexCount();
for (uint32_t v = 0; v < vertexCount; v++)
- m_mesh->texcoord(v) = m_unifiedMesh->texcoord(m_chartToUnifiedMap[v]);
+ m_mesh->texcoord(v) = m_unifiedMesh->texcoord(m_chartVertexToUnifiedVertexMap[v]);
+ // Can destroy unified mesh now.
+ // But not if the parameterization is invalid, the unified mesh will be needed for PiecewiseParameterization.
+ if (!m_isInvalid)
+ destroyUnifiedMesh();
+ // Need to store texcoords for backup/restore so packing can be run multiple times.
+ backupTexcoords();
}
- Vector2 computeParametricBounds() const {
+ Vector2 computeParametricBounds() const
+ {
Vector2 minCorner(FLT_MAX, FLT_MAX);
Vector2 maxCorner(-FLT_MAX, -FLT_MAX);
const uint32_t vertexCount = m_mesh->vertexCount();
@@ -6590,7 +7550,34 @@ public:
return (maxCorner - minCorner) * 0.5f;
}
+ void restoreTexcoords()
+ {
+ memcpy(m_mesh->texcoords(), m_backupTexcoords.data(), m_mesh->vertexCount() * sizeof(Vector2));
+ }
+
private:
+ void backupTexcoords()
+ {
+ m_backupTexcoords.resize(m_mesh->vertexCount());
+ memcpy(m_backupTexcoords.data(), m_mesh->texcoords(), m_mesh->vertexCount() * sizeof(Vector2));
+ }
+
+ void destroyUnifiedMesh()
+ {
+ if (m_unifiedMesh) {
+ m_unifiedMesh->~Mesh();
+ XA_FREE(m_unifiedMesh);
+ m_unifiedMesh = nullptr;
+ }
+ if (m_unmodifiedUnifiedMesh) {
+ m_unmodifiedUnifiedMesh->~Mesh();
+ XA_FREE(m_unmodifiedUnifiedMesh);
+ m_unmodifiedUnifiedMesh = nullptr;
+ }
+ // Don't need this when unified meshes are destroyed.
+ m_chartVertexToUnifiedVertexMap.destroy();
+ }
+
Basis m_basis;
Mesh *m_mesh;
Mesh *m_unifiedMesh;
@@ -6600,467 +7587,511 @@ private:
uint32_t m_initialFaceCount; // Before fixing T-junctions and/or closing holes.
uint32_t m_closedHolesCount, m_fixedTJunctionsCount;
- // List of faces of the original mesh that belong to this chart.
- Array<uint32_t> m_faceArray;
+ // List of faces of the source mesh that belong to this chart.
+ Array<uint32_t> m_faceToSourceFaceMap;
- // Map vertices of the chart mesh to vertices of the original mesh.
- Array<uint32_t> m_chartToOriginalMap;
+ // Map vertices of the chart mesh to vertices of the source mesh.
+ Array<uint32_t> m_vertexToSourceVertexMap;
- Array<uint32_t> m_chartToUnifiedMap;
+ Array<uint32_t> m_chartVertexToUnifiedVertexMap;
+
+ Array<Vector2> m_backupTexcoords;
Quality m_quality;
#if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
Array<uint32_t> m_paramFlippedFaces;
#endif
+ bool m_isInvalid;
};
-struct CreateChartTaskArgs {
- const Mesh *mesh;
+struct CreateAndParameterizeChartTaskArgs
+{
const Basis *basis;
+ ThreadLocal<UniformGrid2> *boundaryGrid;
+ Chart *chart; // output
+ Array<Chart *> charts; // output (if more than one chart)
+ ThreadLocal<ChartCtorBuffers> *chartBuffers;
+ const Mesh *mesh;
+ const ParameterizeOptions *options;
+#if XA_RECOMPUTE_CHARTS
+ ThreadLocal<PiecewiseParam> *pp;
+#endif
ConstArrayView<uint32_t> faces;
- uint32_t meshId;
uint32_t chartGroupId;
uint32_t chartId;
- ThreadLocal<ChartCtorBuffers> *chartBuffers;
- Chart **chart;
};
-static void runCreateChartTask(void *userData) {
- XA_PROFILE_START(createChartMeshesThread)
- auto args = (CreateChartTaskArgs *)userData;
- *(args->chart) = XA_NEW_ARGS(MemTag::Default, Chart, args->chartBuffers->get(), *(args->basis), args->faces, args->mesh, args->meshId, args->chartGroupId, args->chartId);
- XA_PROFILE_END(createChartMeshesThread)
-}
-
-struct ParameterizeChartTaskArgs {
- Chart *chart;
- ParameterizeFunc func;
- ThreadLocal<UniformGrid2> *boundaryGrid;
-};
-
-static void runParameterizeChartTask(void *userData) {
- auto args = (ParameterizeChartTaskArgs *)userData;
- Mesh *mesh = args->chart->unifiedMesh();
- XA_PROFILE_START(parameterizeChartsOrthogonal) {
- // Project vertices to plane.
- const uint32_t vertexCount = mesh->vertexCount();
- const Basis &basis = args->chart->basis();
- for (uint32_t i = 0; i < vertexCount; i++)
- mesh->texcoord(i) = Vector2(dot(basis.tangent, mesh->position(i)), dot(basis.bitangent, mesh->position(i)));
- }
- XA_PROFILE_END(parameterizeChartsOrthogonal)
- // Computing charts checks for flipped triangles and boundary intersection. Don't need to do that again here if chart is planar.
- if (args->chart->type() != ChartType::Planar)
- args->chart->evaluateOrthoQuality(args->boundaryGrid->get());
- if (args->chart->type() == ChartType::LSCM) {
- XA_PROFILE_START(parameterizeChartsLSCM)
- if (args->func)
- args->func(&mesh->position(0).x, &mesh->texcoord(0).x, mesh->vertexCount(), mesh->indices(), mesh->indexCount());
- else
- computeLeastSquaresConformalMap(mesh);
- XA_PROFILE_END(parameterizeChartsLSCM)
- args->chart->evaluateQuality(args->boundaryGrid->get());
+static void runCreateAndParameterizeChartTask(void *userData)
+{
+ auto args = (CreateAndParameterizeChartTaskArgs *)userData;
+ XA_PROFILE_START(createChartMesh)
+ args->chart = XA_NEW_ARGS(MemTag::Default, Chart, args->chartBuffers->get(), *args->options, *args->basis, args->faces, args->mesh, args->chartGroupId, args->chartId);
+ XA_PROFILE_END(createChartMesh)
+ args->chart->parameterize(*args->options, args->boundaryGrid->get());
+#if XA_RECOMPUTE_CHARTS
+ if (!args->chart->isInvalid())
+ return;
+ // Recompute charts with invalid parameterizations.
+ XA_PROFILE_START(parameterizeChartsRecompute)
+ Chart *invalidChart = args->chart;
+ // Fixing t-junctions rewrites unified mesh faces, and we need to map faces back to input mesh. So use the unmodified unified mesh.
+ const Mesh *invalidMesh = invalidChart->unmodifiedUnifiedMesh();
+ uint32_t faceCount = 0;
+ if (invalidMesh) {
+ faceCount = invalidMesh->faceCount();
+ } else {
+ invalidMesh = invalidChart->unifiedMesh();
+ faceCount = invalidChart->initialFaceCount(); // Not invalidMesh->faceCount(). Don't want faces added by hole closing.
}
- // Transfer parameterization from unified mesh to chart mesh.
- args->chart->transferParameterization();
-}
-
-// Set of charts corresponding to mesh faces in the same face group.
-class ChartGroup {
-public:
- ChartGroup(uint32_t id, const Mesh *sourceMesh, uint16_t faceGroup) :
- m_sourceId(sourceMesh->id()), m_id(id), m_isVertexMap(faceGroup == Mesh::kInvalidFaceGroup), m_paramAddedChartsCount(0), m_paramDeletedChartsCount(0) {
- // Create new mesh from the source mesh, using faces that belong to this group.
- const uint32_t sourceFaceCount = sourceMesh->faceCount();
- if (!m_isVertexMap) {
- m_faceToSourceFaceMap.reserve(sourceMesh->faceGroupFaceCount(faceGroup));
- for (Mesh::GroupFaceIterator it(sourceMesh, faceGroup); !it.isDone(); it.advance())
- m_faceToSourceFaceMap.push_back(it.face());
- } else {
- for (uint32_t f = 0; f < sourceFaceCount; f++) {
- if (sourceMesh->faceGroupAt(f) == faceGroup)
- m_faceToSourceFaceMap.push_back(f);
+ PiecewiseParam &pp = args->pp->get();
+ pp.reset(invalidMesh, faceCount);
+#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
+ char filename[256];
+ XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_chart_%03u_recomputed.obj", args->mesh->id(), args->chartGroupId, args->chartId);
+ FILE *file;
+ XA_FOPEN(file, filename, "w");
+ uint32_t subChartIndex = 0;
+#endif
+ for (;;) {
+ XA_PROFILE_START(parameterizeChartsPiecewise)
+ const bool facesRemaining = pp.computeChart();
+ XA_PROFILE_END(parameterizeChartsPiecewise)
+ if (!facesRemaining)
+ break;
+ Chart *chart = XA_NEW_ARGS(MemTag::Default, Chart, args->chartBuffers->get(), invalidChart, invalidMesh, pp.chartFaces(), pp.texcoords(), args->mesh);
+ args->charts.push_back(chart);
+#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
+ if (file) {
+ for (uint32_t j = 0; j < invalidMesh->vertexCount(); j++) {
+ fprintf(file, "v %g %g %g\n", invalidMesh->position(j).x, invalidMesh->position(j).y, invalidMesh->position(j).z);
+ fprintf(file, "vt %g %g\n", pp.texcoords()[j].x, pp.texcoords()[j].y);
}
- }
- // Only initial meshes have face groups and ignored faces. The only flag we care about is HasNormals.
- const uint32_t faceCount = m_faceToSourceFaceMap.size();
- XA_DEBUG_ASSERT(faceCount > 0);
- const uint32_t approxVertexCount = faceCount * 3;
- m_mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), approxVertexCount, faceCount, sourceMesh->flags() & MeshFlags::HasNormals);
- m_vertexToSourceVertexMap.reserve(approxVertexCount);
- HashMap<uint32_t> sourceVertexToVertexMap(MemTag::Mesh, approxVertexCount);
- for (uint32_t f = 0; f < faceCount; f++) {
- const uint32_t face = m_faceToSourceFaceMap[f];
- for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = sourceMesh->vertexAt(face * 3 + i);
- if (sourceVertexToVertexMap.get(vertex) == UINT32_MAX) {
- sourceVertexToVertexMap.add(vertex);
- m_vertexToSourceVertexMap.push_back(vertex);
- Vector3 normal(0.0f);
- if (sourceMesh->flags() & MeshFlags::HasNormals)
- normal = sourceMesh->normal(vertex);
- m_mesh->addVertex(sourceMesh->position(vertex), normal, sourceMesh->texcoord(vertex));
+ fprintf(file, "o chart%03u\n", subChartIndex);
+ fprintf(file, "s off\n");
+ for (uint32_t f = 0; f < pp.chartFaces().length; f++) {
+ fprintf(file, "f ");
+ const uint32_t face = pp.chartFaces()[f];
+ for (uint32_t j = 0; j < 3; j++) {
+ const uint32_t index = invalidMesh->vertexCount() * subChartIndex + invalidMesh->vertexAt(face * 3 + j) + 1; // 1-indexed
+ fprintf(file, "%d/%d/%c", index, index, j == 2 ? '\n' : ' ');
}
}
}
- // Add faces.
- for (uint32_t f = 0; f < faceCount; f++) {
- const uint32_t face = m_faceToSourceFaceMap[f];
- uint32_t indices[3];
- for (uint32_t i = 0; i < 3; i++) {
- const uint32_t vertex = sourceMesh->vertexAt(face * 3 + i);
- indices[i] = sourceVertexToVertexMap.get(vertex);
- XA_DEBUG_ASSERT(indices[i] != UINT32_MAX);
- }
- // Don't copy flags, it doesn't matter if a face is ignored after this point. All ignored faces get their own vertex map (m_isVertexMap) ChartGroup.
- // Don't hash edges if m_isVertexMap, they may be degenerate.
- Mesh::AddFaceResult::Enum result = m_mesh->addFace(indices, false, !m_isVertexMap);
- XA_UNUSED(result);
- XA_DEBUG_ASSERT(result == Mesh::AddFaceResult::OK);
- }
- if (!m_isVertexMap) {
- m_mesh->createColocals();
- m_mesh->createBoundaries();
- }
-#if XA_DEBUG_EXPORT_OBJ_CHART_GROUPS
- char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u.obj", m_sourceId, m_id);
- m_mesh->writeObjFile(filename);
-#else
- XA_UNUSED(m_id);
+ subChartIndex++;
+#endif
+ }
+#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
+ if (file)
+ fclose(file);
#endif
+ XA_PROFILE_END(parameterizeChartsRecompute)
+#endif // XA_RECOMPUTE_CHARTS
+}
+
+// Set of charts corresponding to mesh faces in the same face group.
+class ChartGroup
+{
+public:
+ ChartGroup(uint32_t id, const Mesh *sourceMesh, const MeshFaceGroups *sourceMeshFaceGroups, MeshFaceGroups::Handle faceGroup) : m_id(id), m_sourceMesh(sourceMesh), m_sourceMeshFaceGroups(sourceMeshFaceGroups), m_faceGroup(faceGroup), m_faceCount(0), m_paramAddedChartsCount(0), m_paramDeletedChartsCount(0)
+ {
}
- ~ChartGroup() {
- m_mesh->~Mesh();
- XA_FREE(m_mesh);
+ ~ChartGroup()
+ {
for (uint32_t i = 0; i < m_charts.size(); i++) {
m_charts[i]->~Chart();
XA_FREE(m_charts[i]);
}
}
+ uint32_t segmentChartCount() const { return m_chartBasis.size(); }
uint32_t chartCount() const { return m_charts.size(); }
Chart *chartAt(uint32_t i) const { return m_charts[i]; }
+ uint32_t faceCount() const { return m_faceCount; }
uint32_t paramAddedChartsCount() const { return m_paramAddedChartsCount; }
uint32_t paramDeletedChartsCount() const { return m_paramDeletedChartsCount; }
- bool isVertexMap() const { return m_isVertexMap; }
- uint32_t mapFaceToSourceFace(uint32_t face) const { return m_faceToSourceFaceMap[face]; }
- uint32_t mapVertexToSourceVertex(uint32_t i) const { return m_vertexToSourceVertexMap[i]; }
- const Mesh *mesh() const { return m_mesh; }
- /*
- Compute charts using a simple segmentation algorithm.
-
- LSCM:
- - identify sharp features using local dihedral angles.
- - identify seed faces farthest from sharp features.
- - grow charts from these seeds.
-
- MCGIM:
- - phase 1: chart growth
- - grow all charts simultaneously using dijkstra search on the dual graph of the mesh.
- - graph edges are weighted based on planarity metric.
- - metric uses distance to global chart normal.
- - terminate when all faces have been assigned.
- - phase 2: seed computation:
- - place new seed of the chart at the most interior face.
- - most interior is evaluated using distance metric only.
-
- - method repeates the two phases, until the location of the seeds does not change.
- - cycles are detected by recording all the previous seeds and chartification terminates.
-
- D-Charts:
-
- - Uniaxial conic metric:
- - N_c = axis of the generalized cone that best fits the chart. (cone can a be cylinder or a plane).
- - omega_c = angle between the face normals and the axis.
- - Fitting error between chart C and tringle t: F(c,t) = (N_c*n_t - cos(omega_c))^2
-
- - Compactness metrics:
- - Roundness:
- - C(c,t) = pi * D(S_c,t)^2 / A_c
- - S_c = chart seed.
- - D(S_c,t) = length of the shortest path inside the chart betwen S_c and t.
- - A_c = chart area.
- - Straightness:
- - P(c,t) = l_out(c,t) / l_in(c,t)
- - l_out(c,t) = lenght of the edges not shared between C and t.
- - l_in(c,t) = lenght of the edges shared between C and t.
-
- - Combined metric:
- - Cost(c,t) = F(c,t)^alpha + C(c,t)^beta + P(c,t)^gamma
- - alpha = 1, beta = 0.7, gamma = 0.5
-
- Our basic approach:
- - Just one iteration of k-means?
- - Avoid dijkstra by greedily growing charts until a threshold is met. Increase threshold and repeat until no faces left.
- - If distortion metric is too high, split chart, add two seeds.
- - If chart size is low, try removing chart.
-
- Postprocess:
- - If topology is not disk:
- - Fill holes, if new faces fit proxy.
- - Find best cut, otherwise.
- - After parameterization:
- - If boundary self-intersects:
- - cut chart along the closest two diametral boundary vertices, repeat parametrization.
- - what if the overlap is on an appendix? How do we find that out and cut appropiately?
- - emphasize roundness metrics to prevent those cases.
- - If interior self-overlaps: preserve boundary parameterization and use mean-value map.
- */
- void computeCharts(TaskScheduler *taskScheduler, const ChartOptions &options, segment::Atlas &atlas, ThreadLocal<ChartCtorBuffers> *chartBuffers) {
- m_chartOptions = options;
- // This function may be called multiple times, so destroy existing charts.
- for (uint32_t i = 0; i < m_charts.size(); i++) {
- m_charts[i]->~Chart();
- XA_FREE(m_charts[i]);
- }
- m_charts.clear();
+ void computeChartFaces(const ChartOptions &options, segment::Atlas &atlas)
+ {
+ // Create mesh from source mesh, using only the faces in this face group.
+ XA_PROFILE_START(createChartGroupMesh)
+ Mesh *mesh = createMesh();
+ XA_PROFILE_END(createChartGroupMesh)
+ // Segment mesh into charts (arrays of faces).
#if XA_DEBUG_SINGLE_CHART
- Array<uint32_t> chartFaces;
- chartFaces.resize(m_mesh->faceCount());
- for (uint32_t i = 0; i < chartFaces.size(); i++)
- chartFaces[i] = i;
- Chart *chart = XA_NEW_ARGS(MemTag::Default, Chart, m_mesh, chartFaces, m_sourceId, m_id, 0);
- m_charts.push_back(chart);
+ m_chartBasis.resize(1);
+ Fit::computeBasis(&mesh->position(0), mesh->vertexCount(), &m_chartBasis[0]);
+ m_chartFaces.resize(1 + mesh->faceCount());
+ m_chartFaces[0] = mesh->faceCount();
+ for (uint32_t i = 0; i < m_chartFaces.size(); i++)
+ m_chartFaces[i + 1] = i;
#else
XA_PROFILE_START(buildAtlas)
- atlas.reset(m_sourceId, m_id, m_mesh, options);
- buildAtlas(atlas, options);
+ atlas.reset(mesh, options);
+ atlas.compute();
XA_PROFILE_END(buildAtlas)
- const uint32_t chartCount = atlas.chartCount();
- m_charts.resize(chartCount);
- Array<CreateChartTaskArgs> taskArgs;
- taskArgs.resize(chartCount);
- for (uint32_t i = 0; i < chartCount; i++) {
- CreateChartTaskArgs &args = taskArgs[i];
- args.basis = &atlas.chartBasis(i);
- args.faces = atlas.chartFaces(i);
- args.mesh = m_mesh;
- args.meshId = m_sourceId;
- args.chartGroupId = m_id;
- args.chartId = i;
- args.chartBuffers = chartBuffers;
- args.chart = &m_charts[i];
- }
- XA_PROFILE_START(createChartMeshesReal)
- TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartCount);
- for (uint32_t i = 0; i < chartCount; i++) {
- Task task;
- task.userData = &taskArgs[i];
- task.func = runCreateChartTask;
- taskScheduler->run(taskGroup, task);
- }
- taskScheduler->wait(&taskGroup);
- XA_PROFILE_END(createChartMeshesReal)
-#endif
#if XA_DEBUG_EXPORT_OBJ_CHARTS
char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_charts.obj", m_sourceId, m_id);
+ XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_charts.obj", m_sourceMesh->id(), m_id);
FILE *file;
XA_FOPEN(file, filename, "w");
if (file) {
- m_mesh->writeObjVertices(file);
- for (uint32_t i = 0; i < chartCount; i++) {
+ mesh->writeObjVertices(file);
+ for (uint32_t i = 0; i < atlas.chartCount(); i++) {
fprintf(file, "o chart_%04d\n", i);
fprintf(file, "s off\n");
- const Array<uint32_t> &faces = builder.chartFaces(i);
- for (uint32_t f = 0; f < faces.size(); f++)
- m_mesh->writeObjFace(file, faces[f]);
+ ConstArrayView<uint32_t> faces = atlas.chartFaces(i);
+ for (uint32_t f = 0; f < faces.length; f++)
+ mesh->writeObjFace(file, faces[f]);
}
- m_mesh->writeObjBoundaryEges(file);
- m_mesh->writeObjLinkedBoundaries(file);
+ mesh->writeObjBoundaryEges(file);
+ mesh->writeObjLinkedBoundaries(file);
fclose(file);
}
#endif
+ // Destroy mesh.
+ const uint32_t faceCount = mesh->faceCount();
+ mesh->~Mesh();
+ XA_FREE(mesh);
+ XA_PROFILE_START(copyChartFaces)
+ // Copy basis.
+ const uint32_t chartCount = atlas.chartCount();
+ m_chartBasis.resize(chartCount);
+ for (uint32_t i = 0; i < chartCount; i++)
+ m_chartBasis[i] = atlas.chartBasis(i);
+ // Copy faces from segment::Atlas to m_chartFaces array with <chart 0 face count> <face 0> <face n> <chart 1 face count> etc. encoding.
+ // segment::Atlas faces refer to the chart group mesh. Map them to the input mesh instead.
+ m_chartFaces.resize(chartCount + faceCount);
+ uint32_t offset = 0;
+ for (uint32_t i = 0; i < chartCount; i++) {
+ ConstArrayView<uint32_t> faces = atlas.chartFaces(i);
+ m_chartFaces[offset++] = faces.length;
+ for (uint32_t j = 0; j < faces.length; j++)
+ m_chartFaces[offset++] = m_faceToSourceFaceMap[faces[j]];
+ }
+ XA_PROFILE_END(copyChartFaces)
+#endif
}
#if XA_RECOMPUTE_CHARTS
- void parameterizeCharts(TaskScheduler *taskScheduler, ParameterizeFunc func, ThreadLocal<UniformGrid2> *boundaryGrid, ThreadLocal<ChartCtorBuffers> *chartBuffers, ThreadLocal<PiecewiseParam> *piecewiseParam)
+ void parameterizeCharts(TaskScheduler *taskScheduler, const ParameterizeOptions &options, ThreadLocal<UniformGrid2> *boundaryGrid, ThreadLocal<ChartCtorBuffers> *chartBuffers, ThreadLocal<PiecewiseParam> *piecewiseParam)
#else
- void parameterizeCharts(TaskScheduler *taskScheduler, ParameterizeFunc func, ThreadLocal<UniformGrid2> *boundaryGrid, ThreadLocal<ChartCtorBuffers> * /*chartBuffers*/)
+ void parameterizeCharts(TaskScheduler* taskScheduler, const ParameterizeOptions &options, ThreadLocal<UniformGrid2>* boundaryGrid, ThreadLocal<ChartCtorBuffers>* chartBuffers)
#endif
{
+ // This function may be called multiple times, so destroy existing charts.
+ for (uint32_t i = 0; i < m_charts.size(); i++) {
+ m_charts[i]->~Chart();
+ XA_FREE(m_charts[i]);
+ }
m_paramAddedChartsCount = 0;
- const uint32_t chartCount = m_charts.size();
- Array<ParameterizeChartTaskArgs> taskArgs;
+ const uint32_t chartCount = m_chartBasis.size();
+ Array<CreateAndParameterizeChartTaskArgs> taskArgs;
taskArgs.resize(chartCount);
+ taskArgs.runCtors(); // Has Array member.
TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartCount);
+ uint32_t offset = 0;
for (uint32_t i = 0; i < chartCount; i++) {
- ParameterizeChartTaskArgs &args = taskArgs[i];
- args.chart = m_charts[i];
- args.func = func;
+ CreateAndParameterizeChartTaskArgs &args = taskArgs[i];
+ args.basis = &m_chartBasis[i];
args.boundaryGrid = boundaryGrid;
+ args.chart = nullptr;
+ args.chartGroupId = m_id;
+ args.chartId = i;
+ args.chartBuffers = chartBuffers;
+ const uint32_t faceCount = m_chartFaces[offset++];
+ args.faces = ConstArrayView<uint32_t>(&m_chartFaces[offset], faceCount);
+ offset += faceCount;
+ args.mesh = m_sourceMesh;
+ args.options = &options;
+#if XA_RECOMPUTE_CHARTS
+ args.pp = piecewiseParam;
+#endif
Task task;
task.userData = &args;
- task.func = runParameterizeChartTask;
+ task.func = runCreateAndParameterizeChartTask;
taskScheduler->run(taskGroup, task);
}
taskScheduler->wait(&taskGroup);
#if XA_RECOMPUTE_CHARTS
- // Find charts with invalid parameterizations.
- Array<Chart *> invalidCharts;
+ // Count charts. Skip invalid ones and include new ones added by recomputing.
+ uint32_t newChartCount = 0;
for (uint32_t i = 0; i < chartCount; i++) {
- Chart *chart = m_charts[i];
- const Quality &quality = chart->quality();
- if (quality.boundaryIntersection || quality.flippedTriangleCount > 0)
- invalidCharts.push_back(chart);
+ if (taskArgs[i].chart->isInvalid())
+ newChartCount += taskArgs[i].charts.size();
+ else
+ newChartCount++;
}
- if (invalidCharts.isEmpty())
- return;
- // Recompute charts with invalid parameterizations.
- PiecewiseParam &pp = piecewiseParam->get();
- for (uint32_t i = 0; i < invalidCharts.size(); i++) {
- Chart *invalidChart = invalidCharts[i];
- // Fixing t-junctions rewrites unified mesh faces, and we need to map faces back to input mesh. So use the unmodified unified mesh.
- const Mesh *invalidMesh = invalidChart->unmodifiedUnifiedMesh();
- uint32_t faceCount = 0;
- if (invalidMesh) {
- faceCount = invalidMesh->faceCount();
- } else {
- invalidMesh = invalidChart->unifiedMesh();
- faceCount = invalidChart->initialFaceCount(); // Not invalidMesh->faceCount(). Don't want faces added by hole closing.
+ m_charts.resize(newChartCount);
+ // Add valid charts first. Destroy invalid ones.
+ uint32_t current = 0;
+ for (uint32_t i = 0; i < chartCount; i++) {
+ Chart *chart = taskArgs[i].chart;
+ if (chart->isInvalid()) {
+ chart->~Chart();
+ XA_FREE(chart);
+ m_paramDeletedChartsCount++;
+ continue;
}
- pp.reset(invalidMesh, faceCount);
-#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
- char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_recomputed_chart_%03u.obj", m_sourceId, m_id, m_paramAddedChartsCount);
- FILE *file;
- XA_FOPEN(file, filename, "w");
- uint32_t subChartIndex = 0;
-#endif
- for (;;) {
- if (!pp.computeChart())
- break;
- Chart *chart = XA_NEW_ARGS(MemTag::Default, Chart, chartBuffers->get(), invalidChart, invalidMesh, pp.chartFaces(), pp.texcoords(), m_mesh, m_sourceId, m_id, m_charts.size());
- m_charts.push_back(chart);
-#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
- if (file) {
- for (uint32_t j = 0; j < invalidMesh->vertexCount(); j++) {
- fprintf(file, "v %g %g %g\n", invalidMesh->position(j).x, invalidMesh->position(j).y, invalidMesh->position(j).z);
- fprintf(file, "vt %g %g\n", pp.texcoords()[j].x, pp.texcoords()[j].y);
- }
- fprintf(file, "o chart%03u\n", subChartIndex);
- fprintf(file, "s off\n");
- for (uint32_t f = 0; f < pp.chartFaces().length; f++) {
- fprintf(file, "f ");
- const uint32_t face = pp.chartFaces()[f];
- for (uint32_t j = 0; j < 3; j++) {
- const uint32_t index = invalidMesh->vertexCount() * subChartIndex + invalidMesh->vertexAt(face * 3 + j) + 1; // 1-indexed
- fprintf(file, "%d/%d/%c", index, index, j == 2 ? '\n' : ' ');
- }
- }
- }
- subChartIndex++;
-#endif
+ m_charts[current++] = chart;
+ }
+ // Now add new charts.
+ for (uint32_t i = 0; i < chartCount; i++) {
+ CreateAndParameterizeChartTaskArgs &args = taskArgs[i];
+ for (uint32_t j = 0; j < args.charts.size(); j++) {
+ m_charts[current++] = args.charts[j];
m_paramAddedChartsCount++;
}
-#if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
- if (file)
- fclose(file);
-#endif
- }
- // Remove and delete the invalid charts.
- for (uint32_t i = 0; i < invalidCharts.size(); i++) {
- Chart *chart = invalidCharts[i];
- removeChart(chart);
- chart->~Chart();
- XA_FREE(chart);
- m_paramDeletedChartsCount++;
}
+#else // XA_RECOMPUTE_CHARTS
+ m_charts.resize(chartCount);
+ for (uint32_t i = 0; i < chartCount; i++)
+ m_charts[i] = taskArgs[i].chart;
#endif // XA_RECOMPUTE_CHARTS
+ taskArgs.runDtors(); // Has Array member.
}
private:
- void buildAtlas(segment::Atlas &atlas, const ChartOptions &options) {
- if (atlas.facesLeft() == 0)
- return;
- // Create initial charts greedely.
- atlas.placeSeeds(options.maxThreshold * 0.5f);
- if (options.maxIterations == 0) {
- XA_DEBUG_ASSERT(atlas.facesLeft() == 0);
- return;
- }
- atlas.relocateSeeds();
- atlas.resetCharts();
- // Restart process growing charts in parallel.
- uint32_t iteration = 0;
- for (;;) {
- atlas.growCharts(options.maxThreshold);
- // When charts cannot grow more: fill holes, merge charts, relocate seeds and start new iteration.
- atlas.fillHoles(options.maxThreshold * 0.5f);
-#if XA_MERGE_CHARTS
- atlas.mergeCharts();
-#endif
- if (++iteration == options.maxIterations)
- break;
- if (!atlas.relocateSeeds())
- break;
- atlas.resetCharts();
+ Mesh *createMesh()
+ {
+ XA_DEBUG_ASSERT(m_faceGroup != MeshFaceGroups::kInvalid);
+ // Create new mesh from the source mesh, using faces that belong to this group.
+ m_faceToSourceFaceMap.reserve(m_sourceMeshFaceGroups->faceCount(m_faceGroup));
+ for (MeshFaceGroups::Iterator it(m_sourceMeshFaceGroups, m_faceGroup); !it.isDone(); it.advance())
+ m_faceToSourceFaceMap.push_back(it.face());
+ // Only initial meshes has ignored faces. The only flag we care about is HasNormals.
+ const uint32_t faceCount = m_faceCount = m_faceToSourceFaceMap.size();
+ XA_DEBUG_ASSERT(faceCount > 0);
+ const uint32_t approxVertexCount = min(faceCount * 3, m_sourceMesh->vertexCount());
+ Mesh *mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, m_sourceMesh->epsilon(), approxVertexCount, faceCount, m_sourceMesh->flags() & MeshFlags::HasNormals);
+ HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToVertexMap(MemTag::Mesh, approxVertexCount);
+ for (uint32_t f = 0; f < faceCount; f++) {
+ const uint32_t face = m_faceToSourceFaceMap[f];
+ for (uint32_t i = 0; i < 3; i++) {
+ const uint32_t vertex = m_sourceMesh->vertexAt(face * 3 + i);
+ if (sourceVertexToVertexMap.get(vertex) == UINT32_MAX) {
+ sourceVertexToVertexMap.add(vertex);
+ Vector3 normal(0.0f);
+ if (m_sourceMesh->flags() & MeshFlags::HasNormals)
+ normal = m_sourceMesh->normal(vertex);
+ mesh->addVertex(m_sourceMesh->position(vertex), normal, m_sourceMesh->texcoord(vertex));
+ }
+ }
}
- // Make sure no holes are left!
- XA_DEBUG_ASSERT(atlas.facesLeft() == 0);
- }
-
- void removeChart(const Chart *chart) {
- for (uint32_t i = 0; i < m_charts.size(); i++) {
- if (m_charts[i] == chart) {
- m_charts.removeAt(i);
- return;
+ // Add faces.
+ for (uint32_t f = 0; f < faceCount; f++) {
+ const uint32_t face = m_faceToSourceFaceMap[f];
+ XA_DEBUG_ASSERT(!m_sourceMesh->isFaceIgnored(face));
+ uint32_t indices[3];
+ for (uint32_t i = 0; i < 3; i++) {
+ const uint32_t vertex = m_sourceMesh->vertexAt(face * 3 + i);
+ indices[i] = sourceVertexToVertexMap.get(vertex);
+ XA_DEBUG_ASSERT(indices[i] != UINT32_MAX);
}
+ // Don't copy flags - ignored faces aren't used by chart groups, they are handled by InvalidMeshGeometry.
+ Mesh::AddFaceResult::Enum result = mesh->addFace(indices);
+ XA_UNUSED(result);
+ XA_DEBUG_ASSERT(result == Mesh::AddFaceResult::OK);
}
+ XA_PROFILE_START(createChartGroupMeshColocals)
+ mesh->createColocals();
+ XA_PROFILE_END(createChartGroupMeshColocals)
+ XA_PROFILE_START(createChartGroupMeshBoundaries)
+ mesh->createBoundaries();
+ mesh->destroyEdgeMap(); // Only needed it for createBoundaries.
+ XA_PROFILE_END(createChartGroupMeshBoundaries)
+#if XA_DEBUG_EXPORT_OBJ_CHART_GROUPS
+ char filename[256];
+ XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u.obj", m_sourceMesh->id(), m_id);
+ mesh->writeObjFile(filename);
+#endif
+ return mesh;
}
- uint32_t m_sourceId, m_id;
- bool m_isVertexMap;
- Mesh *m_mesh;
+ const uint32_t m_id;
+ const Mesh * const m_sourceMesh;
+ const MeshFaceGroups * const m_sourceMeshFaceGroups;
+ const MeshFaceGroups::Handle m_faceGroup;
Array<uint32_t> m_faceToSourceFaceMap; // List of faces of the source mesh that belong to this chart group.
- Array<uint32_t> m_vertexToSourceVertexMap; // Map vertices of the mesh to vertices of the source mesh.
+ Array<Basis> m_chartBasis; // Copied from segment::Atlas.
+ Array<uint32_t> m_chartFaces; // Copied from segment::Atlas. Encoding: <chart 0 face count> <face 0> <face n> <chart 1 face count> etc.
Array<Chart *> m_charts;
- ChartOptions m_chartOptions;
+ uint32_t m_faceCount; // Set by createMesh(). Used for sorting.
uint32_t m_paramAddedChartsCount; // Number of new charts added by recomputing charts with invalid parameterizations.
uint32_t m_paramDeletedChartsCount; // Number of charts with invalid parameterizations that were deleted, after charts were recomputed.
};
-struct CreateChartGroupTaskArgs {
- uint16_t faceGroup;
- uint32_t groupId;
- const Mesh *mesh;
- ChartGroup **chartGroup;
+// References invalid faces and vertices in a mesh.
+struct InvalidMeshGeometry
+{
+ // Invalid faces have the face groups MeshFaceGroups::kInvalid.
+ void extract(const Mesh *mesh, const MeshFaceGroups *meshFaceGroups)
+ {
+ // Copy invalid faces.
+ m_faces.clear();
+ const uint32_t meshFaceCount = mesh->faceCount();
+ for (uint32_t f = 0; f < meshFaceCount; f++) {
+ if (meshFaceGroups->groupAt(f) == MeshFaceGroups::kInvalid)
+ m_faces.push_back(f);
+ }
+ // Create *unique* list of vertices of invalid faces.
+ const uint32_t faceCount = m_faces.size();
+ m_indices.resize(faceCount * 3);
+ const uint32_t approxVertexCount = min(faceCount * 3, mesh->vertexCount());
+ m_vertexToSourceVertexMap.clear();
+ m_vertexToSourceVertexMap.reserve(approxVertexCount);
+ HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToVertexMap(MemTag::Mesh, approxVertexCount);
+ for (uint32_t f = 0; f < faceCount; f++) {
+ const uint32_t face = m_faces[f];
+ for (uint32_t i = 0; i < 3; i++) {
+ const uint32_t vertex = mesh->vertexAt(face * 3 + i);
+ uint32_t newVertex = sourceVertexToVertexMap.get(vertex);
+ if (newVertex == UINT32_MAX) {
+ newVertex = sourceVertexToVertexMap.add(vertex);
+ m_vertexToSourceVertexMap.push_back(vertex);
+ }
+ m_indices[f * 3 + i] = newVertex;
+ }
+ }
+ }
+
+ ConstArrayView<uint32_t> faces() const { return m_faces; }
+ ConstArrayView<uint32_t> indices() const { return m_indices; }
+ ConstArrayView<uint32_t> vertices() const { return m_vertexToSourceVertexMap; }
+
+private:
+ Array<uint32_t> m_faces, m_indices;
+ Array<uint32_t> m_vertexToSourceVertexMap; // Map face vertices to vertices of the source mesh.
};
-static void runCreateChartGroupTask(void *userData) {
- XA_PROFILE_START(addMeshCreateChartGroupsThread)
- auto args = (CreateChartGroupTaskArgs *)userData;
- *(args->chartGroup) = XA_NEW_ARGS(MemTag::Default, ChartGroup, args->groupId, args->mesh, args->faceGroup);
- XA_PROFILE_END(addMeshCreateChartGroupsThread)
+struct ChartGroupComputeChartFacesTaskArgs
+{
+ ThreadLocal<segment::Atlas> *atlas;
+ ChartGroup *chartGroup;
+ const ChartOptions *options;
+ Progress *progress;
+};
+
+static void runChartGroupComputeChartFacesJob(void *userData)
+{
+ auto args = (ChartGroupComputeChartFacesTaskArgs *)userData;
+ if (args->progress->cancel)
+ return;
+ XA_PROFILE_START(chartGroupComputeChartsThread)
+ args->chartGroup->computeChartFaces(*args->options, args->atlas->get());
+ XA_PROFILE_END(chartGroupComputeChartsThread)
}
-struct ComputeChartsTaskArgs {
- TaskScheduler *taskScheduler;
- ChartGroup *chartGroup;
+struct MeshComputeChartFacesTaskArgs
+{
+ Array<ChartGroup *> *chartGroups; // output
+ InvalidMeshGeometry *invalidMeshGeometry; // output
ThreadLocal<segment::Atlas> *atlas;
- ThreadLocal<ChartCtorBuffers> *chartBuffers;
const ChartOptions *options;
Progress *progress;
+ const Mesh *sourceMesh;
+ TaskScheduler *taskScheduler;
};
-static void runComputeChartsJob(void *userData) {
- auto args = (ComputeChartsTaskArgs *)userData;
+#if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
+static uint32_t s_faceGroupsCurrentVertex = 0;
+#endif
+
+static void runMeshComputeChartFacesJob(void *userData)
+{
+ auto args = (MeshComputeChartFacesTaskArgs *)userData;
if (args->progress->cancel)
return;
XA_PROFILE_START(computeChartsThread)
- args->chartGroup->computeCharts(args->taskScheduler, *args->options, args->atlas->get(), args->chartBuffers);
+ // Create face groups.
+ XA_PROFILE_START(createFaceGroups)
+ MeshFaceGroups *meshFaceGroups = XA_NEW_ARGS(MemTag::Mesh, MeshFaceGroups, args->sourceMesh);
+ meshFaceGroups->compute();
+ const uint32_t chartGroupCount = meshFaceGroups->groupCount();
+ XA_PROFILE_END(createFaceGroups)
+ if (args->progress->cancel)
+ goto cleanup;
+#if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
+ {
+ static std::mutex s_mutex;
+ std::lock_guard<std::mutex> lock(s_mutex);
+ char filename[256];
+ XA_SPRINTF(filename, sizeof(filename), "debug_face_groups.obj");
+ FILE *file;
+ XA_FOPEN(file, filename, s_faceGroupsCurrentVertex == 0 ? "w" : "a");
+ if (file) {
+ const Mesh *mesh = args->sourceMesh;
+ mesh->writeObjVertices(file);
+ // groups
+ uint32_t numGroups = 0;
+ for (uint32_t i = 0; i < mesh->faceCount(); i++) {
+ if (meshFaceGroups->groupAt(i) != MeshFaceGroups::kInvalid)
+ numGroups = max(numGroups, meshFaceGroups->groupAt(i) + 1);
+ }
+ for (uint32_t i = 0; i < numGroups; i++) {
+ fprintf(file, "o mesh_%03u_group_%04d\n", mesh->id(), i);
+ fprintf(file, "s off\n");
+ for (uint32_t f = 0; f < mesh->faceCount(); f++) {
+ if (meshFaceGroups->groupAt(f) == i)
+ mesh->writeObjFace(file, f, s_faceGroupsCurrentVertex);
+ }
+ }
+ fprintf(file, "o mesh_%03u_group_ignored\n", mesh->id());
+ fprintf(file, "s off\n");
+ for (uint32_t f = 0; f < mesh->faceCount(); f++) {
+ if (meshFaceGroups->groupAt(f) == MeshFaceGroups::kInvalid)
+ mesh->writeObjFace(file, f, s_faceGroupsCurrentVertex);
+ }
+ mesh->writeObjBoundaryEges(file);
+ s_faceGroupsCurrentVertex += mesh->vertexCount();
+ fclose(file);
+ }
+ }
+#endif
+ // Create a chart group for each face group.
+ args->chartGroups->resize(chartGroupCount);
+ for (uint32_t i = 0; i < chartGroupCount; i++)
+ (*args->chartGroups)[i] = XA_NEW_ARGS(MemTag::Default, ChartGroup, i, args->sourceMesh, meshFaceGroups, MeshFaceGroups::Handle(i));
+ // Extract invalid geometry via the invalid face group (MeshFaceGroups::kInvalid).
+ XA_PROFILE_START(extractInvalidMeshGeometry)
+ args->invalidMeshGeometry->extract(args->sourceMesh, meshFaceGroups);
+ XA_PROFILE_END(extractInvalidMeshGeometry)
+ // One task for each chart group - compute chart faces.
+ {
+ XA_PROFILE_START(chartGroupComputeChartsReal)
+ Array<ChartGroupComputeChartFacesTaskArgs> taskArgs;
+ taskArgs.resize(chartGroupCount);
+ for (uint32_t i = 0; i < chartGroupCount; i++) {
+ taskArgs[i].atlas = args->atlas;
+ taskArgs[i].chartGroup = (*args->chartGroups)[i];
+ taskArgs[i].options = args->options;
+ taskArgs[i].progress = args->progress;
+ }
+ TaskGroupHandle taskGroup = args->taskScheduler->createTaskGroup(chartGroupCount);
+ for (uint32_t i = 0; i < chartGroupCount; i++) {
+ Task task;
+ task.userData = &taskArgs[i];
+ task.func = runChartGroupComputeChartFacesJob;
+ args->taskScheduler->run(taskGroup, task);
+ }
+ args->taskScheduler->wait(&taskGroup);
+ XA_PROFILE_END(chartGroupComputeChartsReal)
+ }
XA_PROFILE_END(computeChartsThread)
args->progress->value++;
args->progress->update();
+cleanup:
+ if (meshFaceGroups) {
+ meshFaceGroups->~MeshFaceGroups();
+ XA_FREE(meshFaceGroups);
+ }
}
-struct ParameterizeChartsTaskArgs {
+struct ParameterizeChartsTaskArgs
+{
TaskScheduler *taskScheduler;
ChartGroup *chartGroup;
- ParameterizeFunc func;
+ const ParameterizeOptions *options;
ThreadLocal<UniformGrid2> *boundaryGrid;
ThreadLocal<ChartCtorBuffers> *chartBuffers;
#if XA_RECOMPUTE_CHARTS
@@ -7069,15 +8100,16 @@ struct ParameterizeChartsTaskArgs {
Progress *progress;
};
-static void runParameterizeChartsJob(void *userData) {
+static void runParameterizeChartsJob(void *userData)
+{
auto args = (ParameterizeChartsTaskArgs *)userData;
if (args->progress->cancel)
return;
XA_PROFILE_START(parameterizeChartsThread)
#if XA_RECOMPUTE_CHARTS
- args->chartGroup->parameterizeCharts(args->taskScheduler, args->func, args->boundaryGrid, args->chartBuffers, args->piecewiseParam);
+ args->chartGroup->parameterizeCharts(args->taskScheduler, *args->options, args->boundaryGrid, args->chartBuffers, args->piecewiseParam);
#else
- args->chartGroup->parameterizeCharts(args->taskScheduler, args->func, args->boundaryGrid, args->chartBuffers);
+ args->chartGroup->parameterizeCharts(args->taskScheduler, *args->options, args->boundaryGrid, args->chartBuffers);
#endif
XA_PROFILE_END(parameterizeChartsThread)
args->progress->value++;
@@ -7085,137 +8117,86 @@ static void runParameterizeChartsJob(void *userData) {
}
/// An atlas is a set of chart groups.
-class Atlas {
+class Atlas
+{
public:
- Atlas() :
- m_meshCount(0), m_chartsComputed(false), m_chartsParameterized(false) {}
+ Atlas() : m_chartsComputed(false), m_chartsParameterized(false) {}
- ~Atlas() {
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- m_chartGroups[i]->~ChartGroup();
- XA_FREE(m_chartGroups[i]);
+ ~Atlas()
+ {
+ for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
+ for (uint32_t j = 0; j < m_meshChartGroups[i].size(); j++) {
+ m_meshChartGroups[i][j]->~ChartGroup();
+ XA_FREE(m_meshChartGroups[i][j]);
+ }
}
+ m_meshChartGroups.runDtors();
+ m_invalidMeshGeometry.runDtors();
}
+ uint32_t meshCount() const { return m_meshes.size(); }
+ const InvalidMeshGeometry &invalidMeshGeometry(uint32_t meshIndex) const { return m_invalidMeshGeometry[meshIndex]; }
bool chartsComputed() const { return m_chartsComputed; }
bool chartsParameterized() const { return m_chartsParameterized; }
- uint32_t chartGroupCount() const { return m_chartGroups.size(); }
- const ChartGroup *chartGroupAt(uint32_t index) const { return m_chartGroups[index]; }
-
- uint32_t chartGroupCount(uint32_t mesh) const {
- uint32_t count = 0;
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- if (m_chartGroupSourceMeshes[i] == mesh)
- count++;
- }
- return count;
- }
-
- const ChartGroup *chartGroupAt(uint32_t mesh, uint32_t group) const {
- for (uint32_t c = 0; c < m_chartGroups.size(); c++) {
- if (m_chartGroupSourceMeshes[c] != mesh)
- continue;
- if (group == 0)
- return m_chartGroups[c];
- group--;
- }
- return nullptr;
- }
+ uint32_t chartGroupCount(uint32_t mesh) const { return m_meshChartGroups[mesh].size(); }
+ const ChartGroup *chartGroupAt(uint32_t mesh, uint32_t group) const { return m_meshChartGroups[mesh][group]; }
- // This function is thread safe.
- void addMesh(TaskScheduler *taskScheduler, const Mesh *mesh) {
- // Create one chart group per face group.
- // If there's any ignored faces in the mesh, create an extra face group for that (vertex map).
- // Chart group creation is slow since it copies a chunk of the source mesh, so use tasks.
- Array<ChartGroup *> chartGroups;
- chartGroups.resize(mesh->faceGroupCount() + (mesh->ignoredFaceCount() > 0 ? 1 : 0));
- Array<CreateChartGroupTaskArgs> taskArgs;
- taskArgs.resize(chartGroups.size());
- for (uint32_t g = 0; g < chartGroups.size(); g++) {
- CreateChartGroupTaskArgs &args = taskArgs[g];
- args.chartGroup = &chartGroups[g];
- args.faceGroup = uint16_t(g < mesh->faceGroupCount() ? g : Mesh::kInvalidFaceGroup);
- args.groupId = g;
- args.mesh = mesh;
- }
- TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartGroups.size());
- for (uint32_t g = 0; g < chartGroups.size(); g++) {
- Task task;
- task.userData = &taskArgs[g];
- task.func = runCreateChartGroupTask;
- taskScheduler->run(taskGroup, task);
- }
- taskScheduler->wait(&taskGroup);
- // Thread-safe append.
- m_addMeshMutex.lock();
- for (uint32_t g = 0; g < chartGroups.size(); g++) {
- m_chartGroups.push_back(chartGroups[g]);
- m_chartGroupSourceMeshes.push_back(mesh->id());
- }
- m_meshCount++;
- m_addMeshMutex.unlock();
- }
-
- // Chart id/index is determined by depth-first hierarchy of mesh -> chart group -> chart.
- // For chart index to be consistent here, chart groups needs to sorted by mesh index. Since addMesh is called by multithreaded tasks, order is indeterminate, so chart groups need to be explicitly sorted after all meshes are added.
- void sortChartGroups() {
- Array<ChartGroup *> oldChartGroups;
- oldChartGroups.resize(m_chartGroups.size());
- memcpy(oldChartGroups.data(), m_chartGroups.data(), sizeof(ChartGroup *) * m_chartGroups.size());
- Array<uint32_t> oldChartGroupSourceMeshes;
- oldChartGroupSourceMeshes.resize(m_chartGroupSourceMeshes.size());
- memcpy(oldChartGroupSourceMeshes.data(), m_chartGroupSourceMeshes.data(), sizeof(uint32_t) * m_chartGroupSourceMeshes.size());
- uint32_t current = 0;
- for (uint32_t i = 0; i < m_meshCount; i++) {
- for (uint32_t j = 0; j < oldChartGroups.size(); j++) {
- if (oldChartGroupSourceMeshes[j] == i) {
- m_chartGroups[current] = oldChartGroups[j];
- m_chartGroupSourceMeshes[current] = oldChartGroupSourceMeshes[j];
- current++;
- }
- }
- }
+ void addMesh(const Mesh *mesh)
+ {
+ m_meshes.push_back(mesh);
}
- bool computeCharts(TaskScheduler *taskScheduler, const ChartOptions &options, ProgressFunc progressFunc, void *progressUserData) {
+ bool computeCharts(TaskScheduler *taskScheduler, const ChartOptions &options, ProgressFunc progressFunc, void *progressUserData)
+ {
+#if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
+ segment::s_planarRegionsCurrentRegion = segment::s_planarRegionsCurrentVertex = 0;
+#endif
m_chartsComputed = false;
m_chartsParameterized = false;
- // Ignore vertex maps.
- uint32_t chartGroupCount = 0;
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- if (!m_chartGroups[i]->isVertexMap())
- chartGroupCount++;
+ // Clear chart groups, since this function may be called multiple times.
+ if (!m_meshChartGroups.isEmpty()) {
+ for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
+ for (uint32_t j = 0; j < m_meshChartGroups[i].size(); j++) {
+ m_meshChartGroups[i][j]->~ChartGroup();
+ XA_FREE(m_meshChartGroups[i][j]);
+ }
+ m_meshChartGroups[i].clear();
+ }
+ XA_ASSERT(m_meshChartGroups.size() == m_meshes.size()); // The number of meshes shouldn't have changed.
}
- Progress progress(ProgressCategory::ComputeCharts, progressFunc, progressUserData, chartGroupCount);
+ m_meshChartGroups.resize(m_meshes.size());
+ m_meshChartGroups.runCtors();
+ m_invalidMeshGeometry.resize(m_meshes.size());
+ m_invalidMeshGeometry.runCtors();
+ // One task per mesh.
+ const uint32_t meshCount = m_meshes.size();
+ Progress progress(ProgressCategory::ComputeCharts, progressFunc, progressUserData, meshCount);
ThreadLocal<segment::Atlas> atlas;
- ThreadLocal<ChartCtorBuffers> chartBuffers;
- Array<ComputeChartsTaskArgs> taskArgs;
- taskArgs.reserve(chartGroupCount);
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- if (!m_chartGroups[i]->isVertexMap()) {
- ComputeChartsTaskArgs args;
- args.taskScheduler = taskScheduler;
- args.chartGroup = m_chartGroups[i];
- args.atlas = &atlas;
- args.chartBuffers = &chartBuffers;
- args.options = &options;
- args.progress = &progress;
- taskArgs.push_back(args);
- }
- }
- // Sort chart groups by mesh indexCount.
- m_chartGroupsRadix = RadixSort();
- Array<float> chartGroupSortData;
- chartGroupSortData.resize(chartGroupCount);
- for (uint32_t i = 0; i < chartGroupCount; i++)
- chartGroupSortData[i] = (float)taskArgs[i].chartGroup->mesh()->indexCount();
- m_chartGroupsRadix.sort(chartGroupSortData);
- // Larger chart group meshes are added first to reduce the chance of thread starvation.
- TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartGroupCount);
- for (uint32_t i = 0; i < chartGroupCount; i++) {
+ Array<MeshComputeChartFacesTaskArgs> taskArgs;
+ taskArgs.resize(meshCount);
+ for (uint32_t i = 0; i < meshCount; i++) {
+ MeshComputeChartFacesTaskArgs &args = taskArgs[i];
+ args.atlas = &atlas;
+ args.chartGroups = &m_meshChartGroups[i];
+ args.invalidMeshGeometry = &m_invalidMeshGeometry[i];
+ args.options = &options;
+ args.progress = &progress;
+ args.sourceMesh = m_meshes[i];
+ args.taskScheduler = taskScheduler;
+ }
+ // Sort meshes by indexCount.
+ Array<float> meshSortData;
+ meshSortData.resize(meshCount);
+ for (uint32_t i = 0; i < meshCount; i++)
+ meshSortData[i] = (float)m_meshes[i]->indexCount();
+ RadixSort meshSort;
+ meshSort.sort(meshSortData);
+ // Larger meshes are added first to reduce the chance of thread starvation.
+ TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(meshCount);
+ for (uint32_t i = 0; i < meshCount; i++) {
Task task;
- task.userData = &taskArgs[m_chartGroupsRadix.ranks()[chartGroupCount - i - 1]];
- task.func = runComputeChartsJob;
+ task.userData = &taskArgs[meshSort.ranks()[meshCount - i - 1]];
+ task.func = runMeshComputeChartFacesJob;
taskScheduler->run(taskGroup, task);
}
taskScheduler->wait(&taskGroup);
@@ -7225,14 +8206,12 @@ public:
return true;
}
- bool parameterizeCharts(TaskScheduler *taskScheduler, ParameterizeFunc func, ProgressFunc progressFunc, void *progressUserData) {
+ bool parameterizeCharts(TaskScheduler *taskScheduler, const ParameterizeOptions &options, ProgressFunc progressFunc, void *progressUserData)
+ {
m_chartsParameterized = false;
- // Ignore vertex maps.
uint32_t chartGroupCount = 0;
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- if (!m_chartGroups[i]->isVertexMap())
- chartGroupCount++;
- }
+ for (uint32_t i = 0; i < m_meshChartGroups.size(); i++)
+ chartGroupCount += m_meshChartGroups[i].size();
Progress progress(ProgressCategory::ParameterizeCharts, progressFunc, progressUserData, chartGroupCount);
ThreadLocal<UniformGrid2> boundaryGrid; // For Quality boundary intersection.
ThreadLocal<ChartCtorBuffers> chartBuffers;
@@ -7240,27 +8219,45 @@ public:
ThreadLocal<PiecewiseParam> piecewiseParam;
#endif
Array<ParameterizeChartsTaskArgs> taskArgs;
- taskArgs.reserve(chartGroupCount);
- for (uint32_t i = 0; i < m_chartGroups.size(); i++) {
- if (!m_chartGroups[i]->isVertexMap()) {
- ParameterizeChartsTaskArgs args;
- args.taskScheduler = taskScheduler;
- args.chartGroup = m_chartGroups[i];
- args.func = func;
- args.boundaryGrid = &boundaryGrid;
- args.chartBuffers = &chartBuffers;
+ taskArgs.resize(chartGroupCount);
+ {
+ uint32_t k = 0;
+ for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
+ const uint32_t count = m_meshChartGroups[i].size();
+ for (uint32_t j = 0; j < count; j++) {
+ ParameterizeChartsTaskArgs &args = taskArgs[k];
+ args.taskScheduler = taskScheduler;
+ args.chartGroup = m_meshChartGroups[i][j];
+ args.options = &options;
+ args.boundaryGrid = &boundaryGrid;
+ args.chartBuffers = &chartBuffers;
#if XA_RECOMPUTE_CHARTS
- args.piecewiseParam = &piecewiseParam;
+ args.piecewiseParam = &piecewiseParam;
#endif
- args.progress = &progress;
- taskArgs.push_back(args);
+ args.progress = &progress;
+ k++;
+ }
}
}
- // Larger chart group meshes are added first to reduce the chance of thread starvation.
+ // Sort chart groups by face count.
+ Array<float> chartGroupSortData;
+ chartGroupSortData.resize(chartGroupCount);
+ {
+ uint32_t k = 0;
+ for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
+ const uint32_t count = m_meshChartGroups[i].size();
+ for (uint32_t j = 0; j < count; j++) {
+ chartGroupSortData[k++] = (float)m_meshChartGroups[i][j]->faceCount();
+ }
+ }
+ }
+ RadixSort chartGroupSort;
+ chartGroupSort.sort(chartGroupSortData);
+ // Larger chart groups are added first to reduce the chance of thread starvation.
TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartGroupCount);
for (uint32_t i = 0; i < chartGroupCount; i++) {
Task task;
- task.userData = &taskArgs[m_chartGroupsRadix.ranks()[chartGroupCount - i - 1]];
+ task.userData = &taskArgs[chartGroupSort.ranks()[chartGroupCount - i - 1]];
task.func = runParameterizeChartsJob;
taskScheduler->run(taskGroup, task);
}
@@ -7272,28 +8269,28 @@ public:
}
private:
- std::mutex m_addMeshMutex;
- uint32_t m_meshCount;
+ Array<const Mesh *> m_meshes;
+ Array<InvalidMeshGeometry> m_invalidMeshGeometry; // 1 per mesh.
+ Array<Array<ChartGroup *> > m_meshChartGroups;
bool m_chartsComputed;
bool m_chartsParameterized;
- Array<ChartGroup *> m_chartGroups;
- RadixSort m_chartGroupsRadix; // By mesh indexCount.
- Array<uint32_t> m_chartGroupSourceMeshes;
};
} // namespace param
namespace pack {
-class AtlasImage {
+class AtlasImage
+{
public:
- AtlasImage(uint32_t width, uint32_t height) :
- m_width(width), m_height(height) {
+ AtlasImage(uint32_t width, uint32_t height) : m_width(width), m_height(height)
+ {
m_data.resize(m_width * m_height);
memset(m_data.data(), 0, sizeof(uint32_t) * m_data.size());
}
- void resize(uint32_t width, uint32_t height) {
+ void resize(uint32_t width, uint32_t height)
+ {
Array<uint32_t> data;
data.resize(width * height);
memset(data.data(), 0, sizeof(uint32_t) * data.size());
@@ -7304,7 +8301,8 @@ public:
data.moveTo(m_data);
}
- void addChart(uint32_t chartIndex, const BitImage *image, const BitImage *imageBilinear, const BitImage *imagePadding, int atlas_w, int atlas_h, int offset_x, int offset_y) {
+ void addChart(uint32_t chartIndex, const BitImage *image, const BitImage *imageBilinear, const BitImage *imagePadding, int atlas_w, int atlas_h, int offset_x, int offset_y)
+ {
const int w = image->width();
const int h = image->height();
for (int y = 0; y < h; y++) {
@@ -7330,13 +8328,15 @@ public:
}
}
- void copyTo(uint32_t *dest, uint32_t destWidth, uint32_t destHeight, int padding) const {
+ void copyTo(uint32_t *dest, uint32_t destWidth, uint32_t destHeight, int padding) const
+ {
for (uint32_t y = 0; y < destHeight; y++)
memcpy(&dest[y * destWidth], &m_data[padding + (y + padding) * m_width], destWidth * sizeof(uint32_t));
}
#if XA_DEBUG_EXPORT_ATLAS_IMAGES
- void writeTga(const char *filename, uint32_t width, uint32_t height) const {
+ void writeTga(const char *filename, uint32_t width, uint32_t height) const
+ {
Array<uint8_t> image;
image.resize(width * height * 3);
for (uint32_t y = 0; y < height; y++) {
@@ -7378,7 +8378,8 @@ private:
Array<uint32_t> m_data;
};
-struct Chart {
+struct Chart
+{
int32_t atlasIndex;
uint32_t material;
uint32_t indexCount;
@@ -7400,18 +8401,20 @@ struct Chart {
uint32_t uniqueVertexCount() const { return uniqueVertices.isEmpty() ? vertexCount : uniqueVertices.size(); }
};
-struct AddChartTaskArgs {
+struct AddChartTaskArgs
+{
ThreadLocal<BoundingBox2D> *boundingBox;
param::Chart *paramChart;
Chart *chart; // out
};
-static void runAddChartTask(void *userData) {
+static void runAddChartTask(void *userData)
+{
XA_PROFILE_START(packChartsAddChartsThread)
auto args = (AddChartTaskArgs *)userData;
param::Chart *paramChart = args->paramChart;
XA_PROFILE_START(packChartsAddChartsRestoreTexcoords)
- paramChart->transferParameterization();
+ paramChart->restoreTexcoords();
XA_PROFILE_END(packChartsAddChartsRestoreTexcoords)
Mesh *mesh = paramChart->mesh();
Chart *chart = args->chart = XA_NEW(MemTag::Default, Chart);
@@ -7445,8 +8448,10 @@ static void runAddChartTask(void *userData) {
XA_PROFILE_END(packChartsAddChartsThread)
}
-struct Atlas {
- ~Atlas() {
+struct Atlas
+{
+ ~Atlas()
+ {
for (uint32_t i = 0; i < m_atlasImages.size(); i++) {
m_atlasImages[i]->~AtlasImage();
XA_FREE(m_atlasImages[i]);
@@ -7470,15 +8475,16 @@ struct Atlas {
const Array<AtlasImage *> &getImages() const { return m_atlasImages; }
float getUtilization(uint32_t atlas) const { return m_utilization[atlas]; }
- void addCharts(TaskScheduler *taskScheduler, param::Atlas *paramAtlas) {
+ void addCharts(TaskScheduler *taskScheduler, param::Atlas *paramAtlas)
+ {
// Count charts.
uint32_t chartCount = 0;
- const uint32_t chartGroupsCount = paramAtlas->chartGroupCount();
- for (uint32_t i = 0; i < chartGroupsCount; i++) {
- const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i);
- if (chartGroup->isVertexMap())
- continue;
- chartCount += chartGroup->chartCount();
+ for (uint32_t i = 0; i < paramAtlas->meshCount(); i++) {
+ const uint32_t chartGroupsCount = paramAtlas->chartGroupCount(i);
+ for (uint32_t j = 0; j < chartGroupsCount; j++) {
+ const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i, j);
+ chartCount += chartGroup->chartCount();
+ }
}
if (chartCount == 0)
return;
@@ -7488,20 +8494,21 @@ struct Atlas {
TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(chartCount);
uint32_t chartIndex = 0;
ThreadLocal<BoundingBox2D> boundingBox;
- for (uint32_t i = 0; i < chartGroupsCount; i++) {
- const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i);
- if (chartGroup->isVertexMap())
- continue;
- const uint32_t count = chartGroup->chartCount();
- for (uint32_t j = 0; j < count; j++) {
- AddChartTaskArgs &args = taskArgs[chartIndex];
- args.boundingBox = &boundingBox;
- args.paramChart = chartGroup->chartAt(j);
- Task task;
- task.userData = &taskArgs[chartIndex];
- task.func = runAddChartTask;
- taskScheduler->run(taskGroup, task);
- chartIndex++;
+ for (uint32_t i = 0; i < paramAtlas->meshCount(); i++) {
+ const uint32_t chartGroupsCount = paramAtlas->chartGroupCount(i);
+ for (uint32_t j = 0; j < chartGroupsCount; j++) {
+ const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i, j);
+ const uint32_t count = chartGroup->chartCount();
+ for (uint32_t k = 0; k < count; k++) {
+ AddChartTaskArgs &args = taskArgs[chartIndex];
+ args.boundingBox = &boundingBox;
+ args.paramChart = chartGroup->chartAt(k);
+ Task task;
+ task.userData = &taskArgs[chartIndex];
+ task.func = runAddChartTask;
+ taskScheduler->run(taskGroup, task);
+ chartIndex++;
+ }
}
}
taskScheduler->wait(&taskGroup);
@@ -7511,7 +8518,8 @@ struct Atlas {
m_charts[i] = taskArgs[i].chart;
}
- void addUvMeshCharts(UvMeshInstance *mesh) {
+ void addUvMeshCharts(UvMeshInstance *mesh)
+ {
BitArray vertexUsed(mesh->texcoords.size());
BoundingBox2D boundingBox;
for (uint32_t c = 0; c < mesh->mesh->charts.size(); c++) {
@@ -7572,7 +8580,8 @@ struct Atlas {
}
// Pack charts in the smallest possible rectangle.
- bool packCharts(const PackOptions &options, ProgressFunc progressFunc, void *progressUserData) {
+ bool packCharts(const PackOptions &options, ProgressFunc progressFunc, void *progressUserData)
+ {
if (progressFunc) {
if (!progressFunc(ProgressCategory::PackCharts, 0, progressUserData))
return false;
@@ -7699,7 +8708,6 @@ struct Atlas {
maxChartPerimeter = max(maxChartPerimeter, chartOrderArray[c]);
}
// Sort charts by perimeter.
- m_radix = RadixSort();
m_radix.sort(chartOrderArray);
const uint32_t *ranks = m_radix.ranks();
// Divide chart perimeter range into buckets.
@@ -7807,7 +8815,8 @@ struct Atlas {
int best_x = 0, best_y = 0;
int best_cw = 0, best_ch = 0;
int best_r = 0;
- for (;;) {
+ for (;;)
+ {
bool firstChartInBitImage = false;
XA_UNUSED(firstChartInBitImage);
if (currentAtlas + 1 > m_bitImages.size()) {
@@ -7840,7 +8849,8 @@ struct Atlas {
if (best_x + best_cw > atlasSizes[currentAtlas].x || best_y + best_ch > atlasSizes[currentAtlas].y) {
for (uint32_t j = 0; j < chartStartPositions.size(); j++)
chartStartPositions[j] = Vector2i(0, 0);
- } else {
+ }
+ else {
chartStartPositions[currentAtlas] = Vector2i(best_x, best_y);
}
}
@@ -7892,10 +8902,8 @@ struct Atlas {
}
texcoord.x = best_x + t.x;
texcoord.y = best_y + t.y;
- if (!options.blockAlign) {
- texcoord.x -= (float)options.padding;
- texcoord.y -= (float)options.padding;
- }
+ texcoord.x -= (float)options.padding;
+ texcoord.y -= (float)options.padding;
XA_ASSERT(texcoord.x >= 0 && texcoord.y >= 0);
XA_ASSERT(isFinite(texcoord.x) && isFinite(texcoord.y));
}
@@ -7908,21 +8916,12 @@ struct Atlas {
}
}
}
- if (options.blockAlign) {
- if (maxResolution == 0) {
- m_width = max(0, atlasSizes[0].x);
- m_height = max(0, atlasSizes[0].y);
- } else {
- m_width = m_height = maxResolution;
- }
+ // Remove padding from outer edges.
+ if (maxResolution == 0) {
+ m_width = max(0, atlasSizes[0].x - (int)options.padding * 2);
+ m_height = max(0, atlasSizes[0].y - (int)options.padding * 2);
} else {
- // Remove padding from outer edges.
- if (maxResolution == 0) {
- m_width = max(0, atlasSizes[0].x - (int)options.padding * 2);
- m_height = max(0, atlasSizes[0].y - (int)options.padding * 2);
- } else {
- m_width = m_height = maxResolution - (int)options.padding * 2;
- }
+ m_width = m_height = maxResolution - (int)options.padding * 2;
}
XA_PRINT(" %dx%d resolution\n", m_width, m_height);
m_utilization.resize(m_bitImages.size());
@@ -7939,7 +8938,8 @@ struct Atlas {
}
if (m_utilization.size() > 1) {
XA_PRINT(" %u: %f%% utilization\n", i, m_utilization[i] * 100.0f);
- } else {
+ }
+ else {
XA_PRINT(" %f%% utilization\n", m_utilization[i] * 100.0f);
}
}
@@ -7962,14 +8962,16 @@ private:
// is occupied at this point. At the end we have many small charts and a large atlas with sparse holes. Finding those holes randomly is slow. A better approach would be to
// start stacking large charts as if they were tetris pieces. Once charts get small try to place them randomly. It may be interesting to try a intermediate strategy, first try
// along one axis and then try exhaustively along that axis.
- bool findChartLocation(const Vector2i &startPosition, bool bruteForce, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, bool blockAligned, uint32_t maxResolution, bool allowRotate) {
+ bool findChartLocation(const Vector2i &startPosition, bool bruteForce, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, bool blockAligned, uint32_t maxResolution, bool allowRotate)
+ {
const int attempts = 4096;
if (bruteForce || attempts >= w * h)
return findChartLocation_bruteForce(startPosition, atlasBitImage, chartBitImage, chartBitImageRotated, w, h, best_x, best_y, best_w, best_h, best_r, blockAligned, maxResolution, allowRotate);
return findChartLocation_random(atlasBitImage, chartBitImage, chartBitImageRotated, w, h, best_x, best_y, best_w, best_h, best_r, attempts, blockAligned, maxResolution, allowRotate);
}
- bool findChartLocation_bruteForce(const Vector2i &startPosition, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, bool blockAligned, uint32_t maxResolution, bool allowRotate) {
+ bool findChartLocation_bruteForce(const Vector2i &startPosition, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, bool blockAligned, uint32_t maxResolution, bool allowRotate)
+ {
const int stepSize = blockAligned ? 4 : 1;
int best_metric = INT_MAX;
// Try two different orientations.
@@ -8014,7 +9016,8 @@ private:
return best_metric != INT_MAX;
}
- bool findChartLocation_random(const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, int minTrialCount, bool blockAligned, uint32_t maxResolution, bool allowRotate) {
+ bool findChartLocation_random(const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, int minTrialCount, bool blockAligned, uint32_t maxResolution, bool allowRotate)
+ {
bool result = false;
const int BLOCK_SIZE = 4;
int best_metric = INT_MAX;
@@ -8069,7 +9072,8 @@ private:
return result;
}
- void addChart(BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int atlas_w, int atlas_h, int offset_x, int offset_y, int r) {
+ void addChart(BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int atlas_w, int atlas_h, int offset_x, int offset_y, int r)
+ {
XA_DEBUG_ASSERT(r == 0 || r == 1);
const BitImage *image = r == 0 ? chartBitImage : chartBitImageRotated;
const int w = image->width();
@@ -8092,7 +9096,8 @@ private:
}
}
- void bilinearExpand(const Chart *chart, BitImage *source, BitImage *dest, BitImage *destRotated, UniformGrid2 &boundaryEdgeGrid) const {
+ void bilinearExpand(const Chart *chart, BitImage *source, BitImage *dest, BitImage *destRotated, UniformGrid2 &boundaryEdgeGrid) const
+ {
boundaryEdgeGrid.reset(chart->vertices, chart->indices);
if (chart->boundaryEdges) {
const uint32_t edgeCount = chart->boundaryEdges->size();
@@ -8147,11 +9152,13 @@ private:
}
}
- struct DrawTriangleCallbackArgs {
+ struct DrawTriangleCallbackArgs
+ {
BitImage *chartBitImage, *chartBitImageRotated;
};
- static bool drawTriangleCallback(void *param, int x, int y) {
+ static bool drawTriangleCallback(void *param, int x, int y)
+ {
auto args = (DrawTriangleCallbackArgs *)param;
args->chartBitImage->set(x, y);
if (args->chartBitImageRotated)
@@ -8173,48 +9180,52 @@ private:
} // namespace pack
} // namespace internal
-struct Context {
+struct Context
+{
Atlas atlas;
- uint32_t meshCount = 0;
internal::Progress *addMeshProgress = nullptr;
internal::TaskGroupHandle addMeshTaskGroup;
internal::param::Atlas paramAtlas;
ProgressFunc progressFunc = nullptr;
void *progressUserData = nullptr;
internal::TaskScheduler *taskScheduler;
+ internal::Array<internal::Mesh *> meshes;
internal::Array<internal::UvMesh *> uvMeshes;
internal::Array<internal::UvMeshInstance *> uvMeshInstances;
};
-Atlas *Create() {
+Atlas *Create()
+{
Context *ctx = XA_NEW(internal::MemTag::Default, Context);
memset(&ctx->atlas, 0, sizeof(Atlas));
ctx->taskScheduler = XA_NEW(internal::MemTag::Default, internal::TaskScheduler);
return &ctx->atlas;
}
-static void DestroyOutputMeshes(Context *ctx) {
+static void DestroyOutputMeshes(Context *ctx)
+{
if (!ctx->atlas.meshes)
return;
for (int i = 0; i < (int)ctx->atlas.meshCount; i++) {
Mesh &mesh = ctx->atlas.meshes[i];
- for (uint32_t j = 0; j < mesh.chartCount; j++) {
- if (mesh.chartArray[j].faceArray)
- XA_FREE(mesh.chartArray[j].faceArray);
- }
- if (mesh.chartArray)
+ if (mesh.chartArray) {
+ for (uint32_t j = 0; j < mesh.chartCount; j++) {
+ if (mesh.chartArray[j].faceArray)
+ XA_FREE(mesh.chartArray[j].faceArray);
+ }
XA_FREE(mesh.chartArray);
+ }
if (mesh.vertexArray)
XA_FREE(mesh.vertexArray);
if (mesh.indexArray)
XA_FREE(mesh.indexArray);
}
- if (ctx->atlas.meshes)
- XA_FREE(ctx->atlas.meshes);
+ XA_FREE(ctx->atlas.meshes);
ctx->atlas.meshes = nullptr;
}
-void Destroy(Atlas *atlas) {
+void Destroy(Atlas *atlas)
+{
XA_DEBUG_ASSERT(atlas);
Context *ctx = (Context *)atlas;
if (atlas->utilization)
@@ -8228,6 +9239,11 @@ void Destroy(Atlas *atlas) {
}
ctx->taskScheduler->~TaskScheduler();
XA_FREE(ctx->taskScheduler);
+ for (uint32_t i = 0; i < ctx->meshes.size(); i++) {
+ internal::Mesh *mesh = ctx->meshes[i];
+ mesh->~Mesh();
+ XA_FREE(mesh);
+ }
for (uint32_t i = 0; i < ctx->uvMeshes.size(); i++) {
internal::UvMesh *mesh = ctx->uvMeshes[i];
for (uint32_t j = 0; j < mesh->charts.size(); j++) {
@@ -8249,12 +9265,14 @@ void Destroy(Atlas *atlas) {
#endif
}
-struct AddMeshTaskArgs {
+struct AddMeshTaskArgs
+{
Context *ctx;
internal::Mesh *mesh;
};
-static void runAddMeshTask(void *userData) {
+static void runAddMeshTask(void *userData)
+{
XA_PROFILE_START(addMeshThread)
auto args = (AddMeshTaskArgs *)userData; // Responsible for freeing this.
internal::Mesh *mesh = args->mesh;
@@ -8268,87 +9286,45 @@ static void runAddMeshTask(void *userData) {
}
if (progress->cancel)
goto cleanup;
- {
- XA_PROFILE_START(addMeshCreateFaceGroups)
- mesh->createFaceGroups();
- XA_PROFILE_END(addMeshCreateFaceGroups)
- }
- if (progress->cancel)
- goto cleanup;
-#if XA_DEBUG_EXPORT_OBJ_SOURCE_MESHES
- char filename[256];
- XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u.obj", mesh->id());
- FILE *file;
- XA_FOPEN(file, filename, "w");
- if (file) {
- mesh->writeObjVertices(file);
- // groups
- uint32_t numGroups = 0;
- for (uint32_t i = 0; i < mesh->faceCount(); i++) {
- if (mesh->faceGroupAt(i) != Mesh::kInvalidFaceGroup)
- numGroups = internal::max(numGroups, mesh->faceGroupAt(i) + 1);
- }
- for (uint32_t i = 0; i < numGroups; i++) {
- fprintf(file, "o group_%04d\n", i);
- fprintf(file, "s off\n");
- for (uint32_t f = 0; f < mesh->faceCount(); f++) {
- if (mesh->faceGroupAt(f) == i)
- mesh->writeObjFace(file, f);
- }
- }
- fprintf(file, "o group_ignored\n");
- fprintf(file, "s off\n");
- for (uint32_t f = 0; f < mesh->faceCount(); f++) {
- if (mesh->faceGroupAt(f) == Mesh::kInvalidFaceGroup)
- mesh->writeObjFace(file, f);
- }
- mesh->writeObjBoundaryEges(file);
- fclose(file);
- }
-#endif
- {
- XA_PROFILE_START(addMeshCreateChartGroupsReal)
- args->ctx->paramAtlas.addMesh(args->ctx->taskScheduler, mesh); // addMesh is thread safe
- XA_PROFILE_END(addMeshCreateChartGroupsReal)
- }
- if (progress->cancel)
- goto cleanup;
progress->value++;
progress->update();
cleanup:
- mesh->~Mesh();
- XA_FREE(mesh);
args->~AddMeshTaskArgs();
XA_FREE(args);
XA_PROFILE_END(addMeshThread)
}
-static internal::Vector3 DecodePosition(const MeshDecl &meshDecl, uint32_t index) {
+static internal::Vector3 DecodePosition(const MeshDecl &meshDecl, uint32_t index)
+{
XA_DEBUG_ASSERT(meshDecl.vertexPositionData);
XA_DEBUG_ASSERT(meshDecl.vertexPositionStride > 0);
return *((const internal::Vector3 *)&((const uint8_t *)meshDecl.vertexPositionData)[meshDecl.vertexPositionStride * index]);
}
-static internal::Vector3 DecodeNormal(const MeshDecl &meshDecl, uint32_t index) {
+static internal::Vector3 DecodeNormal(const MeshDecl &meshDecl, uint32_t index)
+{
XA_DEBUG_ASSERT(meshDecl.vertexNormalData);
XA_DEBUG_ASSERT(meshDecl.vertexNormalStride > 0);
return *((const internal::Vector3 *)&((const uint8_t *)meshDecl.vertexNormalData)[meshDecl.vertexNormalStride * index]);
}
-static internal::Vector2 DecodeUv(const MeshDecl &meshDecl, uint32_t index) {
+static internal::Vector2 DecodeUv(const MeshDecl &meshDecl, uint32_t index)
+{
XA_DEBUG_ASSERT(meshDecl.vertexUvData);
XA_DEBUG_ASSERT(meshDecl.vertexUvStride > 0);
return *((const internal::Vector2 *)&((const uint8_t *)meshDecl.vertexUvData)[meshDecl.vertexUvStride * index]);
}
-static uint32_t DecodeIndex(IndexFormat::Enum format, const void *indexData, int32_t offset, uint32_t i) {
+static uint32_t DecodeIndex(IndexFormat::Enum format, const void *indexData, int32_t offset, uint32_t i)
+{
XA_DEBUG_ASSERT(indexData);
if (format == IndexFormat::UInt16)
return uint16_t((int32_t)((const uint16_t *)indexData)[i] + offset);
return uint32_t((int32_t)((const uint32_t *)indexData)[i] + offset);
}
-AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t meshCountHint) {
+AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t meshCountHint)
+{
XA_DEBUG_ASSERT(atlas);
if (!atlas) {
XA_PRINT_WARNING("AddMesh: atlas is null.\n");
@@ -8360,19 +9336,20 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
return AddMeshError::Error;
}
#if XA_PROFILE
- if (ctx->meshCount == 0)
+ if (ctx->meshes.isEmpty())
internal::s_profile.addMeshReal = clock();
#endif
// Don't know how many times AddMesh will be called, so progress needs to adjusted each time.
if (!ctx->addMeshProgress) {
ctx->addMeshProgress = XA_NEW_ARGS(internal::MemTag::Default, internal::Progress, ProgressCategory::AddMesh, ctx->progressFunc, ctx->progressUserData, 1);
- } else {
- ctx->addMeshProgress->setMaxValue(internal::max(ctx->meshCount + 1, meshCountHint));
+ }
+ else {
+ ctx->addMeshProgress->setMaxValue(internal::max(ctx->meshes.size() + 1, meshCountHint));
}
XA_PROFILE_START(addMeshCopyData)
const bool hasIndices = meshDecl.indexCount > 0;
const uint32_t indexCount = hasIndices ? meshDecl.indexCount : meshDecl.vertexCount;
- XA_PRINT("Adding mesh %d: %u vertices, %u triangles\n", ctx->meshCount, meshDecl.vertexCount, indexCount / 3);
+ XA_PRINT("Adding mesh %d: %u vertices, %u triangles\n", ctx->meshes.size(), meshDecl.vertexCount, indexCount / 3);
// Expecting triangle faces.
if ((indexCount % 3) != 0)
return AddMeshError::InvalidIndexCount;
@@ -8384,10 +9361,10 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
return AddMeshError::IndexOutOfRange;
}
}
- uint32_t meshFlags = internal::MeshFlags::HasFaceGroups | internal::MeshFlags::HasIgnoredFaces;
+ uint32_t meshFlags = internal::MeshFlags::HasIgnoredFaces;
if (meshDecl.vertexNormalData)
meshFlags |= internal::MeshFlags::HasNormals;
- internal::Mesh *mesh = XA_NEW_ARGS(internal::MemTag::Mesh, internal::Mesh, meshDecl.epsilon, meshDecl.vertexCount, indexCount / 3, meshFlags, ctx->meshCount);
+ internal::Mesh *mesh = XA_NEW_ARGS(internal::MemTag::Mesh, internal::Mesh, meshDecl.epsilon, meshDecl.vertexCount, indexCount / 3, meshFlags, ctx->meshes.size());
for (uint32_t i = 0; i < meshDecl.vertexCount; i++) {
internal::Vector3 normal(0.0f);
internal::Vector2 texcoord(0.0f);
@@ -8397,6 +9374,8 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
texcoord = DecodeUv(meshDecl, i);
mesh->addVertex(DecodePosition(meshDecl, i), normal, texcoord);
}
+ const uint32_t kMaxWarnings = 50;
+ uint32_t warningCount = 0;
for (uint32_t i = 0; i < indexCount / 3; i++) {
uint32_t tri[3];
for (int j = 0; j < 3; j++)
@@ -8408,14 +9387,16 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
const uint32_t index2 = tri[(j + 1) % 3];
if (index1 == index2) {
ignore = true;
- XA_PRINT(" Degenerate edge: index %d, index %d\n", index1, index2);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" Degenerate edge: index %d, index %d\n", index1, index2);
break;
}
const internal::Vector3 &pos1 = mesh->position(index1);
const internal::Vector3 &pos2 = mesh->position(index2);
if (internal::length(pos2 - pos1) <= 0.0f) {
ignore = true;
- XA_PRINT(" Zero length edge: index %d position (%g %g %g), index %d position (%g %g %g)\n", index1, pos1.x, pos1.y, pos1.z, index2, pos2.x, pos2.y, pos2.z);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" Zero length edge: index %d position (%g %g %g), index %d position (%g %g %g)\n", index1, pos1.x, pos1.y, pos1.z, index2, pos2.x, pos2.y, pos2.z);
break;
}
}
@@ -8424,14 +9405,16 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
for (int j = 0; j < 3; j++) {
const internal::Vector3 &pos = mesh->position(tri[j]);
if (internal::isNan(pos.x) || internal::isNan(pos.y) || internal::isNan(pos.z)) {
- XA_PRINT(" NAN position in face: %d\n", i);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" NAN position in face: %d\n", i);
ignore = true;
break;
}
if (meshDecl.vertexNormalData) {
const internal::Vector3 &normal = mesh->normal(tri[j]);
if (internal::isNan(normal.x) || internal::isNan(normal.y) || internal::isNan(normal.z)) {
- XA_PRINT(" NAN normal in face: %d\n", i);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" NAN normal in face: %d\n", i);
ignore = true;
break;
}
@@ -8439,7 +9422,8 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
if (meshDecl.vertexUvData) {
const internal::Vector2 &uv = mesh->texcoord(tri[j]);
if (internal::isNan(uv.x) || internal::isNan(uv.y)) {
- XA_PRINT(" NAN texture coordinate in face: %d\n", i);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" NAN texture coordinate in face: %d\n", i);
ignore = true;
break;
}
@@ -8455,20 +9439,26 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
area = internal::length(internal::cross(b - a, c - a)) * 0.5f;
if (area <= internal::kAreaEpsilon) {
ignore = true;
- XA_PRINT(" Zero area face: %d, indices (%d %d %d), area is %f\n", i, tri[0], tri[1], tri[2], area);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" Zero area face: %d, indices (%d %d %d), area is %f\n", i, tri[0], tri[1], tri[2], area);
}
}
if (!ignore) {
if (internal::equal(a, b, meshDecl.epsilon) || internal::equal(a, c, meshDecl.epsilon) || internal::equal(b, c, meshDecl.epsilon)) {
ignore = true;
- XA_PRINT(" Degenerate face: %d, area is %f\n", i, area);
+ if (++warningCount <= kMaxWarnings)
+ XA_PRINT(" Degenerate face: %d, area is %f\n", i, area);
}
}
if (meshDecl.faceIgnoreData && meshDecl.faceIgnoreData[i])
ignore = true;
mesh->addFace(tri[0], tri[1], tri[2], ignore);
}
+ if (warningCount > kMaxWarnings)
+ XA_PRINT(" %u additional warnings truncated\n", warningCount - kMaxWarnings);
XA_PROFILE_END(addMeshCopyData)
+ ctx->meshes.push_back(mesh);
+ ctx->paramAtlas.addMesh(mesh);
if (ctx->addMeshTaskGroup.value == UINT32_MAX)
ctx->addMeshTaskGroup = ctx->taskScheduler->createTaskGroup();
AddMeshTaskArgs *taskArgs = XA_NEW(internal::MemTag::Default, AddMeshTaskArgs); // The task frees this.
@@ -8478,11 +9468,11 @@ AddMeshError::Enum AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t mesh
task.userData = taskArgs;
task.func = runAddMeshTask;
ctx->taskScheduler->run(ctx->addMeshTaskGroup, task);
- ctx->meshCount++;
return AddMeshError::Success;
}
-void AddMeshJoin(Atlas *atlas) {
+void AddMeshJoin(Atlas *atlas)
+{
XA_DEBUG_ASSERT(atlas);
if (!atlas) {
XA_PRINT_WARNING("AddMeshJoin: atlas is null.\n");
@@ -8495,41 +9485,43 @@ void AddMeshJoin(Atlas *atlas) {
ctx->addMeshProgress->~Progress();
XA_FREE(ctx->addMeshProgress);
ctx->addMeshProgress = nullptr;
- ctx->paramAtlas.sortChartGroups();
#if XA_PROFILE
- XA_PRINT("Added %u meshes\n", ctx->meshCount);
+ XA_PRINT("Added %u meshes\n", ctx->meshes.size());
internal::s_profile.addMeshReal = clock() - internal::s_profile.addMeshReal;
#endif
XA_PROFILE_PRINT_AND_RESET(" Total (real): ", addMeshReal)
XA_PROFILE_PRINT_AND_RESET(" Copy data: ", addMeshCopyData)
XA_PROFILE_PRINT_AND_RESET(" Total (thread): ", addMeshThread)
XA_PROFILE_PRINT_AND_RESET(" Create colocals: ", addMeshCreateColocals)
- XA_PROFILE_PRINT_AND_RESET(" Create face groups: ", addMeshCreateFaceGroups)
- XA_PROFILE_PRINT_AND_RESET(" Create chart groups (real): ", addMeshCreateChartGroupsReal)
- XA_PROFILE_PRINT_AND_RESET(" Create chart groups (thread): ", addMeshCreateChartGroupsThread)
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
+#endif
XA_PRINT_MEM_USAGE
+#if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
+ internal::param::s_faceGroupsCurrentVertex = 0;
+#endif
}
-struct EdgeKey {
+struct EdgeKey
+{
EdgeKey() {}
- EdgeKey(const EdgeKey &k) :
- v0(k.v0), v1(k.v1) {}
- EdgeKey(uint32_t v0, uint32_t v1) :
- v0(v0), v1(v1) {}
+ EdgeKey(const EdgeKey &k) : v0(k.v0), v1(k.v1) {}
+ EdgeKey(uint32_t v0, uint32_t v1) : v0(v0), v1(v1) {}
bool operator==(const EdgeKey &k) const { return v0 == k.v0 && v1 == k.v1; }
uint32_t v0;
uint32_t v1;
};
-AddMeshError::Enum AddUvMesh(Atlas *atlas, const UvMeshDecl &decl) {
+AddMeshError::Enum AddUvMesh(Atlas *atlas, const UvMeshDecl &decl)
+{
XA_DEBUG_ASSERT(atlas);
if (!atlas) {
XA_PRINT_WARNING("AddUvMesh: atlas is null.\n");
return AddMeshError::Error;
}
Context *ctx = (Context *)atlas;
- if (ctx->meshCount > 0) {
+ if (!ctx->meshes.isEmpty()) {
XA_PRINT_WARNING("AddUvMesh: Meshes and UV meshes cannot be added to the same atlas.\n");
return AddMeshError::Error;
}
@@ -8632,7 +9624,8 @@ AddMeshError::Enum AddUvMesh(Atlas *atlas, const UvMeshDecl &decl) {
return AddMeshError::Success;
}
-void ComputeCharts(Atlas *atlas, ChartOptions chartOptions) {
+void ComputeCharts(Atlas *atlas, ChartOptions options)
+{
if (!atlas) {
XA_PRINT_WARNING("ComputeCharts: atlas is null.\n");
return;
@@ -8643,69 +9636,66 @@ void ComputeCharts(Atlas *atlas, ChartOptions chartOptions) {
return;
}
AddMeshJoin(atlas);
- if (ctx->meshCount == 0) {
+ if (ctx->meshes.isEmpty()) {
XA_PRINT_WARNING("ComputeCharts: No meshes. Call AddMesh first.\n");
return;
}
XA_PRINT("Computing charts\n");
- uint32_t chartCount = 0, chartsWithHolesCount = 0, holesCount = 0, chartsWithTJunctionsCount = 0, tJunctionsCount = 0;
XA_PROFILE_START(computeChartsReal)
- if (!ctx->paramAtlas.computeCharts(ctx->taskScheduler, chartOptions, ctx->progressFunc, ctx->progressUserData)) {
+ if (!ctx->paramAtlas.computeCharts(ctx->taskScheduler, options, ctx->progressFunc, ctx->progressUserData)) {
XA_PRINT(" Cancelled by user\n");
return;
}
XA_PROFILE_END(computeChartsReal)
- // Count charts and print warnings.
- for (uint32_t i = 0; i < ctx->meshCount; i++) {
+ // Count charts.
+ uint32_t chartCount = 0;
+ const uint32_t meshCount = ctx->meshes.size();
+ for (uint32_t i = 0; i < meshCount; i++) {
for (uint32_t j = 0; j < ctx->paramAtlas.chartGroupCount(i); j++) {
const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, j);
- if (chartGroup->isVertexMap())
- continue;
- for (uint32_t k = 0; k < chartGroup->chartCount(); k++) {
- const internal::param::Chart *chart = chartGroup->chartAt(k);
-#if XA_PRINT_CHART_WARNINGS
- if (chart->warningFlags() & internal::param::ChartWarningFlags::CloseHolesFailed)
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): failed to close holes\n", chartCount, i, j, k);
- if (chart->warningFlags() & internal::param::ChartWarningFlags::FixTJunctionsDuplicatedEdge)
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): fixing t-junctions created non-manifold geometry\n", chartCount, i, j, k);
- if (chart->warningFlags() & internal::param::ChartWarningFlags::FixTJunctionsFailed)
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): fixing t-junctions failed\n", chartCount, i, j, k);
- if (chart->warningFlags() & internal::param::ChartWarningFlags::TriangulateDuplicatedEdge)
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): triangulation created non-manifold geometry\n", chartCount, i, j, k);
-#endif
- holesCount += chart->closedHolesCount();
- if (chart->closedHolesCount() > 0)
- chartsWithHolesCount++;
- tJunctionsCount += chart->fixedTJunctionsCount();
- if (chart->fixedTJunctionsCount() > 0)
- chartsWithTJunctionsCount++;
- chartCount++;
- }
+ chartCount += chartGroup->segmentChartCount();
}
}
- if (holesCount > 0)
- XA_PRINT(" Closed %u holes in %u charts\n", holesCount, chartsWithHolesCount);
- if (tJunctionsCount > 0)
- XA_PRINT(" Fixed %u t-junctions in %u charts\n", tJunctionsCount, chartsWithTJunctionsCount);
XA_PRINT(" %u charts\n", chartCount);
+#if XA_PROFILE
+ XA_PRINT(" Chart groups\n");
+ uint32_t chartGroupCount = 0;
+ for (uint32_t i = 0; i < meshCount; i++) {
+ XA_PRINT(" Mesh %u: %u chart groups\n", i, ctx->paramAtlas.chartGroupCount(i));
+ chartGroupCount += ctx->paramAtlas.chartGroupCount(i);
+ }
+ XA_PRINT(" %u total\n", chartGroupCount);
+#endif
XA_PROFILE_PRINT_AND_RESET(" Total (real): ", computeChartsReal)
XA_PROFILE_PRINT_AND_RESET(" Total (thread): ", computeChartsThread)
- XA_PROFILE_PRINT_AND_RESET(" Build atlas: ", buildAtlas)
- XA_PROFILE_PRINT_AND_RESET(" Init: ", buildAtlasInit)
- XA_PROFILE_PRINT_AND_RESET(" Place seeds: ", buildAtlasPlaceSeeds)
- XA_PROFILE_PRINT_AND_RESET(" Relocate seeds: ", buildAtlasRelocateSeeds)
- XA_PROFILE_PRINT_AND_RESET(" Reset charts: ", buildAtlasResetCharts)
- XA_PROFILE_PRINT_AND_RESET(" Grow charts: ", buildAtlasGrowCharts)
- XA_PROFILE_PRINT_AND_RESET(" Merge charts: ", buildAtlasMergeCharts)
- XA_PROFILE_PRINT_AND_RESET(" Fill holes: ", buildAtlasFillHoles)
- XA_PROFILE_PRINT_AND_RESET(" Create chart meshes (real): ", createChartMeshesReal)
- XA_PROFILE_PRINT_AND_RESET(" Create chart meshes (thread): ", createChartMeshesThread)
- XA_PROFILE_PRINT_AND_RESET(" Fix t-junctions: ", fixChartMeshTJunctions)
- XA_PROFILE_PRINT_AND_RESET(" Close holes: ", closeChartMeshHoles)
+ XA_PROFILE_PRINT_AND_RESET(" Create face groups: ", createFaceGroups)
+ XA_PROFILE_PRINT_AND_RESET(" Extract invalid mesh geometry: ", extractInvalidMeshGeometry)
+ XA_PROFILE_PRINT_AND_RESET(" Chart group compute charts (real): ", chartGroupComputeChartsReal)
+ XA_PROFILE_PRINT_AND_RESET(" Chart group compute charts (thread): ", chartGroupComputeChartsThread)
+ XA_PROFILE_PRINT_AND_RESET(" Create chart group mesh: ", createChartGroupMesh)
+ XA_PROFILE_PRINT_AND_RESET(" Create colocals: ", createChartGroupMeshColocals)
+ XA_PROFILE_PRINT_AND_RESET(" Create boundaries: ", createChartGroupMeshBoundaries)
+ XA_PROFILE_PRINT_AND_RESET(" Build atlas: ", buildAtlas)
+ XA_PROFILE_PRINT_AND_RESET(" Init: ", buildAtlasInit)
+ XA_PROFILE_PRINT_AND_RESET(" Planar charts: ", planarCharts)
+ XA_PROFILE_PRINT_AND_RESET(" Clustered charts: ", clusteredCharts)
+ XA_PROFILE_PRINT_AND_RESET(" Place seeds: ", clusteredChartsPlaceSeeds)
+ XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", clusteredChartsPlaceSeedsBoundaryIntersection)
+ XA_PROFILE_PRINT_AND_RESET(" Relocate seeds: ", clusteredChartsRelocateSeeds)
+ XA_PROFILE_PRINT_AND_RESET(" Reset: ", clusteredChartsReset)
+ XA_PROFILE_PRINT_AND_RESET(" Grow: ", clusteredChartsGrow)
+ XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", clusteredChartsGrowBoundaryIntersection)
+ XA_PROFILE_PRINT_AND_RESET(" Merge: ", clusteredChartsMerge)
+ XA_PROFILE_PRINT_AND_RESET(" Fill holes: ", clusteredChartsFillHoles)
+ XA_PROFILE_PRINT_AND_RESET(" Copy chart faces: ", copyChartFaces)
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
+#endif
XA_PRINT_MEM_USAGE
}
-void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
+void ParameterizeCharts(Atlas *atlas, ParameterizeOptions options)
+{
if (!atlas) {
XA_PRINT_WARNING("ParameterizeCharts: atlas is null.\n");
return;
@@ -8734,19 +9724,34 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
DestroyOutputMeshes(ctx);
XA_PRINT("Parameterizing charts\n");
XA_PROFILE_START(parameterizeChartsReal)
- if (!ctx->paramAtlas.parameterizeCharts(ctx->taskScheduler, func, ctx->progressFunc, ctx->progressUserData)) {
+ if (!ctx->paramAtlas.parameterizeCharts(ctx->taskScheduler, options, ctx->progressFunc, ctx->progressUserData)) {
XA_PRINT(" Cancelled by user\n");
- return;
+ return;
}
XA_PROFILE_END(parameterizeChartsReal)
- uint32_t chartCount = 0, orthoChartsCount = 0, planarChartsCount = 0, lscmChartsCount = 0, piecewiseChartsCount = 0, chartsAddedCount = 0, chartsDeletedCount = 0;
- for (uint32_t i = 0; i < ctx->meshCount; i++) {
+ const uint32_t meshCount = ctx->meshes.size();
+ uint32_t chartCount = 0, chartsWithHolesCount = 0, holesCount = 0, chartsWithTJunctionsCount = 0, tJunctionsCount = 0, orthoChartsCount = 0, planarChartsCount = 0, lscmChartsCount = 0, piecewiseChartsCount = 0, chartsAddedCount = 0, chartsDeletedCount = 0;
+ for (uint32_t i = 0; i < meshCount; i++) {
for (uint32_t j = 0; j < ctx->paramAtlas.chartGroupCount(i); j++) {
const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, j);
- if (chartGroup->isVertexMap())
- continue;
for (uint32_t k = 0; k < chartGroup->chartCount(); k++) {
const internal::param::Chart *chart = chartGroup->chartAt(k);
+#if XA_PRINT_CHART_WARNINGS
+ if (chart->warningFlags() & internal::param::ChartWarningFlags::CloseHolesFailed)
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): failed to close holes\n", chartCount, i, j, k);
+ if (chart->warningFlags() & internal::param::ChartWarningFlags::FixTJunctionsDuplicatedEdge)
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): fixing t-junctions created non-manifold geometry\n", chartCount, i, j, k);
+ if (chart->warningFlags() & internal::param::ChartWarningFlags::FixTJunctionsFailed)
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): fixing t-junctions failed\n", chartCount, i, j, k);
+ if (chart->warningFlags() & internal::param::ChartWarningFlags::TriangulateDuplicatedEdge)
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u): triangulation created non-manifold geometry\n", chartCount, i, j, k);
+#endif
+ holesCount += chart->closedHolesCount();
+ if (chart->closedHolesCount() > 0)
+ chartsWithHolesCount++;
+ tJunctionsCount += chart->fixedTJunctionsCount();
+ if (chart->fixedTJunctionsCount() > 0)
+ chartsWithTJunctionsCount++;
if (chart->type() == ChartType::Planar)
planarChartsCount++;
else if (chart->type() == ChartType::Ortho)
@@ -8761,19 +9766,21 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
chartsDeletedCount += chartGroup->paramDeletedChartsCount();
}
}
+ if (holesCount > 0)
+ XA_PRINT(" %u holes closed in %u charts\n", holesCount, chartsWithHolesCount);
+ if (tJunctionsCount > 0)
+ XA_PRINT(" %u t-junctions fixed in %u charts\n", tJunctionsCount, chartsWithTJunctionsCount);
XA_PRINT(" %u planar charts, %u ortho charts, %u LSCM charts, %u piecewise charts\n", planarChartsCount, orthoChartsCount, lscmChartsCount, piecewiseChartsCount);
if (chartsDeletedCount > 0) {
XA_PRINT(" %u charts with invalid parameterizations replaced with %u new charts\n", chartsDeletedCount, chartsAddedCount);
XA_PRINT(" %u charts\n", chartCount);
}
uint32_t chartIndex = 0, invalidParamCount = 0;
- for (uint32_t i = 0; i < ctx->meshCount; i++) {
+ for (uint32_t i = 0; i < meshCount; i++) {
for (uint32_t j = 0; j < ctx->paramAtlas.chartGroupCount(i); j++) {
const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, j);
- if (chartGroup->isVertexMap())
- continue;
for (uint32_t k = 0; k < chartGroup->chartCount(); k++) {
- const internal::param::Chart *chart = chartGroup->chartAt(k);
+ internal::param::Chart *chart = chartGroup->chartAt(k);
const internal::param::Quality &quality = chart->quality();
#if XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION
{
@@ -8782,7 +9789,6 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
chart->unifiedMesh()->writeObjFile(filename);
}
#endif
- bool invalid = false;
const char *type = "LSCM";
if (chart->type() == ChartType::Planar)
type = "planar";
@@ -8790,18 +9796,15 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
type = "ortho";
else if (chart->type() == ChartType::Piecewise)
type = "piecewise";
- if (quality.boundaryIntersection) {
- invalid = true;
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, self-intersecting boundary.\n", chartIndex, i, j, k, type);
- }
- if (quality.flippedTriangleCount > 0) {
- invalid = true;
- XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, %u / %u flipped triangles.\n", chartIndex, i, j, k, type, quality.flippedTriangleCount, quality.totalTriangleCount);
- }
- if (invalid)
+ if (chart->isInvalid()) {
+ if (quality.boundaryIntersection) {
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, self-intersecting boundary.\n", chartIndex, i, j, k, type);
+ }
+ if (quality.flippedTriangleCount > 0) {
+ XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, %u / %u flipped triangles.\n", chartIndex, i, j, k, type, quality.flippedTriangleCount, quality.totalTriangleCount);
+ }
invalidParamCount++;
#if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
- if (invalid) {
char filename[256];
XA_SPRINTF(filename, sizeof(filename), "debug_chart_%03u_invalid_parameterization.obj", chartIndex);
const internal::Mesh *mesh = chart->unifiedMesh();
@@ -8822,8 +9825,8 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
mesh->writeObjLinkedBoundaries(file);
fclose(file);
}
- }
#endif
+ }
chartIndex++;
}
}
@@ -8832,20 +9835,30 @@ void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func) {
XA_PRINT_WARNING(" %u charts with invalid parameterizations\n", invalidParamCount);
XA_PROFILE_PRINT_AND_RESET(" Total (real): ", parameterizeChartsReal)
XA_PROFILE_PRINT_AND_RESET(" Total (thread): ", parameterizeChartsThread)
+ XA_PROFILE_PRINT_AND_RESET(" Create chart mesh: ", createChartMesh)
+ XA_PROFILE_PRINT_AND_RESET(" Fix t-junctions: ", fixChartMeshTJunctions)
+ XA_PROFILE_PRINT_AND_RESET(" Close holes: ", closeChartMeshHoles)
XA_PROFILE_PRINT_AND_RESET(" Orthogonal: ", parameterizeChartsOrthogonal)
XA_PROFILE_PRINT_AND_RESET(" LSCM: ", parameterizeChartsLSCM)
+ XA_PROFILE_PRINT_AND_RESET(" Recompute: ", parameterizeChartsRecompute)
+ XA_PROFILE_PRINT_AND_RESET(" Piecewise: ", parameterizeChartsPiecewise)
+ XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", parameterizeChartsPiecewiseBoundaryIntersection)
XA_PROFILE_PRINT_AND_RESET(" Evaluate quality: ", parameterizeChartsEvaluateQuality)
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
+#endif
XA_PRINT_MEM_USAGE
}
-void PackCharts(Atlas *atlas, PackOptions packOptions) {
+void PackCharts(Atlas *atlas, PackOptions packOptions)
+{
// Validate arguments and context state.
if (!atlas) {
XA_PRINT_WARNING("PackCharts: atlas is null.\n");
return;
}
Context *ctx = (Context *)atlas;
- if (ctx->meshCount == 0 && ctx->uvMeshInstances.isEmpty()) {
+ if (ctx->meshes.isEmpty() && ctx->uvMeshInstances.isEmpty()) {
XA_PRINT_WARNING("PackCharts: No meshes. Call AddMesh or AddUvMesh first.\n");
return;
}
@@ -8880,7 +9893,8 @@ void PackCharts(Atlas *atlas, PackOptions packOptions) {
if (!ctx->uvMeshInstances.isEmpty()) {
for (uint32_t i = 0; i < ctx->uvMeshInstances.size(); i++)
packAtlas.addUvMeshCharts(ctx->uvMeshInstances[i]);
- } else
+ }
+ else
packAtlas.addCharts(ctx->taskScheduler, &ctx->paramAtlas);
XA_PROFILE_END(packChartsAddCharts)
XA_PROFILE_START(packCharts)
@@ -8901,7 +9915,7 @@ void PackCharts(Atlas *atlas, PackOptions packOptions) {
if (packOptions.createImage) {
atlas->image = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, atlas->atlasCount * atlas->width * atlas->height);
for (uint32_t i = 0; i < atlas->atlasCount; i++)
- packAtlas.getImages()[i]->copyTo(&atlas->image[atlas->width * atlas->height * i], atlas->width, atlas->height, packOptions.blockAlign ? 0 : packOptions.padding);
+ packAtlas.getImages()[i]->copyTo(&atlas->image[atlas->width * atlas->height * i], atlas->width, atlas->height, packOptions.padding);
}
XA_PROFILE_PRINT_AND_RESET(" Total: ", packCharts)
XA_PROFILE_PRINT_AND_RESET(" Add charts (real): ", packChartsAddCharts)
@@ -8911,6 +9925,9 @@ void PackCharts(Atlas *atlas, PackOptions packOptions) {
XA_PROFILE_PRINT_AND_RESET(" Dilate (padding): ", packChartsDilate)
XA_PROFILE_PRINT_AND_RESET(" Find location: ", packChartsFindLocation)
XA_PROFILE_PRINT_AND_RESET(" Blit: ", packChartsBlit)
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
+#endif
XA_PRINT_MEM_USAGE
XA_PRINT("Building output meshes\n");
XA_PROFILE_START(buildOutputMeshes)
@@ -8920,91 +9937,92 @@ void PackCharts(Atlas *atlas, PackOptions packOptions) {
return;
}
if (ctx->uvMeshInstances.isEmpty())
- atlas->meshCount = ctx->meshCount;
+ atlas->meshCount = ctx->meshes.size();
else
atlas->meshCount = ctx->uvMeshInstances.size();
atlas->meshes = XA_ALLOC_ARRAY(internal::MemTag::Default, Mesh, atlas->meshCount);
memset(atlas->meshes, 0, sizeof(Mesh) * atlas->meshCount);
if (ctx->uvMeshInstances.isEmpty()) {
uint32_t chartIndex = 0;
- for (uint32_t i = 0; i < ctx->meshCount; i++) {
+ for (uint32_t i = 0; i < atlas->meshCount; i++) {
Mesh &outputMesh = atlas->meshes[i];
- // Count and alloc arrays. Ignore vertex mapped chart groups in Mesh::chartCount, since they're ignored faces.
+ // Count and alloc arrays.
+ const internal::param::InvalidMeshGeometry &invalid = ctx->paramAtlas.invalidMeshGeometry(i);
+ outputMesh.vertexCount += invalid.vertices().length;
+ outputMesh.indexCount += invalid.faces().length * 3;
for (uint32_t cg = 0; cg < ctx->paramAtlas.chartGroupCount(i); cg++) {
const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, cg);
- if (chartGroup->isVertexMap()) {
- outputMesh.vertexCount += chartGroup->mesh()->vertexCount();
- outputMesh.indexCount += chartGroup->mesh()->faceCount() * 3;
- } else {
- for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
- const internal::param::Chart *chart = chartGroup->chartAt(c);
- outputMesh.vertexCount += chart->mesh()->vertexCount();
- outputMesh.indexCount += chart->mesh()->faceCount() * 3;
- outputMesh.chartCount++;
- }
+ for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
+ const internal::param::Chart *chart = chartGroup->chartAt(c);
+ outputMesh.vertexCount += chart->mesh()->vertexCount();
+ outputMesh.indexCount += chart->mesh()->faceCount() * 3;
+ outputMesh.chartCount++;
}
}
outputMesh.vertexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Vertex, outputMesh.vertexCount);
outputMesh.indexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputMesh.indexCount);
outputMesh.chartArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Chart, outputMesh.chartCount);
- XA_PRINT(" mesh %u: %u vertices, %u triangles, %u charts\n", i, outputMesh.vertexCount, outputMesh.indexCount / 3, outputMesh.chartCount);
+ XA_PRINT(" Mesh %u: %u vertices, %u triangles, %u charts\n", i, outputMesh.vertexCount, outputMesh.indexCount / 3, outputMesh.chartCount);
// Copy mesh data.
- uint32_t firstVertex = 0, meshChartIndex = 0;
+ uint32_t firstVertex = 0;
+ {
+ const internal::param::InvalidMeshGeometry &mesh = ctx->paramAtlas.invalidMeshGeometry(i);
+ internal::ConstArrayView<uint32_t> faces = mesh.faces();
+ internal::ConstArrayView<uint32_t> indices = mesh.indices();
+ internal::ConstArrayView<uint32_t> vertices = mesh.vertices();
+ // Vertices.
+ for (uint32_t v = 0; v < vertices.length; v++) {
+ Vertex &vertex = outputMesh.vertexArray[v];
+ vertex.atlasIndex = -1;
+ vertex.chartIndex = -1;
+ vertex.uv[0] = vertex.uv[1] = 0.0f;
+ vertex.xref = vertices[v];
+ }
+ // Indices.
+ for (uint32_t f = 0; f < faces.length; f++) {
+ const uint32_t indexOffset = faces[f] * 3;
+ for (uint32_t j = 0; j < 3; j++)
+ outputMesh.indexArray[indexOffset + j] = indices[f * 3 + j];
+ }
+ firstVertex = vertices.length;
+ }
+ uint32_t meshChartIndex = 0;
for (uint32_t cg = 0; cg < ctx->paramAtlas.chartGroupCount(i); cg++) {
const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, cg);
- if (chartGroup->isVertexMap()) {
- const internal::Mesh *mesh = chartGroup->mesh();
+ for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
+ const internal::param::Chart *chart = chartGroup->chartAt(c);
+ const internal::Mesh *mesh = chart->mesh();
// Vertices.
for (uint32_t v = 0; v < mesh->vertexCount(); v++) {
Vertex &vertex = outputMesh.vertexArray[firstVertex + v];
- vertex.atlasIndex = -1;
- vertex.chartIndex = -1;
- vertex.uv[0] = vertex.uv[1] = 0.0f;
- vertex.xref = chartGroup->mapVertexToSourceVertex(v);
+ vertex.atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
+ XA_DEBUG_ASSERT(vertex.atlasIndex >= 0);
+ vertex.chartIndex = (int32_t)chartIndex;
+ const internal::Vector2 &uv = mesh->texcoord(v);
+ vertex.uv[0] = internal::max(0.0f, uv.x);
+ vertex.uv[1] = internal::max(0.0f, uv.y);
+ vertex.xref = chart->mapChartVertexToSourceVertex(v);
}
// Indices.
for (uint32_t f = 0; f < mesh->faceCount(); f++) {
- const uint32_t indexOffset = chartGroup->mapFaceToSourceFace(f) * 3;
+ const uint32_t indexOffset = chart->mapFaceToSourceFace(f) * 3;
for (uint32_t j = 0; j < 3; j++)
outputMesh.indexArray[indexOffset + j] = firstVertex + mesh->vertexAt(f * 3 + j);
}
+ // Charts.
+ Chart *outputChart = &outputMesh.chartArray[meshChartIndex];
+ const int32_t atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
+ XA_DEBUG_ASSERT(atlasIndex >= 0);
+ outputChart->atlasIndex = (uint32_t)atlasIndex;
+ outputChart->type = chart->isInvalid() ? ChartType::Invalid : chart->type();
+ outputChart->faceCount = mesh->faceCount();
+ outputChart->faceArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputChart->faceCount);
+ for (uint32_t f = 0; f < outputChart->faceCount; f++)
+ outputChart->faceArray[f] = chart->mapFaceToSourceFace(f);
+ outputChart->material = 0;
+ meshChartIndex++;
+ chartIndex++;
firstVertex += mesh->vertexCount();
- } else {
- for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
- const internal::param::Chart *chart = chartGroup->chartAt(c);
- const internal::Mesh *mesh = chart->mesh();
- // Vertices.
- for (uint32_t v = 0; v < mesh->vertexCount(); v++) {
- Vertex &vertex = outputMesh.vertexArray[firstVertex + v];
- vertex.atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
- XA_DEBUG_ASSERT(vertex.atlasIndex >= 0);
- vertex.chartIndex = (int32_t)chartIndex;
- const internal::Vector2 &uv = mesh->texcoord(v);
- vertex.uv[0] = internal::max(0.0f, uv.x);
- vertex.uv[1] = internal::max(0.0f, uv.y);
- vertex.xref = chartGroup->mapVertexToSourceVertex(chart->mapChartVertexToOriginalVertex(v));
- }
- // Indices.
- for (uint32_t f = 0; f < mesh->faceCount(); f++) {
- const uint32_t indexOffset = chartGroup->mapFaceToSourceFace(chart->mapFaceToSourceFace(f)) * 3;
- for (uint32_t j = 0; j < 3; j++)
- outputMesh.indexArray[indexOffset + j] = firstVertex + mesh->vertexAt(f * 3 + j);
- }
- // Charts.
- Chart *outputChart = &outputMesh.chartArray[meshChartIndex];
- const int32_t atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
- XA_DEBUG_ASSERT(atlasIndex >= 0);
- outputChart->atlasIndex = (uint32_t)atlasIndex;
- outputChart->type = chart->type();
- outputChart->faceCount = mesh->faceCount();
- outputChart->faceArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputChart->faceCount);
- for (uint32_t f = 0; f < outputChart->faceCount; f++)
- outputChart->faceArray[f] = chartGroup->mapFaceToSourceFace(chart->mapFaceToSourceFace(f));
- outputChart->material = 0;
- meshChartIndex++;
- chartIndex++;
- firstVertex += mesh->vertexCount();
- }
}
}
XA_DEBUG_ASSERT(outputMesh.vertexCount == firstVertex);
@@ -9078,10 +10096,14 @@ void PackCharts(Atlas *atlas, PackOptions packOptions) {
ctx->progressFunc(ProgressCategory::BuildOutputMeshes, 100, ctx->progressUserData);
XA_PROFILE_END(buildOutputMeshes)
XA_PROFILE_PRINT_AND_RESET(" Total: ", buildOutputMeshes)
+#if XA_PROFILE_ALLOC
+ XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
+#endif
XA_PRINT_MEM_USAGE
}
-void Generate(Atlas *atlas, ChartOptions chartOptions, ParameterizeFunc paramFunc, PackOptions packOptions) {
+void Generate(Atlas *atlas, ChartOptions chartOptions, ParameterizeOptions parameterizeOptions, PackOptions packOptions)
+{
if (!atlas) {
XA_PRINT_WARNING("Generate: atlas is null.\n");
return;
@@ -9091,16 +10113,17 @@ void Generate(Atlas *atlas, ChartOptions chartOptions, ParameterizeFunc paramFun
XA_PRINT_WARNING("Generate: This function should not be called with UV meshes.\n");
return;
}
- if (ctx->meshCount == 0) {
+ if (ctx->meshes.isEmpty()) {
XA_PRINT_WARNING("Generate: No meshes. Call AddMesh first.\n");
return;
}
ComputeCharts(atlas, chartOptions);
- ParameterizeCharts(atlas, paramFunc);
+ ParameterizeCharts(atlas, parameterizeOptions);
PackCharts(atlas, packOptions);
}
-void SetProgressCallback(Atlas *atlas, ProgressFunc progressFunc, void *progressUserData) {
+void SetProgressCallback(Atlas *atlas, ProgressFunc progressFunc, void *progressUserData)
+{
if (!atlas) {
XA_PRINT_WARNING("SetProgressCallback: atlas is null.\n");
return;
@@ -9110,17 +10133,20 @@ void SetProgressCallback(Atlas *atlas, ProgressFunc progressFunc, void *progress
ctx->progressUserData = progressUserData;
}
-void SetAlloc(ReallocFunc reallocFunc, FreeFunc freeFunc) {
+void SetAlloc(ReallocFunc reallocFunc, FreeFunc freeFunc)
+{
internal::s_realloc = reallocFunc;
internal::s_free = freeFunc;
}
-void SetPrint(PrintFunc print, bool verbose) {
+void SetPrint(PrintFunc print, bool verbose)
+{
internal::s_print = print;
internal::s_printVerbose = verbose;
}
-const char *StringForEnum(AddMeshError::Enum error) {
+const char *StringForEnum(AddMeshError::Enum error)
+{
if (error == AddMeshError::Error)
return "Unspecified error";
if (error == AddMeshError::IndexOutOfRange)
@@ -9130,7 +10156,8 @@ const char *StringForEnum(AddMeshError::Enum error) {
return "Success";
}
-const char *StringForEnum(ProgressCategory::Enum category) {
+const char *StringForEnum(ProgressCategory::Enum category)
+{
if (category == ProgressCategory::AddMesh)
return "Adding mesh(es)";
if (category == ProgressCategory::ComputeCharts)
diff --git a/thirdparty/xatlas/xatlas.h b/thirdparty/xatlas/xatlas.h
index e59f493287..cc47f4837e 100644
--- a/thirdparty/xatlas/xatlas.h
+++ b/thirdparty/xatlas/xatlas.h
@@ -1,7 +1,7 @@
/*
MIT License
-Copyright (c) 2018-2019 Jonathan Young
+Copyright (c) 2018-2020 Jonathan Young
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -42,18 +42,19 @@ struct ChartType
Planar,
Ortho,
LSCM,
- Piecewise
+ Piecewise,
+ Invalid
};
};
// A group of connected faces, belonging to a single atlas.
struct Chart
{
- uint32_t atlasIndex; // Sub-atlas index.
uint32_t *faceArray;
+ uint32_t atlasIndex; // Sub-atlas index.
uint32_t faceCount;
- uint32_t material;
ChartType::Enum type;
+ uint32_t material;
};
// Output vertex.
@@ -69,10 +70,10 @@ struct Vertex
struct Mesh
{
Chart *chartArray;
- uint32_t chartCount;
uint32_t *indexArray;
- uint32_t indexCount;
Vertex *vertexArray;
+ uint32_t chartCount;
+ uint32_t indexCount;
uint32_t vertexCount;
};
@@ -84,15 +85,15 @@ static const uint32_t kImageIsPaddingBit = 0x20000000;
// Empty on creation. Populated after charts are packed.
struct Atlas
{
+ uint32_t *image;
+ Mesh *meshes; // The output meshes, corresponding to each AddMesh call.
uint32_t width; // Atlas width in texels.
uint32_t height; // Atlas height in texels.
uint32_t atlasCount; // Number of sub-atlases. Equal to 0 unless PackOptions resolution is changed from default (0).
uint32_t chartCount; // Total number of charts in all meshes.
uint32_t meshCount; // Number of output meshes. Equal to the number of times AddMesh was called.
- Mesh *meshes; // The output meshes, corresponding to each AddMesh call.
float *utilization; // Normalized atlas texel utilization array. E.g. a value of 0.8 means 20% empty space. atlasCount in length.
float texelsPerUnit; // Equal to PackOptions texelsPerUnit if texelsPerUnit > 0, otherwise an estimated value to match PackOptions resolution.
- uint32_t *image;
};
// Create an empty atlas.
@@ -112,22 +113,23 @@ struct IndexFormat
// Input mesh declaration.
struct MeshDecl
{
- uint32_t vertexCount = 0;
const void *vertexPositionData = nullptr;
- uint32_t vertexPositionStride = 0;
const void *vertexNormalData = nullptr; // optional
- uint32_t vertexNormalStride = 0; // optional
const void *vertexUvData = nullptr; // optional. The input UVs are provided as a hint to the chart generator.
- uint32_t vertexUvStride = 0; // optional
- uint32_t indexCount = 0;
const void *indexData = nullptr; // optional
- int32_t indexOffset = 0; // optional. Add this offset to all indices.
- IndexFormat::Enum indexFormat = IndexFormat::UInt16;
// Optional. indexCount / 3 (triangle count) in length.
// Don't atlas faces set to true. Ignored faces still exist in the output meshes, Vertex uv is set to (0, 0) and Vertex atlasIndex to -1.
const bool *faceIgnoreData = nullptr;
+ uint32_t vertexCount = 0;
+ uint32_t vertexPositionStride = 0;
+ uint32_t vertexNormalStride = 0; // optional
+ uint32_t vertexUvStride = 0; // optional
+ uint32_t indexCount = 0;
+ int32_t indexOffset = 0; // optional. Add this offset to all indices.
+ IndexFormat::Enum indexFormat = IndexFormat::UInt16;
+
// Vertex positions within epsilon distance of each other are considered colocal.
float epsilon = 1.192092896e-07F;
};
@@ -151,14 +153,14 @@ void AddMeshJoin(Atlas *atlas);
struct UvMeshDecl
{
+ const void *vertexUvData = nullptr;
+ const void *indexData = nullptr; // optional
+ const uint32_t *faceMaterialData = nullptr; // Optional. Faces with different materials won't be assigned to the same chart. Must be indexCount / 3 in length.
uint32_t vertexCount = 0;
uint32_t vertexStride = 0;
- const void *vertexUvData = nullptr;
uint32_t indexCount = 0;
- const void *indexData = nullptr; // optional
int32_t indexOffset = 0; // optional. Add this offset to all indices.
IndexFormat::Enum indexFormat = IndexFormat::UInt16;
- const uint32_t *faceMaterialData = nullptr; // Optional. Faces with different materials won't be assigned to the same chart. Must be indexCount / 3 in length.
bool rotateCharts = true;
};
@@ -170,24 +172,31 @@ struct ChartOptions
float maxBoundaryLength = 0.0f; // Don't grow charts to have a longer boundary than this. 0 means no limit.
// Weights determine chart growth. Higher weights mean higher cost for that metric.
- float proxyFitMetricWeight = 2.0f; // Angle between face and average chart normal.
- float roundnessMetricWeight = 0.01f;
- float straightnessMetricWeight = 6.0f;
- float normalSeamMetricWeight = 4.0f; // If > 1000, normal seams are fully respected.
- float textureSeamMetricWeight = 0.5f;
+ float normalDeviationWeight = 2.0f; // Angle between face and average chart normal.
+ float roundnessWeight = 0.01f;
+ float straightnessWeight = 6.0f;
+ float normalSeamWeight = 4.0f; // If > 1000, normal seams are fully respected.
+ float textureSeamWeight = 0.5f;
- float maxThreshold = 2.0f; // If total of all metrics * weights > maxThreshold, don't grow chart. Lower values result in more charts.
+ float maxCost = 2.0f; // If total of all metrics * weights > maxCost, don't grow chart. Lower values result in more charts.
uint32_t maxIterations = 1; // Number of iterations of the chart growing and seeding phases. Higher values result in better charts.
};
// Call after all AddMesh calls. Can be called multiple times to recompute charts with different options.
-void ComputeCharts(Atlas *atlas, ChartOptions chartOptions = ChartOptions());
+void ComputeCharts(Atlas *atlas, ChartOptions options = ChartOptions());
// Custom parameterization function. texcoords initial values are an orthogonal parameterization.
typedef void (*ParameterizeFunc)(const float *positions, float *texcoords, uint32_t vertexCount, const uint32_t *indices, uint32_t indexCount);
+struct ParameterizeOptions
+{
+ ParameterizeFunc func = nullptr;
+ bool closeHoles = true; // If the custom parameterization function works with multiple boundaries, this can be set to false to improve performance.
+ bool fixTJunctions = true; // If meshes don't have T-junctions, this can be set to false to improve performance.
+};
+
// Call after ComputeCharts. Can be called multiple times to re-parameterize charts with a different ParameterizeFunc.
-void ParameterizeCharts(Atlas *atlas, ParameterizeFunc func = nullptr);
+void ParameterizeCharts(Atlas *atlas, ParameterizeOptions options = ParameterizeOptions());
struct PackOptions
{
@@ -224,7 +233,7 @@ struct PackOptions
void PackCharts(Atlas *atlas, PackOptions packOptions = PackOptions());
// Equivalent to calling ComputeCharts, ParameterizeCharts and PackCharts in sequence. Can be called multiple times to regenerate with different options.
-void Generate(Atlas *atlas, ChartOptions chartOptions = ChartOptions(), ParameterizeFunc paramFunc = nullptr, PackOptions packOptions = PackOptions());
+void Generate(Atlas *atlas, ChartOptions chartOptions = ChartOptions(), ParameterizeOptions parameterizeOptions = ParameterizeOptions(), PackOptions packOptions = PackOptions());
// Progress tracking.
struct ProgressCategory