From 5cecb3ed1789d6f9308e5f47900ab53b5f283353 Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Wed, 25 Jan 2023 14:13:22 -0800 Subject: [PATCH 1/9] Added package io.github.axisangles.ktmath --- server/resources/ThirdPartyNotices.txt | 236 ++++++++++- .../github/axisangles/ktmath/EulerAngles.kt | 102 +++++ .../github/axisangles/ktmath/LICENSE-APACHE | 201 ++++++++++ .../io/github/axisangles/ktmath/LICENSE-MIT | 21 + .../java/io/github/axisangles/ktmath/Main.kt | 364 +++++++++++++++++ .../io/github/axisangles/ktmath/Matrix3.kt | 368 +++++++++++++++++ .../io/github/axisangles/ktmath/Quaternion.kt | 371 ++++++++++++++++++ .../io/github/axisangles/ktmath/Vector3.kt | 90 +++++ 8 files changed, 1751 insertions(+), 2 deletions(-) create mode 100644 server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt create mode 100644 server/src/main/java/io/github/axisangles/ktmath/LICENSE-APACHE create mode 100644 server/src/main/java/io/github/axisangles/ktmath/LICENSE-MIT create mode 100644 server/src/main/java/io/github/axisangles/ktmath/Main.kt create mode 100644 server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt create mode 100644 server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt create mode 100644 server/src/main/java/io/github/axisangles/ktmath/Vector3.kt diff --git a/server/resources/ThirdPartyNotices.txt b/server/resources/ThirdPartyNotices.txt index 800fab491..8f9e8c7d4 100644 --- a/server/resources/ThirdPartyNotices.txt +++ b/server/resources/ThirdPartyNotices.txt @@ -1269,7 +1269,7 @@ https://github.com/melloware/jintellitype Apache License Version 2.0, January 2004 - http://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -1501,7 +1501,7 @@ exhaustive, and do not form part of our licenses. such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations - for the public: + for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= @@ -1844,3 +1844,235 @@ licenses. Creative Commons may be contacted at creativecommons.org. --------------------------------------------------------------- + +ktmath +axisangles@gmail.com + +MIT License + +Copyright (c) 2023 Donald F Reynolds + +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. + +ktmath +axisangles@gmail.com + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Donald F Reynolds + + 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. + +--------------------------------------------------------------- diff --git a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt new file mode 100644 index 000000000..32a278e5f --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt @@ -0,0 +1,102 @@ +@file:Suppress("unused") +package io.github.axisangles.ktmath + +import kotlin.math.cos +import kotlin.math.sin + +enum class EulerOrder {XYZ, YZX, ZXY, ZYX, YXZ, XZY} + +// prefer Y.toX +// but if ambiguous, use X.fromY +/* + * Euler Angles contains both the x y z angle parameters and the order of application + */ +data class EulerAngles(val order: EulerOrder, val x: Float, val y: Float, val z: Float) { + /** + * creates a quaternion which represents the same rotation as this eulerAngles + * @return the quaternion + */ + fun toQuaternion(): Quaternion { + val cX = cos(x/2f) + val cY = cos(y/2f) + val cZ = cos(z/2f) + val sX = sin(x/2f) + val sY = sin(y/2f) + val sZ = sin(z/2f) + + return when (order) { + EulerOrder.XYZ -> Quaternion( + cX*cY*cZ - sX*sY*sZ, + cY*cZ*sX + cX*sY*sZ, + cX*cZ*sY - cY*sX*sZ, + cZ*sX*sY + cX*cY*sZ) + EulerOrder.YZX -> Quaternion( + cX*cY*cZ - sX*sY*sZ, + cY*cZ*sX + cX*sY*sZ, + cX*cZ*sY + cY*sX*sZ, + cX*cY*sZ - cZ*sX*sY) + EulerOrder.ZXY -> Quaternion( + cX*cY*cZ - sX*sY*sZ, + cY*cZ*sX - cX*sY*sZ, + cX*cZ*sY + cY*sX*sZ, + cZ*sX*sY + cX*cY*sZ) + EulerOrder.ZYX -> Quaternion( + cX*cY*cZ + sX*sY*sZ, + cY*cZ*sX - cX*sY*sZ, + cX*cZ*sY + cY*sX*sZ, + cX*cY*sZ - cZ*sX*sY) + EulerOrder.YXZ -> Quaternion( + cX*cY*cZ + sX*sY*sZ, + cY*cZ*sX + cX*sY*sZ, + cX*cZ*sY - cY*sX*sZ, + cX*cY*sZ - cZ*sX*sY) + EulerOrder.XZY -> Quaternion( + cX*cY*cZ + sX*sY*sZ, + cY*cZ*sX - cX*sY*sZ, + cX*cZ*sY - cY*sX*sZ, + cZ*sX*sY + cX*cY*sZ) + } + } + + // temp, replace with direct conversion later + //fun toMatrix(): Matrix3 = this.toQuaternion().toMatrix() + /** + * creates a matrix which represents the same rotation as this eulerAngles + * @return the matrix + */ + fun toMatrix(): Matrix3 { + val cX = cos(x) + val cY = cos(y) + val cZ = cos(z) + val sX = sin(x) + val sY = sin(y) + val sZ = sin(z) + + return when (order) { + EulerOrder.XYZ -> Matrix3( + cY*cZ, -cY*sZ, sY, + cZ*sX*sY + cX*sZ, cX*cZ - sX*sY*sZ, -cY*sX, + sX*sZ - cX*cZ*sY, cZ*sX + cX*sY*sZ, cX*cY) + EulerOrder.YZX -> Matrix3( + cY*cZ, sX*sY - cX*cY*sZ, cX*sY + cY*sX*sZ, + sZ, cX*cZ, -cZ*sX, + -cZ*sY, cY*sX + cX*sY*sZ, cX*cY - sX*sY*sZ) + EulerOrder.ZXY -> Matrix3( + cY*cZ - sX*sY*sZ, -cX*sZ, cZ*sY + cY*sX*sZ, + cZ*sX*sY + cY*sZ, cX*cZ, sY*sZ - cY*cZ*sX, + -cX*sY, sX, cX*cY) + EulerOrder.ZYX -> Matrix3( + cY*cZ, cZ*sX*sY - cX*sZ, cX*cZ*sY + sX*sZ, + cY*sZ, cX*cZ + sX*sY*sZ, cX*sY*sZ - cZ*sX, + -sY, cY*sX, cX*cY) + EulerOrder.YXZ -> Matrix3( + cY*cZ + sX*sY*sZ, cZ*sX*sY - cY*sZ, cX*sY, + cX*sZ, cX*cZ, -sX, + cY*sX*sZ - cZ*sY, cY*cZ*sX + sY*sZ, cX*cY) + EulerOrder.XZY -> Matrix3( + cY*cZ, -sZ, cZ*sY, + sX*sY + cX*cY*sZ, cX*cZ, cX*sY*sZ - cY*sX, + cY*sX*sZ - cX*sY, cZ*sX, cX*cY + sX*sY*sZ) + } + } +} diff --git a/server/src/main/java/io/github/axisangles/ktmath/LICENSE-APACHE b/server/src/main/java/io/github/axisangles/ktmath/LICENSE-APACHE new file mode 100644 index 000000000..b15a06491 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Donald F Reynolds + + 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. diff --git a/server/src/main/java/io/github/axisangles/ktmath/LICENSE-MIT b/server/src/main/java/io/github/axisangles/ktmath/LICENSE-MIT new file mode 100644 index 000000000..39ed2df92 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Donald F Reynolds + +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. diff --git a/server/src/main/java/io/github/axisangles/ktmath/Main.kt b/server/src/main/java/io/github/axisangles/ktmath/Main.kt new file mode 100644 index 000000000..62297fd32 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/Main.kt @@ -0,0 +1,364 @@ +package io.github.axisangles.ktmath + +import kotlin.math.* +import kotlin.system.measureTimeMillis + +var randSeed = 0 +fun randInt(): Int { + randSeed = (1103515245*randSeed + 12345).mod(2147483648).toInt() + return randSeed +} + +fun randFloat(): Float { + return randInt().toFloat()/2147483648f +} + +fun randGaussian(): Float { + var thing = 1f - randFloat() + while (thing == 0f) { + // no 0s allowed + thing = 1f - randFloat() + } + return sqrt(-2f*ln(thing))*cos(PI.toFloat()*randFloat()) +} + +fun randMatrix(): Matrix3 { + return Matrix3( + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian() + ) +} + +fun randQuaternion(): Quaternion { + return Quaternion(randGaussian(), randGaussian(), randGaussian(), randGaussian()) +} + +fun randRotMatrix(): Matrix3 { + return randQuaternion().toMatrix() +} + +fun randVector(): Vector3 { + return Vector3(randGaussian(), randGaussian(), randGaussian()) +} + +fun testEulerMatrix(order: EulerOrder, M: Matrix3, exception: String) { + // We convert to euler angles and back and see if they are reasonably similar + val N = M.toEulerAngles(order).toMatrix() + if ((N - M).norm() > 1e-6) { + println("norm error: " + (N - M).norm().toString()) + throw Exception(exception) + } +} + +fun testEulerConversion(order: EulerOrder, exception: String) { + for (i in 1..1000) { + testEulerMatrix(order, randRotMatrix(), exception) + } +} + +fun testMatrixOrthonormalize() { + for (i in 1..1000) { + val M = randMatrix() + + val N = M.invTranspose().orthonormalize() + val O = M.orthonormalize() + if ((N - O).norm() > 1e-5) { + println("norm error: " + (N - O).norm().toString()) + throw Exception("Matrix orthonormalization accuracy test failed") + } + } +} + +fun testQuatMatrixConversion() { + for (i in 1..1000) { + val M = randRotMatrix() + val N = (randGaussian()*M.toQuaternion()).toMatrix() + if ((N - M).norm() > 1e-6) { + println("norm error: " + (N - M).norm().toString()) + throw Exception("Quaternion Matrix conversion accuracy test failed") + } + } +} + +fun relError(a: Matrix3, b: Matrix3): Float { + val combinedLen = sqrt((a.normSq() + b.normSq())/2f) + if (combinedLen == 0f) return 0f + + return (b - a).norm()/combinedLen +} + +fun relError(a: Vector3, b: Vector3): Float { + val combinedLen = sqrt((a.lenSq() + b.lenSq())/2f) + if (combinedLen == 0f) return 0f + + return (b - a).len()/combinedLen +} + +fun relError(a: Quaternion, b: Quaternion): Float { + val combinedLen = sqrt((a.lenSq() + b.lenSq())/2f) + if (combinedLen == 0f) return 0f + + return (b - a).len()/combinedLen +} + +fun checkError(eta: Float, a: Matrix3, b: Matrix3): Boolean { + return (b - a).normSq() <= eta*eta*(a.normSq() + b.normSq()) +} + +fun checkError(eta: Float, a: Quaternion, b: Quaternion): Boolean { + return (b - a).lenSq() <= eta*eta*(a.lenSq() + b.lenSq()) +} + +fun checkError(eta: Float, a: Vector3, b: Vector3): Boolean { + return (b - a).lenSq() <= eta*eta*(a.lenSq() + b.lenSq()) +} + +fun checkError(eta: Float, A: Quaternion): Boolean { + return A.lenSq() <= eta*eta +} + +fun testQuaternionInv() { + for (i in 1..1000) { + val Q = randQuaternion() + + if (relError(Q*Q.inv(), Quaternion.ONE) > 1e-6f) + throw Exception("Quaternion inv accuracy test failed") + } +} + +fun testQuaternionDiv() { + for (i in 1..1000) { + val Q = randQuaternion() + + if (!checkError(1e-6f, Q/Q, Quaternion.ONE)) + throw Exception("Quaternion div accuracy test failed") + if (!checkError(1e-6f, 2f/Q, 2f*Q.inv())) + throw Exception("Float/Quaternion accuracy test failed") + if (!checkError(1e-6f, Q/2f, 0.5f*Q)) + throw Exception("Quaternion/Float accuracy test failed") + } +} + +// 19 binary digits of accuracy +fun testQuaternionPow() { + for (i in 1..1000) { + val Q = randQuaternion() + + if (!checkError(2e-6f, Q.pow(-1f), Q.inv())) + throw Exception("Quaternion pow -1 accuracy test failed") + if (!checkError(2e-6f, Q.pow(0f), Quaternion.ONE)) + throw Exception("Quaternion pow 0 accuracy test failed") + if (!checkError(2e-6f, Q.pow(1f), Q)) + throw Exception("Quaternion pow 1 accuracy test failed") + if (!checkError(2e-6f, Q.pow(2f), Q*Q)) + throw Exception("Quaternion pow 2 accuracy test failed") + } +} + +fun testQuaternionSandwich() { + for (i in 1..1000) { + val Q = randQuaternion() + val v = randVector() + + if (!checkError(5e-7f, Q.toMatrix()*v, Q.sandwich(v))) + throw Exception("Quaternion sandwich accuracy test failed") + } +} + +// projection and alignment are expected to be less accurate in some extreme cases +// so we expect to see some cases in which half the bits are lost +fun testQuaternionProjectAlign() { + for (i in 1..1000) { + val Q = randQuaternion() + val v = randVector() + + if (!checkError(1e-4f, Q.align(v, v), Q.project(v))) { + println(Q.align(v, v) - Q.project(v)) + println(Q.align(v, v)) + println(Q.project(v)) + println(Q) + throw Exception("Quaternion project/align accuracy test failed") + } + } +} + +fun testQuaternionRotationVector() { + for (i in 1..1000) { + val Q = randQuaternion().unit() + val P = Quaternion.fromRotationVector(Q.toRotationVector()) + + if (!checkError(5e-7f, Q, P)) { + throw Exception("Quaternion toRotationVector fromRotationVector accuracy test failed") + } + } +} + +fun testQuaternionEulerAngles(order: EulerOrder, exception: String) { + for (i in 1..1000) { + val Q = randQuaternion().unit() + val P = Q.toEulerAngles(order).toQuaternion().twinNearest(Q) + + if (!checkError(2e-7f, Q, P)) { + println(relError(Q, P)) + throw Exception(exception) + } + } +} + +fun testEulerSingularity(order: EulerOrder, M: Matrix3, exception: String) { + for (i in 1..1000) { + val R = 1e-6f*randMatrix() + val S = M + R + if (S.det() <= 0f) return + + val error = (S.toEulerAnglesAssumingOrthonormal(order).toMatrix() - S).norm() + if (error > 2f*R.norm() + 1e-6f) { + throw Exception(exception) + } + } +} + +fun testEulerConversions(order: EulerOrder, exception: String) { + for (i in 1..1000) { + val e = EulerAngles(order, 6.28318f*randFloat(), 6.28318f*randFloat(), 6.28318f*randFloat()) + val N = e.toMatrix() + val M = e.toQuaternion().toMatrix() + if ((N - M).norm() > 1e-6) { + throw Exception(exception) + } + } +} + + +fun main() { + val X90 = Matrix3( + 1f, 0f, 0f, + 0f, 0f, -1f, + 0f, 1f, 0f + ) + val Y90 = Matrix3( + 0f, 0f, 1f, + 0f, 1f, 0f, + -1f, 0f, 0f + ) + val Z90 = Matrix3( + 0f, -1f, 0f, + 1f, 0f, 0f, + 0f, 0f, 1f + ) + + testMatrixOrthonormalize() + testQuatMatrixConversion() + testQuaternionEulerAngles(EulerOrder.XYZ, "Quaternion EulerAnglesXYZ accuracy test failed") + testQuaternionEulerAngles(EulerOrder.YZX, "Quaternion EulerAnglesYZX accuracy test failed") + testQuaternionEulerAngles(EulerOrder.ZXY, "Quaternion EulerAnglesZXY accuracy test failed") + testQuaternionEulerAngles(EulerOrder.ZYX, "Quaternion EulerAnglesZYX accuracy test failed") + testQuaternionEulerAngles(EulerOrder.YXZ, "Quaternion EulerAnglesYXZ accuracy test failed") + testQuaternionEulerAngles(EulerOrder.XZY, "Quaternion EulerAnglesXZY accuracy test failed") + + testQuaternionInv() + testQuaternionDiv() + testQuaternionPow() + testQuaternionSandwich() + testQuaternionProjectAlign() + testQuaternionRotationVector() + + println(Matrix3.IDENTITY.average(Y90)) + + testEulerConversions(EulerOrder.XYZ, "fromEulerAnglesXYZ Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.YZX, "fromEulerAnglesYZX Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.ZXY, "fromEulerAnglesZXY Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.ZYX, "fromEulerAnglesZYX Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.YXZ, "fromEulerAnglesYXZ Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.XZY, "fromEulerAnglesXZY Quaternion or Matrix3 accuracy test failed") + + // EULER ANGLE TESTS + testEulerConversion(EulerOrder.XYZ, "toEulerAnglesXYZ accuracy test failed") + testEulerConversion(EulerOrder.YZX, "toEulerAnglesYZX accuracy test failed") + testEulerConversion(EulerOrder.ZXY, "toEulerAnglesZXY accuracy test failed") + testEulerConversion(EulerOrder.ZYX, "toEulerAnglesZYX accuracy test failed") + testEulerConversion(EulerOrder.YXZ, "toEulerAnglesYXZ accuracy test failed") + testEulerConversion(EulerOrder.XZY, "toEulerAnglesXZY accuracy test failed") + + // test robustness to noise + testEulerSingularity(EulerOrder.XYZ, Y90, "toEulerAnglesXYZ singularity accuracy test failed") + testEulerSingularity(EulerOrder.YZX, Z90, "toEulerAnglesYZX singularity accuracy test failed") + testEulerSingularity(EulerOrder.ZXY, X90, "toEulerAnglesZXY singularity accuracy test failed") + testEulerSingularity(EulerOrder.ZYX, Y90, "toEulerAnglesZYX singularity accuracy test failed") + testEulerSingularity(EulerOrder.YXZ, X90, "toEulerAnglesYXZ singularity accuracy test failed") + testEulerSingularity(EulerOrder.XZY, Z90, "toEulerAnglesXZY singularity accuracy test failed") + + + + // speed test a linear (align) method against some standard math functions +// var x = Quaternion(1f, 2f, 3f, 4f) +// +// var dtAlignTotal: Long = 0 +// var dtOrthonormalizeTotal: Long = 0 +// var dtAtan2Total: Long = 0 +// var dtAsinTotal: Long = 0 +// +// for (i in 1..10) { +// val dtAlign = measureTimeMillis { +// for (i in 1..1_000_000) { +// val u = Vector3(1f, 0f, 0f) +// val v = Vector3(0f, 1f, 0f) +// // to make sure it is not optimized away +// x = x.align(u, v) +// // internally, x.align is: +// // val U = Quaternion(0f, u) +// // val V = Quaternion(0f, v) +// // x = (V*x/U + (V/U).len()*x)/2f +// } +// } +// +// var y = x.toMatrix() +// val dtOrthonormalize = measureTimeMillis { +// for (i in 1..1_000_000) { +// // to make sure it is not optimized away +// y = y.orthonormalize() +// // internally, x.align is: +// // val U = Quaternion(0f, u) +// // val V = Quaternion(0f, v) +// // x = (V*x/U + (V/U).len()*x)/2f +// } +// } +// +// var z = 0f; +// val dtAtan2 = measureTimeMillis { +// for (i in 1..1_000_000) { +// z+= atan2(i.toFloat(), i.toFloat()) // 45 degrees +// } +// } +// +// var w = 0f; +// val dtAsin = measureTimeMillis { +// for (i in 1..1_000_000) { +// w+= asin(i.toFloat()*0.7071f/i.toFloat()) // 45 degrees +// } +// } +// +// dtAlignTotal += dtAlign +// dtOrthonormalizeTotal += dtOrthonormalize +// dtAtan2Total += dtAtan2 +// dtAsinTotal += dtAsin +// } +// +// println(x) +// +// println(dtAlignTotal) // 213 +// println(dtOrthonormalizeTotal) // 244 +// println(dtAtan2Total) // 610 +// println(dtAsinTotal) // 3558 + + +// var x = Quaternion(2f, 1f, 4f, 3f) +// val dtPow = measureTimeMillis { +// for (i in 1..10_000_000) { +// x = x.pow(1f) +// } +// } +// +// println(dtPow) +} \ No newline at end of file diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt new file mode 100644 index 000000000..f1700a830 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -0,0 +1,368 @@ +@file:Suppress("unused") +package io.github.axisangles.ktmath + +import kotlin.math.* + +data class Matrix3 ( + val xx: Float, val yx: Float, val zx: Float, + val xy: Float, val yy: Float, val zy: Float, + val xz: Float, val yz: Float, val zz: Float +) { + companion object { + val ZERO = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + val IDENTITY = Matrix3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) + } + + /** + * creates a new matrix from x y and z column vectors + */ + constructor(x: Vector3, y: Vector3, z: Vector3) : this( + x.x, y.x, z.x, + x.y, y.y, z.y, + x.z, y.z, z.z) + + // column getters + val x get() = Vector3(xx, xy, xz) + val y get() = Vector3(yx, yy, yz) + val z get() = Vector3(zx, zy, zz) + + // row getters + val xRow get() = Vector3(xx, yx, zx) + val yRow get() = Vector3(xy, yy, zy) + val zRow get() = Vector3(xz, yz, zz) + + operator fun unaryMinus(): Matrix3 = Matrix3( + -xx, -yx, -zx, + -xy, -yy, -zy, + -xz, -yz, -zz) + + operator fun plus(that: Matrix3): Matrix3 = Matrix3( + this.xx + that.xx, this.yx + that.yx, this.zx + that.zx, + this.xy + that.xy, this.yy + that.yy, this.zy + that.zy, + this.xz + that.xz, this.yz + that.yz, this.zz + that.zz) + + operator fun minus(that: Matrix3): Matrix3 = Matrix3( + this.xx - that.xx, this.yx - that.yx, this.zx - that.zx, + this.xy - that.xy, this.yy - that.yy, this.zy - that.zy, + this.xz - that.xz, this.yz - that.yz, this.zz - that.zz) + + operator fun times(that: Float): Matrix3 = Matrix3( + this.xx*that, this.yx*that, this.zx*that, + this.xy*that, this.yy*that, this.zy*that, + this.xz*that, this.yz*that, this.zz*that) + + operator fun times(that: Vector3): Vector3 = Vector3( + this.xx*that.x + this.yx*that.y + this.zx*that.z, + this.xy*that.x + this.yy*that.y + this.zy*that.z, + this.xz*that.x + this.yz*that.y + this.zz*that.z) + + operator fun times(that: Matrix3): Matrix3 = Matrix3( + this.xx*that.xx + this.yx*that.xy + this.zx*that.xz, + this.xx*that.yx + this.yx*that.yy + this.zx*that.yz, + this.xx*that.zx + this.yx*that.zy + this.zx*that.zz, + this.xy*that.xx + this.yy*that.xy + this.zy*that.xz, + this.xy*that.yx + this.yy*that.yy + this.zy*that.yz, + this.xy*that.zx + this.yy*that.zy + this.zy*that.zz, + this.xz*that.xx + this.yz*that.xy + this.zz*that.xz, + this.xz*that.yx + this.yz*that.yy + this.zz*that.yz, + this.xz*that.zx + this.yz*that.zy + this.zz*that.zz) + + /** + * computes the square of the frobenius norm of this matrix + * @return the frobenius norm squared + */ + fun normSq(): Float = xx*xx + yx*yx + zx*zx + xy*xy + yy*yy + zy*zy + xz*xz + yz*yz + zz*zz + + /** + * computes the frobenius norm of this matrix + * @return the frobenius norm + */ + fun norm(): Float = sqrt(normSq()) + + /** + * computes the determinant of this matrix + * @return the determinant + */ + fun det(): Float = (xz*yx - xx*yz)*zy + (xx*yy - xy*yx)*zz + (xy*yz - xz*yy)*zx + + /** + * computes the trace of this matrix + * @return the trace + */ + fun trace(): Float = xx + yy + zz + + /** + * computes the transpose of this matrix + * @return the transpose matrix + */ + fun transpose(): Matrix3 = Matrix3( + xx, xy, xz, + yx, yy, yz, + zx, zy, zz) + + /** + * computes the inverse of this matrix + * @return the inverse matrix + */ + fun inv(): Matrix3 { + val det = det() + return Matrix3( + (yy*zz - yz*zy)/det, (yz*zx - yx*zz)/det, (yx*zy - yy*zx)/det, + (xz*zy - xy*zz)/det, (xx*zz - xz*zx)/det, (xy*zx - xx*zy)/det, + (xy*yz - xz*yy)/det, (xz*yx - xx*yz)/det, (xx*yy - xy*yx)/det) + } + + operator fun div(that: Float): Matrix3 = this*(1f/that) + + /** + * computes the right division, this * that^-1 + */ + operator fun div(that: Matrix3): Matrix3 = this*that.inv() + + /** + * computes the inverse transpose of this matrix + * @return the inverse transpose matrix + */ + fun invTranspose(): Matrix3 { + val det = det() + return Matrix3( + (yy*zz - yz*zy)/det, (xz*zy - xy*zz)/det, (xy*yz - xz*yy)/det, + (yz*zx - yx*zz)/det, (xx*zz - xz*zx)/det, (xz*yx - xx*yz)/det, + (yx*zy - yy*zx)/det, (xy*zx - xx*zy)/det, (xx*yy - xy*yx)/det) + } + + /** + * computes the nearest orthonormal matrix to this matrix + * @return the rotation matrix + */ + fun orthonormalize(): Matrix3 { + var curMat = this + var curDet = Float.POSITIVE_INFINITY + + for (i in 1..100) { + val newMat = (curMat + curMat.invTranspose())/2f + val newDet = abs(newMat.det()) + // should almost always exit immediately + if (newDet >= curDet) return curMat + if (newDet <= 1.0000001f) return newMat + curMat = newMat + curDet = newDet + } + + return curMat + } + + /** + * finds the rotation matrix closest to all given rotation matrices. + * multiply input matrices by a weight for weighted averaging. + * WARNING: NOT ANGULAR + * @param others a variable number of additional matrices to average + * @return the average rotation matrix + */ + fun average(vararg others: Matrix3): Matrix3 { + var count = 1f + var sum = this + others.forEach { + count += 1f + sum += it + } + return (sum/count).orthonormalize() + } + + /** + * linearly interpolates this matrix to that matrix by t + * @param that the matrix towards which to interpolate + * @param t the amount by which to interpolate + * @return the interpolated matrix + */ + fun lerp(that: Matrix3, t: Float): Matrix3 = (1f - t)*this + t*that + + // assumes this matrix is orthonormal and converts this to a quaternion + /** + * creates a quaternion representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * @return the quaternion + */ + fun toQuaternionAssumingOrthonormal(): Quaternion { + if (this.det() <= 0f) + throw Exception("Attempt to convert negative determinant matrix to quaternion") + + return if (yy > -zz && zz > -xx && xx > -yy) { + Quaternion(1 + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() + } else if (xx > yy && xx > zz) { + Quaternion(yz - zy, 1 + xx - yy - zz, xy + yx, xz + zx).unit() + } else if (yy > zz) { + Quaternion(zx - xz, xy + yx, 1 - xx + yy - zz, yz + zy).unit() + } else { + Quaternion(xy - yx, xz + zx, yz + zy, 1 - xx - yy + zz).unit() + } + } + + // orthogonalizes the matrix then returns the quaternion + /** + * creates a quaternion representing the same rotation as this matrix + * @return the quaternion + */ + fun toQuaternion(): Quaternion = orthonormalize().toQuaternionAssumingOrthonormal() + + + /* + the standard algorithm: + + yAng = asin(clamp(zx, -1, 1)) + if (abs(zx) < 0.9999999f) { + xAng = atan2(-zy, zz) + zAng = atan2(-yx, xx) + } else { + xAng = atan2(yz, yy) + zAng = 0 + } + + + + problems with the standard algorithm: + + 1) + yAng = asin(clamp(zx, -1, 1)) + + FIX: + yAng = atan2(zx, sqrt(zy*zy + zz*zz)) + + this loses many bits of accuracy when near the singularity, zx = +-1 and + can cause the algorithm to return completely inaccurate results with only + small floating point errors in the matrix. this happens because zx is + NOT sin(pitch), but rather errorTerm*sin(pitch), and small changes in zx + when zx is near +-1 make large changes in asin(zx). + + + + 2) + if (abs(zx) < 0.9999999f) { + + FIX: + if (zy*zy + zz*zz > 0f) { + + this clause, meant to reduce the inaccuracy of the code following does + not actually test for the condition that makes the following atans unstable. + that is, when (zy, zz) and (yx, xx) are near 0. + after several matrix multiplications, the error term is expected to be + larger than 0.0000001. Often times, this clause will not catch the conditions + it is trying to catch. + + + + 3) + zAng = atan2(-yx, xx) + + FIX: + zAng = atan2(xy*zz - xz*zy, yy*zz - yz*zy) + + xAng and zAng are being computed separately. In the case of near singularity + the angles of xAng and zAng are effectively added together as they represent + the same operation (a rotation about the global y-axis). When computed + separately, it is not guaranteed that the xAng + zAng add together to give + the actual final rotation about the global y-axis. + + + + 4) + after many matrix operations are performed, without orthonormalization + the matrix will contain floating point errors that will throw off the + accuracy of any euler angles algorithm. orthonormalization should be + built into the prerequisites for this function + */ + + +// fun toEulerAnglesXYZFaulty(): EulerAngles { +// return if (abs(zx) < 0.9999999f) +// EulerAngles(EulerOrder.XYZ, +// atan2(-zy, zz), +// asin(zx.coerceIn(-1f, 1f)), +// atan2(-yx, xx)) +// else +// EulerAngles(EulerOrder.XYZ, +// atan2(yz, yy), +// asin(zx.coerceIn(-1f, 1f)), +// 0f) +// } + + /** + * creates an eulerAngles representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * @return the eulerAngles + */ + fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { + if (this.det() <= 0f) + throw Exception("Attempt to convert negative determinant matrix to euler angles") + + val ETA = 1.57079632f + when (order) { + EulerOrder.XYZ -> { + val kc = zy*zy + zz*zz + if (kc == 0f) return EulerAngles(EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f) + + return EulerAngles(EulerOrder.XYZ, + atan2( -zy, zz), + atan2( zx, sqrt(kc)), + atan2(xy*zz - xz*zy, yy*zz - yz*zy)) + } + EulerOrder.YZX -> { + val kc = xx*xx + xz*xz + if (kc == 0f) return EulerAngles(EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy)) + + return EulerAngles(EulerOrder.YZX, + atan2(xx*yz - xz*yx, xx*zz - xz*zx), + atan2( -xz, xx), + atan2( xy, sqrt(kc))) + } + EulerOrder.ZXY -> { + val kc = yy*yy + yx*yx + if (kc == 0f) return EulerAngles(EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx)) + + return EulerAngles(EulerOrder.ZXY, + atan2( yz, sqrt(kc)), + atan2(yy*zx - yx*zy, yy*xx - yx*xy), + atan2( -yx, yy)) + } + EulerOrder.ZYX -> { + val kc = xy*xy + xx*xx + if (kc == 0f) return EulerAngles(EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy)) + + return EulerAngles(EulerOrder.ZYX, + atan2(zx*xy - zy*xx, yy*xx - yx*xy), + atan2( -xz, sqrt(kc)), + atan2( xy, xx)) + } + EulerOrder.YXZ -> { + val kc = zx*zx + zz*zz + if (kc == 0f) return EulerAngles(EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f) + + return EulerAngles(EulerOrder.YXZ, + atan2( -zy, sqrt(kc)), + atan2( zx, zz), + atan2(yz*zx - yx*zz, xx*zz - xz*zx)) + } + EulerOrder.XZY -> { + val kc = yz*yz + yy*yy + if (kc == 0f) return EulerAngles(EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx)) + + return EulerAngles(EulerOrder.XZY, + atan2( yz, yy), + atan2(xy*yz - xz*yy, zz*yy - zy*yz), + atan2( -yx, sqrt(kc))) + } + else -> { + throw Exception("EulerAngles not implemented for given EulerOrder") + } + } + } + + // orthogonalizes the matrix then returns the euler angles + /** + * creates an eulerAngles representing the same rotation as this matrix + * @return the eulerAngles + */ + fun toEulerAngles(order: EulerOrder): EulerAngles = orthonormalize().toEulerAnglesAssumingOrthonormal(order) +} + +operator fun Float.times(that: Matrix3): Matrix3 = that*this + +operator fun Float.div(that: Matrix3): Matrix3 = that.inv()*this diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt new file mode 100644 index 000000000..6f811c547 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -0,0 +1,371 @@ +@file:Suppress("unused") +package io.github.axisangles.ktmath + +import kotlin.math.* + +/** + * A Quaternion class properly implementing Quaternions as a real component and 3 imaginary components + * All operations are well-defined + */ +data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { + companion object { + val ZERO = Quaternion(0f, 0f, 0f, 0f) + val ONE = Quaternion(1f, 0f, 0f, 0f) + val I = Quaternion(0f, 1f, 0f, 0f) + val J = Quaternion(0f, 0f, 1f, 0f) + val K = Quaternion(0f, 0f, 0f, 1f) + + // creates a new quaternion representing the rotation about axis v by rotational angle v + /** + * creates a new quaternion representing the rotation about axis v by rotational angle of v's length + * @return the new quaternion + **/ + fun fromRotationVector(v: Vector3): Quaternion = Quaternion(0f, v/2f).exp() + } + + constructor(w: Float, xyz: Vector3) : this(w, xyz.x, xyz.y, xyz.z) + + /** + * @return the imaginary components as a vector3 + **/ + val xyz get(): Vector3 = Vector3(x, y, z) + + /** + * @return the quaternion with only the w component + **/ + val re get(): Quaternion = Quaternion(w, 0f, 0f, 0f) + + /** + * @return the quaternion with only x y z components + **/ + val im get(): Quaternion = Quaternion(0f, x, y, z) + + operator fun unaryMinus(): Quaternion = Quaternion(-w, -x, -y, -z) + + operator fun plus(that: Quaternion): Quaternion = Quaternion( + this.w + that.w, + this.x + that.x, + this.y + that.y, + this.z + that.z + ) + + operator fun plus(that: Float): Quaternion = Quaternion(this.w + that, this.x, this.y, this.z) + + operator fun minus(that: Quaternion): Quaternion = Quaternion( + this.w - that.w, + this.x - that.x, + this.y - that.y, + this.z - that.z + ) + + operator fun minus(that: Float): Quaternion = Quaternion(this.w - that, this.x, this.y, this.z) + + /** + * computes the dot product of this quaternion with that quaternion + * @param that the quaternion with which to be dotted + * @return the inversed quaternion + **/ + fun dot(that: Quaternion): Float = this.w*that.w + this.x*that.x + this.y*that.y + this.z*that.z + + /** + * computes the square of the length of this quaternion + * @return the length squared + **/ + fun lenSq(): Float = w*w + x*x + y*y + z*z + + /** + * computes the length of this quaternion + * @return the length + **/ + fun len(): Float = sqrt(w*w + x*x + y*y + z*z) + + /** + * @return the normalized quaternion + **/ + fun unit(): Quaternion { + val m = len() + return if (m == 0f) ZERO else this/m + } + + operator fun times(that: Float): Quaternion = Quaternion( + this.w*that, + this.x*that, + this.y*that, + this.z*that + ) + + operator fun times(that: Quaternion): Quaternion = Quaternion( + this.w*that.w - this.x*that.x - this.y*that.y - this.z*that.z, + this.x*that.w + this.w*that.x - this.z*that.y + this.y*that.z, + this.y*that.w + this.z*that.x + this.w*that.y - this.x*that.z, + this.z*that.w - this.y*that.x + this.x*that.y + this.w*that.z + ) + + /** + * computes the inverse of this quaternion + * @return the inversed quaternion + **/ + fun inv(): Quaternion { + val lenSq = lenSq() + return Quaternion( + w/lenSq, + -x/lenSq, + -y/lenSq, + -z/lenSq + ) + } + + operator fun div(that: Float): Quaternion = this*(1f/that) + + /** + * computes right division, this * that^-1 + **/ + operator fun div(that: Quaternion): Quaternion = this*that.inv() + + /** + * @return the conjugate of this quaternion + **/ + fun conj(): Quaternion = Quaternion(w, -x, -y, -z) + + /** + * computes the logarithm of this quaternion + * @return the log of this quaternion + **/ + fun log(): Quaternion { + val co = w + val si = xyz.len() + val len = len() + + if (si == 0f) { + return Quaternion(ln(len), xyz/w) + } + + val ang = atan2(si, co) + return Quaternion(ln(len), ang/si*xyz) + } + + /** + * raises e to the power of this quaternion + * @return the exponentiated quaternion + **/ + fun exp(): Quaternion { + val ang = xyz.len() + val len = exp(w) + + if (ang == 0f) { + return Quaternion(len, len*xyz) + } + + val co = cos(ang) + val si = sin(ang) + return Quaternion(len*co, len*si/ang*xyz) + } + + /** + * raises this quaternion to the power of t + * @param t the power by which to raise this quaternion + * @return the powered quaternion + **/ + fun pow(t: Float): Quaternion = (log()*t).exp() + + // for a slight improvement in performance + // not fully implemented +// fun pow(t: Float): Quaternion { +// val imLen = imLen() +// val ang = atan2(imLen, w) +// +// val len = len().pow(t) +// val co = cos(t*ang) +// val si = sin(t*ang) +// +// return if (imLen == 0f) { +// Quaternion( +// len*co, +// len*t*x, +// len*t*y, +// len*t*z +// ) +// } else { +// Quaternion( +// len*co, +// len*si*x/imLen, +// len*si*y/imLen, +// len*si*z/imLen +// ) +// } +// } + + /** + * between this and -this, picks the one nearest to that + * @param that the quaternion to be nearest + * @return nearest quaternion + **/ + fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) -this else this + + /** + * interpolates from this quaternion to that quaternion by t in quaternion space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun interp(that: Quaternion, t: Float) = + if (t == 0f) { + this + } else if (t == 1f) { + that + } else if (t < 0.5f) { + (that/this).pow(t)*this + } else { + (this/that).pow(1f - t)*that + } + + /** + * interpolates from this quaternion to that quaternion by t in rotation space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun interpR(that: Quaternion, t: Float) = this.interp(that.twinNearest(this), t) + + /** + * linearly interpolates from this quaternion to that quaternion by t in quaternion space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun lerp(that: Quaternion, t: Float): Quaternion = (1f - t)*this + t*that + + /** + * linearly interpolates from this quaternion to that quaternion by t in rotation space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun lerpR(that: Quaternion, t: Float) = this.lerp(that.twinNearest(this), t) + + /** + * computes this quaternion's angle to identity in quaternion space + * @return angle + **/ + fun angle(): Float = atan2(xyz.len(), w) + + /** + * computes this quaternion's angle to identity in rotation space + * @return angle + **/ + fun angleR(): Float = 2f*atan2(xyz.len(), abs(w)) + + /** + * computes the angle between this quaternion and that quaternion in quaternion space + * @param that the other quaternion + * @return angle + **/ + fun angleTo(that: Quaternion): Float = (this/that).angle() + + /** + * computes the angle between this quaternion and that quaternion in rotation space + * @param that the other quaternion + * @return angle + **/ + fun angleToR(that: Quaternion): Float = (this/that).angleR() + + /** + * computes the angle this quaternion rotates about the u axis in quaternion space + * @param u the axis + * @return angle + **/ + fun angleAbout(u: Vector3): Float { + val uDotIm = u.dot(xyz) + val uLen = u.len() + return atan2(uDotIm, uLen*w) + } + + /** + * computes the angle this quaternion rotates about the u axis in rotation space + * @param u the axis + * @return angle + **/ + fun angleAboutR(u: Vector3): Float { + val uDotIm = u.dot(xyz) + val uLen = u.len() + return if (uDotIm < 0f) { + 2f*atan2(-uDotIm, -uLen*w) + } else { + 2f*atan2(uDotIm, uLen*w) + } + } + + /** + * finds Q, the quaternion nearest to this quaternion representing a rotation purely about the global u axis + * Q is NOT unitized + * @param v the global axis + * @return Q + **/ + fun project(v: Vector3) = Quaternion(w, xyz.dot(v)/v.lenSq()*v) + + /** + * finds Q, the quaternion nearest to this quaternion representing a rotation NOT on the global u axis. + * Q is NOT unitized + * @param v the global axis + * @return Q + **/ + fun reject(v: Vector3) = Quaternion(w, v.cross(xyz).cross(v)/v.lenSq()) + + /** + * finds Q, the quaternion nearest to this quaternion whose local u direction aligns with the global v direction. + * Q is NOT unitized + * @param u the local direction + * @param v the global direction + * @return Q + **/ + fun align(u: Vector3, v: Vector3): Quaternion { + val U = Quaternion(0f, u) + val V = Quaternion(0f, v) + + return (V*this/U + (V/U).len()*this)/2f + } + + /** + * applies this quaternion's rotation to that vector + * @param that the vector to be transformed + * @return that vector transformed by this quaternion + **/ + fun sandwich(that: Vector3): Vector3 = (this*Quaternion(0f, that)/this).xyz + + /** + * computes this quaternion's rotation axis + * @return rotation axis + **/ + fun axis(): Vector3 = xyz.unit() + + /** + * computes the rotation vector representing this quaternion's rotation + * @return rotation vector + **/ + fun toRotationVector(): Vector3 = 2f*log().xyz + + /** + * computes the matrix representing this quaternion's rotation + * @return rotation matrix + **/ + fun toMatrix(): Matrix3 { + val d = lenSq() + return Matrix3( + (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d, 2f*(w*y + x*z)/d, + 2f*(x*y + w*z)/d, (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d, + 2f*(x*z - w*y)/d, 2f*(w*x + y*z)/d, (w*w - x*x - y*y + z*z)/d + ) + } + + /** + * computes the euler angles representing this quaternion's rotation + * @param order the order in which to decompose this quaternion into euler angles + * @return euler angles + **/ + fun toEulerAngles(order: EulerOrder): EulerAngles = this.toMatrix().toEulerAnglesAssumingOrthonormal(order) +} + +operator fun Float.plus(that: Quaternion): Quaternion = that + this +operator fun Float.minus(that: Quaternion): Quaternion = -that + this +operator fun Float.times(that: Quaternion): Quaternion = that*this +operator fun Float.div(that: Quaternion): Quaternion = that.inv()*this diff --git a/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt new file mode 100644 index 000000000..37624d190 --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt @@ -0,0 +1,90 @@ +@file:Suppress("unused") +package io.github.axisangles.ktmath + +import kotlin.math.atan2 +import kotlin.math.sqrt + +data class Vector3(val x: Float, val y: Float, val z: Float) { + companion object { + val ZERO = Vector3( 0f, 0f, 0f) + val POS_X = Vector3( 1f, 0f, 0f) + val POS_Y = Vector3( 0f, 1f, 0f) + val POS_Z = Vector3( 0f, 0f, 1f) + val NEG_X = Vector3(-1f, 0f, 0f) + val NEG_Y = Vector3( 0f, -1f, 0f) + val NEG_Z = Vector3( 0f, 0f, -1f) + } + + operator fun unaryMinus() = Vector3(-x, -y, -z) + + operator fun plus(that: Vector3) = Vector3( + this.x + that.x, + this.y + that.y, + this.z + that.z + ) + + operator fun minus(that: Vector3) = Vector3( + this.x - that.x, + this.y - that.y, + this.z - that.z + ) + + /** + * computes the dot product of this vector with that vector + * @param that the vector with which to be dotted + * @return the dot product + **/ + fun dot(that: Vector3) = this.x*that.x + this.y*that.y + this.z*that.z + + /** + * computes the cross product of this vector with that vector + * @param that the vector with which to be crossed + * @return the cross product + **/ + fun cross(that: Vector3) = Vector3( + this.y*that.z - this.z*that.y, + this.z*that.x - this.x*that.z, + this.x*that.y - this.y*that.x + ) + /** + * computes the square of the length of this vector + * @return the length squared + **/ + fun lenSq() = x*x + y*y + z*z + + /** + * computes the length of this quaternion + * @return the length + **/ + fun len() = sqrt(x*x + y*y + z*z) + + /** + * @return the normalized vector + **/ + fun unit(): Vector3 { + val m = len() + return if (m == 0f) ZERO else this/m + } + + operator fun times(that: Float) = Vector3( + this.x*that, + this.y*that, + this.z*that + ) + + // computes division of this vector3 by a float + operator fun div(that: Float) = Vector3( + this.x/that, + this.y/that, + this.z/that + ) + + /** + * computes the angle between this vector with that vector + * @param that the vector to which the angle is computed + * @return the angle + **/ + fun angleTo(that: Vector3): Float = atan2(this.cross(that).len(), this.dot(that)) +} + +operator fun Float.times(that: Vector3): Vector3 = that*this From c5733069c1660127e4d4744cbb8d26b557cf3e6a Mon Sep 17 00:00:00 2001 From: ImUrX Date: Wed, 25 Jan 2023 21:21:29 -0300 Subject: [PATCH 2/9] add tests and spotlessfix --- .editorconfig | 1 + server/build.gradle.kts | 3 +- .../github/axisangles/ktmath/EulerAngles.kt | 183 +++--- .../java/io/github/axisangles/ktmath/Main.kt | 378 ++++++------ .../io/github/axisangles/ktmath/Matrix3.kt | 519 ++++++++-------- .../io/github/axisangles/ktmath/Quaternion.kt | 571 +++++++++--------- .../io/github/axisangles/ktmath/Vector3.kt | 144 ++--- .../axisangles/ktmath/QuaternionTest.kt | 157 +++++ 8 files changed, 1082 insertions(+), 874 deletions(-) create mode 100644 server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt diff --git a/.editorconfig b/.editorconfig index 5e8edbf21..3d0b69f1d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -21,3 +21,4 @@ max_line_length = 88 indent_size = 4 indent_style = tab max_line_length = 88 +ij_kotlin_packages_to_use_import_on_demand = java.util.*,kotlin.math.* diff --git a/server/build.gradle.kts b/server/build.gradle.kts index 0a8b3795c..597412843 100644 --- a/server/build.gradle.kts +++ b/server/build.gradle.kts @@ -139,7 +139,8 @@ configure { "indent_size" to 4, "indent_style" to "tab", // "max_line_length" to 88, - "ktlint_experimental" to "enabled" + "ktlint_experimental" to "enabled", + "ij_kotlin_packages_to_use_import_on_demand" to "java.util.*,kotlin.math.*" ) val ktlintVersion = "0.47.1" kotlinGradle { diff --git a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt index 32a278e5f..e027cf4df 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt @@ -1,10 +1,11 @@ @file:Suppress("unused") + package io.github.axisangles.ktmath import kotlin.math.cos import kotlin.math.sin -enum class EulerOrder {XYZ, YZX, ZXY, ZYX, YXZ, XZY} +enum class EulerOrder { XYZ, YZX, ZXY, ZYX, YXZ, XZY } // prefer Y.toX // but if ambiguous, use X.fromY @@ -12,91 +13,103 @@ enum class EulerOrder {XYZ, YZX, ZXY, ZYX, YXZ, XZY} * Euler Angles contains both the x y z angle parameters and the order of application */ data class EulerAngles(val order: EulerOrder, val x: Float, val y: Float, val z: Float) { - /** - * creates a quaternion which represents the same rotation as this eulerAngles - * @return the quaternion - */ - fun toQuaternion(): Quaternion { - val cX = cos(x/2f) - val cY = cos(y/2f) - val cZ = cos(z/2f) - val sX = sin(x/2f) - val sY = sin(y/2f) - val sZ = sin(z/2f) + /** + * creates a quaternion which represents the same rotation as this eulerAngles + * @return the quaternion + */ + fun toQuaternion(): Quaternion { + val cX = cos(x / 2f) + val cY = cos(y / 2f) + val cZ = cos(z / 2f) + val sX = sin(x / 2f) + val sY = sin(y / 2f) + val sZ = sin(z / 2f) - return when (order) { - EulerOrder.XYZ -> Quaternion( - cX*cY*cZ - sX*sY*sZ, - cY*cZ*sX + cX*sY*sZ, - cX*cZ*sY - cY*sX*sZ, - cZ*sX*sY + cX*cY*sZ) - EulerOrder.YZX -> Quaternion( - cX*cY*cZ - sX*sY*sZ, - cY*cZ*sX + cX*sY*sZ, - cX*cZ*sY + cY*sX*sZ, - cX*cY*sZ - cZ*sX*sY) - EulerOrder.ZXY -> Quaternion( - cX*cY*cZ - sX*sY*sZ, - cY*cZ*sX - cX*sY*sZ, - cX*cZ*sY + cY*sX*sZ, - cZ*sX*sY + cX*cY*sZ) - EulerOrder.ZYX -> Quaternion( - cX*cY*cZ + sX*sY*sZ, - cY*cZ*sX - cX*sY*sZ, - cX*cZ*sY + cY*sX*sZ, - cX*cY*sZ - cZ*sX*sY) - EulerOrder.YXZ -> Quaternion( - cX*cY*cZ + sX*sY*sZ, - cY*cZ*sX + cX*sY*sZ, - cX*cZ*sY - cY*sX*sZ, - cX*cY*sZ - cZ*sX*sY) - EulerOrder.XZY -> Quaternion( - cX*cY*cZ + sX*sY*sZ, - cY*cZ*sX - cX*sY*sZ, - cX*cZ*sY - cY*sX*sZ, - cZ*sX*sY + cX*cY*sZ) - } - } + return when (order) { + EulerOrder.XYZ -> Quaternion( + cX * cY * cZ - sX * sY * sZ, + cY * cZ * sX + cX * sY * sZ, + cX * cZ * sY - cY * sX * sZ, + cZ * sX * sY + cX * cY * sZ + ) + EulerOrder.YZX -> Quaternion( + cX * cY * cZ - sX * sY * sZ, + cY * cZ * sX + cX * sY * sZ, + cX * cZ * sY + cY * sX * sZ, + cX * cY * sZ - cZ * sX * sY + ) + EulerOrder.ZXY -> Quaternion( + cX * cY * cZ - sX * sY * sZ, + cY * cZ * sX - cX * sY * sZ, + cX * cZ * sY + cY * sX * sZ, + cZ * sX * sY + cX * cY * sZ + ) + EulerOrder.ZYX -> Quaternion( + cX * cY * cZ + sX * sY * sZ, + cY * cZ * sX - cX * sY * sZ, + cX * cZ * sY + cY * sX * sZ, + cX * cY * sZ - cZ * sX * sY + ) + EulerOrder.YXZ -> Quaternion( + cX * cY * cZ + sX * sY * sZ, + cY * cZ * sX + cX * sY * sZ, + cX * cZ * sY - cY * sX * sZ, + cX * cY * sZ - cZ * sX * sY + ) + EulerOrder.XZY -> Quaternion( + cX * cY * cZ + sX * sY * sZ, + cY * cZ * sX - cX * sY * sZ, + cX * cZ * sY - cY * sX * sZ, + cZ * sX * sY + cX * cY * sZ + ) + } + } - // temp, replace with direct conversion later - //fun toMatrix(): Matrix3 = this.toQuaternion().toMatrix() - /** - * creates a matrix which represents the same rotation as this eulerAngles - * @return the matrix - */ - fun toMatrix(): Matrix3 { - val cX = cos(x) - val cY = cos(y) - val cZ = cos(z) - val sX = sin(x) - val sY = sin(y) - val sZ = sin(z) + // temp, replace with direct conversion later + // fun toMatrix(): Matrix3 = this.toQuaternion().toMatrix() + /** + * creates a matrix which represents the same rotation as this eulerAngles + * @return the matrix + */ + fun toMatrix(): Matrix3 { + val cX = cos(x) + val cY = cos(y) + val cZ = cos(z) + val sX = sin(x) + val sY = sin(y) + val sZ = sin(z) - return when (order) { - EulerOrder.XYZ -> Matrix3( - cY*cZ, -cY*sZ, sY, - cZ*sX*sY + cX*sZ, cX*cZ - sX*sY*sZ, -cY*sX, - sX*sZ - cX*cZ*sY, cZ*sX + cX*sY*sZ, cX*cY) - EulerOrder.YZX -> Matrix3( - cY*cZ, sX*sY - cX*cY*sZ, cX*sY + cY*sX*sZ, - sZ, cX*cZ, -cZ*sX, - -cZ*sY, cY*sX + cX*sY*sZ, cX*cY - sX*sY*sZ) - EulerOrder.ZXY -> Matrix3( - cY*cZ - sX*sY*sZ, -cX*sZ, cZ*sY + cY*sX*sZ, - cZ*sX*sY + cY*sZ, cX*cZ, sY*sZ - cY*cZ*sX, - -cX*sY, sX, cX*cY) - EulerOrder.ZYX -> Matrix3( - cY*cZ, cZ*sX*sY - cX*sZ, cX*cZ*sY + sX*sZ, - cY*sZ, cX*cZ + sX*sY*sZ, cX*sY*sZ - cZ*sX, - -sY, cY*sX, cX*cY) - EulerOrder.YXZ -> Matrix3( - cY*cZ + sX*sY*sZ, cZ*sX*sY - cY*sZ, cX*sY, - cX*sZ, cX*cZ, -sX, - cY*sX*sZ - cZ*sY, cY*cZ*sX + sY*sZ, cX*cY) - EulerOrder.XZY -> Matrix3( - cY*cZ, -sZ, cZ*sY, - sX*sY + cX*cY*sZ, cX*cZ, cX*sY*sZ - cY*sX, - cY*sX*sZ - cX*sY, cZ*sX, cX*cY + sX*sY*sZ) - } - } + return when (order) { + EulerOrder.XYZ -> Matrix3( + cY * cZ, -cY * sZ, sY, + cZ * sX * sY + cX * sZ, cX * cZ - sX * sY * sZ, -cY * sX, + sX * sZ - cX * cZ * sY, cZ * sX + cX * sY * sZ, cX * cY + ) + EulerOrder.YZX -> Matrix3( + cY * cZ, sX * sY - cX * cY * sZ, cX * sY + cY * sX * sZ, + sZ, cX * cZ, -cZ * sX, + -cZ * sY, cY * sX + cX * sY * sZ, cX * cY - sX * sY * sZ + ) + EulerOrder.ZXY -> Matrix3( + cY * cZ - sX * sY * sZ, -cX * sZ, cZ * sY + cY * sX * sZ, + cZ * sX * sY + cY * sZ, cX * cZ, sY * sZ - cY * cZ * sX, + -cX * sY, sX, cX * cY + ) + EulerOrder.ZYX -> Matrix3( + cY * cZ, cZ * sX * sY - cX * sZ, cX * cZ * sY + sX * sZ, + cY * sZ, cX * cZ + sX * sY * sZ, cX * sY * sZ - cZ * sX, + -sY, cY * sX, cX * cY + ) + EulerOrder.YXZ -> Matrix3( + cY * cZ + sX * sY * sZ, cZ * sX * sY - cY * sZ, cX * sY, + cX * sZ, cX * cZ, -sX, + cY * sX * sZ - cZ * sY, cY * cZ * sX + sY * sZ, cX * cY + ) + EulerOrder.XZY -> Matrix3( + cY * cZ, -sZ, cZ * sY, + sX * sY + cX * cY * sZ, cX * cZ, cX * sY * sZ - cY * sX, + cY * sX * sZ - cX * sY, cZ * sX, cX * cY + sX * sY * sZ + ) + } + } } diff --git a/server/src/main/java/io/github/axisangles/ktmath/Main.kt b/server/src/main/java/io/github/axisangles/ktmath/Main.kt index 62297fd32..a64ae0fbf 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Main.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Main.kt @@ -1,297 +1,302 @@ package io.github.axisangles.ktmath import kotlin.math.* -import kotlin.system.measureTimeMillis var randSeed = 0 fun randInt(): Int { - randSeed = (1103515245*randSeed + 12345).mod(2147483648).toInt() - return randSeed + randSeed = (1103515245 * randSeed + 12345).mod(2147483648).toInt() + return randSeed } fun randFloat(): Float { - return randInt().toFloat()/2147483648f + return randInt().toFloat() / 2147483648f } fun randGaussian(): Float { - var thing = 1f - randFloat() - while (thing == 0f) { - // no 0s allowed - thing = 1f - randFloat() - } - return sqrt(-2f*ln(thing))*cos(PI.toFloat()*randFloat()) + var thing = 1f - randFloat() + while (thing == 0f) { + // no 0s allowed + thing = 1f - randFloat() + } + return sqrt(-2f * ln(thing)) * cos(PI.toFloat() * randFloat()) } fun randMatrix(): Matrix3 { - return Matrix3( - randGaussian(), randGaussian(), randGaussian(), - randGaussian(), randGaussian(), randGaussian(), - randGaussian(), randGaussian(), randGaussian() - ) + return Matrix3( + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian() + ) } fun randQuaternion(): Quaternion { - return Quaternion(randGaussian(), randGaussian(), randGaussian(), randGaussian()) + return Quaternion(randGaussian(), randGaussian(), randGaussian(), randGaussian()) } fun randRotMatrix(): Matrix3 { - return randQuaternion().toMatrix() + return randQuaternion().toMatrix() } fun randVector(): Vector3 { - return Vector3(randGaussian(), randGaussian(), randGaussian()) + return Vector3(randGaussian(), randGaussian(), randGaussian()) } fun testEulerMatrix(order: EulerOrder, M: Matrix3, exception: String) { - // We convert to euler angles and back and see if they are reasonably similar - val N = M.toEulerAngles(order).toMatrix() - if ((N - M).norm() > 1e-6) { - println("norm error: " + (N - M).norm().toString()) - throw Exception(exception) - } + // We convert to euler angles and back and see if they are reasonably similar + val N = M.toEulerAngles(order).toMatrix() + if ((N - M).norm() > 1e-6) { + println("norm error: " + (N - M).norm().toString()) + throw Exception(exception) + } } fun testEulerConversion(order: EulerOrder, exception: String) { - for (i in 1..1000) { - testEulerMatrix(order, randRotMatrix(), exception) - } + for (i in 1..1000) { + testEulerMatrix(order, randRotMatrix(), exception) + } } fun testMatrixOrthonormalize() { - for (i in 1..1000) { - val M = randMatrix() + for (i in 1..1000) { + val M = randMatrix() - val N = M.invTranspose().orthonormalize() - val O = M.orthonormalize() - if ((N - O).norm() > 1e-5) { - println("norm error: " + (N - O).norm().toString()) - throw Exception("Matrix orthonormalization accuracy test failed") - } - } + val N = M.invTranspose().orthonormalize() + val O = M.orthonormalize() + if ((N - O).norm() > 1e-5) { + println("norm error: " + (N - O).norm().toString()) + throw Exception("Matrix orthonormalization accuracy test failed") + } + } } fun testQuatMatrixConversion() { - for (i in 1..1000) { - val M = randRotMatrix() - val N = (randGaussian()*M.toQuaternion()).toMatrix() - if ((N - M).norm() > 1e-6) { - println("norm error: " + (N - M).norm().toString()) - throw Exception("Quaternion Matrix conversion accuracy test failed") - } - } + for (i in 1..1000) { + val M = randRotMatrix() + val N = (randGaussian() * M.toQuaternion()).toMatrix() + if ((N - M).norm() > 1e-6) { + println("norm error: " + (N - M).norm().toString()) + throw Exception("Quaternion Matrix conversion accuracy test failed") + } + } } fun relError(a: Matrix3, b: Matrix3): Float { - val combinedLen = sqrt((a.normSq() + b.normSq())/2f) - if (combinedLen == 0f) return 0f + val combinedLen = sqrt((a.normSq() + b.normSq()) / 2f) + if (combinedLen == 0f) return 0f - return (b - a).norm()/combinedLen + return (b - a).norm() / combinedLen } fun relError(a: Vector3, b: Vector3): Float { - val combinedLen = sqrt((a.lenSq() + b.lenSq())/2f) - if (combinedLen == 0f) return 0f + val combinedLen = sqrt((a.lenSq() + b.lenSq()) / 2f) + if (combinedLen == 0f) return 0f - return (b - a).len()/combinedLen + return (b - a).len() / combinedLen } fun relError(a: Quaternion, b: Quaternion): Float { - val combinedLen = sqrt((a.lenSq() + b.lenSq())/2f) - if (combinedLen == 0f) return 0f + val combinedLen = sqrt((a.lenSq() + b.lenSq()) / 2f) + if (combinedLen == 0f) return 0f - return (b - a).len()/combinedLen + return (b - a).len() / combinedLen } fun checkError(eta: Float, a: Matrix3, b: Matrix3): Boolean { - return (b - a).normSq() <= eta*eta*(a.normSq() + b.normSq()) + return (b - a).normSq() <= eta * eta * (a.normSq() + b.normSq()) } fun checkError(eta: Float, a: Quaternion, b: Quaternion): Boolean { - return (b - a).lenSq() <= eta*eta*(a.lenSq() + b.lenSq()) + return (b - a).lenSq() <= eta * eta * (a.lenSq() + b.lenSq()) } fun checkError(eta: Float, a: Vector3, b: Vector3): Boolean { - return (b - a).lenSq() <= eta*eta*(a.lenSq() + b.lenSq()) + return (b - a).lenSq() <= eta * eta * (a.lenSq() + b.lenSq()) } fun checkError(eta: Float, A: Quaternion): Boolean { - return A.lenSq() <= eta*eta + return A.lenSq() <= eta * eta } fun testQuaternionInv() { - for (i in 1..1000) { - val Q = randQuaternion() + for (i in 1..1000) { + val Q = randQuaternion() - if (relError(Q*Q.inv(), Quaternion.ONE) > 1e-6f) - throw Exception("Quaternion inv accuracy test failed") - } + if (relError(Q * Q.inv(), Quaternion.ONE) > 1e-6f) { + throw Exception("Quaternion inv accuracy test failed") + } + } } fun testQuaternionDiv() { - for (i in 1..1000) { - val Q = randQuaternion() + for (i in 1..1000) { + val Q = randQuaternion() - if (!checkError(1e-6f, Q/Q, Quaternion.ONE)) - throw Exception("Quaternion div accuracy test failed") - if (!checkError(1e-6f, 2f/Q, 2f*Q.inv())) - throw Exception("Float/Quaternion accuracy test failed") - if (!checkError(1e-6f, Q/2f, 0.5f*Q)) - throw Exception("Quaternion/Float accuracy test failed") - } + if (!checkError(1e-6f, Q/Q, Quaternion.ONE)) { + throw Exception("Quaternion div accuracy test failed") + } + if (!checkError(1e-6f, 2f/Q, 2f*Q.inv())) { + throw Exception("Float/Quaternion accuracy test failed") + } + if (!checkError(1e-6f, Q/2f, 0.5f*Q)) { + throw Exception("Quaternion/Float accuracy test failed") + } + } } // 19 binary digits of accuracy fun testQuaternionPow() { - for (i in 1..1000) { - val Q = randQuaternion() + for (i in 1..1000) { + val Q = randQuaternion() - if (!checkError(2e-6f, Q.pow(-1f), Q.inv())) - throw Exception("Quaternion pow -1 accuracy test failed") - if (!checkError(2e-6f, Q.pow(0f), Quaternion.ONE)) - throw Exception("Quaternion pow 0 accuracy test failed") - if (!checkError(2e-6f, Q.pow(1f), Q)) - throw Exception("Quaternion pow 1 accuracy test failed") - if (!checkError(2e-6f, Q.pow(2f), Q*Q)) - throw Exception("Quaternion pow 2 accuracy test failed") - } + if (!checkError(2e-6f, Q.pow(-1f), Q.inv())) { + throw Exception("Quaternion pow -1 accuracy test failed") + } + if (!checkError(2e-6f, Q.pow(0f), Quaternion.ONE)) { + throw Exception("Quaternion pow 0 accuracy test failed") + } + if (!checkError(2e-6f, Q.pow(1f), Q)) { + throw Exception("Quaternion pow 1 accuracy test failed") + } + if (!checkError(2e-6f, Q.pow(2f), Q*Q)) { + throw Exception("Quaternion pow 2 accuracy test failed") + } + } } fun testQuaternionSandwich() { - for (i in 1..1000) { - val Q = randQuaternion() - val v = randVector() + for (i in 1..1000) { + val Q = randQuaternion() + val v = randVector() - if (!checkError(5e-7f, Q.toMatrix()*v, Q.sandwich(v))) - throw Exception("Quaternion sandwich accuracy test failed") - } + if (!checkError(5e-7f, Q.toMatrix()*v, Q.sandwich(v))) { + throw Exception("Quaternion sandwich accuracy test failed") + } + } } // projection and alignment are expected to be less accurate in some extreme cases // so we expect to see some cases in which half the bits are lost fun testQuaternionProjectAlign() { - for (i in 1..1000) { - val Q = randQuaternion() - val v = randVector() + for (i in 1..1000) { + val Q = randQuaternion() + val v = randVector() - if (!checkError(1e-4f, Q.align(v, v), Q.project(v))) { - println(Q.align(v, v) - Q.project(v)) - println(Q.align(v, v)) - println(Q.project(v)) - println(Q) - throw Exception("Quaternion project/align accuracy test failed") - } - } + if (!checkError(1e-4f, Q.align(v, v), Q.project(v))) { + println(Q.align(v, v) - Q.project(v)) + println(Q.align(v, v)) + println(Q.project(v)) + println(Q) + throw Exception("Quaternion project/align accuracy test failed") + } + } } fun testQuaternionRotationVector() { - for (i in 1..1000) { - val Q = randQuaternion().unit() - val P = Quaternion.fromRotationVector(Q.toRotationVector()) + for (i in 1..1000) { + val Q = randQuaternion().unit() + val P = Quaternion.fromRotationVector(Q.toRotationVector()) - if (!checkError(5e-7f, Q, P)) { - throw Exception("Quaternion toRotationVector fromRotationVector accuracy test failed") - } - } + if (!checkError(5e-7f, Q, P)) { + throw Exception("Quaternion toRotationVector fromRotationVector accuracy test failed") + } + } } fun testQuaternionEulerAngles(order: EulerOrder, exception: String) { - for (i in 1..1000) { - val Q = randQuaternion().unit() - val P = Q.toEulerAngles(order).toQuaternion().twinNearest(Q) + for (i in 1..1000) { + val Q = randQuaternion().unit() + val P = Q.toEulerAngles(order).toQuaternion().twinNearest(Q) - if (!checkError(2e-7f, Q, P)) { - println(relError(Q, P)) - throw Exception(exception) - } - } + if (!checkError(2e-7f, Q, P)) { + println(relError(Q, P)) + throw Exception(exception) + } + } } fun testEulerSingularity(order: EulerOrder, M: Matrix3, exception: String) { - for (i in 1..1000) { - val R = 1e-6f*randMatrix() - val S = M + R - if (S.det() <= 0f) return + for (i in 1..1000) { + val R = 1e-6f * randMatrix() + val S = M + R + if (S.det() <= 0f) return - val error = (S.toEulerAnglesAssumingOrthonormal(order).toMatrix() - S).norm() - if (error > 2f*R.norm() + 1e-6f) { - throw Exception(exception) - } - } + val error = (S.toEulerAnglesAssumingOrthonormal(order).toMatrix() - S).norm() + if (error > 2f * R.norm() + 1e-6f) { + throw Exception(exception) + } + } } fun testEulerConversions(order: EulerOrder, exception: String) { - for (i in 1..1000) { - val e = EulerAngles(order, 6.28318f*randFloat(), 6.28318f*randFloat(), 6.28318f*randFloat()) - val N = e.toMatrix() - val M = e.toQuaternion().toMatrix() - if ((N - M).norm() > 1e-6) { - throw Exception(exception) - } - } + for (i in 1..1000) { + val e = EulerAngles(order, 6.28318f * randFloat(), 6.28318f * randFloat(), 6.28318f * randFloat()) + val N = e.toMatrix() + val M = e.toQuaternion().toMatrix() + if ((N - M).norm() > 1e-6) { + throw Exception(exception) + } + } } - fun main() { - val X90 = Matrix3( - 1f, 0f, 0f, - 0f, 0f, -1f, - 0f, 1f, 0f - ) - val Y90 = Matrix3( - 0f, 0f, 1f, - 0f, 1f, 0f, - -1f, 0f, 0f - ) - val Z90 = Matrix3( - 0f, -1f, 0f, - 1f, 0f, 0f, - 0f, 0f, 1f - ) + val X90 = Matrix3( + 1f, 0f, 0f, + 0f, 0f, -1f, + 0f, 1f, 0f + ) + val Y90 = Matrix3( + 0f, 0f, 1f, + 0f, 1f, 0f, + -1f, 0f, 0f + ) + val Z90 = Matrix3( + 0f, -1f, 0f, + 1f, 0f, 0f, + 0f, 0f, 1f + ) - testMatrixOrthonormalize() - testQuatMatrixConversion() - testQuaternionEulerAngles(EulerOrder.XYZ, "Quaternion EulerAnglesXYZ accuracy test failed") - testQuaternionEulerAngles(EulerOrder.YZX, "Quaternion EulerAnglesYZX accuracy test failed") - testQuaternionEulerAngles(EulerOrder.ZXY, "Quaternion EulerAnglesZXY accuracy test failed") - testQuaternionEulerAngles(EulerOrder.ZYX, "Quaternion EulerAnglesZYX accuracy test failed") - testQuaternionEulerAngles(EulerOrder.YXZ, "Quaternion EulerAnglesYXZ accuracy test failed") - testQuaternionEulerAngles(EulerOrder.XZY, "Quaternion EulerAnglesXZY accuracy test failed") + testMatrixOrthonormalize() + testQuatMatrixConversion() + testQuaternionEulerAngles(EulerOrder.XYZ, "Quaternion EulerAnglesXYZ accuracy test failed") + testQuaternionEulerAngles(EulerOrder.YZX, "Quaternion EulerAnglesYZX accuracy test failed") + testQuaternionEulerAngles(EulerOrder.ZXY, "Quaternion EulerAnglesZXY accuracy test failed") + testQuaternionEulerAngles(EulerOrder.ZYX, "Quaternion EulerAnglesZYX accuracy test failed") + testQuaternionEulerAngles(EulerOrder.YXZ, "Quaternion EulerAnglesYXZ accuracy test failed") + testQuaternionEulerAngles(EulerOrder.XZY, "Quaternion EulerAnglesXZY accuracy test failed") - testQuaternionInv() - testQuaternionDiv() - testQuaternionPow() - testQuaternionSandwich() - testQuaternionProjectAlign() - testQuaternionRotationVector() + testQuaternionInv() + testQuaternionDiv() + testQuaternionPow() + testQuaternionSandwich() + testQuaternionProjectAlign() + testQuaternionRotationVector() - println(Matrix3.IDENTITY.average(Y90)) + println(Matrix3.IDENTITY.average(Y90)) - testEulerConversions(EulerOrder.XYZ, "fromEulerAnglesXYZ Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.YZX, "fromEulerAnglesYZX Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.ZXY, "fromEulerAnglesZXY Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.ZYX, "fromEulerAnglesZYX Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.YXZ, "fromEulerAnglesYXZ Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.XZY, "fromEulerAnglesXZY Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.XYZ, "fromEulerAnglesXYZ Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.YZX, "fromEulerAnglesYZX Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.ZXY, "fromEulerAnglesZXY Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.ZYX, "fromEulerAnglesZYX Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.YXZ, "fromEulerAnglesYXZ Quaternion or Matrix3 accuracy test failed") + testEulerConversions(EulerOrder.XZY, "fromEulerAnglesXZY Quaternion or Matrix3 accuracy test failed") - // EULER ANGLE TESTS - testEulerConversion(EulerOrder.XYZ, "toEulerAnglesXYZ accuracy test failed") - testEulerConversion(EulerOrder.YZX, "toEulerAnglesYZX accuracy test failed") - testEulerConversion(EulerOrder.ZXY, "toEulerAnglesZXY accuracy test failed") - testEulerConversion(EulerOrder.ZYX, "toEulerAnglesZYX accuracy test failed") - testEulerConversion(EulerOrder.YXZ, "toEulerAnglesYXZ accuracy test failed") - testEulerConversion(EulerOrder.XZY, "toEulerAnglesXZY accuracy test failed") + // EULER ANGLE TESTS + testEulerConversion(EulerOrder.XYZ, "toEulerAnglesXYZ accuracy test failed") + testEulerConversion(EulerOrder.YZX, "toEulerAnglesYZX accuracy test failed") + testEulerConversion(EulerOrder.ZXY, "toEulerAnglesZXY accuracy test failed") + testEulerConversion(EulerOrder.ZYX, "toEulerAnglesZYX accuracy test failed") + testEulerConversion(EulerOrder.YXZ, "toEulerAnglesYXZ accuracy test failed") + testEulerConversion(EulerOrder.XZY, "toEulerAnglesXZY accuracy test failed") - // test robustness to noise - testEulerSingularity(EulerOrder.XYZ, Y90, "toEulerAnglesXYZ singularity accuracy test failed") - testEulerSingularity(EulerOrder.YZX, Z90, "toEulerAnglesYZX singularity accuracy test failed") - testEulerSingularity(EulerOrder.ZXY, X90, "toEulerAnglesZXY singularity accuracy test failed") - testEulerSingularity(EulerOrder.ZYX, Y90, "toEulerAnglesZYX singularity accuracy test failed") - testEulerSingularity(EulerOrder.YXZ, X90, "toEulerAnglesYXZ singularity accuracy test failed") - testEulerSingularity(EulerOrder.XZY, Z90, "toEulerAnglesXZY singularity accuracy test failed") + // test robustness to noise + testEulerSingularity(EulerOrder.XYZ, Y90, "toEulerAnglesXYZ singularity accuracy test failed") + testEulerSingularity(EulerOrder.YZX, Z90, "toEulerAnglesYZX singularity accuracy test failed") + testEulerSingularity(EulerOrder.ZXY, X90, "toEulerAnglesZXY singularity accuracy test failed") + testEulerSingularity(EulerOrder.ZYX, Y90, "toEulerAnglesZYX singularity accuracy test failed") + testEulerSingularity(EulerOrder.YXZ, X90, "toEulerAnglesYXZ singularity accuracy test failed") + testEulerSingularity(EulerOrder.XZY, Z90, "toEulerAnglesXZY singularity accuracy test failed") - - - // speed test a linear (align) method against some standard math functions + // speed test a linear (align) method against some standard math functions // var x = Quaternion(1f, 2f, 3f, 4f) // // var dtAlignTotal: Long = 0 @@ -352,7 +357,6 @@ fun main() { // println(dtAtan2Total) // 610 // println(dtAsinTotal) // 3558 - // var x = Quaternion(2f, 1f, 4f, 3f) // val dtPow = measureTimeMillis { // for (i in 1..10_000_000) { @@ -361,4 +365,4 @@ fun main() { // } // // println(dtPow) -} \ No newline at end of file +} diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index f1700a830..cedf34526 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -1,209 +1,226 @@ @file:Suppress("unused") + package io.github.axisangles.ktmath import kotlin.math.* -data class Matrix3 ( - val xx: Float, val yx: Float, val zx: Float, - val xy: Float, val yy: Float, val zy: Float, - val xz: Float, val yz: Float, val zz: Float +data class Matrix3( + val xx: Float, + val yx: Float, + val zx: Float, + val xy: Float, + val yy: Float, + val zy: Float, + val xz: Float, + val yz: Float, + val zz: Float ) { - companion object { - val ZERO = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) - val IDENTITY = Matrix3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) - } + companion object { + val ZERO = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + val IDENTITY = Matrix3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) + } - /** - * creates a new matrix from x y and z column vectors - */ - constructor(x: Vector3, y: Vector3, z: Vector3) : this( - x.x, y.x, z.x, - x.y, y.y, z.y, - x.z, y.z, z.z) + /** + * creates a new matrix from x y and z column vectors + */ + constructor(x: Vector3, y: Vector3, z: Vector3) : this( + x.x, y.x, z.x, + x.y, y.y, z.y, + x.z, y.z, z.z + ) - // column getters - val x get() = Vector3(xx, xy, xz) - val y get() = Vector3(yx, yy, yz) - val z get() = Vector3(zx, zy, zz) + // column getters + val x get() = Vector3(xx, xy, xz) + val y get() = Vector3(yx, yy, yz) + val z get() = Vector3(zx, zy, zz) - // row getters - val xRow get() = Vector3(xx, yx, zx) - val yRow get() = Vector3(xy, yy, zy) - val zRow get() = Vector3(xz, yz, zz) + // row getters + val xRow get() = Vector3(xx, yx, zx) + val yRow get() = Vector3(xy, yy, zy) + val zRow get() = Vector3(xz, yz, zz) - operator fun unaryMinus(): Matrix3 = Matrix3( - -xx, -yx, -zx, - -xy, -yy, -zy, - -xz, -yz, -zz) + operator fun unaryMinus(): Matrix3 = Matrix3( + -xx, -yx, -zx, + -xy, -yy, -zy, + -xz, -yz, -zz + ) - operator fun plus(that: Matrix3): Matrix3 = Matrix3( - this.xx + that.xx, this.yx + that.yx, this.zx + that.zx, - this.xy + that.xy, this.yy + that.yy, this.zy + that.zy, - this.xz + that.xz, this.yz + that.yz, this.zz + that.zz) + operator fun plus(that: Matrix3): Matrix3 = Matrix3( + this.xx + that.xx, this.yx + that.yx, this.zx + that.zx, + this.xy + that.xy, this.yy + that.yy, this.zy + that.zy, + this.xz + that.xz, this.yz + that.yz, this.zz + that.zz + ) - operator fun minus(that: Matrix3): Matrix3 = Matrix3( - this.xx - that.xx, this.yx - that.yx, this.zx - that.zx, - this.xy - that.xy, this.yy - that.yy, this.zy - that.zy, - this.xz - that.xz, this.yz - that.yz, this.zz - that.zz) + operator fun minus(that: Matrix3): Matrix3 = Matrix3( + this.xx - that.xx, this.yx - that.yx, this.zx - that.zx, + this.xy - that.xy, this.yy - that.yy, this.zy - that.zy, + this.xz - that.xz, this.yz - that.yz, this.zz - that.zz + ) - operator fun times(that: Float): Matrix3 = Matrix3( - this.xx*that, this.yx*that, this.zx*that, - this.xy*that, this.yy*that, this.zy*that, - this.xz*that, this.yz*that, this.zz*that) + operator fun times(that: Float): Matrix3 = Matrix3( + this.xx * that, this.yx * that, this.zx * that, + this.xy * that, this.yy * that, this.zy * that, + this.xz * that, this.yz * that, this.zz * that + ) - operator fun times(that: Vector3): Vector3 = Vector3( - this.xx*that.x + this.yx*that.y + this.zx*that.z, - this.xy*that.x + this.yy*that.y + this.zy*that.z, - this.xz*that.x + this.yz*that.y + this.zz*that.z) + operator fun times(that: Vector3): Vector3 = Vector3( + this.xx * that.x + this.yx * that.y + this.zx * that.z, + this.xy * that.x + this.yy * that.y + this.zy * that.z, + this.xz * that.x + this.yz * that.y + this.zz * that.z + ) - operator fun times(that: Matrix3): Matrix3 = Matrix3( - this.xx*that.xx + this.yx*that.xy + this.zx*that.xz, - this.xx*that.yx + this.yx*that.yy + this.zx*that.yz, - this.xx*that.zx + this.yx*that.zy + this.zx*that.zz, - this.xy*that.xx + this.yy*that.xy + this.zy*that.xz, - this.xy*that.yx + this.yy*that.yy + this.zy*that.yz, - this.xy*that.zx + this.yy*that.zy + this.zy*that.zz, - this.xz*that.xx + this.yz*that.xy + this.zz*that.xz, - this.xz*that.yx + this.yz*that.yy + this.zz*that.yz, - this.xz*that.zx + this.yz*that.zy + this.zz*that.zz) + operator fun times(that: Matrix3): Matrix3 = Matrix3( + this.xx * that.xx + this.yx * that.xy + this.zx * that.xz, + this.xx * that.yx + this.yx * that.yy + this.zx * that.yz, + this.xx * that.zx + this.yx * that.zy + this.zx * that.zz, + this.xy * that.xx + this.yy * that.xy + this.zy * that.xz, + this.xy * that.yx + this.yy * that.yy + this.zy * that.yz, + this.xy * that.zx + this.yy * that.zy + this.zy * that.zz, + this.xz * that.xx + this.yz * that.xy + this.zz * that.xz, + this.xz * that.yx + this.yz * that.yy + this.zz * that.yz, + this.xz * that.zx + this.yz * that.zy + this.zz * that.zz + ) - /** - * computes the square of the frobenius norm of this matrix - * @return the frobenius norm squared - */ - fun normSq(): Float = xx*xx + yx*yx + zx*zx + xy*xy + yy*yy + zy*zy + xz*xz + yz*yz + zz*zz + /** + * computes the square of the frobenius norm of this matrix + * @return the frobenius norm squared + */ + fun normSq(): Float = xx * xx + yx * yx + zx * zx + xy * xy + yy * yy + zy * zy + xz * xz + yz * yz + zz * zz - /** - * computes the frobenius norm of this matrix - * @return the frobenius norm - */ - fun norm(): Float = sqrt(normSq()) + /** + * computes the frobenius norm of this matrix + * @return the frobenius norm + */ + fun norm(): Float = sqrt(normSq()) - /** - * computes the determinant of this matrix - * @return the determinant - */ - fun det(): Float = (xz*yx - xx*yz)*zy + (xx*yy - xy*yx)*zz + (xy*yz - xz*yy)*zx + /** + * computes the determinant of this matrix + * @return the determinant + */ + fun det(): Float = (xz * yx - xx * yz) * zy + (xx * yy - xy * yx) * zz + (xy * yz - xz * yy) * zx - /** - * computes the trace of this matrix - * @return the trace - */ - fun trace(): Float = xx + yy + zz + /** + * computes the trace of this matrix + * @return the trace + */ + fun trace(): Float = xx + yy + zz - /** - * computes the transpose of this matrix - * @return the transpose matrix - */ - fun transpose(): Matrix3 = Matrix3( - xx, xy, xz, - yx, yy, yz, - zx, zy, zz) + /** + * computes the transpose of this matrix + * @return the transpose matrix + */ + fun transpose(): Matrix3 = Matrix3( + xx, xy, xz, + yx, yy, yz, + zx, zy, zz + ) - /** - * computes the inverse of this matrix - * @return the inverse matrix - */ - fun inv(): Matrix3 { - val det = det() - return Matrix3( - (yy*zz - yz*zy)/det, (yz*zx - yx*zz)/det, (yx*zy - yy*zx)/det, - (xz*zy - xy*zz)/det, (xx*zz - xz*zx)/det, (xy*zx - xx*zy)/det, - (xy*yz - xz*yy)/det, (xz*yx - xx*yz)/det, (xx*yy - xy*yx)/det) - } + /** + * computes the inverse of this matrix + * @return the inverse matrix + */ + fun inv(): Matrix3 { + val det = det() + return Matrix3( + (yy * zz - yz * zy) / det, (yz * zx - yx * zz) / det, (yx * zy - yy * zx) / det, + (xz * zy - xy * zz) / det, (xx * zz - xz * zx) / det, (xy * zx - xx * zy) / det, + (xy * yz - xz * yy) / det, (xz * yx - xx * yz) / det, (xx * yy - xy * yx) / det + ) + } - operator fun div(that: Float): Matrix3 = this*(1f/that) + operator fun div(that: Float): Matrix3 = this * (1f / that) - /** - * computes the right division, this * that^-1 - */ - operator fun div(that: Matrix3): Matrix3 = this*that.inv() + /** + * computes the right division, this * that^-1 + */ + operator fun div(that: Matrix3): Matrix3 = this * that.inv() - /** - * computes the inverse transpose of this matrix - * @return the inverse transpose matrix - */ - fun invTranspose(): Matrix3 { - val det = det() - return Matrix3( - (yy*zz - yz*zy)/det, (xz*zy - xy*zz)/det, (xy*yz - xz*yy)/det, - (yz*zx - yx*zz)/det, (xx*zz - xz*zx)/det, (xz*yx - xx*yz)/det, - (yx*zy - yy*zx)/det, (xy*zx - xx*zy)/det, (xx*yy - xy*yx)/det) - } + /** + * computes the inverse transpose of this matrix + * @return the inverse transpose matrix + */ + fun invTranspose(): Matrix3 { + val det = det() + return Matrix3( + (yy * zz - yz * zy) / det, (xz * zy - xy * zz) / det, (xy * yz - xz * yy) / det, + (yz * zx - yx * zz) / det, (xx * zz - xz * zx) / det, (xz * yx - xx * yz) / det, + (yx * zy - yy * zx) / det, (xy * zx - xx * zy) / det, (xx * yy - xy * yx) / det + ) + } - /** - * computes the nearest orthonormal matrix to this matrix - * @return the rotation matrix - */ - fun orthonormalize(): Matrix3 { - var curMat = this - var curDet = Float.POSITIVE_INFINITY + /** + * computes the nearest orthonormal matrix to this matrix + * @return the rotation matrix + */ + fun orthonormalize(): Matrix3 { + var curMat = this + var curDet = Float.POSITIVE_INFINITY - for (i in 1..100) { - val newMat = (curMat + curMat.invTranspose())/2f - val newDet = abs(newMat.det()) - // should almost always exit immediately - if (newDet >= curDet) return curMat - if (newDet <= 1.0000001f) return newMat - curMat = newMat - curDet = newDet - } + for (i in 1..100) { + val newMat = (curMat + curMat.invTranspose()) / 2f + val newDet = abs(newMat.det()) + // should almost always exit immediately + if (newDet >= curDet) return curMat + if (newDet <= 1.0000001f) return newMat + curMat = newMat + curDet = newDet + } - return curMat - } + return curMat + } - /** - * finds the rotation matrix closest to all given rotation matrices. - * multiply input matrices by a weight for weighted averaging. - * WARNING: NOT ANGULAR - * @param others a variable number of additional matrices to average - * @return the average rotation matrix - */ - fun average(vararg others: Matrix3): Matrix3 { - var count = 1f - var sum = this - others.forEach { - count += 1f - sum += it - } - return (sum/count).orthonormalize() - } + /** + * finds the rotation matrix closest to all given rotation matrices. + * multiply input matrices by a weight for weighted averaging. + * WARNING: NOT ANGULAR + * @param others a variable number of additional matrices to average + * @return the average rotation matrix + */ + fun average(vararg others: Matrix3): Matrix3 { + var count = 1f + var sum = this + others.forEach { + count += 1f + sum += it + } + return (sum / count).orthonormalize() + } - /** - * linearly interpolates this matrix to that matrix by t - * @param that the matrix towards which to interpolate - * @param t the amount by which to interpolate - * @return the interpolated matrix - */ - fun lerp(that: Matrix3, t: Float): Matrix3 = (1f - t)*this + t*that + /** + * linearly interpolates this matrix to that matrix by t + * @param that the matrix towards which to interpolate + * @param t the amount by which to interpolate + * @return the interpolated matrix + */ + fun lerp(that: Matrix3, t: Float): Matrix3 = (1f - t) * this + t * that - // assumes this matrix is orthonormal and converts this to a quaternion - /** - * creates a quaternion representing the same rotation as this matrix, assuming the matrix is a rotation matrix - * @return the quaternion - */ - fun toQuaternionAssumingOrthonormal(): Quaternion { - if (this.det() <= 0f) - throw Exception("Attempt to convert negative determinant matrix to quaternion") + // assumes this matrix is orthonormal and converts this to a quaternion + /** + * creates a quaternion representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * @return the quaternion + */ + fun toQuaternionAssumingOrthonormal(): Quaternion { + if (this.det() <= 0f) { + throw Exception("Attempt to convert negative determinant matrix to quaternion") + } - return if (yy > -zz && zz > -xx && xx > -yy) { - Quaternion(1 + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() - } else if (xx > yy && xx > zz) { - Quaternion(yz - zy, 1 + xx - yy - zz, xy + yx, xz + zx).unit() - } else if (yy > zz) { - Quaternion(zx - xz, xy + yx, 1 - xx + yy - zz, yz + zy).unit() - } else { - Quaternion(xy - yx, xz + zx, yz + zy, 1 - xx - yy + zz).unit() - } - } - - // orthogonalizes the matrix then returns the quaternion - /** - * creates a quaternion representing the same rotation as this matrix - * @return the quaternion - */ - fun toQuaternion(): Quaternion = orthonormalize().toQuaternionAssumingOrthonormal() + return if (yy > -zz && zz > -xx && xx > -yy) { + Quaternion(1 + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() + } else if (xx > yy && xx > zz) { + Quaternion(yz - zy, 1 + xx - yy - zz, xy + yx, xz + zx).unit() + } else if (yy > zz) { + Quaternion(zx - xz, xy + yx, 1 - xx + yy - zz, yz + zy).unit() + } else { + Quaternion(xy - yx, xz + zx, yz + zy, 1 - xx - yy + zz).unit() + } + } + // orthogonalizes the matrix then returns the quaternion + /** + * creates a quaternion representing the same rotation as this matrix + * @return the quaternion + */ + fun toQuaternion(): Quaternion = orthonormalize().toQuaternionAssumingOrthonormal() /* the standard algorithm: @@ -271,7 +288,6 @@ data class Matrix3 ( built into the prerequisites for this function */ - // fun toEulerAnglesXYZFaulty(): EulerAngles { // return if (abs(zx) < 0.9999999f) // EulerAngles(EulerOrder.XYZ, @@ -285,84 +301,97 @@ data class Matrix3 ( // 0f) // } - /** - * creates an eulerAngles representing the same rotation as this matrix, assuming the matrix is a rotation matrix - * @return the eulerAngles - */ - fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { - if (this.det() <= 0f) - throw Exception("Attempt to convert negative determinant matrix to euler angles") + /** + * creates an eulerAngles representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * @return the eulerAngles + */ + fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { + if (this.det() <= 0f) { + throw Exception("Attempt to convert negative determinant matrix to euler angles") + } - val ETA = 1.57079632f - when (order) { - EulerOrder.XYZ -> { - val kc = zy*zy + zz*zz - if (kc == 0f) return EulerAngles(EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f) + val ETA = 1.57079632f + when (order) { + EulerOrder.XYZ -> { + val kc = zy * zy + zz * zz + if (kc == 0f) return EulerAngles(EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f) - return EulerAngles(EulerOrder.XYZ, - atan2( -zy, zz), - atan2( zx, sqrt(kc)), - atan2(xy*zz - xz*zy, yy*zz - yz*zy)) - } - EulerOrder.YZX -> { - val kc = xx*xx + xz*xz - if (kc == 0f) return EulerAngles(EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy)) + return EulerAngles( + EulerOrder.XYZ, + atan2(-zy, zz), + atan2(zx, sqrt(kc)), + atan2(xy * zz - xz * zy, yy * zz - yz * zy) + ) + } + EulerOrder.YZX -> { + val kc = xx * xx + xz * xz + if (kc == 0f) return EulerAngles(EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy)) - return EulerAngles(EulerOrder.YZX, - atan2(xx*yz - xz*yx, xx*zz - xz*zx), - atan2( -xz, xx), - atan2( xy, sqrt(kc))) - } - EulerOrder.ZXY -> { - val kc = yy*yy + yx*yx - if (kc == 0f) return EulerAngles(EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx)) + return EulerAngles( + EulerOrder.YZX, + atan2(xx * yz - xz * yx, xx * zz - xz * zx), + atan2(-xz, xx), + atan2(xy, sqrt(kc)) + ) + } + EulerOrder.ZXY -> { + val kc = yy * yy + yx * yx + if (kc == 0f) return EulerAngles(EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx)) - return EulerAngles(EulerOrder.ZXY, - atan2( yz, sqrt(kc)), - atan2(yy*zx - yx*zy, yy*xx - yx*xy), - atan2( -yx, yy)) - } - EulerOrder.ZYX -> { - val kc = xy*xy + xx*xx - if (kc == 0f) return EulerAngles(EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy)) + return EulerAngles( + EulerOrder.ZXY, + atan2(yz, sqrt(kc)), + atan2(yy * zx - yx * zy, yy * xx - yx * xy), + atan2(-yx, yy) + ) + } + EulerOrder.ZYX -> { + val kc = xy * xy + xx * xx + if (kc == 0f) return EulerAngles(EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy)) - return EulerAngles(EulerOrder.ZYX, - atan2(zx*xy - zy*xx, yy*xx - yx*xy), - atan2( -xz, sqrt(kc)), - atan2( xy, xx)) - } - EulerOrder.YXZ -> { - val kc = zx*zx + zz*zz - if (kc == 0f) return EulerAngles(EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f) + return EulerAngles( + EulerOrder.ZYX, + atan2(zx * xy - zy * xx, yy * xx - yx * xy), + atan2(-xz, sqrt(kc)), + atan2(xy, xx) + ) + } + EulerOrder.YXZ -> { + val kc = zx * zx + zz * zz + if (kc == 0f) return EulerAngles(EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f) - return EulerAngles(EulerOrder.YXZ, - atan2( -zy, sqrt(kc)), - atan2( zx, zz), - atan2(yz*zx - yx*zz, xx*zz - xz*zx)) - } - EulerOrder.XZY -> { - val kc = yz*yz + yy*yy - if (kc == 0f) return EulerAngles(EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx)) + return EulerAngles( + EulerOrder.YXZ, + atan2(-zy, sqrt(kc)), + atan2(zx, zz), + atan2(yz * zx - yx * zz, xx * zz - xz * zx) + ) + } + EulerOrder.XZY -> { + val kc = yz * yz + yy * yy + if (kc == 0f) return EulerAngles(EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx)) - return EulerAngles(EulerOrder.XZY, - atan2( yz, yy), - atan2(xy*yz - xz*yy, zz*yy - zy*yz), - atan2( -yx, sqrt(kc))) - } - else -> { - throw Exception("EulerAngles not implemented for given EulerOrder") - } - } - } + return EulerAngles( + EulerOrder.XZY, + atan2(yz, yy), + atan2(xy * yz - xz * yy, zz * yy - zy * yz), + atan2(-yx, sqrt(kc)) + ) + } + else -> { + throw Exception("EulerAngles not implemented for given EulerOrder") + } + } + } - // orthogonalizes the matrix then returns the euler angles - /** - * creates an eulerAngles representing the same rotation as this matrix - * @return the eulerAngles - */ - fun toEulerAngles(order: EulerOrder): EulerAngles = orthonormalize().toEulerAnglesAssumingOrthonormal(order) + // orthogonalizes the matrix then returns the euler angles + /** + * creates an eulerAngles representing the same rotation as this matrix + * @return the eulerAngles + */ + fun toEulerAngles(order: EulerOrder): EulerAngles = orthonormalize().toEulerAnglesAssumingOrthonormal(order) } -operator fun Float.times(that: Matrix3): Matrix3 = that*this +operator fun Float.times(that: Matrix3): Matrix3 = that * this -operator fun Float.div(that: Matrix3): Matrix3 = that.inv()*this +operator fun Float.div(that: Matrix3): Matrix3 = that.inv() * this diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index 6f811c547..856742c82 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -1,4 +1,5 @@ @file:Suppress("unused") + package io.github.axisangles.ktmath import kotlin.math.* @@ -8,168 +9,168 @@ import kotlin.math.* * All operations are well-defined */ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { - companion object { - val ZERO = Quaternion(0f, 0f, 0f, 0f) - val ONE = Quaternion(1f, 0f, 0f, 0f) - val I = Quaternion(0f, 1f, 0f, 0f) - val J = Quaternion(0f, 0f, 1f, 0f) - val K = Quaternion(0f, 0f, 0f, 1f) + companion object { + val ZERO = Quaternion(0f, 0f, 0f, 0f) + val ONE = Quaternion(1f, 0f, 0f, 0f) + val I = Quaternion(0f, 1f, 0f, 0f) + val J = Quaternion(0f, 0f, 1f, 0f) + val K = Quaternion(0f, 0f, 0f, 1f) - // creates a new quaternion representing the rotation about axis v by rotational angle v - /** - * creates a new quaternion representing the rotation about axis v by rotational angle of v's length - * @return the new quaternion - **/ - fun fromRotationVector(v: Vector3): Quaternion = Quaternion(0f, v/2f).exp() - } + // creates a new quaternion representing the rotation about axis v by rotational angle v + /** + * creates a new quaternion representing the rotation about axis v by rotational angle of v's length + * @return the new quaternion + **/ + fun fromRotationVector(v: Vector3): Quaternion = Quaternion(0f, v / 2f).exp() + } - constructor(w: Float, xyz: Vector3) : this(w, xyz.x, xyz.y, xyz.z) + constructor(w: Float, xyz: Vector3) : this(w, xyz.x, xyz.y, xyz.z) - /** - * @return the imaginary components as a vector3 - **/ - val xyz get(): Vector3 = Vector3(x, y, z) + /** + * @return the imaginary components as a vector3 + **/ + val xyz get(): Vector3 = Vector3(x, y, z) - /** - * @return the quaternion with only the w component - **/ - val re get(): Quaternion = Quaternion(w, 0f, 0f, 0f) + /** + * @return the quaternion with only the w component + **/ + val re get(): Quaternion = Quaternion(w, 0f, 0f, 0f) - /** - * @return the quaternion with only x y z components - **/ - val im get(): Quaternion = Quaternion(0f, x, y, z) + /** + * @return the quaternion with only x y z components + **/ + val im get(): Quaternion = Quaternion(0f, x, y, z) - operator fun unaryMinus(): Quaternion = Quaternion(-w, -x, -y, -z) + operator fun unaryMinus(): Quaternion = Quaternion(-w, -x, -y, -z) - operator fun plus(that: Quaternion): Quaternion = Quaternion( - this.w + that.w, - this.x + that.x, - this.y + that.y, - this.z + that.z - ) + operator fun plus(that: Quaternion): Quaternion = Quaternion( + this.w + that.w, + this.x + that.x, + this.y + that.y, + this.z + that.z + ) - operator fun plus(that: Float): Quaternion = Quaternion(this.w + that, this.x, this.y, this.z) + operator fun plus(that: Float): Quaternion = Quaternion(this.w + that, this.x, this.y, this.z) - operator fun minus(that: Quaternion): Quaternion = Quaternion( - this.w - that.w, - this.x - that.x, - this.y - that.y, - this.z - that.z - ) + operator fun minus(that: Quaternion): Quaternion = Quaternion( + this.w - that.w, + this.x - that.x, + this.y - that.y, + this.z - that.z + ) - operator fun minus(that: Float): Quaternion = Quaternion(this.w - that, this.x, this.y, this.z) + operator fun minus(that: Float): Quaternion = Quaternion(this.w - that, this.x, this.y, this.z) - /** - * computes the dot product of this quaternion with that quaternion - * @param that the quaternion with which to be dotted - * @return the inversed quaternion - **/ - fun dot(that: Quaternion): Float = this.w*that.w + this.x*that.x + this.y*that.y + this.z*that.z + /** + * computes the dot product of this quaternion with that quaternion + * @param that the quaternion with which to be dotted + * @return the inversed quaternion + **/ + fun dot(that: Quaternion): Float = this.w * that.w + this.x * that.x + this.y * that.y + this.z * that.z - /** - * computes the square of the length of this quaternion - * @return the length squared - **/ - fun lenSq(): Float = w*w + x*x + y*y + z*z + /** + * computes the square of the length of this quaternion + * @return the length squared + **/ + fun lenSq(): Float = w * w + x * x + y * y + z * z - /** - * computes the length of this quaternion - * @return the length - **/ - fun len(): Float = sqrt(w*w + x*x + y*y + z*z) + /** + * computes the length of this quaternion + * @return the length + **/ + fun len(): Float = sqrt(w * w + x * x + y * y + z * z) - /** - * @return the normalized quaternion - **/ - fun unit(): Quaternion { - val m = len() - return if (m == 0f) ZERO else this/m - } + /** + * @return the normalized quaternion + **/ + fun unit(): Quaternion { + val m = len() + return if (m == 0f) ZERO else this / m + } - operator fun times(that: Float): Quaternion = Quaternion( - this.w*that, - this.x*that, - this.y*that, - this.z*that - ) + operator fun times(that: Float): Quaternion = Quaternion( + this.w * that, + this.x * that, + this.y * that, + this.z * that + ) - operator fun times(that: Quaternion): Quaternion = Quaternion( - this.w*that.w - this.x*that.x - this.y*that.y - this.z*that.z, - this.x*that.w + this.w*that.x - this.z*that.y + this.y*that.z, - this.y*that.w + this.z*that.x + this.w*that.y - this.x*that.z, - this.z*that.w - this.y*that.x + this.x*that.y + this.w*that.z - ) + operator fun times(that: Quaternion): Quaternion = Quaternion( + this.w * that.w - this.x * that.x - this.y * that.y - this.z * that.z, + this.x * that.w + this.w * that.x - this.z * that.y + this.y * that.z, + this.y * that.w + this.z * that.x + this.w * that.y - this.x * that.z, + this.z * that.w - this.y * that.x + this.x * that.y + this.w * that.z + ) - /** - * computes the inverse of this quaternion - * @return the inversed quaternion - **/ - fun inv(): Quaternion { - val lenSq = lenSq() - return Quaternion( - w/lenSq, - -x/lenSq, - -y/lenSq, - -z/lenSq - ) - } + /** + * computes the inverse of this quaternion + * @return the inversed quaternion + **/ + fun inv(): Quaternion { + val lenSq = lenSq() + return Quaternion( + w / lenSq, + -x / lenSq, + -y / lenSq, + -z / lenSq + ) + } - operator fun div(that: Float): Quaternion = this*(1f/that) + operator fun div(that: Float): Quaternion = this * (1f / that) - /** - * computes right division, this * that^-1 - **/ - operator fun div(that: Quaternion): Quaternion = this*that.inv() + /** + * computes right division, this * that^-1 + **/ + operator fun div(that: Quaternion): Quaternion = this * that.inv() - /** - * @return the conjugate of this quaternion - **/ - fun conj(): Quaternion = Quaternion(w, -x, -y, -z) + /** + * @return the conjugate of this quaternion + **/ + fun conj(): Quaternion = Quaternion(w, -x, -y, -z) - /** - * computes the logarithm of this quaternion - * @return the log of this quaternion - **/ - fun log(): Quaternion { - val co = w - val si = xyz.len() - val len = len() + /** + * computes the logarithm of this quaternion + * @return the log of this quaternion + **/ + fun log(): Quaternion { + val co = w + val si = xyz.len() + val len = len() - if (si == 0f) { - return Quaternion(ln(len), xyz/w) - } + if (si == 0f) { + return Quaternion(ln(len), xyz / w) + } - val ang = atan2(si, co) - return Quaternion(ln(len), ang/si*xyz) - } + val ang = atan2(si, co) + return Quaternion(ln(len), ang / si * xyz) + } - /** - * raises e to the power of this quaternion - * @return the exponentiated quaternion - **/ - fun exp(): Quaternion { - val ang = xyz.len() - val len = exp(w) + /** + * raises e to the power of this quaternion + * @return the exponentiated quaternion + **/ + fun exp(): Quaternion { + val ang = xyz.len() + val len = exp(w) - if (ang == 0f) { - return Quaternion(len, len*xyz) - } + if (ang == 0f) { + return Quaternion(len, len * xyz) + } - val co = cos(ang) - val si = sin(ang) - return Quaternion(len*co, len*si/ang*xyz) - } + val co = cos(ang) + val si = sin(ang) + return Quaternion(len * co, len * si / ang * xyz) + } - /** - * raises this quaternion to the power of t - * @param t the power by which to raise this quaternion - * @return the powered quaternion - **/ - fun pow(t: Float): Quaternion = (log()*t).exp() + /** + * raises this quaternion to the power of t + * @param t the power by which to raise this quaternion + * @return the powered quaternion + **/ + fun pow(t: Float): Quaternion = (log() * t).exp() - // for a slight improvement in performance - // not fully implemented + // for a slight improvement in performance + // not fully implemented // fun pow(t: Float): Quaternion { // val imLen = imLen() // val ang = atan2(imLen, w) @@ -195,177 +196,177 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { // } // } - /** - * between this and -this, picks the one nearest to that - * @param that the quaternion to be nearest - * @return nearest quaternion - **/ - fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) -this else this + /** + * between this and -this, picks the one nearest to that + * @param that the quaternion to be nearest + * @return nearest quaternion + **/ + fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) -this else this - /** - * interpolates from this quaternion to that quaternion by t in quaternion space - * @param that the quaternion to interpolate to - * @param t the amount to interpolate - * @return interpolated quaternion - **/ - fun interp(that: Quaternion, t: Float) = - if (t == 0f) { - this - } else if (t == 1f) { - that - } else if (t < 0.5f) { - (that/this).pow(t)*this - } else { - (this/that).pow(1f - t)*that - } + /** + * interpolates from this quaternion to that quaternion by t in quaternion space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun interp(that: Quaternion, t: Float) = + if (t == 0f) { + this + } else if (t == 1f) { + that + } else if (t < 0.5f) { + (that / this).pow(t) * this + } else { + (this / that).pow(1f - t) * that + } - /** - * interpolates from this quaternion to that quaternion by t in rotation space - * @param that the quaternion to interpolate to - * @param t the amount to interpolate - * @return interpolated quaternion - **/ - fun interpR(that: Quaternion, t: Float) = this.interp(that.twinNearest(this), t) + /** + * interpolates from this quaternion to that quaternion by t in rotation space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun interpR(that: Quaternion, t: Float) = this.interp(that.twinNearest(this), t) - /** - * linearly interpolates from this quaternion to that quaternion by t in quaternion space - * @param that the quaternion to interpolate to - * @param t the amount to interpolate - * @return interpolated quaternion - **/ - fun lerp(that: Quaternion, t: Float): Quaternion = (1f - t)*this + t*that + /** + * linearly interpolates from this quaternion to that quaternion by t in quaternion space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun lerp(that: Quaternion, t: Float): Quaternion = (1f - t) * this + t * that - /** - * linearly interpolates from this quaternion to that quaternion by t in rotation space - * @param that the quaternion to interpolate to - * @param t the amount to interpolate - * @return interpolated quaternion - **/ - fun lerpR(that: Quaternion, t: Float) = this.lerp(that.twinNearest(this), t) + /** + * linearly interpolates from this quaternion to that quaternion by t in rotation space + * @param that the quaternion to interpolate to + * @param t the amount to interpolate + * @return interpolated quaternion + **/ + fun lerpR(that: Quaternion, t: Float) = this.lerp(that.twinNearest(this), t) - /** - * computes this quaternion's angle to identity in quaternion space - * @return angle - **/ - fun angle(): Float = atan2(xyz.len(), w) + /** + * computes this quaternion's angle to identity in quaternion space + * @return angle + **/ + fun angle(): Float = atan2(xyz.len(), w) - /** - * computes this quaternion's angle to identity in rotation space - * @return angle - **/ - fun angleR(): Float = 2f*atan2(xyz.len(), abs(w)) + /** + * computes this quaternion's angle to identity in rotation space + * @return angle + **/ + fun angleR(): Float = 2f * atan2(xyz.len(), abs(w)) - /** - * computes the angle between this quaternion and that quaternion in quaternion space - * @param that the other quaternion - * @return angle - **/ - fun angleTo(that: Quaternion): Float = (this/that).angle() + /** + * computes the angle between this quaternion and that quaternion in quaternion space + * @param that the other quaternion + * @return angle + **/ + fun angleTo(that: Quaternion): Float = (this / that).angle() - /** - * computes the angle between this quaternion and that quaternion in rotation space - * @param that the other quaternion - * @return angle - **/ - fun angleToR(that: Quaternion): Float = (this/that).angleR() + /** + * computes the angle between this quaternion and that quaternion in rotation space + * @param that the other quaternion + * @return angle + **/ + fun angleToR(that: Quaternion): Float = (this / that).angleR() - /** - * computes the angle this quaternion rotates about the u axis in quaternion space - * @param u the axis - * @return angle - **/ - fun angleAbout(u: Vector3): Float { - val uDotIm = u.dot(xyz) - val uLen = u.len() - return atan2(uDotIm, uLen*w) - } + /** + * computes the angle this quaternion rotates about the u axis in quaternion space + * @param u the axis + * @return angle + **/ + fun angleAbout(u: Vector3): Float { + val uDotIm = u.dot(xyz) + val uLen = u.len() + return atan2(uDotIm, uLen * w) + } - /** - * computes the angle this quaternion rotates about the u axis in rotation space - * @param u the axis - * @return angle - **/ - fun angleAboutR(u: Vector3): Float { - val uDotIm = u.dot(xyz) - val uLen = u.len() - return if (uDotIm < 0f) { - 2f*atan2(-uDotIm, -uLen*w) - } else { - 2f*atan2(uDotIm, uLen*w) - } - } + /** + * computes the angle this quaternion rotates about the u axis in rotation space + * @param u the axis + * @return angle + **/ + fun angleAboutR(u: Vector3): Float { + val uDotIm = u.dot(xyz) + val uLen = u.len() + return if (uDotIm < 0f) { + 2f * atan2(-uDotIm, -uLen * w) + } else { + 2f * atan2(uDotIm, uLen * w) + } + } - /** - * finds Q, the quaternion nearest to this quaternion representing a rotation purely about the global u axis - * Q is NOT unitized - * @param v the global axis - * @return Q - **/ - fun project(v: Vector3) = Quaternion(w, xyz.dot(v)/v.lenSq()*v) + /** + * finds Q, the quaternion nearest to this quaternion representing a rotation purely about the global u axis + * Q is NOT unitized + * @param v the global axis + * @return Q + **/ + fun project(v: Vector3) = Quaternion(w, xyz.dot(v) / v.lenSq() * v) - /** - * finds Q, the quaternion nearest to this quaternion representing a rotation NOT on the global u axis. - * Q is NOT unitized - * @param v the global axis - * @return Q - **/ - fun reject(v: Vector3) = Quaternion(w, v.cross(xyz).cross(v)/v.lenSq()) + /** + * finds Q, the quaternion nearest to this quaternion representing a rotation NOT on the global u axis. + * Q is NOT unitized + * @param v the global axis + * @return Q + **/ + fun reject(v: Vector3) = Quaternion(w, v.cross(xyz).cross(v) / v.lenSq()) - /** - * finds Q, the quaternion nearest to this quaternion whose local u direction aligns with the global v direction. - * Q is NOT unitized - * @param u the local direction - * @param v the global direction - * @return Q - **/ - fun align(u: Vector3, v: Vector3): Quaternion { - val U = Quaternion(0f, u) - val V = Quaternion(0f, v) + /** + * finds Q, the quaternion nearest to this quaternion whose local u direction aligns with the global v direction. + * Q is NOT unitized + * @param u the local direction + * @param v the global direction + * @return Q + **/ + fun align(u: Vector3, v: Vector3): Quaternion { + val U = Quaternion(0f, u) + val V = Quaternion(0f, v) - return (V*this/U + (V/U).len()*this)/2f - } + return (V * this / U + (V / U).len() * this) / 2f + } - /** - * applies this quaternion's rotation to that vector - * @param that the vector to be transformed - * @return that vector transformed by this quaternion - **/ - fun sandwich(that: Vector3): Vector3 = (this*Quaternion(0f, that)/this).xyz + /** + * applies this quaternion's rotation to that vector + * @param that the vector to be transformed + * @return that vector transformed by this quaternion + **/ + fun sandwich(that: Vector3): Vector3 = (this * Quaternion(0f, that) / this).xyz - /** - * computes this quaternion's rotation axis - * @return rotation axis - **/ - fun axis(): Vector3 = xyz.unit() + /** + * computes this quaternion's rotation axis + * @return rotation axis + **/ + fun axis(): Vector3 = xyz.unit() - /** - * computes the rotation vector representing this quaternion's rotation - * @return rotation vector - **/ - fun toRotationVector(): Vector3 = 2f*log().xyz + /** + * computes the rotation vector representing this quaternion's rotation + * @return rotation vector + **/ + fun toRotationVector(): Vector3 = 2f * log().xyz - /** - * computes the matrix representing this quaternion's rotation - * @return rotation matrix - **/ - fun toMatrix(): Matrix3 { - val d = lenSq() - return Matrix3( - (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d, 2f*(w*y + x*z)/d, - 2f*(x*y + w*z)/d, (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d, - 2f*(x*z - w*y)/d, 2f*(w*x + y*z)/d, (w*w - x*x - y*y + z*z)/d - ) - } + /** + * computes the matrix representing this quaternion's rotation + * @return rotation matrix + **/ + fun toMatrix(): Matrix3 { + val d = lenSq() + return Matrix3( + (w * w + x * x - y * y - z * z) / d, 2f * (x * y - w * z) / d, 2f * (w * y + x * z) / d, + 2f * (x * y + w * z) / d, (w * w - x * x + y * y - z * z) / d, 2f * (y * z - w * x) / d, + 2f * (x * z - w * y) / d, 2f * (w * x + y * z) / d, (w * w - x * x - y * y + z * z) / d + ) + } - /** - * computes the euler angles representing this quaternion's rotation - * @param order the order in which to decompose this quaternion into euler angles - * @return euler angles - **/ - fun toEulerAngles(order: EulerOrder): EulerAngles = this.toMatrix().toEulerAnglesAssumingOrthonormal(order) + /** + * computes the euler angles representing this quaternion's rotation + * @param order the order in which to decompose this quaternion into euler angles + * @return euler angles + **/ + fun toEulerAngles(order: EulerOrder): EulerAngles = this.toMatrix().toEulerAnglesAssumingOrthonormal(order) } operator fun Float.plus(that: Quaternion): Quaternion = that + this operator fun Float.minus(that: Quaternion): Quaternion = -that + this -operator fun Float.times(that: Quaternion): Quaternion = that*this -operator fun Float.div(that: Quaternion): Quaternion = that.inv()*this +operator fun Float.times(that: Quaternion): Quaternion = that * this +operator fun Float.div(that: Quaternion): Quaternion = that.inv() * this diff --git a/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt index 37624d190..db9a7221c 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt @@ -1,90 +1,92 @@ @file:Suppress("unused") + package io.github.axisangles.ktmath import kotlin.math.atan2 import kotlin.math.sqrt data class Vector3(val x: Float, val y: Float, val z: Float) { - companion object { - val ZERO = Vector3( 0f, 0f, 0f) - val POS_X = Vector3( 1f, 0f, 0f) - val POS_Y = Vector3( 0f, 1f, 0f) - val POS_Z = Vector3( 0f, 0f, 1f) - val NEG_X = Vector3(-1f, 0f, 0f) - val NEG_Y = Vector3( 0f, -1f, 0f) - val NEG_Z = Vector3( 0f, 0f, -1f) - } + companion object { + val ZERO = Vector3(0f, 0f, 0f) + val POS_X = Vector3(1f, 0f, 0f) + val POS_Y = Vector3(0f, 1f, 0f) + val POS_Z = Vector3(0f, 0f, 1f) + val NEG_X = Vector3(-1f, 0f, 0f) + val NEG_Y = Vector3(0f, -1f, 0f) + val NEG_Z = Vector3(0f, 0f, -1f) + } - operator fun unaryMinus() = Vector3(-x, -y, -z) + operator fun unaryMinus() = Vector3(-x, -y, -z) - operator fun plus(that: Vector3) = Vector3( - this.x + that.x, - this.y + that.y, - this.z + that.z - ) + operator fun plus(that: Vector3) = Vector3( + this.x + that.x, + this.y + that.y, + this.z + that.z + ) - operator fun minus(that: Vector3) = Vector3( - this.x - that.x, - this.y - that.y, - this.z - that.z - ) + operator fun minus(that: Vector3) = Vector3( + this.x - that.x, + this.y - that.y, + this.z - that.z + ) - /** - * computes the dot product of this vector with that vector - * @param that the vector with which to be dotted - * @return the dot product - **/ - fun dot(that: Vector3) = this.x*that.x + this.y*that.y + this.z*that.z + /** + * computes the dot product of this vector with that vector + * @param that the vector with which to be dotted + * @return the dot product + **/ + fun dot(that: Vector3) = this.x * that.x + this.y * that.y + this.z * that.z - /** - * computes the cross product of this vector with that vector - * @param that the vector with which to be crossed - * @return the cross product - **/ - fun cross(that: Vector3) = Vector3( - this.y*that.z - this.z*that.y, - this.z*that.x - this.x*that.z, - this.x*that.y - this.y*that.x - ) - /** - * computes the square of the length of this vector - * @return the length squared - **/ - fun lenSq() = x*x + y*y + z*z + /** + * computes the cross product of this vector with that vector + * @param that the vector with which to be crossed + * @return the cross product + **/ + fun cross(that: Vector3) = Vector3( + this.y * that.z - this.z * that.y, + this.z * that.x - this.x * that.z, + this.x * that.y - this.y * that.x + ) - /** - * computes the length of this quaternion - * @return the length - **/ - fun len() = sqrt(x*x + y*y + z*z) + /** + * computes the square of the length of this vector + * @return the length squared + **/ + fun lenSq() = x * x + y * y + z * z - /** - * @return the normalized vector - **/ - fun unit(): Vector3 { - val m = len() - return if (m == 0f) ZERO else this/m - } + /** + * computes the length of this quaternion + * @return the length + **/ + fun len() = sqrt(x * x + y * y + z * z) - operator fun times(that: Float) = Vector3( - this.x*that, - this.y*that, - this.z*that - ) + /** + * @return the normalized vector + **/ + fun unit(): Vector3 { + val m = len() + return if (m == 0f) ZERO else this / m + } - // computes division of this vector3 by a float - operator fun div(that: Float) = Vector3( - this.x/that, - this.y/that, - this.z/that - ) + operator fun times(that: Float) = Vector3( + this.x * that, + this.y * that, + this.z * that + ) - /** - * computes the angle between this vector with that vector - * @param that the vector to which the angle is computed - * @return the angle - **/ - fun angleTo(that: Vector3): Float = atan2(this.cross(that).len(), this.dot(that)) + // computes division of this vector3 by a float + operator fun div(that: Float) = Vector3( + this.x / that, + this.y / that, + this.z / that + ) + + /** + * computes the angle between this vector with that vector + * @param that the vector to which the angle is computed + * @return the angle + **/ + fun angleTo(that: Vector3): Float = atan2(this.cross(that).len(), this.dot(that)) } -operator fun Float.times(that: Vector3): Vector3 = that*this +operator fun Float.times(that: Vector3): Vector3 = that * this diff --git a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt new file mode 100644 index 000000000..ca4906ffe --- /dev/null +++ b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt @@ -0,0 +1,157 @@ +package io.github.axisangles.ktmath + +import kotlin.math.* +import kotlin.test.Test +import kotlin.test.assertTrue + +class QuaternionTest { + + @Test + fun plus() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(6f, 8f, 10f, 12f) + assertEquals(q3, q1 + q2) + } + + @Test + fun times() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(-60f, 12f, 30f, 24f) + assertEquals(q3, q1 * q2) + } + + @Test + fun timesScalarRhs() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(2f, 4f, 6f, 8f) + assertEquals(q2, q1 * 2f) + } + + @Test + fun timesScalarLhs() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(2f, 4f, 6f, 8f) + assertEquals(q2, 2f * q1) + } + + @Test + fun inverse() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(1f / 30f, -2f / 30f, -3f / 30f, -4f / 30f) + assertEquals(q2, q1.inv()) + } + + @Test + fun rightDiv() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(-60f, 12f, 30f, 24f) + assertEquals(q1, q3 / q2) + } + + @Test + fun rightDivFloatRhs() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(2f, 4f, 6f, 8f) + assertEquals(q1, q2 / 2f) + } + + @Test + fun rightDivFloatLhs() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(1f / 15f, -2f / 15f, -1f / 5f, -4f / 15f) + + assertEquals(q2, 2f / q1) + } + + @Test + fun pow() { + val q = Quaternion(1f, 2f, 3f, 4f) + assertEquals(q.pow(1f), q, 1e-5) + assertEquals(q.pow(2f), q * q, 1e-5) + assertEquals(q.pow(0f), Quaternion.ONE, 1e-5) + assertEquals(q.pow(-1f), q.inv(), 1e-5) + } + + @Test + fun interp() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(2.405691f, 3.5124686f, 4.619246f, 5.7260237f) + assertEquals(q1.interp(q2, 0.5f), q3, 1e-7) + } + + @Test + fun interpR() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = -Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(2.405691f, 3.5124686f, 4.619246f, 5.7260237f) + assertEquals(q1.interpR(q2, 0.5f), q3, 1e-7) + } + + @Test + fun lerp() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(5f, 6f, 7f, 8f) + val q3 = Quaternion(3f, 4f, 5f, 6f) + assertEquals(q1.lerp(q2, 0.5f), q3, 1e-7) + } + + companion object { + private const val RELATIVE_TOLERANCE = 0.0 + + internal fun assertEquals( + expected: Quaternion, + actual: Quaternion, + tolerance: Double = RELATIVE_TOLERANCE + ) { + val len = (actual - expected).lenSq() + val squareSum = expected.lenSq() + actual.lenSq() + assertTrue( + len <= tolerance * tolerance * squareSum, + "Expected: $expected but got: $actual" + ) + } + } +} + +var randSeed = 0 +fun randInt(): Int { + randSeed = (1103515245 * randSeed + 12345).mod(2147483648).toInt() + return randSeed +} + +fun randFloat(): Float { + return randInt().toFloat() / 2147483648 +} + +fun randGaussian(): Float { + var thing = 1f - randFloat() + while (thing == 0f) { + // no 0s allowed + thing = 1f - randFloat() + } + return sqrt(-2f * ln(thing)) * cos(PI.toFloat() * randFloat()) +} + +fun randMatrix(): Matrix3 { + return Matrix3( + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian(), + randGaussian(), randGaussian(), randGaussian() + ) +} + +fun randQuaternion(): Quaternion { + return Quaternion(randGaussian(), randGaussian(), randGaussian(), randGaussian()) +} + +fun randRotMatrix(): Matrix3 { + return randQuaternion().toMatrix() +} + +fun randVector(): Vector3 { + return Vector3(randGaussian(), randGaussian(), randGaussian()) +} From bed94a9ed8be054a68eacc455a02321e06b50ce2 Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Thu, 26 Jan 2023 13:53:30 -0800 Subject: [PATCH 3/9] Fixed Quaternion angleAboutR, Added FloatMath, Quaternion.fromTo, switched to atan(co, si), Added more Quaternion tests --- .../io/github/axisangles/ktmath/FloatMath.kt | 71 ++++++++++++++++++ .../io/github/axisangles/ktmath/Matrix3.kt | 12 +-- .../io/github/axisangles/ktmath/Quaternion.kt | 75 +++++++++++-------- .../axisangles/ktmath/QuaternionTest.kt | 74 ++++++++++++++++++ 4 files changed, 193 insertions(+), 39 deletions(-) create mode 100644 server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt diff --git a/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt b/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt new file mode 100644 index 000000000..683b9256a --- /dev/null +++ b/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt @@ -0,0 +1,71 @@ +package io.github.axisangles.ktmath + +import kotlin.math.sqrt + +/** + * guarantees last bit floating point accuracy + */ +fun atan(co: Float, si: Float) = atan(co.toDouble(), si.toDouble()).toFloat() +fun atan(ta: Float) = atan(ta.toDouble()).toFloat() +fun acos(co: Float) = acos(co.toDouble()).toFloat() +fun asin(si: Float) = asin(si.toDouble()).toFloat() + + +fun atan(co: Double, si: Double) = + if (co == 0.0 && si == 0.0) 0.0 + else atanFold1(co, si) + +fun atan(ta: Double) = when (ta) { + 1.0/0.0 -> 1.570796326794897 + -1.0/0.0 -> -1.570796326794897 + else -> atanFold1(1.0, ta) +} +fun acos(co: Double) = atanFold1(co, sqrt(1.0 - co*co)) +fun asin(si: Double) = atanFold1(sqrt(1.0 - si*si), si) + +// The goal was to make use of as much FMA and parallel instruction execution as possible +// make a viktor version to replace this in the future +private fun atanFold1(x: Double, y: Double) = + if (y < 0.0) -atanFold2(x, -y) + else atanFold2(x, y) + +private fun atanFold2(x: Double, y: Double) = + if (x < 0.0) 3.141592653589793 - atanFold3(-x, y) + else atanFold3(x, y) + +private fun atanFold3(x: Double, y: Double) = + if (y > x) 1.570796326794897 - atanFold4(y, x) + else atanFold4(x, y) + +private fun atanFold4(x: Double, y: Double) = + if (y > 0.4142135623730950*x) 0.7853981633974483 - atanFold5( + x + y, x - y) + else atanFold5(x, y) + +private fun atanFold5(x: Double, y: Double) = + if (y > 0.1989123673796580*x) 0.3926990816987242 - atanFold6( + x + 0.4142135623730950*y, 0.4142135623730950*x - y) + else atanFold6(x, y) + +private fun atanFold6(x: Double, y: Double) = + if (y > 0.09849140335716425*x) 0.1963495408493621 - atanFold7( + x + 0.1989123673796580*y, 0.1989123673796580*x - y) + else atanFold7(x, y) + +private fun atanFold7(x: Double, y: Double) = + if (y > 0.04912684976946725*x) 0.09817477042468103 - atanFinal( + x + 0.09849140335716425*y, 0.09849140335716425*x - y) + else atanFinal(x, y) + +private fun atanFinal(x: Double, y: Double): Double { + val s = y/x + val t = s*s + return s*(1.0 - t*(1.0/3.0 - t*(1.0/5.0)))// - t*(1.0/7.0))))// - t*(1.0/9.0)))))// - t*(1.0/11.0 - t*(1.0/13.0 - t*(1.0/15.0)))))))) +// val r = y/x +// val s = r*r +// val t = s*s +// // help the CPU take advantage of parallel instruction execution +// val odd = s*(1.0/3.0 + t*(1.0/7.0)) +// val evn = 1.0 + t*(1.0/5.0 + t*(1.0/9.0)) +// return r*(evn - odd) +} diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index cedf34526..12ce08611 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -153,6 +153,10 @@ data class Matrix3( * @return the rotation matrix */ fun orthonormalize(): Matrix3 { + if (this.det() <= 0f) { // maybe this doesn't have to be so + throw Exception("Attempt to convert non-positive determinant matrix to rotation matrix") + } + var curMat = this var curDet = Float.POSITIVE_INFINITY @@ -200,10 +204,6 @@ data class Matrix3( * @return the quaternion */ fun toQuaternionAssumingOrthonormal(): Quaternion { - if (this.det() <= 0f) { - throw Exception("Attempt to convert negative determinant matrix to quaternion") - } - return if (yy > -zz && zz > -xx && xx > -yy) { Quaternion(1 + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() } else if (xx > yy && xx > zz) { @@ -306,10 +306,6 @@ data class Matrix3( * @return the eulerAngles */ fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { - if (this.det() <= 0f) { - throw Exception("Attempt to convert negative determinant matrix to euler angles") - } - val ETA = 1.57079632f when (order) { EulerOrder.XYZ -> { diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index 856742c82..4ffa3adc1 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -22,6 +22,21 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @return the new quaternion **/ fun fromRotationVector(v: Vector3): Quaternion = Quaternion(0f, v / 2f).exp() + + /** + * finds Q, the smallest-angled quaternion whose local u direction aligns with + * the global v direction. + * @param u the local direction + * @param v the global direction + * @return Q + **/ + fun fromTo(u: Vector3, v: Vector3): Quaternion { + val U = Quaternion(0f, u) + val V = Quaternion(0f, v) + val D = V / U + + return (D + D.len()).unit() + } } constructor(w: Float, xyz: Vector3) : this(w, xyz.x, xyz.y, xyz.z) @@ -59,14 +74,16 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { this.z - that.z ) - operator fun minus(that: Float): Quaternion = Quaternion(this.w - that, this.x, this.y, this.z) + operator fun minus(that: Float): Quaternion = + Quaternion(this.w - that, this.x, this.y, this.z) /** * computes the dot product of this quaternion with that quaternion * @param that the quaternion with which to be dotted - * @return the inversed quaternion + * @return the inverse quaternion **/ - fun dot(that: Quaternion): Float = this.w * that.w + this.x * that.x + this.y * that.y + this.z * that.z + fun dot(that: Quaternion): Float = + this.w * that.w + this.x * that.x + this.y * that.y + this.z * that.z /** * computes the square of the length of this quaternion @@ -141,7 +158,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { return Quaternion(ln(len), xyz / w) } - val ang = atan2(si, co) + val ang = atan(co, si) return Quaternion(ln(len), ang / si * xyz) } @@ -172,16 +189,15 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { // for a slight improvement in performance // not fully implemented // fun pow(t: Float): Quaternion { -// val imLen = imLen() -// val ang = atan2(imLen, w) +// val imLen = xyz.Len() +// val ang = atan(w, imLen) // // val len = len().pow(t) // val co = cos(t*ang) // val si = sin(t*ang) // // return if (imLen == 0f) { -// Quaternion( -// len*co, +// Quaternion(len*co, // len*t*x, // len*t*y, // len*t*z @@ -248,13 +264,13 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * computes this quaternion's angle to identity in quaternion space * @return angle **/ - fun angle(): Float = atan2(xyz.len(), w) + fun angle(): Float = atan(w, xyz.len()) /** * computes this quaternion's angle to identity in rotation space * @return angle **/ - fun angleR(): Float = 2f * atan2(xyz.len(), abs(w)) + fun angleR(): Float = 2f * atan(abs(w), xyz.len()) /** * computes the angle between this quaternion and that quaternion in quaternion space @@ -276,9 +292,9 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @return angle **/ fun angleAbout(u: Vector3): Float { - val uDotIm = u.dot(xyz) - val uLen = u.len() - return atan2(uDotIm, uLen * w) + val si = u.dot(xyz) + val co = u.len()*w + return atan(co, si) } /** @@ -287,34 +303,30 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @return angle **/ fun angleAboutR(u: Vector3): Float { - val uDotIm = u.dot(xyz) - val uLen = u.len() - return if (uDotIm < 0f) { - 2f * atan2(-uDotIm, -uLen * w) - } else { - 2f * atan2(uDotIm, uLen * w) - } - } + val si = u.dot(xyz) + val co = u.len()*w + return 2f * atan(abs(co), si) + }//: Float = 2f*this.twinNearest(Quaternion.ONE).angleAbout(u) /** - * finds Q, the quaternion nearest to this quaternion representing a rotation purely about the global u axis - * Q is NOT unitized + * finds Q, the quaternion nearest to this quaternion representing a rotation purely + * about the global u axis. Q is NOT unitized * @param v the global axis * @return Q **/ fun project(v: Vector3) = Quaternion(w, xyz.dot(v) / v.lenSq() * v) /** - * finds Q, the quaternion nearest to this quaternion representing a rotation NOT on the global u axis. - * Q is NOT unitized + * finds Q, the quaternion nearest to this quaternion representing a rotation NOT + * on the global u axis. Q is NOT unitized * @param v the global axis * @return Q **/ fun reject(v: Vector3) = Quaternion(w, v.cross(xyz).cross(v) / v.lenSq()) /** - * finds Q, the quaternion nearest to this quaternion whose local u direction aligns with the global v direction. - * Q is NOT unitized + * finds Q, the quaternion nearest to this quaternion whose local u direction aligns + * with the global v direction. Q is NOT unitized * @param u the local direction * @param v the global direction * @return Q @@ -351,11 +363,12 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { **/ fun toMatrix(): Matrix3 { val d = lenSq() + /* ktlint-disable */ return Matrix3( - (w * w + x * x - y * y - z * z) / d, 2f * (x * y - w * z) / d, 2f * (w * y + x * z) / d, - 2f * (x * y + w * z) / d, (w * w - x * x + y * y - z * z) / d, 2f * (y * z - w * x) / d, - 2f * (x * z - w * y) / d, 2f * (w * x + y * z) / d, (w * w - x * x - y * y + z * z) / d - ) + (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d , 2f*(w*y + x*z)/d , + 2f*(x*y + w*z)/d , (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d , + 2f*(x*z - w*y)/d , 2f*(w*x + y*z)/d , (w*w - x*x - y*y + z*z)/d) + /* ktlint-enable */ } /** diff --git a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt index ca4906ffe..cd143ec65 100644 --- a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt +++ b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt @@ -2,6 +2,7 @@ package io.github.axisangles.ktmath import kotlin.math.* import kotlin.test.Test +import kotlin.test.assertEquals import kotlin.test.assertTrue class QuaternionTest { @@ -99,6 +100,79 @@ class QuaternionTest { assertEquals(q1.lerp(q2, 0.5f), q3, 1e-7) } + @Test + fun lerpR() { + val q1 = Quaternion(1f, 2f, 3f, 4f) + val q2 = Quaternion(-5f, -6f, -7f, -8f) + val q3 = Quaternion(3f, 4f, 5f, 6f) + assertEquals(q1.lerpR(q2, 0.5f), q3, 1e-7) + } + + @Test + fun angleTo() { + val q1 = Quaternion(1f, 0f, 0f, 0f) + val q2 = Quaternion(0f, 1f, 0f, 0f) + assertEquals(q1.angleTo(q2), PI.toFloat()/2f) + } + + @Test + fun angleToR() { + val q1 = Quaternion(1f, 0f, 0f, 0f) + val q2 = Quaternion(0f, 1f, 0f, 0f) + assertEquals(q1.angleToR(q2), PI.toFloat()) + } + + @Test + fun angle() { + val q = Quaternion(0f, 1f, 0f, 0f) + assertEquals(q.angle(), PI.toFloat()/2f) + } + + @Test + fun angleR() { + val q = Quaternion(0f, 1f, 0f, 0f) + assertEquals(q.angleR(), PI.toFloat()) + } + + @Test + fun angleAbout() { + val q = Quaternion(1f, 1f, 1f, 0f) + assertEquals(q.angleAbout(Vector3.POS_Y), PI.toFloat()/4f) + } + + @Test + fun angleAboutR() { + val q = Quaternion(1f, 1f, 1f, 0f) + assertEquals(q.angleAboutR(Vector3.POS_Y), PI.toFloat()/2f) + } + + @Test + fun project() { + val q1 = Quaternion(1f, 1f, 1f, 0f) + val q2 = Quaternion(1f, 0f, 1f, 0f) + assertEquals(q1.project(Vector3.POS_Y), q2) + } + + @Test + fun reject() { + val q1 = Quaternion(1f, 1f, 1f, 0f) + val q2 = Quaternion(1f, 1f, 0f, 0f) + assertEquals(q1.reject(Vector3.POS_Y), q2) + } + + @Test + fun align() { + val q1 = Quaternion(0f, 1f, 0f, 0f) + val q2 = Quaternion(0f, 0.5f, 0.5f, 0f) + assertEquals(q1.align(Vector3.POS_X, Vector3.POS_Y), q2) + } + + @Test + fun fromTo() { + val q1 = Quaternion(1f, 0f, 0f, 1f).unit() + assertEquals(Quaternion.fromTo(Vector3.POS_X, Vector3.POS_Y), q1) + } + companion object { private const val RELATIVE_TOLERANCE = 0.0 From 07d97e0d774f016ec84cf5af20105abe3391167b Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Thu, 26 Jan 2023 18:09:52 -0800 Subject: [PATCH 4/9] Added more Quaternion tests, Changed toRotationVector to return values (-pi < x <= pi) in line with other rotation space conversions --- .../io/github/axisangles/ktmath/FloatMath.kt | 71 ----------------- .../io/github/axisangles/ktmath/Quaternion.kt | 16 ++-- .../axisangles/ktmath/QuaternionTest.kt | 79 ++++++++++++++++++- 3 files changed, 84 insertions(+), 82 deletions(-) delete mode 100644 server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt diff --git a/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt b/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt deleted file mode 100644 index 683b9256a..000000000 --- a/server/src/main/java/io/github/axisangles/ktmath/FloatMath.kt +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.axisangles.ktmath - -import kotlin.math.sqrt - -/** - * guarantees last bit floating point accuracy - */ -fun atan(co: Float, si: Float) = atan(co.toDouble(), si.toDouble()).toFloat() -fun atan(ta: Float) = atan(ta.toDouble()).toFloat() -fun acos(co: Float) = acos(co.toDouble()).toFloat() -fun asin(si: Float) = asin(si.toDouble()).toFloat() - - -fun atan(co: Double, si: Double) = - if (co == 0.0 && si == 0.0) 0.0 - else atanFold1(co, si) - -fun atan(ta: Double) = when (ta) { - 1.0/0.0 -> 1.570796326794897 - -1.0/0.0 -> -1.570796326794897 - else -> atanFold1(1.0, ta) -} -fun acos(co: Double) = atanFold1(co, sqrt(1.0 - co*co)) -fun asin(si: Double) = atanFold1(sqrt(1.0 - si*si), si) - -// The goal was to make use of as much FMA and parallel instruction execution as possible -// make a viktor version to replace this in the future -private fun atanFold1(x: Double, y: Double) = - if (y < 0.0) -atanFold2(x, -y) - else atanFold2(x, y) - -private fun atanFold2(x: Double, y: Double) = - if (x < 0.0) 3.141592653589793 - atanFold3(-x, y) - else atanFold3(x, y) - -private fun atanFold3(x: Double, y: Double) = - if (y > x) 1.570796326794897 - atanFold4(y, x) - else atanFold4(x, y) - -private fun atanFold4(x: Double, y: Double) = - if (y > 0.4142135623730950*x) 0.7853981633974483 - atanFold5( - x + y, x - y) - else atanFold5(x, y) - -private fun atanFold5(x: Double, y: Double) = - if (y > 0.1989123673796580*x) 0.3926990816987242 - atanFold6( - x + 0.4142135623730950*y, 0.4142135623730950*x - y) - else atanFold6(x, y) - -private fun atanFold6(x: Double, y: Double) = - if (y > 0.09849140335716425*x) 0.1963495408493621 - atanFold7( - x + 0.1989123673796580*y, 0.1989123673796580*x - y) - else atanFold7(x, y) - -private fun atanFold7(x: Double, y: Double) = - if (y > 0.04912684976946725*x) 0.09817477042468103 - atanFinal( - x + 0.09849140335716425*y, 0.09849140335716425*x - y) - else atanFinal(x, y) - -private fun atanFinal(x: Double, y: Double): Double { - val s = y/x - val t = s*s - return s*(1.0 - t*(1.0/3.0 - t*(1.0/5.0)))// - t*(1.0/7.0))))// - t*(1.0/9.0)))))// - t*(1.0/11.0 - t*(1.0/13.0 - t*(1.0/15.0)))))))) -// val r = y/x -// val s = r*r -// val t = s*s -// // help the CPU take advantage of parallel instruction execution -// val odd = s*(1.0/3.0 + t*(1.0/7.0)) -// val evn = 1.0 + t*(1.0/5.0 + t*(1.0/9.0)) -// return r*(evn - odd) -} diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index 4ffa3adc1..36b01ad79 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -158,7 +158,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { return Quaternion(ln(len), xyz / w) } - val ang = atan(co, si) + val ang = atan2(si, co) return Quaternion(ln(len), ang / si * xyz) } @@ -264,13 +264,13 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * computes this quaternion's angle to identity in quaternion space * @return angle **/ - fun angle(): Float = atan(w, xyz.len()) + fun angle(): Float = atan2(xyz.len(), w) /** * computes this quaternion's angle to identity in rotation space * @return angle **/ - fun angleR(): Float = 2f * atan(abs(w), xyz.len()) + fun angleR(): Float = 2f * atan2(xyz.len(), abs(w)) /** * computes the angle between this quaternion and that quaternion in quaternion space @@ -294,7 +294,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { fun angleAbout(u: Vector3): Float { val si = u.dot(xyz) val co = u.len()*w - return atan(co, si) + return atan2(si, co) } /** @@ -302,11 +302,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param u the axis * @return angle **/ - fun angleAboutR(u: Vector3): Float { - val si = u.dot(xyz) - val co = u.len()*w - return 2f * atan(abs(co), si) - }//: Float = 2f*this.twinNearest(Quaternion.ONE).angleAbout(u) + fun angleAboutR(u: Vector3): Float = 2f * twinNearest(ONE).angleAbout(u) /** * finds Q, the quaternion nearest to this quaternion representing a rotation purely @@ -355,7 +351,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * computes the rotation vector representing this quaternion's rotation * @return rotation vector **/ - fun toRotationVector(): Vector3 = 2f * log().xyz + fun toRotationVector(): Vector3 = 2f * twinNearest(ONE).log().xyz /** * computes the matrix representing this quaternion's rotation diff --git a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt index cd143ec65..00b02ac14 100644 --- a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt +++ b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt @@ -170,7 +170,84 @@ class QuaternionTest { @Test fun fromTo() { val q1 = Quaternion(1f, 0f, 0f, 1f).unit() - assertEquals(Quaternion.fromTo(Vector3.POS_X, Vector3.POS_Y), q1) + assertEquals(q1, Quaternion.fromTo(Vector3.POS_X, Vector3.POS_Y)) + } + + @Test + fun sandwich() { + val v1 = Quaternion(1f, 1f, 0f, 0f).sandwich(Vector3(1f, 1f, 0f)) + val v2 = Vector3(1f, 0f, 1f) + assertEquals(v2, v1) + } + + @Test + fun axis() { + val v1 = Quaternion(0f, Quaternion(1f, 2f, 3f, 4f).axis()) + val v2 = Quaternion(0f, Vector3(0.37139067f, 0.557086f, 0.74278134f)) + assertEquals(v2, v1, 1e-7) + } + + @Test + fun toRotationVector() { + val v1 = Quaternion(1f, 2f, 3f, 4f).toRotationVector() + val v2 = Vector3(1.0303806f, 1.5455709f, 2.0607612f) + assertEquals(v2, v1) + } + + @Test + fun fromRotationVector() { + val v1 = Quaternion.fromRotationVector(Vector3(1f, 2f, 3f)) + val v2 = Quaternion(-0.29555118f, 0.25532186f, 0.5106437f, 0.7659656f) + assertEquals(v2, v1) + } + + @Test + fun toMatrix() { + /* ktlint-disable */ + val m1 = Matrix3( + -1f, 0f, 0f, + 0f, -1f, 0f, + 0f, 0f, 1f) + /* ktlint-enable */ + val m2 = Quaternion(0f, 0f, 0f, 2f).toMatrix() + assertEquals(m1, m2) + } + + private fun testEulerAngles(order: EulerOrder) { + val inputQ = Quaternion(1f, 2f, 3f, 4f).unit() + val outputQ = inputQ.toEulerAngles(order) + .toQuaternion().twinNearest(Quaternion.ONE) + assertEquals(inputQ, outputQ, 1e-7) + } + + @Test + fun eulerAnglesXYZ() { + testEulerAngles(EulerOrder.XYZ) + } + + @Test + fun eulerAnglesYZX() { + testEulerAngles(EulerOrder.YZX) + } + + @Test + fun eulerAnglesZXY() { + testEulerAngles(EulerOrder.ZXY) + } + + @Test + fun eulerAnglesZYX() { + testEulerAngles(EulerOrder.ZYX) + } + + @Test + fun eulerAnglesYXZ() { + testEulerAngles(EulerOrder.YXZ) + } + + @Test + fun eulerAnglesXZY() { + testEulerAngles(EulerOrder.XZY) } companion object { From 2cf7d6b2d3779334349c949d3cd1310d041e6553 Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Thu, 26 Jan 2023 19:32:57 -0800 Subject: [PATCH 5/9] Changed ONE to IDENTITY and ZERO to NULL. Added Quaternion.fromRotationVector(x, y, z) --- .../java/io/github/axisangles/ktmath/Main.kt | 6 ++-- .../io/github/axisangles/ktmath/Matrix3.kt | 2 +- .../io/github/axisangles/ktmath/Quaternion.kt | 30 ++++++++++++++----- .../io/github/axisangles/ktmath/Vector3.kt | 4 +-- .../axisangles/ktmath/QuaternionTest.kt | 12 ++++---- 5 files changed, 35 insertions(+), 19 deletions(-) diff --git a/server/src/main/java/io/github/axisangles/ktmath/Main.kt b/server/src/main/java/io/github/axisangles/ktmath/Main.kt index a64ae0fbf..f9204f04a 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Main.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Main.kt @@ -121,7 +121,7 @@ fun testQuaternionInv() { for (i in 1..1000) { val Q = randQuaternion() - if (relError(Q * Q.inv(), Quaternion.ONE) > 1e-6f) { + if (relError(Q * Q.inv(), Quaternion.IDENTITY) > 1e-6f) { throw Exception("Quaternion inv accuracy test failed") } } @@ -131,7 +131,7 @@ fun testQuaternionDiv() { for (i in 1..1000) { val Q = randQuaternion() - if (!checkError(1e-6f, Q/Q, Quaternion.ONE)) { + if (!checkError(1e-6f, Q/Q, Quaternion.IDENTITY)) { throw Exception("Quaternion div accuracy test failed") } if (!checkError(1e-6f, 2f/Q, 2f*Q.inv())) { @@ -151,7 +151,7 @@ fun testQuaternionPow() { if (!checkError(2e-6f, Q.pow(-1f), Q.inv())) { throw Exception("Quaternion pow -1 accuracy test failed") } - if (!checkError(2e-6f, Q.pow(0f), Quaternion.ONE)) { + if (!checkError(2e-6f, Q.pow(0f), Quaternion.IDENTITY)) { throw Exception("Quaternion pow 0 accuracy test failed") } if (!checkError(2e-6f, Q.pow(1f), Q)) { diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index 12ce08611..52fca5488 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -16,7 +16,7 @@ data class Matrix3( val zz: Float ) { companion object { - val ZERO = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + val NULL = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) val IDENTITY = Matrix3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) } diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index 36b01ad79..b886d661d 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -10,19 +10,32 @@ import kotlin.math.* */ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { companion object { - val ZERO = Quaternion(0f, 0f, 0f, 0f) - val ONE = Quaternion(1f, 0f, 0f, 0f) + val NULL = Quaternion(0f, 0f, 0f, 0f) + val IDENTITY = Quaternion(1f, 0f, 0f, 0f) val I = Quaternion(0f, 1f, 0f, 0f) val J = Quaternion(0f, 0f, 1f, 0f) val K = Quaternion(0f, 0f, 0f, 1f) // creates a new quaternion representing the rotation about axis v by rotational angle v /** - * creates a new quaternion representing the rotation about axis v by rotational angle of v's length + * creates a new quaternion representing the rotation about v's axis + * by an angle of v's length + * @param v the rotation vector * @return the new quaternion **/ fun fromRotationVector(v: Vector3): Quaternion = Quaternion(0f, v / 2f).exp() + /** + * creates a new quaternion representing the rotation about axis v + * by an angle of v's length + * @param vx the rotation vector's x component + * @param vy the rotation vector's y component + * @param vz the rotation vector's z component + * @return the new quaternion + **/ + fun fromRotationVector(vx: Float, vy: Float, vz: Float): Quaternion = + fromRotationVector(Vector3(vx, vy, vz)) + /** * finds Q, the smallest-angled quaternion whose local u direction aligns with * the global v direction. @@ -39,6 +52,9 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { } } + /** + * @return the quaternion with w real component and xyz imaginary components + */ constructor(w: Float, xyz: Vector3) : this(w, xyz.x, xyz.y, xyz.z) /** @@ -102,7 +118,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { **/ fun unit(): Quaternion { val m = len() - return if (m == 0f) ZERO else this / m + return if (m == 0f) NULL else this / m } operator fun times(that: Float): Quaternion = Quaternion( @@ -293,7 +309,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { **/ fun angleAbout(u: Vector3): Float { val si = u.dot(xyz) - val co = u.len()*w + val co = u.len() * w return atan2(si, co) } @@ -302,7 +318,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param u the axis * @return angle **/ - fun angleAboutR(u: Vector3): Float = 2f * twinNearest(ONE).angleAbout(u) + fun angleAboutR(u: Vector3): Float = 2f * twinNearest(IDENTITY).angleAbout(u) /** * finds Q, the quaternion nearest to this quaternion representing a rotation purely @@ -351,7 +367,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * computes the rotation vector representing this quaternion's rotation * @return rotation vector **/ - fun toRotationVector(): Vector3 = 2f * twinNearest(ONE).log().xyz + fun toRotationVector(): Vector3 = 2f * twinNearest(IDENTITY).log().xyz /** * computes the matrix representing this quaternion's rotation diff --git a/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt index db9a7221c..6e181f826 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Vector3.kt @@ -7,7 +7,7 @@ import kotlin.math.sqrt data class Vector3(val x: Float, val y: Float, val z: Float) { companion object { - val ZERO = Vector3(0f, 0f, 0f) + val NULL = Vector3(0f, 0f, 0f) val POS_X = Vector3(1f, 0f, 0f) val POS_Y = Vector3(0f, 1f, 0f) val POS_Z = Vector3(0f, 0f, 1f) @@ -65,7 +65,7 @@ data class Vector3(val x: Float, val y: Float, val z: Float) { **/ fun unit(): Vector3 { val m = len() - return if (m == 0f) ZERO else this / m + return if (m == 0f) NULL else this / m } operator fun times(that: Float) = Vector3( diff --git a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt index 00b02ac14..e3223100a 100644 --- a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt +++ b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt @@ -72,7 +72,7 @@ class QuaternionTest { val q = Quaternion(1f, 2f, 3f, 4f) assertEquals(q.pow(1f), q, 1e-5) assertEquals(q.pow(2f), q * q, 1e-5) - assertEquals(q.pow(0f), Quaternion.ONE, 1e-5) + assertEquals(q.pow(0f), Quaternion.IDENTITY, 1e-5) assertEquals(q.pow(-1f), q.inv(), 1e-5) } @@ -112,7 +112,7 @@ class QuaternionTest { fun angleTo() { val q1 = Quaternion(1f, 0f, 0f, 0f) val q2 = Quaternion(0f, 1f, 0f, 0f) - assertEquals(q1.angleTo(q2), PI.toFloat()/2f) + assertEquals(q1.angleTo(q2), PI.toFloat() / 2f) } @Test @@ -125,7 +125,7 @@ class QuaternionTest { @Test fun angle() { val q = Quaternion(0f, 1f, 0f, 0f) - assertEquals(q.angle(), PI.toFloat()/2f) + assertEquals(q.angle(), PI.toFloat() / 2f) } @Test @@ -137,13 +137,13 @@ class QuaternionTest { @Test fun angleAbout() { val q = Quaternion(1f, 1f, 1f, 0f) - assertEquals(q.angleAbout(Vector3.POS_Y), PI.toFloat()/4f) + assertEquals(q.angleAbout(Vector3.POS_Y), PI.toFloat() / 4f) } @Test fun angleAboutR() { val q = Quaternion(1f, 1f, 1f, 0f) - assertEquals(q.angleAboutR(Vector3.POS_Y), PI.toFloat()/2f) + assertEquals(q.angleAboutR(Vector3.POS_Y), PI.toFloat() / 2f) } @Test @@ -216,7 +216,7 @@ class QuaternionTest { private fun testEulerAngles(order: EulerOrder) { val inputQ = Quaternion(1f, 2f, 3f, 4f).unit() val outputQ = inputQ.toEulerAngles(order) - .toQuaternion().twinNearest(Quaternion.ONE) + .toQuaternion().twinNearest(Quaternion.IDENTITY) assertEquals(inputQ, outputQ, 1e-7) } From f2cf6dffcf05ed4717f9e2aea75f5951d72f0030 Mon Sep 17 00:00:00 2001 From: ImUrX Date: Sat, 28 Jan 2023 20:13:20 -0300 Subject: [PATCH 6/9] linting --- .../github/axisangles/ktmath/EulerAngles.kt | 39 ++-- .../io/github/axisangles/ktmath/Matrix3.kt | 196 ++++++++++-------- .../io/github/axisangles/ktmath/Quaternion.kt | 68 +++--- 3 files changed, 173 insertions(+), 130 deletions(-) diff --git a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt index e027cf4df..57bc8a611 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt @@ -80,36 +80,39 @@ data class EulerAngles(val order: EulerOrder, val x: Float, val y: Float, val z: val sZ = sin(z) return when (order) { + // ktlint ruining spacing + /* ktlint-disable */ EulerOrder.XYZ -> Matrix3( - cY * cZ, -cY * sZ, sY, - cZ * sX * sY + cX * sZ, cX * cZ - sX * sY * sZ, -cY * sX, - sX * sZ - cX * cZ * sY, cZ * sX + cX * sY * sZ, cX * cY + cY*cZ, -cY*sZ, sY, + cZ*sX*sY + cX*sZ, cX*cZ - sX*sY*sZ, -cY*sX, + sX*sZ - cX*cZ*sY, cZ*sX + cX*sY*sZ, cX*cY ) EulerOrder.YZX -> Matrix3( - cY * cZ, sX * sY - cX * cY * sZ, cX * sY + cY * sX * sZ, - sZ, cX * cZ, -cZ * sX, - -cZ * sY, cY * sX + cX * sY * sZ, cX * cY - sX * sY * sZ + cY * cZ, sX * sY - cX * cY * sZ, cX * sY + cY * sX * sZ, + sZ, cX * cZ, -cZ * sX, + -cZ * sY, cY * sX + cX * sY * sZ, cX * cY - sX * sY * sZ ) EulerOrder.ZXY -> Matrix3( - cY * cZ - sX * sY * sZ, -cX * sZ, cZ * sY + cY * sX * sZ, - cZ * sX * sY + cY * sZ, cX * cZ, sY * sZ - cY * cZ * sX, - -cX * sY, sX, cX * cY + cY * cZ - sX * sY * sZ, -cX * sZ, cZ * sY + cY * sX * sZ, + cZ * sX * sY + cY * sZ, cX * cZ, sY * sZ - cY * cZ * sX, + -cX * sY, sX, cX * cY ) EulerOrder.ZYX -> Matrix3( - cY * cZ, cZ * sX * sY - cX * sZ, cX * cZ * sY + sX * sZ, - cY * sZ, cX * cZ + sX * sY * sZ, cX * sY * sZ - cZ * sX, - -sY, cY * sX, cX * cY + cY * cZ, cZ * sX * sY - cX * sZ, cX * cZ * sY + sX * sZ, + cY * sZ, cX * cZ + sX * sY * sZ, cX * sY * sZ - cZ * sX, + -sY, cY * sX, cX * cY ) EulerOrder.YXZ -> Matrix3( - cY * cZ + sX * sY * sZ, cZ * sX * sY - cY * sZ, cX * sY, - cX * sZ, cX * cZ, -sX, - cY * sX * sZ - cZ * sY, cY * cZ * sX + sY * sZ, cX * cY + cY * cZ + sX * sY * sZ, cZ * sX * sY - cY * sZ, cX * sY, + cX * sZ, cX * cZ, -sX, + cY * sX * sZ - cZ * sY, cY * cZ * sX + sY * sZ, cX * cY ) EulerOrder.XZY -> Matrix3( - cY * cZ, -sZ, cZ * sY, - sX * sY + cX * cY * sZ, cX * cZ, cX * sY * sZ - cY * sX, - cY * sX * sZ - cX * sY, cZ * sX, cX * cY + sX * sY * sZ + cY * cZ, -sZ, cZ * sY, + sX * sY + cX * cY * sZ, cX * cZ, cX * sY * sZ - cY * sX, + cY * sX * sZ - cX * sY, cZ * sX, cX * cY + sX * sY * sZ ) + /* ktlint-enable */ } } } diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index 52fca5488..9c68b0f30 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -4,20 +4,24 @@ package io.github.axisangles.ktmath import kotlin.math.* +/* ktlint-disable */ data class Matrix3( - val xx: Float, - val yx: Float, - val zx: Float, - val xy: Float, - val yy: Float, - val zy: Float, - val xz: Float, - val yz: Float, - val zz: Float + val xx: Float, val yx: Float, val zx: Float, + val xy: Float, val yy: Float, val zy: Float, + val xz: Float, val yz: Float, val zz: Float ) { +/* ktlint-enable */ companion object { - val NULL = Matrix3(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) - val IDENTITY = Matrix3(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) + val NULL = Matrix3( + 0f, 0f, 0f, + 0f, 0f, 0f, + 0f, 0f, 0f + ) + val IDENTITY = Matrix3( + 1f, 0f, 0f, + 0f, 1f, 0f, + 0f, 0f, 1f + ) } /** @@ -85,7 +89,9 @@ data class Matrix3( * computes the square of the frobenius norm of this matrix * @return the frobenius norm squared */ - fun normSq(): Float = xx * xx + yx * yx + zx * zx + xy * xy + yy * yy + zy * zy + xz * xz + yz * yz + zz * zz + fun normSq(): Float = (xx * xx + yx * yx + zx * zx + + xy * xy + yy * yy + zy * zy + + xz * xz + yz * yz + zz * zz) /** * computes the frobenius norm of this matrix @@ -97,7 +103,9 @@ data class Matrix3( * computes the determinant of this matrix * @return the determinant */ - fun det(): Float = (xz * yx - xx * yz) * zy + (xx * yy - xy * yx) * zz + (xy * yz - xz * yy) * zx + fun det(): Float = ((xz * yx - xx * yz) * zy + + (xx * yy - xy * yx) * zz + + (xy * yz - xz * yy) * zx) /** * computes the trace of this matrix @@ -200,7 +208,8 @@ data class Matrix3( // assumes this matrix is orthonormal and converts this to a quaternion /** - * creates a quaternion representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * creates a quaternion representing the same rotation as this matrix, + * assuming the matrix is a rotation matrix * @return the quaternion */ fun toQuaternionAssumingOrthonormal(): Quaternion { @@ -222,87 +231,88 @@ data class Matrix3( */ fun toQuaternion(): Quaternion = orthonormalize().toQuaternionAssumingOrthonormal() - /* - the standard algorithm: + /* + the standard algorithm: - yAng = asin(clamp(zx, -1, 1)) - if (abs(zx) < 0.9999999f) { - xAng = atan2(-zy, zz) - zAng = atan2(-yx, xx) - } else { - xAng = atan2(yz, yy) - zAng = 0 - } + yAng = asin(clamp(zx, -1, 1)) + if (abs(zx) < 0.9999999f) { + xAng = atan2(-zy, zz) + zAng = atan2(-yx, xx) + } else { + xAng = atan2(yz, yy) + zAng = 0 + } - problems with the standard algorithm: + problems with the standard algorithm: - 1) - yAng = asin(clamp(zx, -1, 1)) + 1) + yAng = asin(clamp(zx, -1, 1)) - FIX: - yAng = atan2(zx, sqrt(zy*zy + zz*zz)) + FIX: + yAng = atan2(zx, sqrt(zy*zy + zz*zz)) - this loses many bits of accuracy when near the singularity, zx = +-1 and - can cause the algorithm to return completely inaccurate results with only - small floating point errors in the matrix. this happens because zx is - NOT sin(pitch), but rather errorTerm*sin(pitch), and small changes in zx - when zx is near +-1 make large changes in asin(zx). + this loses many bits of accuracy when near the singularity, zx = +-1 and + can cause the algorithm to return completely inaccurate results with only + small floating point errors in the matrix. this happens because zx is + NOT sin(pitch), but rather errorTerm*sin(pitch), and small changes in zx + when zx is near +-1 make large changes in asin(zx). - 2) - if (abs(zx) < 0.9999999f) { + 2) + if (abs(zx) < 0.9999999f) { - FIX: - if (zy*zy + zz*zz > 0f) { + FIX: + if (zy*zy + zz*zz > 0f) { - this clause, meant to reduce the inaccuracy of the code following does - not actually test for the condition that makes the following atans unstable. - that is, when (zy, zz) and (yx, xx) are near 0. - after several matrix multiplications, the error term is expected to be - larger than 0.0000001. Often times, this clause will not catch the conditions - it is trying to catch. + this clause, meant to reduce the inaccuracy of the code following does + not actually test for the condition that makes the following atans unstable. + that is, when (zy, zz) and (yx, xx) are near 0. + after several matrix multiplications, the error term is expected to be + larger than 0.0000001. Often times, this clause will not catch the conditions + it is trying to catch. - 3) - zAng = atan2(-yx, xx) + 3) + zAng = atan2(-yx, xx) - FIX: - zAng = atan2(xy*zz - xz*zy, yy*zz - yz*zy) + FIX: + zAng = atan2(xy*zz - xz*zy, yy*zz - yz*zy) - xAng and zAng are being computed separately. In the case of near singularity - the angles of xAng and zAng are effectively added together as they represent - the same operation (a rotation about the global y-axis). When computed - separately, it is not guaranteed that the xAng + zAng add together to give - the actual final rotation about the global y-axis. + xAng and zAng are being computed separately. In the case of near singularity + the angles of xAng and zAng are effectively added together as they represent + the same operation (a rotation about the global y-axis). When computed + separately, it is not guaranteed that the xAng + zAng add together to give + the actual final rotation about the global y-axis. - 4) - after many matrix operations are performed, without orthonormalization - the matrix will contain floating point errors that will throw off the - accuracy of any euler angles algorithm. orthonormalization should be - built into the prerequisites for this function - */ + 4) + after many matrix operations are performed, without orthonormalization + the matrix will contain floating point errors that will throw off the + accuracy of any euler angles algorithm. orthonormalization should be + built into the prerequisites for this function + */ -// fun toEulerAnglesXYZFaulty(): EulerAngles { -// return if (abs(zx) < 0.9999999f) -// EulerAngles(EulerOrder.XYZ, -// atan2(-zy, zz), -// asin(zx.coerceIn(-1f, 1f)), -// atan2(-yx, xx)) -// else -// EulerAngles(EulerOrder.XYZ, -// atan2(yz, yy), -// asin(zx.coerceIn(-1f, 1f)), -// 0f) -// } +//fun toEulerAnglesXYZFaulty(): EulerAngles { +// return if (abs(zx) < 0.9999999f) +// EulerAngles(EulerOrder.XYZ, +// atan2(-zy, zz), +// asin(zx.coerceIn(-1f, 1f)), +// atan2(-yx, xx)) +// else +// EulerAngles(EulerOrder.XYZ, +// atan2(yz, yy), +// asin(zx.coerceIn(-1f, 1f)), +// 0f) +//} /** - * creates an eulerAngles representing the same rotation as this matrix, assuming the matrix is a rotation matrix + * creates an eulerAngles representing the same rotation as this matrix, + * assuming the matrix is a rotation matrix * @return the eulerAngles */ fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { @@ -310,7 +320,11 @@ data class Matrix3( when (order) { EulerOrder.XYZ -> { val kc = zy * zy + zz * zz - if (kc == 0f) return EulerAngles(EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f) + if (kc == 0f) { + return EulerAngles( + EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f + ) + } return EulerAngles( EulerOrder.XYZ, @@ -321,7 +335,11 @@ data class Matrix3( } EulerOrder.YZX -> { val kc = xx * xx + xz * xz - if (kc == 0f) return EulerAngles(EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy)) + if (kc == 0f) { + return EulerAngles( + EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy) + ) + } return EulerAngles( EulerOrder.YZX, @@ -332,7 +350,11 @@ data class Matrix3( } EulerOrder.ZXY -> { val kc = yy * yy + yx * yx - if (kc == 0f) return EulerAngles(EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx)) + if (kc == 0f) { + return EulerAngles( + EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx) + ) + } return EulerAngles( EulerOrder.ZXY, @@ -343,7 +365,11 @@ data class Matrix3( } EulerOrder.ZYX -> { val kc = xy * xy + xx * xx - if (kc == 0f) return EulerAngles(EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy)) + if (kc == 0f) { + return EulerAngles( + EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy) + ) + } return EulerAngles( EulerOrder.ZYX, @@ -354,7 +380,11 @@ data class Matrix3( } EulerOrder.YXZ -> { val kc = zx * zx + zz * zz - if (kc == 0f) return EulerAngles(EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f) + if (kc == 0f) { + return EulerAngles( + EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f + ) + } return EulerAngles( EulerOrder.YXZ, @@ -365,7 +395,11 @@ data class Matrix3( } EulerOrder.XZY -> { val kc = yz * yz + yy * yy - if (kc == 0f) return EulerAngles(EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx)) + if (kc == 0f) { + return EulerAngles( + EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx) + ) + } return EulerAngles( EulerOrder.XZY, @@ -374,9 +408,6 @@ data class Matrix3( atan2(-yx, sqrt(kc)) ) } - else -> { - throw Exception("EulerAngles not implemented for given EulerOrder") - } } } @@ -385,7 +416,8 @@ data class Matrix3( * creates an eulerAngles representing the same rotation as this matrix * @return the eulerAngles */ - fun toEulerAngles(order: EulerOrder): EulerAngles = orthonormalize().toEulerAnglesAssumingOrthonormal(order) + fun toEulerAngles(order: EulerOrder): EulerAngles = + orthonormalize().toEulerAnglesAssumingOrthonormal(order) } operator fun Float.times(that: Matrix3): Matrix3 = that * this diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index b886d661d..67e8fd762 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -81,7 +81,8 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { this.z + that.z ) - operator fun plus(that: Float): Quaternion = Quaternion(this.w + that, this.x, this.y, this.z) + operator fun plus(that: Float): Quaternion = + Quaternion(this.w + that, this.x, this.y, this.z) operator fun minus(that: Quaternion): Quaternion = Quaternion( this.w - that.w, @@ -118,7 +119,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { **/ fun unit(): Quaternion { val m = len() - return if (m == 0f) NULL else this / m + return if (m == 0f) NULL else (this / m) } operator fun times(that: Float): Quaternion = Quaternion( @@ -204,36 +205,40 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { // for a slight improvement in performance // not fully implemented -// fun pow(t: Float): Quaternion { -// val imLen = xyz.Len() -// val ang = atan(w, imLen) +// fun pow(t: Float): Quaternion { +// val imLen = xyz.Len() +// val ang = atan(w, imLen) // -// val len = len().pow(t) -// val co = cos(t*ang) -// val si = sin(t*ang) +// val len = len().pow(t) +// val co = cos(t*ang) +// val si = sin(t*ang) // -// return if (imLen == 0f) { -// Quaternion(len*co, -// len*t*x, -// len*t*y, -// len*t*z -// ) -// } else { -// Quaternion( -// len*co, -// len*si*x/imLen, -// len*si*y/imLen, -// len*si*z/imLen -// ) -// } -// } +// return if (imLen == 0f) { +// Quaternion(len*co, +// len*t*x, +// len*t*y, +// len*t*z +// ) +// } else { +// Quaternion( +// len*co, +// len*si*x/imLen, +// len*si*y/imLen, +// len*si*z/imLen +// ) +// } +// } /** * between this and -this, picks the one nearest to that * @param that the quaternion to be nearest * @return nearest quaternion **/ - fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) -this else this + fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) { + -this + } else { + this + } /** * interpolates from this quaternion to that quaternion by t in quaternion space @@ -261,7 +266,8 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { fun interpR(that: Quaternion, t: Float) = this.interp(that.twinNearest(this), t) /** - * linearly interpolates from this quaternion to that quaternion by t in quaternion space + * linearly interpolates from this quaternion to that quaternion by t in + * quaternion space * @param that the quaternion to interpolate to * @param t the amount to interpolate * @return interpolated quaternion @@ -269,7 +275,8 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { fun lerp(that: Quaternion, t: Float): Quaternion = (1f - t) * this + t * that /** - * linearly interpolates from this quaternion to that quaternion by t in rotation space + * linearly interpolates from this quaternion to that quaternion by t in + * rotation space * @param that the quaternion to interpolate to * @param t the amount to interpolate * @return interpolated quaternion @@ -377,9 +384,9 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { val d = lenSq() /* ktlint-disable */ return Matrix3( - (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d , 2f*(w*y + x*z)/d , - 2f*(x*y + w*z)/d , (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d , - 2f*(x*z - w*y)/d , 2f*(w*x + y*z)/d , (w*w - x*x - y*y + z*z)/d) + (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d, 2f*(w*y + x*z)/d, + 2f*(x*y + w*z)/d, (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d, + 2f*(x*z - w*y)/d, 2f*(w*x + y*z)/d, (w*w - x*x - y*y + z*z)/d) /* ktlint-enable */ } @@ -388,7 +395,8 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param order the order in which to decompose this quaternion into euler angles * @return euler angles **/ - fun toEulerAngles(order: EulerOrder): EulerAngles = this.toMatrix().toEulerAnglesAssumingOrthonormal(order) + fun toEulerAngles(order: EulerOrder): EulerAngles = + this.toMatrix().toEulerAnglesAssumingOrthonormal(order) } operator fun Float.plus(that: Quaternion): Quaternion = that + this From cfd405c1d045243107aa7e6cdc5ae532ebb25b3e Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Sat, 28 Jan 2023 22:38:04 -0800 Subject: [PATCH 7/9] Clean up Renamed all base Quaternion function with R variant (IE angle and angleR) to have a Q at the end (angle -> angleQ) Cleaned up the matrices which are otherwise hard to read without special formatting --- .../github/axisangles/ktmath/EulerAngles.kt | 52 ++- .../java/io/github/axisangles/ktmath/Main.kt | 368 ------------------ .../io/github/axisangles/ktmath/Matrix3.kt | 72 ++-- .../io/github/axisangles/ktmath/Quaternion.kt | 65 +--- .../axisangles/ktmath/QuaternionTest.kt | 20 +- 5 files changed, 71 insertions(+), 506 deletions(-) delete mode 100644 server/src/main/java/io/github/axisangles/ktmath/Main.kt diff --git a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt index 57bc8a611..4cf58daad 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/EulerAngles.kt @@ -7,11 +7,6 @@ import kotlin.math.sin enum class EulerOrder { XYZ, YZX, ZXY, ZYX, YXZ, XZY } -// prefer Y.toX -// but if ambiguous, use X.fromY -/* - * Euler Angles contains both the x y z angle parameters and the order of application - */ data class EulerAngles(val order: EulerOrder, val x: Float, val y: Float, val z: Float) { /** * creates a quaternion which represents the same rotation as this eulerAngles @@ -83,35 +78,34 @@ data class EulerAngles(val order: EulerOrder, val x: Float, val y: Float, val z: // ktlint ruining spacing /* ktlint-disable */ EulerOrder.XYZ -> Matrix3( - cY*cZ, -cY*sZ, sY, - cZ*sX*sY + cX*sZ, cX*cZ - sX*sY*sZ, -cY*sX, - sX*sZ - cX*cZ*sY, cZ*sX + cX*sY*sZ, cX*cY - ) + cY*cZ , -cY*sZ , sY , + cZ*sX*sY + cX*sZ , cX*cZ - sX*sY*sZ , -cY*sX , + sX*sZ - cX*cZ*sY , cZ*sX + cX*sY*sZ , cX*cY ) + EulerOrder.YZX -> Matrix3( - cY * cZ, sX * sY - cX * cY * sZ, cX * sY + cY * sX * sZ, - sZ, cX * cZ, -cZ * sX, - -cZ * sY, cY * sX + cX * sY * sZ, cX * cY - sX * sY * sZ - ) + cY*cZ , sX*sY - cX*cY*sZ , cX*sY + cY*sX*sZ , + sZ , cX*cZ , -cZ*sX , + -cZ*sY , cY*sX + cX*sY*sZ , cX*cY - sX*sY*sZ ) + EulerOrder.ZXY -> Matrix3( - cY * cZ - sX * sY * sZ, -cX * sZ, cZ * sY + cY * sX * sZ, - cZ * sX * sY + cY * sZ, cX * cZ, sY * sZ - cY * cZ * sX, - -cX * sY, sX, cX * cY - ) + cY*cZ - sX*sY*sZ , -cX*sZ , cZ*sY + cY*sX*sZ , + cZ*sX*sY + cY*sZ , cX*cZ , sY*sZ - cY*cZ*sX , + -cX*sY , sX , cX*cY ) + EulerOrder.ZYX -> Matrix3( - cY * cZ, cZ * sX * sY - cX * sZ, cX * cZ * sY + sX * sZ, - cY * sZ, cX * cZ + sX * sY * sZ, cX * sY * sZ - cZ * sX, - -sY, cY * sX, cX * cY - ) + cY*cZ , cZ*sX*sY - cX*sZ , cX*cZ*sY + sX*sZ , + cY*sZ , cX*cZ + sX*sY*sZ , cX*sY*sZ - cZ*sX , + -sY , cY*sX , cX*cY ) + EulerOrder.YXZ -> Matrix3( - cY * cZ + sX * sY * sZ, cZ * sX * sY - cY * sZ, cX * sY, - cX * sZ, cX * cZ, -sX, - cY * sX * sZ - cZ * sY, cY * cZ * sX + sY * sZ, cX * cY - ) + cY*cZ + sX*sY*sZ , cZ*sX*sY - cY*sZ , cX*sY , + cX*sZ , cX*cZ , -sX , + cY*sX*sZ - cZ*sY , cY*cZ*sX + sY*sZ , cX*cY ) + EulerOrder.XZY -> Matrix3( - cY * cZ, -sZ, cZ * sY, - sX * sY + cX * cY * sZ, cX * cZ, cX * sY * sZ - cY * sX, - cY * sX * sZ - cX * sY, cZ * sX, cX * cY + sX * sY * sZ - ) + cY*cZ , -sZ , cZ*sY , + sX*sY + cX*cY*sZ , cX*cZ , cX*sY*sZ - cY*sX , + cY*sX*sZ - cX*sY , cZ*sX , cX*cY + sX*sY*sZ ) /* ktlint-enable */ } } diff --git a/server/src/main/java/io/github/axisangles/ktmath/Main.kt b/server/src/main/java/io/github/axisangles/ktmath/Main.kt deleted file mode 100644 index f9204f04a..000000000 --- a/server/src/main/java/io/github/axisangles/ktmath/Main.kt +++ /dev/null @@ -1,368 +0,0 @@ -package io.github.axisangles.ktmath - -import kotlin.math.* - -var randSeed = 0 -fun randInt(): Int { - randSeed = (1103515245 * randSeed + 12345).mod(2147483648).toInt() - return randSeed -} - -fun randFloat(): Float { - return randInt().toFloat() / 2147483648f -} - -fun randGaussian(): Float { - var thing = 1f - randFloat() - while (thing == 0f) { - // no 0s allowed - thing = 1f - randFloat() - } - return sqrt(-2f * ln(thing)) * cos(PI.toFloat() * randFloat()) -} - -fun randMatrix(): Matrix3 { - return Matrix3( - randGaussian(), randGaussian(), randGaussian(), - randGaussian(), randGaussian(), randGaussian(), - randGaussian(), randGaussian(), randGaussian() - ) -} - -fun randQuaternion(): Quaternion { - return Quaternion(randGaussian(), randGaussian(), randGaussian(), randGaussian()) -} - -fun randRotMatrix(): Matrix3 { - return randQuaternion().toMatrix() -} - -fun randVector(): Vector3 { - return Vector3(randGaussian(), randGaussian(), randGaussian()) -} - -fun testEulerMatrix(order: EulerOrder, M: Matrix3, exception: String) { - // We convert to euler angles and back and see if they are reasonably similar - val N = M.toEulerAngles(order).toMatrix() - if ((N - M).norm() > 1e-6) { - println("norm error: " + (N - M).norm().toString()) - throw Exception(exception) - } -} - -fun testEulerConversion(order: EulerOrder, exception: String) { - for (i in 1..1000) { - testEulerMatrix(order, randRotMatrix(), exception) - } -} - -fun testMatrixOrthonormalize() { - for (i in 1..1000) { - val M = randMatrix() - - val N = M.invTranspose().orthonormalize() - val O = M.orthonormalize() - if ((N - O).norm() > 1e-5) { - println("norm error: " + (N - O).norm().toString()) - throw Exception("Matrix orthonormalization accuracy test failed") - } - } -} - -fun testQuatMatrixConversion() { - for (i in 1..1000) { - val M = randRotMatrix() - val N = (randGaussian() * M.toQuaternion()).toMatrix() - if ((N - M).norm() > 1e-6) { - println("norm error: " + (N - M).norm().toString()) - throw Exception("Quaternion Matrix conversion accuracy test failed") - } - } -} - -fun relError(a: Matrix3, b: Matrix3): Float { - val combinedLen = sqrt((a.normSq() + b.normSq()) / 2f) - if (combinedLen == 0f) return 0f - - return (b - a).norm() / combinedLen -} - -fun relError(a: Vector3, b: Vector3): Float { - val combinedLen = sqrt((a.lenSq() + b.lenSq()) / 2f) - if (combinedLen == 0f) return 0f - - return (b - a).len() / combinedLen -} - -fun relError(a: Quaternion, b: Quaternion): Float { - val combinedLen = sqrt((a.lenSq() + b.lenSq()) / 2f) - if (combinedLen == 0f) return 0f - - return (b - a).len() / combinedLen -} - -fun checkError(eta: Float, a: Matrix3, b: Matrix3): Boolean { - return (b - a).normSq() <= eta * eta * (a.normSq() + b.normSq()) -} - -fun checkError(eta: Float, a: Quaternion, b: Quaternion): Boolean { - return (b - a).lenSq() <= eta * eta * (a.lenSq() + b.lenSq()) -} - -fun checkError(eta: Float, a: Vector3, b: Vector3): Boolean { - return (b - a).lenSq() <= eta * eta * (a.lenSq() + b.lenSq()) -} - -fun checkError(eta: Float, A: Quaternion): Boolean { - return A.lenSq() <= eta * eta -} - -fun testQuaternionInv() { - for (i in 1..1000) { - val Q = randQuaternion() - - if (relError(Q * Q.inv(), Quaternion.IDENTITY) > 1e-6f) { - throw Exception("Quaternion inv accuracy test failed") - } - } -} - -fun testQuaternionDiv() { - for (i in 1..1000) { - val Q = randQuaternion() - - if (!checkError(1e-6f, Q/Q, Quaternion.IDENTITY)) { - throw Exception("Quaternion div accuracy test failed") - } - if (!checkError(1e-6f, 2f/Q, 2f*Q.inv())) { - throw Exception("Float/Quaternion accuracy test failed") - } - if (!checkError(1e-6f, Q/2f, 0.5f*Q)) { - throw Exception("Quaternion/Float accuracy test failed") - } - } -} - -// 19 binary digits of accuracy -fun testQuaternionPow() { - for (i in 1..1000) { - val Q = randQuaternion() - - if (!checkError(2e-6f, Q.pow(-1f), Q.inv())) { - throw Exception("Quaternion pow -1 accuracy test failed") - } - if (!checkError(2e-6f, Q.pow(0f), Quaternion.IDENTITY)) { - throw Exception("Quaternion pow 0 accuracy test failed") - } - if (!checkError(2e-6f, Q.pow(1f), Q)) { - throw Exception("Quaternion pow 1 accuracy test failed") - } - if (!checkError(2e-6f, Q.pow(2f), Q*Q)) { - throw Exception("Quaternion pow 2 accuracy test failed") - } - } -} - -fun testQuaternionSandwich() { - for (i in 1..1000) { - val Q = randQuaternion() - val v = randVector() - - if (!checkError(5e-7f, Q.toMatrix()*v, Q.sandwich(v))) { - throw Exception("Quaternion sandwich accuracy test failed") - } - } -} - -// projection and alignment are expected to be less accurate in some extreme cases -// so we expect to see some cases in which half the bits are lost -fun testQuaternionProjectAlign() { - for (i in 1..1000) { - val Q = randQuaternion() - val v = randVector() - - if (!checkError(1e-4f, Q.align(v, v), Q.project(v))) { - println(Q.align(v, v) - Q.project(v)) - println(Q.align(v, v)) - println(Q.project(v)) - println(Q) - throw Exception("Quaternion project/align accuracy test failed") - } - } -} - -fun testQuaternionRotationVector() { - for (i in 1..1000) { - val Q = randQuaternion().unit() - val P = Quaternion.fromRotationVector(Q.toRotationVector()) - - if (!checkError(5e-7f, Q, P)) { - throw Exception("Quaternion toRotationVector fromRotationVector accuracy test failed") - } - } -} - -fun testQuaternionEulerAngles(order: EulerOrder, exception: String) { - for (i in 1..1000) { - val Q = randQuaternion().unit() - val P = Q.toEulerAngles(order).toQuaternion().twinNearest(Q) - - if (!checkError(2e-7f, Q, P)) { - println(relError(Q, P)) - throw Exception(exception) - } - } -} - -fun testEulerSingularity(order: EulerOrder, M: Matrix3, exception: String) { - for (i in 1..1000) { - val R = 1e-6f * randMatrix() - val S = M + R - if (S.det() <= 0f) return - - val error = (S.toEulerAnglesAssumingOrthonormal(order).toMatrix() - S).norm() - if (error > 2f * R.norm() + 1e-6f) { - throw Exception(exception) - } - } -} - -fun testEulerConversions(order: EulerOrder, exception: String) { - for (i in 1..1000) { - val e = EulerAngles(order, 6.28318f * randFloat(), 6.28318f * randFloat(), 6.28318f * randFloat()) - val N = e.toMatrix() - val M = e.toQuaternion().toMatrix() - if ((N - M).norm() > 1e-6) { - throw Exception(exception) - } - } -} - -fun main() { - val X90 = Matrix3( - 1f, 0f, 0f, - 0f, 0f, -1f, - 0f, 1f, 0f - ) - val Y90 = Matrix3( - 0f, 0f, 1f, - 0f, 1f, 0f, - -1f, 0f, 0f - ) - val Z90 = Matrix3( - 0f, -1f, 0f, - 1f, 0f, 0f, - 0f, 0f, 1f - ) - - testMatrixOrthonormalize() - testQuatMatrixConversion() - testQuaternionEulerAngles(EulerOrder.XYZ, "Quaternion EulerAnglesXYZ accuracy test failed") - testQuaternionEulerAngles(EulerOrder.YZX, "Quaternion EulerAnglesYZX accuracy test failed") - testQuaternionEulerAngles(EulerOrder.ZXY, "Quaternion EulerAnglesZXY accuracy test failed") - testQuaternionEulerAngles(EulerOrder.ZYX, "Quaternion EulerAnglesZYX accuracy test failed") - testQuaternionEulerAngles(EulerOrder.YXZ, "Quaternion EulerAnglesYXZ accuracy test failed") - testQuaternionEulerAngles(EulerOrder.XZY, "Quaternion EulerAnglesXZY accuracy test failed") - - testQuaternionInv() - testQuaternionDiv() - testQuaternionPow() - testQuaternionSandwich() - testQuaternionProjectAlign() - testQuaternionRotationVector() - - println(Matrix3.IDENTITY.average(Y90)) - - testEulerConversions(EulerOrder.XYZ, "fromEulerAnglesXYZ Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.YZX, "fromEulerAnglesYZX Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.ZXY, "fromEulerAnglesZXY Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.ZYX, "fromEulerAnglesZYX Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.YXZ, "fromEulerAnglesYXZ Quaternion or Matrix3 accuracy test failed") - testEulerConversions(EulerOrder.XZY, "fromEulerAnglesXZY Quaternion or Matrix3 accuracy test failed") - - // EULER ANGLE TESTS - testEulerConversion(EulerOrder.XYZ, "toEulerAnglesXYZ accuracy test failed") - testEulerConversion(EulerOrder.YZX, "toEulerAnglesYZX accuracy test failed") - testEulerConversion(EulerOrder.ZXY, "toEulerAnglesZXY accuracy test failed") - testEulerConversion(EulerOrder.ZYX, "toEulerAnglesZYX accuracy test failed") - testEulerConversion(EulerOrder.YXZ, "toEulerAnglesYXZ accuracy test failed") - testEulerConversion(EulerOrder.XZY, "toEulerAnglesXZY accuracy test failed") - - // test robustness to noise - testEulerSingularity(EulerOrder.XYZ, Y90, "toEulerAnglesXYZ singularity accuracy test failed") - testEulerSingularity(EulerOrder.YZX, Z90, "toEulerAnglesYZX singularity accuracy test failed") - testEulerSingularity(EulerOrder.ZXY, X90, "toEulerAnglesZXY singularity accuracy test failed") - testEulerSingularity(EulerOrder.ZYX, Y90, "toEulerAnglesZYX singularity accuracy test failed") - testEulerSingularity(EulerOrder.YXZ, X90, "toEulerAnglesYXZ singularity accuracy test failed") - testEulerSingularity(EulerOrder.XZY, Z90, "toEulerAnglesXZY singularity accuracy test failed") - - // speed test a linear (align) method against some standard math functions -// var x = Quaternion(1f, 2f, 3f, 4f) -// -// var dtAlignTotal: Long = 0 -// var dtOrthonormalizeTotal: Long = 0 -// var dtAtan2Total: Long = 0 -// var dtAsinTotal: Long = 0 -// -// for (i in 1..10) { -// val dtAlign = measureTimeMillis { -// for (i in 1..1_000_000) { -// val u = Vector3(1f, 0f, 0f) -// val v = Vector3(0f, 1f, 0f) -// // to make sure it is not optimized away -// x = x.align(u, v) -// // internally, x.align is: -// // val U = Quaternion(0f, u) -// // val V = Quaternion(0f, v) -// // x = (V*x/U + (V/U).len()*x)/2f -// } -// } -// -// var y = x.toMatrix() -// val dtOrthonormalize = measureTimeMillis { -// for (i in 1..1_000_000) { -// // to make sure it is not optimized away -// y = y.orthonormalize() -// // internally, x.align is: -// // val U = Quaternion(0f, u) -// // val V = Quaternion(0f, v) -// // x = (V*x/U + (V/U).len()*x)/2f -// } -// } -// -// var z = 0f; -// val dtAtan2 = measureTimeMillis { -// for (i in 1..1_000_000) { -// z+= atan2(i.toFloat(), i.toFloat()) // 45 degrees -// } -// } -// -// var w = 0f; -// val dtAsin = measureTimeMillis { -// for (i in 1..1_000_000) { -// w+= asin(i.toFloat()*0.7071f/i.toFloat()) // 45 degrees -// } -// } -// -// dtAlignTotal += dtAlign -// dtOrthonormalizeTotal += dtOrthonormalize -// dtAtan2Total += dtAtan2 -// dtAsinTotal += dtAsin -// } -// -// println(x) -// -// println(dtAlignTotal) // 213 -// println(dtOrthonormalizeTotal) // 244 -// println(dtAtan2Total) // 610 -// println(dtAsinTotal) // 3558 - -// var x = Quaternion(2f, 1f, 4f, 3f) -// val dtPow = measureTimeMillis { -// for (i in 1..10_000_000) { -// x = x.pow(1f) -// } -// } -// -// println(dtPow) -} diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index 9c68b0f30..dc6787dec 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -89,9 +89,10 @@ data class Matrix3( * computes the square of the frobenius norm of this matrix * @return the frobenius norm squared */ - fun normSq(): Float = (xx * xx + yx * yx + zx * zx - + xy * xy + yy * yy + zy * zy - + xz * xz + yz * yz + zz * zz) + fun normSq(): Float = + xx * xx + yx * yx + zx * zx + + xy * xy + yy * yy + zy * zy + + xz * xz + yz * yz + zz * zz /** * computes the frobenius norm of this matrix @@ -103,9 +104,10 @@ data class Matrix3( * computes the determinant of this matrix * @return the determinant */ - fun det(): Float = ((xz * yx - xx * yz) * zy - + (xx * yy - xy * yx) * zz - + (xy * yz - xz * yy) * zx) + fun det(): Float = + (xz * yx - xx * yz) * zy + + (xx * yy - xy * yx) * zz + + (xy * yz - xz * yy) * zx /** * computes the trace of this matrix @@ -297,34 +299,18 @@ data class Matrix3( built into the prerequisites for this function */ -//fun toEulerAnglesXYZFaulty(): EulerAngles { -// return if (abs(zx) < 0.9999999f) -// EulerAngles(EulerOrder.XYZ, -// atan2(-zy, zz), -// asin(zx.coerceIn(-1f, 1f)), -// atan2(-yx, xx)) -// else -// EulerAngles(EulerOrder.XYZ, -// atan2(yz, yy), -// asin(zx.coerceIn(-1f, 1f)), -// 0f) -//} - /** * creates an eulerAngles representing the same rotation as this matrix, * assuming the matrix is a rotation matrix * @return the eulerAngles */ fun toEulerAnglesAssumingOrthonormal(order: EulerOrder): EulerAngles { - val ETA = 1.57079632f + val ETA = 1.5707964f when (order) { EulerOrder.XYZ -> { val kc = zy * zy + zz * zz - if (kc == 0f) { - return EulerAngles( - EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.XYZ, + atan2(yz, yy), ETA.withSign(zx), 0f) return EulerAngles( EulerOrder.XYZ, @@ -335,11 +321,8 @@ data class Matrix3( } EulerOrder.YZX -> { val kc = xx * xx + xz * xz - if (kc == 0f) { - return EulerAngles( - EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy) - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.YZX, + 0f, atan2(zx, zz), ETA.withSign(xy)) return EulerAngles( EulerOrder.YZX, @@ -350,11 +333,8 @@ data class Matrix3( } EulerOrder.ZXY -> { val kc = yy * yy + yx * yx - if (kc == 0f) { - return EulerAngles( - EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx) - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.ZXY, + ETA.withSign(yz), 0f, atan2(xy, xx)) return EulerAngles( EulerOrder.ZXY, @@ -365,11 +345,8 @@ data class Matrix3( } EulerOrder.ZYX -> { val kc = xy * xy + xx * xx - if (kc == 0f) { - return EulerAngles( - EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy) - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.ZYX, + 0f, ETA.withSign(-xz), atan2(-yx, yy)) return EulerAngles( EulerOrder.ZYX, @@ -378,13 +355,11 @@ data class Matrix3( atan2(xy, xx) ) } + EulerOrder.YXZ -> { val kc = zx * zx + zz * zz - if (kc == 0f) { - return EulerAngles( - EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.YXZ, + ETA.withSign(-zy), atan2(-xz, xx), 0f) return EulerAngles( EulerOrder.YXZ, @@ -395,11 +370,8 @@ data class Matrix3( } EulerOrder.XZY -> { val kc = yz * yz + yy * yy - if (kc == 0f) { - return EulerAngles( - EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx) - ) - } + if (kc == 0f) return EulerAngles(EulerOrder.XZY, + atan2(-zy, zz), 0f, ETA.withSign(-yx)) return EulerAngles( EulerOrder.XZY, diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index 67e8fd762..d756e4b7c 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -4,10 +4,6 @@ package io.github.axisangles.ktmath import kotlin.math.* -/** - * A Quaternion class properly implementing Quaternions as a real component and 3 imaginary components - * All operations are well-defined - */ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { companion object { val NULL = Quaternion(0f, 0f, 0f, 0f) @@ -138,7 +134,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { /** * computes the inverse of this quaternion - * @return the inversed quaternion + * @return the inverse quaternion **/ fun inv(): Quaternion { val lenSq = lenSq() @@ -203,42 +199,13 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { **/ fun pow(t: Float): Quaternion = (log() * t).exp() - // for a slight improvement in performance - // not fully implemented -// fun pow(t: Float): Quaternion { -// val imLen = xyz.Len() -// val ang = atan(w, imLen) -// -// val len = len().pow(t) -// val co = cos(t*ang) -// val si = sin(t*ang) -// -// return if (imLen == 0f) { -// Quaternion(len*co, -// len*t*x, -// len*t*y, -// len*t*z -// ) -// } else { -// Quaternion( -// len*co, -// len*si*x/imLen, -// len*si*y/imLen, -// len*si*z/imLen -// ) -// } -// } - /** - * between this and -this, picks the one nearest to that + * between this and -this, picks the one nearest to that quaternion * @param that the quaternion to be nearest * @return nearest quaternion **/ - fun twinNearest(that: Quaternion): Quaternion = if (this.dot(that) < 0f) { - -this - } else { - this - } + fun twinNearest(that: Quaternion): Quaternion = + if (this.dot(that) < 0f) -this else this /** * interpolates from this quaternion to that quaternion by t in quaternion space @@ -246,7 +213,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param t the amount to interpolate * @return interpolated quaternion **/ - fun interp(that: Quaternion, t: Float) = + fun interpQ(that: Quaternion, t: Float) = if (t == 0f) { this } else if (t == 1f) { @@ -263,7 +230,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param t the amount to interpolate * @return interpolated quaternion **/ - fun interpR(that: Quaternion, t: Float) = this.interp(that.twinNearest(this), t) + fun interpR(that: Quaternion, t: Float) = this.interpQ(that.twinNearest(this), t) /** * linearly interpolates from this quaternion to that quaternion by t in @@ -272,7 +239,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param t the amount to interpolate * @return interpolated quaternion **/ - fun lerp(that: Quaternion, t: Float): Quaternion = (1f - t) * this + t * that + fun lerpQ(that: Quaternion, t: Float): Quaternion = (1f - t) * this + t * that /** * linearly interpolates from this quaternion to that quaternion by t in @@ -281,13 +248,13 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param t the amount to interpolate * @return interpolated quaternion **/ - fun lerpR(that: Quaternion, t: Float) = this.lerp(that.twinNearest(this), t) + fun lerpR(that: Quaternion, t: Float) = this.lerpQ(that.twinNearest(this), t) /** * computes this quaternion's angle to identity in quaternion space * @return angle **/ - fun angle(): Float = atan2(xyz.len(), w) + fun angleQ(): Float = atan2(xyz.len(), w) /** * computes this quaternion's angle to identity in rotation space @@ -300,7 +267,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param that the other quaternion * @return angle **/ - fun angleTo(that: Quaternion): Float = (this / that).angle() + fun angleToQ(that: Quaternion): Float = (this / that).angleQ() /** * computes the angle between this quaternion and that quaternion in rotation space @@ -314,7 +281,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param u the axis * @return angle **/ - fun angleAbout(u: Vector3): Float { + fun angleAboutQ(u: Vector3): Float { val si = u.dot(xyz) val co = u.len() * w return atan2(si, co) @@ -325,7 +292,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { * @param u the axis * @return angle **/ - fun angleAboutR(u: Vector3): Float = 2f * twinNearest(IDENTITY).angleAbout(u) + fun angleAboutR(u: Vector3): Float = 2f * twinNearest(IDENTITY).angleAboutQ(u) /** * finds Q, the quaternion nearest to this quaternion representing a rotation purely @@ -365,7 +332,7 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { fun sandwich(that: Vector3): Vector3 = (this * Quaternion(0f, that) / this).xyz /** - * computes this quaternion's rotation axis + * computes this quaternion's unit length rotation axis * @return rotation axis **/ fun axis(): Vector3 = xyz.unit() @@ -384,9 +351,9 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { val d = lenSq() /* ktlint-disable */ return Matrix3( - (w*w + x*x - y*y - z*z)/d, 2f*(x*y - w*z)/d, 2f*(w*y + x*z)/d, - 2f*(x*y + w*z)/d, (w*w - x*x + y*y - z*z)/d, 2f*(y*z - w*x)/d, - 2f*(x*z - w*y)/d, 2f*(w*x + y*z)/d, (w*w - x*x - y*y + z*z)/d) + (w*w + x*x - y*y - z*z)/d , 2f*(x*y - w*z)/d , 2f*(w*y + x*z)/d , + 2f*(x*y + w*z)/d , (w*w - x*x + y*y - z*z)/d , 2f*(y*z - w*x)/d , + 2f*(x*z - w*y)/d , 2f*(w*x + y*z)/d , (w*w - x*x - y*y + z*z)/d ) /* ktlint-enable */ } diff --git a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt index e3223100a..5b5e4d95b 100644 --- a/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt +++ b/server/src/test/java/io/github/axisangles/ktmath/QuaternionTest.kt @@ -77,11 +77,11 @@ class QuaternionTest { } @Test - fun interp() { + fun interpQ() { val q1 = Quaternion(1f, 2f, 3f, 4f) val q2 = Quaternion(5f, 6f, 7f, 8f) val q3 = Quaternion(2.405691f, 3.5124686f, 4.619246f, 5.7260237f) - assertEquals(q1.interp(q2, 0.5f), q3, 1e-7) + assertEquals(q1.interpQ(q2, 0.5f), q3, 1e-7) } @Test @@ -93,11 +93,11 @@ class QuaternionTest { } @Test - fun lerp() { + fun lerpQ() { val q1 = Quaternion(1f, 2f, 3f, 4f) val q2 = Quaternion(5f, 6f, 7f, 8f) val q3 = Quaternion(3f, 4f, 5f, 6f) - assertEquals(q1.lerp(q2, 0.5f), q3, 1e-7) + assertEquals(q1.lerpQ(q2, 0.5f), q3, 1e-7) } @Test @@ -109,10 +109,10 @@ class QuaternionTest { } @Test - fun angleTo() { + fun angleToQ() { val q1 = Quaternion(1f, 0f, 0f, 0f) val q2 = Quaternion(0f, 1f, 0f, 0f) - assertEquals(q1.angleTo(q2), PI.toFloat() / 2f) + assertEquals(q1.angleToQ(q2), PI.toFloat() / 2f) } @Test @@ -123,9 +123,9 @@ class QuaternionTest { } @Test - fun angle() { + fun angleQ() { val q = Quaternion(0f, 1f, 0f, 0f) - assertEquals(q.angle(), PI.toFloat() / 2f) + assertEquals(q.angleQ(), PI.toFloat() / 2f) } @Test @@ -135,9 +135,9 @@ class QuaternionTest { } @Test - fun angleAbout() { + fun angleAboutQ() { val q = Quaternion(1f, 1f, 1f, 0f) - assertEquals(q.angleAbout(Vector3.POS_Y), PI.toFloat() / 4f) + assertEquals(q.angleAboutQ(Vector3.POS_Y), PI.toFloat() / 4f) } @Test From b45e37ce4bf3926cd722ce65e7ea2584bc3435e4 Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Sat, 28 Jan 2023 23:25:12 -0800 Subject: [PATCH 8/9] how --- server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt index d756e4b7c..be13fc413 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Quaternion.kt @@ -12,7 +12,6 @@ data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) { val J = Quaternion(0f, 0f, 1f, 0f) val K = Quaternion(0f, 0f, 0f, 1f) - // creates a new quaternion representing the rotation about axis v by rotational angle v /** * creates a new quaternion representing the rotation about v's axis * by an angle of v's length From bc69532d9abb84b3af44018b006b4314419411ac Mon Sep 17 00:00:00 2001 From: AxisAngles Date: Wed, 1 Feb 2023 23:30:01 -0800 Subject: [PATCH 9/9] Improved conditions for toEulerAngles mathematics Added comment justifying orthonormalize method --- .../io/github/axisangles/ktmath/Matrix3.kt | 66 ++++++++++++------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt index dc6787dec..90818007c 100644 --- a/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt +++ b/server/src/main/java/io/github/axisangles/ktmath/Matrix3.kt @@ -158,6 +158,28 @@ data class Matrix3( ) } + /* + The following method returns the best guess rotation matrix. + In general, a square matrix can be represented as an + orthogonal matrix * symmetric matrix. + M = O*S + A symmetric matrix's transpose is itself. + An orthogonal matrix's transpose is its inverse. + S^T = S + O^T = O^-1 + If we perform the following process, we can factor out O. + M + M^-T + = O*S + (O*S)^-T + = O*S + O^-T*S^-T + = O*S + O*S^-T + = O*(S + S^-T) + So we see if we perform M + M^-T, the rotation, O, remains unchanged. + Iterating M = (M + M^-T)/2, we converge the symmetric part to identity. + + This converges exponentially (one digit per iteration) when it is far from a + rotation matrix, and quadratically (double the digits each iteration) when it + is close to a rotation matrix. + */ /** * computes the nearest orthonormal matrix to this matrix * @return the rotation matrix @@ -216,13 +238,13 @@ data class Matrix3( */ fun toQuaternionAssumingOrthonormal(): Quaternion { return if (yy > -zz && zz > -xx && xx > -yy) { - Quaternion(1 + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() + Quaternion(1f + xx + yy + zz, yz - zy, zx - xz, xy - yx).unit() } else if (xx > yy && xx > zz) { - Quaternion(yz - zy, 1 + xx - yy - zz, xy + yx, xz + zx).unit() + Quaternion(yz - zy, 1f + xx - yy - zz, xy + yx, xz + zx).unit() } else if (yy > zz) { - Quaternion(zx - xz, xy + yx, 1 - xx + yy - zz, yz + zy).unit() + Quaternion(zx - xz, xy + yx, 1f - xx + yy - zz, yz + zy).unit() } else { - Quaternion(xy - yx, xz + zx, yz + zy, 1 - xx - yy + zz).unit() + Quaternion(xy - yx, xz + zx, yz + zy, 1f - xx - yy + zz).unit() } } @@ -308,76 +330,76 @@ data class Matrix3( val ETA = 1.5707964f when (order) { EulerOrder.XYZ -> { - val kc = zy * zy + zz * zz - if (kc == 0f) return EulerAngles(EulerOrder.XYZ, + val kc = sqrt(zy * zy + zz * zz) + if (kc < 1e-7f) return EulerAngles(EulerOrder.XYZ, atan2(yz, yy), ETA.withSign(zx), 0f) return EulerAngles( EulerOrder.XYZ, atan2(-zy, zz), - atan2(zx, sqrt(kc)), + atan2(zx, kc), atan2(xy * zz - xz * zy, yy * zz - yz * zy) ) } EulerOrder.YZX -> { - val kc = xx * xx + xz * xz - if (kc == 0f) return EulerAngles(EulerOrder.YZX, + val kc = sqrt(xx * xx + xz * xz) + if (kc < 1e-7f) return EulerAngles(EulerOrder.YZX, 0f, atan2(zx, zz), ETA.withSign(xy)) return EulerAngles( EulerOrder.YZX, atan2(xx * yz - xz * yx, xx * zz - xz * zx), atan2(-xz, xx), - atan2(xy, sqrt(kc)) + atan2(xy, kc) ) } EulerOrder.ZXY -> { - val kc = yy * yy + yx * yx - if (kc == 0f) return EulerAngles(EulerOrder.ZXY, + val kc = sqrt(yy * yy + yx * yx) + if (kc < 1e-7f) return EulerAngles(EulerOrder.ZXY, ETA.withSign(yz), 0f, atan2(xy, xx)) return EulerAngles( EulerOrder.ZXY, - atan2(yz, sqrt(kc)), + atan2(yz, kc), atan2(yy * zx - yx * zy, yy * xx - yx * xy), atan2(-yx, yy) ) } EulerOrder.ZYX -> { - val kc = xy * xy + xx * xx - if (kc == 0f) return EulerAngles(EulerOrder.ZYX, + val kc = sqrt(xy * xy + xx * xx) + if (kc < 1e-7f) return EulerAngles(EulerOrder.ZYX, 0f, ETA.withSign(-xz), atan2(-yx, yy)) return EulerAngles( EulerOrder.ZYX, atan2(zx * xy - zy * xx, yy * xx - yx * xy), - atan2(-xz, sqrt(kc)), + atan2(-xz, kc), atan2(xy, xx) ) } EulerOrder.YXZ -> { - val kc = zx * zx + zz * zz - if (kc == 0f) return EulerAngles(EulerOrder.YXZ, + val kc = sqrt(zx * zx + zz * zz) + if (kc < 1e-7f) return EulerAngles(EulerOrder.YXZ, ETA.withSign(-zy), atan2(-xz, xx), 0f) return EulerAngles( EulerOrder.YXZ, - atan2(-zy, sqrt(kc)), + atan2(-zy, kc), atan2(zx, zz), atan2(yz * zx - yx * zz, xx * zz - xz * zx) ) } EulerOrder.XZY -> { - val kc = yz * yz + yy * yy - if (kc == 0f) return EulerAngles(EulerOrder.XZY, + val kc = sqrt(yz * yz + yy * yy) + if (kc < 1e-7f) return EulerAngles(EulerOrder.XZY, atan2(-zy, zz), 0f, ETA.withSign(-yx)) return EulerAngles( EulerOrder.XZY, atan2(yz, yy), atan2(xy * yz - xz * yy, zz * yy - zy * yz), - atan2(-yx, sqrt(kc)) + atan2(-yx, kc) ) } }