├── .github └── workflows │ └── continuous.yml ├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── armadillo.gif ├── armadillo_cut_low.obj ├── cmake └── libigl.cmake └── main.cpp /.github/workflows/continuous.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | #################### 13 | # Linux / macOS 14 | #################### 15 | 16 | Unix: 17 | name: ${{ matrix.name }} (${{ matrix.config }}) 18 | runs-on: ${{ matrix.os }} 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | os: [ubuntu-20.04, macos-latest] 23 | config: [Release] 24 | include: 25 | - os: macos-latest 26 | name: macOS 27 | - os: ubuntu-20.04 28 | name: Linux 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@v1 32 | with: 33 | fetch-depth: 10 34 | 35 | - name: Dependencies (Linux) 36 | if: runner.os == 'Linux' 37 | run: | 38 | sudo apt-get update 39 | sudo apt-get install \ 40 | libglu1-mesa-dev \ 41 | xorg-dev \ 42 | ccache 43 | 44 | - name: Dependencies (macOS) 45 | if: runner.os == 'macOS' 46 | run: brew install ccache 47 | 48 | - name: Cache Build 49 | id: cache-build 50 | uses: actions/cache@v1 51 | with: 52 | path: ~/.ccache 53 | key: ${{ runner.os }}-${{ matrix.config }}-${{ matrix.static }}-cache 54 | 55 | - name: Prepare ccache 56 | run: | 57 | ccache --max-size=1.0G 58 | ccache -V && ccache --show-stats && ccache --zero-stats 59 | 60 | - name: Configure 61 | run: | 62 | mkdir -p build 63 | cd build 64 | cmake .. \ 65 | -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ 66 | -DCMAKE_BUILD_TYPE=${{ matrix.config }} 67 | 68 | - name: Build 69 | run: cd build; make -j2; ccache --show-stats 70 | 71 | #################### 72 | # Windows 73 | #################### 74 | 75 | Windows: 76 | name: Windows (${{ matrix.config }}) 77 | runs-on: windows-2019 78 | env: 79 | CC: cl.exe 80 | CXX: cl.exe 81 | strategy: 82 | fail-fast: false 83 | matrix: 84 | config: [Release] 85 | steps: 86 | - name: Checkout repository 87 | uses: actions/checkout@v1 88 | with: 89 | fetch-depth: 10 90 | 91 | - name: Install Ninja 92 | uses: seanmiddleditch/gha-setup-ninja@master 93 | 94 | - name: Set env variable for sccache 95 | run: | 96 | echo "appdata=$env:LOCALAPPDATA" >> ${env:GITHUB_ENV} 97 | 98 | - name: Cache build 99 | id: cache-build 100 | uses: actions/cache@v1 101 | with: 102 | path: ${{ env.appdata }}\Mozilla\sccache 103 | key: ${{ runner.os }}-${{ matrix.config }}-${{ matrix.static }}-cache 104 | 105 | - name: Prepare sccache 106 | run: | 107 | iwr -useb 'https://raw.githubusercontent.com/scoopinstaller/install/master/install.ps1' -outfile 'install.ps1' 108 | .\install.ps1 -RunAsAdmin 109 | scoop install sccache --global 110 | # Scoop modifies the PATH so we make it available for the next steps of the job 111 | echo "${env:PATH}" >> ${env:GITHUB_PATH} 112 | 113 | # We run configure + build in the same step, since they both need to call VsDevCmd 114 | # Also, cmd uses ^ to break commands into multiple lines (in powershell this is `) 115 | - name: Configure and build 116 | shell: cmd 117 | run: | 118 | call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\Tools\VsDevCmd.bat" -arch=x64 119 | cmake -G Ninja ^ 120 | -DCMAKE_CXX_COMPILER_LAUNCHER=sccache ^ 121 | -DCMAKE_BUILD_TYPE=${{ matrix.config }} ^ 122 | -DCMAKE_JOB_POOLS=pool-linking=1;pool-compilation=2 ^ 123 | -DCMAKE_JOB_POOL_COMPILE:STRING=pool-compilation ^ 124 | -DCMAKE_JOB_POOL_LINK:STRING=pool-linking ^ 125 | -B build ^ 126 | -S . 127 | cmake --build build 128 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | 30 | *.un~ 31 | *.swo 32 | *.swp 33 | 34 | build/* 35 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.16) 2 | project(example) 3 | 4 | list(PREPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) 5 | 6 | # Libigl 7 | include(libigl) 8 | 9 | # Enable the target igl::glfw 10 | igl_include(glfw) 11 | 12 | include(FetchContent) 13 | FetchContent_Declare( 14 | tinyad 15 | GIT_REPOSITORY https://github.com/patr-schm/tinyad.git 16 | GIT_TAG 75093e14ef0d7bb39657c5f3b2aba1251afaa38c 17 | ) 18 | #FetchContent_MakeAvailable(tinyad) 19 | 20 | FetchContent_GetProperties(tinyad) 21 | if(NOT tinyad_POPULATED) 22 | # Fetch the content using previously declared details 23 | FetchContent_Populate(tinyad) 24 | message(STATUS "tinyad_SOURCE_DIR: ${tinyad_SOURCE_DIR}") 25 | message(STATUS "tinyad_BINARY_DIR: ${tinyad_BINARY_DIR}") 26 | add_subdirectory(${tinyad_SOURCE_DIR} ${tinyad_BINARY_DIR}) 27 | endif() 28 | 29 | # Add your project files 30 | file(GLOB SRC_FILES *.cpp) 31 | add_executable(${PROJECT_NAME} ${SRC_FILES}) 32 | target_compile_definitions(${PROJECT_NAME} PUBLIC SOURCE_PATH="${CMAKE_CURRENT_SOURCE_DIR}") 33 | target_link_libraries(${PROJECT_NAME} PUBLIC igl::glfw TinyAD) 34 | # tinyad needs C++17 (not sure if that means this project does too) 35 | target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17) 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. "Contributor" 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. "Contributor Version" 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. "Covered Software" 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the terms of 34 | a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. "Larger Work" 41 | 42 | means a work that combines Covered Software with other material, in a 43 | separate file or files, that is not Covered Software. 44 | 45 | 1.8. "License" 46 | 47 | means this document. 48 | 49 | 1.9. "Licensable" 50 | 51 | means having the right to grant, to the maximum extent possible, whether 52 | at the time of the initial grant or subsequently, any and all of the 53 | rights conveyed by this License. 54 | 55 | 1.10. "Modifications" 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, 60 | deletion from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. "Patent Claims" of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, 67 | process, and apparatus claims, in any patent Licensable by such 68 | Contributor that would be infringed, but for the grant of the License, 69 | by the making, using, selling, offering for sale, having made, import, 70 | or transfer of either its Contributions or its Contributor Version. 71 | 72 | 1.12. "Secondary License" 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. "Source Code Form" 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. "You" (or "Your") 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, "You" includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, "control" means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or 104 | as part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its 108 | Contributions or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution 113 | become effective for each Contribution on the date the Contributor first 114 | distributes such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under 119 | this License. No additional rights or licenses will be implied from the 120 | distribution or licensing of Covered Software under this License. 121 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 122 | Contributor: 123 | 124 | a. for any code that a Contributor has removed from Covered Software; or 125 | 126 | b. for infringements caused by: (i) Your and any other third party's 127 | modifications of Covered Software, or (ii) the combination of its 128 | Contributions with other software (except as part of its Contributor 129 | Version); or 130 | 131 | c. under Patent Claims infringed by Covered Software in the absence of 132 | its Contributions. 133 | 134 | This License does not grant any rights in the trademarks, service marks, 135 | or logos of any Contributor (except as may be necessary to comply with 136 | the notice requirements in Section 3.4). 137 | 138 | 2.4. Subsequent Licenses 139 | 140 | No Contributor makes additional grants as a result of Your choice to 141 | distribute the Covered Software under a subsequent version of this 142 | License (see Section 10.2) or under the terms of a Secondary License (if 143 | permitted under the terms of Section 3.3). 144 | 145 | 2.5. Representation 146 | 147 | Each Contributor represents that the Contributor believes its 148 | Contributions are its original creation(s) or it has sufficient rights to 149 | grant the rights to its Contributions conveyed by this License. 150 | 151 | 2.6. Fair Use 152 | 153 | This License is not intended to limit any rights You have under 154 | applicable copyright doctrines of fair use, fair dealing, or other 155 | equivalents. 156 | 157 | 2.7. Conditions 158 | 159 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 160 | Section 2.1. 161 | 162 | 163 | 3. Responsibilities 164 | 165 | 3.1. Distribution of Source Form 166 | 167 | All distribution of Covered Software in Source Code Form, including any 168 | Modifications that You create or to which You contribute, must be under 169 | the terms of this License. You must inform recipients that the Source 170 | Code Form of the Covered Software is governed by the terms of this 171 | License, and how they can obtain a copy of this License. You may not 172 | attempt to alter or restrict the recipients' rights in the Source Code 173 | Form. 174 | 175 | 3.2. Distribution of Executable Form 176 | 177 | If You distribute Covered Software in Executable Form then: 178 | 179 | a. such Covered Software must also be made available in Source Code Form, 180 | as described in Section 3.1, and You must inform recipients of the 181 | Executable Form how they can obtain a copy of such Source Code Form by 182 | reasonable means in a timely manner, at a charge no more than the cost 183 | of distribution to the recipient; and 184 | 185 | b. You may distribute such Executable Form under the terms of this 186 | License, or sublicense it under different terms, provided that the 187 | license for the Executable Form does not attempt to limit or alter the 188 | recipients' rights in the Source Code Form under this License. 189 | 190 | 3.3. Distribution of a Larger Work 191 | 192 | You may create and distribute a Larger Work under terms of Your choice, 193 | provided that You also comply with the requirements of this License for 194 | the Covered Software. If the Larger Work is a combination of Covered 195 | Software with a work governed by one or more Secondary Licenses, and the 196 | Covered Software is not Incompatible With Secondary Licenses, this 197 | License permits You to additionally distribute such Covered Software 198 | under the terms of such Secondary License(s), so that the recipient of 199 | the Larger Work may, at their option, further distribute the Covered 200 | Software under the terms of either this License or such Secondary 201 | License(s). 202 | 203 | 3.4. Notices 204 | 205 | You may not remove or alter the substance of any license notices 206 | (including copyright notices, patent notices, disclaimers of warranty, or 207 | limitations of liability) contained within the Source Code Form of the 208 | Covered Software, except that You may alter any license notices to the 209 | extent required to remedy known factual inaccuracies. 210 | 211 | 3.5. Application of Additional Terms 212 | 213 | You may choose to offer, and to charge a fee for, warranty, support, 214 | indemnity or liability obligations to one or more recipients of Covered 215 | Software. However, You may do so only on Your own behalf, and not on 216 | behalf of any Contributor. You must make it absolutely clear that any 217 | such warranty, support, indemnity, or liability obligation is offered by 218 | You alone, and You hereby agree to indemnify every Contributor for any 219 | liability incurred by such Contributor as a result of warranty, support, 220 | indemnity or liability terms You offer. You may include additional 221 | disclaimers of warranty and limitations of liability specific to any 222 | jurisdiction. 223 | 224 | 4. Inability to Comply Due to Statute or Regulation 225 | 226 | If it is impossible for You to comply with any of the terms of this License 227 | with respect to some or all of the Covered Software due to statute, 228 | judicial order, or regulation then You must: (a) comply with the terms of 229 | this License to the maximum extent possible; and (b) describe the 230 | limitations and the code they affect. Such description must be placed in a 231 | text file included with all distributions of the Covered Software under 232 | this License. Except to the extent prohibited by statute or regulation, 233 | such description must be sufficiently detailed for a recipient of ordinary 234 | skill to be able to understand it. 235 | 236 | 5. Termination 237 | 238 | 5.1. The rights granted under this License will terminate automatically if You 239 | fail to comply with any of its terms. However, if You become compliant, 240 | then the rights granted under this License from a particular Contributor 241 | are reinstated (a) provisionally, unless and until such Contributor 242 | explicitly and finally terminates Your grants, and (b) on an ongoing 243 | basis, if such Contributor fails to notify You of the non-compliance by 244 | some reasonable means prior to 60 days after You have come back into 245 | compliance. Moreover, Your grants from a particular Contributor are 246 | reinstated on an ongoing basis if such Contributor notifies You of the 247 | non-compliance by some reasonable means, this is the first time You have 248 | received notice of non-compliance with this License from such 249 | Contributor, and You become compliant prior to 30 days after Your receipt 250 | of the notice. 251 | 252 | 5.2. If You initiate litigation against any entity by asserting a patent 253 | infringement claim (excluding declaratory judgment actions, 254 | counter-claims, and cross-claims) alleging that a Contributor Version 255 | directly or indirectly infringes any patent, then the rights granted to 256 | You by any and all Contributors for the Covered Software under Section 257 | 2.1 of this License shall terminate. 258 | 259 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 260 | license agreements (excluding distributors and resellers) which have been 261 | validly granted by You or Your distributors under this License prior to 262 | termination shall survive termination. 263 | 264 | 6. Disclaimer of Warranty 265 | 266 | Covered Software is provided under this License on an "as is" basis, 267 | without warranty of any kind, either expressed, implied, or statutory, 268 | including, without limitation, warranties that the Covered Software is free 269 | of defects, merchantable, fit for a particular purpose or non-infringing. 270 | The entire risk as to the quality and performance of the Covered Software 271 | is with You. Should any Covered Software prove defective in any respect, 272 | You (not any Contributor) assume the cost of any necessary servicing, 273 | repair, or correction. This disclaimer of warranty constitutes an essential 274 | part of this License. No use of any Covered Software is authorized under 275 | this License except under this disclaimer. 276 | 277 | 7. Limitation of Liability 278 | 279 | Under no circumstances and under no legal theory, whether tort (including 280 | negligence), contract, or otherwise, shall any Contributor, or anyone who 281 | distributes Covered Software as permitted above, be liable to You for any 282 | direct, indirect, special, incidental, or consequential damages of any 283 | character including, without limitation, damages for lost profits, loss of 284 | goodwill, work stoppage, computer failure or malfunction, or any and all 285 | other commercial damages or losses, even if such party shall have been 286 | informed of the possibility of such damages. This limitation of liability 287 | shall not apply to liability for death or personal injury resulting from 288 | such party's negligence to the extent applicable law prohibits such 289 | limitation. Some jurisdictions do not allow the exclusion or limitation of 290 | incidental or consequential damages, so this exclusion and limitation may 291 | not apply to You. 292 | 293 | 8. Litigation 294 | 295 | Any litigation relating to this License may be brought only in the courts 296 | of a jurisdiction where the defendant maintains its principal place of 297 | business and such litigation shall be governed by laws of that 298 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 299 | in this Section shall prevent a party's ability to bring cross-claims or 300 | counter-claims. 301 | 302 | 9. Miscellaneous 303 | 304 | This License represents the complete agreement concerning the subject 305 | matter hereof. If any provision of this License is held to be 306 | unenforceable, such provision shall be reformed only to the extent 307 | necessary to make it enforceable. Any law or regulation which provides that 308 | the language of a contract shall be construed against the drafter shall not 309 | be used to construe this License against a Contributor. 310 | 311 | 312 | 10. Versions of the License 313 | 314 | 10.1. New Versions 315 | 316 | Mozilla Foundation is the license steward. Except as provided in Section 317 | 10.3, no one other than the license steward has the right to modify or 318 | publish new versions of this License. Each version will be given a 319 | distinguishing version number. 320 | 321 | 10.2. Effect of New Versions 322 | 323 | You may distribute the Covered Software under the terms of the version 324 | of the License under which You originally received the Covered Software, 325 | or under the terms of any subsequent version published by the license 326 | steward. 327 | 328 | 10.3. Modified Versions 329 | 330 | If you create software not governed by this License, and you want to 331 | create a new license for such software, you may create and use a 332 | modified version of this License if you rename the license and remove 333 | any references to the name of the license steward (except to note that 334 | such modified license differs from this License). 335 | 336 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 337 | Licenses If You choose to distribute Source Code Form that is 338 | Incompatible With Secondary Licenses under the terms of this version of 339 | the License, the notice described in Exhibit B of this License must be 340 | attached. 341 | 342 | Exhibit A - Source Code Form License Notice 343 | 344 | This Source Code Form is subject to the 345 | terms of the Mozilla Public License, v. 346 | 2.0. If a copy of the MPL was not 347 | distributed with this file, You can 348 | obtain one at 349 | http://mozilla.org/MPL/2.0/. 350 | 351 | If it is not possible or desirable to put the notice in a particular file, 352 | then You may include the notice in a location (such as a LICENSE file in a 353 | relevant directory) where a recipient would be likely to look for such a 354 | notice. 355 | 356 | You may add additional accurate notices of copyright ownership. 357 | 358 | Exhibit B - "Incompatible With Secondary Licenses" Notice 359 | 360 | This Source Code Form is "Incompatible 361 | With Secondary Licenses", as defined by 362 | the Mozilla Public License, v. 2.0. 363 | 364 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libigl 🤝 TinyAD 2 | 3 | A small example project mixing [libigl](https://github.com/libigl/libigl/) and 4 | [TinyAD](https://github.com/patr-schm/TinyAD). Launches the libigl viewer while 5 | in a separate thread optimizing an armadillo mesh's parametrization. 6 | 7 | ## Compile 8 | 9 | Compile this project using the standard cmake routine: 10 | 11 | mkdir build 12 | cd build 13 | cmake .. 14 | make 15 | 16 | This should find and build the dependencies and create a `example` binary. 17 | 18 | ## Run 19 | 20 | From within the `build` directory just issue: 21 | 22 | ./example 23 | 24 | A glfw app should launch displaying an animating Armadillo parametrization. 25 | 26 | ![](armadillo.gif) 27 | 28 | _Derived from 29 | [parametrization_libigl.cc](https://github.com/patr-schm/TinyAD-Examples/blob/main/apps/parametrization_libigl.cc)_ 30 | 31 | ## Ordering 32 | 33 | TinyAD operates most conveniently on nodal vector values (e.g., vertex positions in `V`). If `V` contains nodal vectors **per row**, then regardless of whether `V` is stored as column-major (e.g., `Eigen::MatrixXd`) or row-major (e.g., `Eigen::Matrix`) the internal order of tiny-ad will correspond to [non-standard](https://en.wikipedia.org/wiki/Vectorization_(mathematics)) **row-major vectorization**. 34 | 35 | That is, if 36 | ``` 37 | V = [ 38 | x₀ y₀ z₀ 39 | x₁ y₁ z₁ 40 | … 41 | xₙ yₙ zₙ 42 | ] 43 | ``` 44 | 45 | Then TinyAD will vectorize this into 46 | ``` 47 | x = [ 48 | x₀ 49 | y₀ 50 | z₀ 51 | x₁ 52 | y₁ 53 | z₁ 54 | … 55 | xₙ 56 | yₙ 57 | zₙ 58 | ] 59 | ``` 60 | 61 | And use a corresponding ordering for gradients and Hessians. 62 | 63 | This is ignorable if you're using the provided `func.x_from_data` and `func.x_to_data`. However, if you're mixing in your own gradients, Hessians, constraint projections, subspace bases, then take care! 64 | -------------------------------------------------------------------------------- /armadillo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alecjacobson/libigl-tinyad-example/dd65e30bd520af1e9ae4371d32a25f83fd6df18b/armadillo.gif -------------------------------------------------------------------------------- /cmake/libigl.cmake: -------------------------------------------------------------------------------- 1 | if(TARGET igl::core) 2 | return() 3 | endif() 4 | 5 | include(FetchContent) 6 | FetchContent_Declare( 7 | libigl 8 | GIT_REPOSITORY https://github.com/libigl/libigl.git 9 | GIT_TAG v2.5.0 10 | ) 11 | FetchContent_MakeAvailable(libigl) 12 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Adapted from: 3 | * This file is part of TinyAD and released under the MIT license. 4 | * Author: Patrick Schmidt 5 | */ 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | /** 24 | * Compute tutte embedding with boundary on circle. 25 | * Per-vertex 2D coordinates returned as n_vertices-by-2 matrix. 26 | */ 27 | inline Eigen::MatrixXd tutte_embedding( 28 | const Eigen::MatrixXd& _V, 29 | const Eigen::MatrixXi& _F) 30 | { 31 | Eigen::VectorXi b; // #constr boundary constraint indices 32 | Eigen::MatrixXd bc; // #constr-by-2 2D boundary constraint positions 33 | Eigen::MatrixXd P; // #V-by-2 2D vertex positions 34 | igl::boundary_loop(_F, b); // Identify boundary vertices 35 | igl::map_vertices_to_circle(_V, b, bc); // Set boundary vertex positions 36 | igl::harmonic(_F, b, bc, 1, P); // Compute interior vertex positions 37 | 38 | return P; 39 | } 40 | 41 | 42 | /** 43 | * Injectively map a disk-topology triangle mesh to the plane 44 | * and optimize the symmetric Dirichlet energy via projected Newton. 45 | */ 46 | int main() 47 | { 48 | // Read mesh and compute Tutte embedding 49 | Eigen::MatrixXd V; // #V-by-3 3D vertex positions 50 | Eigen::MatrixXi F; // #F-by-3 indices into V 51 | igl::readOBJ(std::string(SOURCE_PATH) + "/armadillo_cut_low.obj", V, F); 52 | Eigen::MatrixXd P = tutte_embedding(V, F); // #V-by-2 2D vertex positions 53 | // 54 | bool redraw = false; 55 | std::mutex m; 56 | std::thread optimization_thread( 57 | [&]() 58 | { 59 | // Pre-compute triangle rest shapes in local coordinate systems 60 | std::vector rest_shapes(F.rows()); 61 | for (int f_idx = 0; f_idx < F.rows(); ++f_idx) 62 | { 63 | // Get 3D vertex positions 64 | Eigen::Vector3d ar_3d = V.row(F(f_idx, 0)); 65 | Eigen::Vector3d br_3d = V.row(F(f_idx, 1)); 66 | Eigen::Vector3d cr_3d = V.row(F(f_idx, 2)); 67 | 68 | // Set up local 2D coordinate system 69 | Eigen::Vector3d n = (br_3d - ar_3d).cross(cr_3d - ar_3d); 70 | Eigen::Vector3d b1 = (br_3d - ar_3d).normalized(); 71 | Eigen::Vector3d b2 = n.cross(b1).normalized(); 72 | 73 | // Express a, b, c in local 2D coordiante system 74 | Eigen::Vector2d ar_2d(0.0, 0.0); 75 | Eigen::Vector2d br_2d((br_3d - ar_3d).dot(b1), 0.0); 76 | Eigen::Vector2d cr_2d((cr_3d - ar_3d).dot(b1), (cr_3d - ar_3d).dot(b2)); 77 | 78 | // Save 2-by-2 matrix with edge vectors as colums 79 | rest_shapes[f_idx] = TinyAD::col_mat(br_2d - ar_2d, cr_2d - ar_2d); 80 | }; 81 | 82 | // Set up function with 2D vertex positions as variables. 83 | auto func = TinyAD::scalar_function<2>(TinyAD::range(V.rows())); 84 | 85 | // Add objective term per face. Each connecting 3 vertices. 86 | func.add_elements<3>(TinyAD::range(F.rows()), [&] (auto& element) -> TINYAD_SCALAR_TYPE(element) 87 | { 88 | // Evaluate element using either double or TinyAD::Double 89 | using T = TINYAD_SCALAR_TYPE(element); 90 | 91 | // Get variable 2D vertex positions 92 | Eigen::Index f_idx = element.handle; 93 | Eigen::Vector2 a = element.variables(F(f_idx, 0)); 94 | Eigen::Vector2 b = element.variables(F(f_idx, 1)); 95 | Eigen::Vector2 c = element.variables(F(f_idx, 2)); 96 | 97 | // Triangle flipped? 98 | Eigen::Matrix2 M = TinyAD::col_mat(b - a, c - a); 99 | if (M.determinant() <= 0.0) 100 | return (T)INFINITY; 101 | 102 | // Get constant 2D rest shape of f 103 | Eigen::Matrix2d Mr = rest_shapes[f_idx]; 104 | double A = 0.5 * Mr.determinant(); 105 | 106 | // Compute symmetric Dirichlet energy 107 | Eigen::Matrix2 J = M * Mr.inverse(); 108 | return A * (J.squaredNorm() + J.inverse().squaredNorm()); 109 | }); 110 | 111 | // Assemble inital x vector from P matrix. 112 | // x_from_data(...) takes a lambda function that maps 113 | // each variable handle (vertex index) to its initial 2D value (Eigen::Vector2d). 114 | Eigen::VectorXd x = func.x_from_data([&] (int v_idx) { 115 | return P.row(v_idx); 116 | }); 117 | 118 | // Projected Newton 119 | TinyAD::LinearSolver solver; 120 | int max_iters = 1000; 121 | double convergence_eps = 1e-2; 122 | for (int i = 0; i < max_iters; ++i) 123 | { 124 | auto [f, g, H_proj] = func.eval_with_hessian_proj(x); 125 | TINYAD_DEBUG_OUT("Energy in iteration " << i << ": " << f); 126 | Eigen::VectorXd d = TinyAD::newton_direction(g, H_proj, solver); 127 | if (TinyAD::newton_decrement(d, g) < convergence_eps) 128 | break; 129 | x = TinyAD::line_search(x, d, f, g, func); 130 | func.x_to_data(x, [&] (int v_idx, const Eigen::Vector2d& p) { 131 | P.row(v_idx) = p; 132 | }); 133 | { 134 | std::lock_guard lock(m); 135 | redraw = true; 136 | } 137 | } 138 | TINYAD_DEBUG_OUT("Final energy: " << func.eval(x)); 139 | 140 | // Write final x vector to P matrix. 141 | // x_to_data(...) takes a lambda function that writes the final value 142 | // of each variable (Eigen::Vector2d) back to our P matrix. 143 | }); 144 | 145 | 146 | // View resulting parametrization 147 | igl::opengl::glfw::Viewer viewer; 148 | viewer.core().is_animating = true; 149 | viewer.data().set_mesh(P, F); 150 | viewer.core().camera_zoom = 2; 151 | viewer.data().show_lines = false; 152 | Eigen::MatrixXd N; 153 | igl::per_vertex_normals(V,F,N); 154 | viewer.data().set_colors( ((N.array()*0.5)+0.5).eval()); 155 | viewer.callback_pre_draw = [&] (igl::opengl::glfw::Viewer& viewer) 156 | { 157 | if(redraw) 158 | { 159 | viewer.data().set_vertices(P); 160 | viewer.core().align_camera_center(P); 161 | viewer.core().camera_zoom = 2; 162 | { 163 | std::lock_guard lock(m); 164 | redraw = false; 165 | } 166 | } 167 | return false; 168 | }; 169 | viewer.launch(); 170 | if(optimization_thread.joinable()) 171 | { 172 | optimization_thread.join(); 173 | } 174 | 175 | return 0; 176 | } 177 | --------------------------------------------------------------------------------