diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aabbc00..e843461 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,10 +3,10 @@ env: JULIA_NUM_THREADS: 2 on: push: - branches: [master] - tags: ['*'] - pull_request: - workflow_dispatch: + branches: + - master + - 'v0.2-revamp' + tags: '*' jobs: test: name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} - ${{ github.event_name }} diff --git a/.gitignore b/.gitignore index 8007493..4fb1ff7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,9 @@ *.jl.mem *.jl.*.mem .DS_Store -/Manifest.toml +Manifest.toml /dev/ /docs/build/ /docs/site/ +/docs/src/examples.md +/docs/src/*.jl diff --git a/LICENSE b/LICENSE index 81ced2c..b9b3466 100644 --- a/LICENSE +++ b/LICENSE @@ -1,297 +1,21 @@ -Copyright (C) 2004-2012 Per-Olof Persson, 2019 Steve Kelly - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS +MIT License + +Copyright (c) 2004-2026 Per-Olof Persson + +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/Project.toml b/Project.toml index 25e2535..d7a9bbf 100644 --- a/Project.toml +++ b/Project.toml @@ -1,22 +1,37 @@ name = "DistMesh" uuid = "f7ee28b6-bfbf-11e9-3e31-8961b86f052c" -authors = ["Steve Kelly "] -version = "0.1.0" +license = "MIT" +version = "0.2.0" +authors = ["Per-Olof Persson "] [deps] -GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +Delaunator = "466f8f70-d5e3-4806-ac0b-a54b75a91218" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" -TetGen = "c5d3f3f7-f850-59f6-8a2e-ffc6dc1317ea" +StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + +[weakdeps] +GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a" +Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" + +[extensions] +DistMeshCairoMakieExt = "CairoMakie" +DistMeshGLMakieExt = ["GLMakie", "GeometryBasics"] +DistMeshPlotsExt = "Plots" [compat] -julia = "1.6" -GeometryBasics = "0.4" -TetGen = "1" +CairoMakie = "0.15" +Delaunator = "0.1" +GLMakie = "0.11, 0.12, 0.13" +LinearAlgebra = "1" +Plots = "1" +StaticArrays = "1.9" +julia = "1.10" [extras] -GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" -TetGen = "c5d3f3f7-f850-59f6-8a2e-ffc6dc1317ea" [targets] -test = ["Test", "GeometryBasics", "TetGen"] +test = ["Test", "CairoMakie"] diff --git a/README.md b/README.md index 85d5afc..fd96ff3 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,66 @@ -# DistMesh +# DistMesh.jl [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://distmesh.juliageometry.org/dev) [![Codecov](https://codecov.io/gh/juliageometry/DistMesh.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/juliageometry/DistMesh.jl) -The package provides a Julia port of the [DistMesh](http://persson.berkeley.edu/distmesh/) algorithm developed by [Per-Olof Persson](http://persson.berkeley.edu/). +**DistMesh.jl** is a Julia generator for unstructured triangular and tetrahedral meshes. It uses [Signed Distance Functions](https://en.wikipedia.org/wiki/Signed_distance_function) (SDFs) to define geometries, enabling the generation of high-quality, isotropic meshes for complex shapes defined by simple mathematical functions. -There have been several improvements made to improve performance and output quality from the original Matlab version. +Primary use cases include Finite Element Analysis (FEA), computational fluid dynamics, and geometric modeling. -[Technical Report](https://sjkellyorg.files.wordpress.com/2020/11/distmesh_sjkelly.pdf) +--- + +## Note on Version 0.2.0 + +Version 0.2.0 represents a major rewrite of `DistMesh.jl`, focusing on replicating the original 2D code but with better performance, native Julia implementations, and integration with the Makie/Plots ecosystems. **This version is now fully MIT licensed.** + +**Legacy Support:** The original N-dimensional meshing code port has been retired in this version to allow for a cleaner architecture. If you require the legacy `distmeshnd` functionality, please pin your package version to v0.1: + +```julia +] add DistMesh@0.1 +``` + +--- + +## Quick Start + +The core function `distmesh2d` generates a mesh based on a distance function, a relative size function, an initial edge length, and a bounding box. + +The code below generates a mesh of the unit circle: + +```julia +using DistMesh + +# Generate mesh: Distance function, size function, resolution, bounding box +msh = distmesh2d(dcircle, huniform, 0.2, ((-1,-1), (1,1))) +``` + +```text +DMesh: 2D, 88 nodes, 143 triangle elements +``` + +Optionally, the mesh can be visualized using various plotting packages: + +```julia +using GLMakie # or Plots, or CairoMakie + +plot(msh) +``` + +![Triangular mesh of the unit circle](docs/src/assets/circle_mesh.png) + +For more details and extensive examples, please see the [DistMesh documentation](https://distmesh.juliageometry.org). + +--- + +## Background + +This package is a Julia port of the [DistMesh](http://persson.berkeley.edu/distmesh/) algorithm developed by [Per-Olof Persson](http://persson.berkeley.edu/). Significant improvements have been made to performance and type stability compared to the original MATLAB implementation. The algorithm is described in the following publications: + +* P.-O. Persson, G. Strang, *[A Simple Mesh Generator in MATLAB](https://persson.berkeley.edu/distmesh/persson04mesh.pdf)*. SIAM Review, Volume 46 (2), pp. 329-345, June 2004. +* P.-O. Persson, *[Mesh Generation for Implicit Geometries](https://persson.berkeley.edu/thesis/persson-thesis-color.pdf)*. Ph.D. thesis, Department of Mathematics, MIT, Dec 2004. + +--- + +## Related Packages + +Several other implementations of the DistMesh algorithm exist in the Julia ecosystem, including [DistMesh-Julia](https://github.com/precise-simulation/distmesh-julia) and [DistMesh2D.jl](https://juliapackages.com/p/distmesh2d). Please consider checking these packages if DistMesh.jl does not meet your specific requirements. diff --git a/bench/.gitignore b/bench/.gitignore deleted file mode 100644 index ff7ba74..0000000 --- a/bench/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.csv -*.json -output/* diff --git a/bench/benchmarks.jl b/bench/benchmarks.jl deleted file mode 100644 index 2b4e886..0000000 --- a/bench/benchmarks.jl +++ /dev/null @@ -1,90 +0,0 @@ -using DistMesh -using BenchmarkTools -using Plots -using Dates -using Descartes -using GeometryBasics -#using JLD -#using HDF5 - -include("util.jl") - -#= -In addition to performance we want to measure the convergence rate. -Ideally this will be somewhat smooth without many fast changes. - -- ttol (retriangulation critera) -- deltat (displacement applied per iteration) - -termination critera: -- ptol (termination critera) -- mamove delta (TBD) - -output for each trial: -- store input parameters (above) -- DistMeshStatistics -- Benchmark Stats -=# - -#= -TODO: - -- Make sure plots have equal yscale -- Consistent quality histogram bins - -Solids: -- Box -- Sphere -- Shelled Sphere -- Torus -- deadmau5 (mouse-head with sphere subtracted from sphere, bad metric distance function) -=# - -# -# Distance Functions -# - -torus(v) = (sqrt(v[1]^2+v[2]^2)-0.5)^2 + v[3]^2 - 0.25 # torus - - -# Define a parent BenchmarkGroup to contain our suite -const suite = BenchmarkGroup() - -# all solids should be in -2:2 for each axis for ease - -println("Benchmarking DistMesh.jl...") - -# -# Algorithms to benchmark -# - -timestamp = Dates.format(now(), "yyyy-mm-ddTHH_MM") -# generate an orthogonal test suite -for ttol in 0.01:0.01:0.05, deltat in 0.05:0.05:0.1, el = 0.1:0.05:0.2 - rt = time() - result = distmesh(torus, - HUniform(), - el, - DistMeshSetup(deltat=deltat,ttol=ttol,distribution=:packed), - origin = GeometryBasics.Point{3,Float64}(-2), - widths = GeometryBasics.Point{3,Float64}(4), - stats=true) - running_time = time() - rt # approximate, since we mostly care about convergence factors - item = "torus$timestamp" - folder = joinpath(@__DIR__, "output") - !isdir(folder) && mkdir(folder) - folder = joinpath(folder, "$item") - !isdir(folder) && mkdir(folder) - param_str = "_ttol=$(ttol)_deltat=$(deltat)_el=$(el)" - # save plots - plotout(result.stats, DistMesh.triangle_qualities(result.points,result.tetrahedra), folder, param_str) - # save dataset as JLD - # jldopen("$folder/$item.jld", "w") do file - # g = g_create(file, param_str) - # g["points"] = p - # g["tets"] = t - # g["stats"] = s - # g["running_time"] = running_time - # end - println(param_str) -end diff --git a/bench/hilbert_perf.jl b/bench/hilbert_perf.jl deleted file mode 100644 index a452fc0..0000000 --- a/bench/hilbert_perf.jl +++ /dev/null @@ -1,12 +0,0 @@ -using DistMesh -using BenchmarkTools -using StaticArrays - -a = [rand(SVector{3,Float64}) for i = 1:50000] - -function test_hilbert(a) - b = copy(a) - DistMesh.hilbertsort!(b) -end - -@benchmark test_hilbert(a) diff --git a/bench/perf.jl b/bench/perf.jl deleted file mode 100644 index 56e7cab..0000000 --- a/bench/perf.jl +++ /dev/null @@ -1,76 +0,0 @@ -using DistMesh -using BenchmarkTools -using GeometryBasics - -# -# DistMesh.jl Performance Benchmarks -# - -# Define a parent BenchmarkGroup to contain our suite -const suite = BenchmarkGroup() -suite["Torus"] = BenchmarkGroup() -suite["Sphere"] = BenchmarkGroup() -suite["Box"] = BenchmarkGroup() - -println("Benchmarking DistMesh.jl...") - -# -# Algorithms to benchmark -# - -algos = [DistMeshSetup(deltat=0.1, distribution=:packed), - DistMeshSetup(distribution=:packed), - DistMeshSetup(deltat=0.1, distribution=:packed,sort=true), - DistMeshSetup(distribution=:packed,sort=true)] - -fn_torus(v) = (sqrt(v[1]^2+v[2]^2)-0.5)^2 + v[3]^2 - 0.25 # torus -fn_sphere(v) = sqrt(sum(v.^2)) -1 -# -# Benchmark algorithms -# - -for algo in algos - for el in (0.15,0.2) - suite["Torus"][string(algo)*" edge="*string(el)] = - @benchmarkable distmesh(fn_torus, - HUniform(), - $el, - $algo, - origin = GeometryBasics.Point{3,Float64}(-2), - widths = GeometryBasics.Point{3,Float64}(4), - stats=false) - suite["Sphere"][string(algo)*" edge="*string(el)] = - @benchmarkable distmesh(fn_sphere, - HUniform(), - $el, - $algo, - origin = GeometryBasics.Point{3,Float64}(-1), - widths = GeometryBasics.Point{3,Float64}(2), - stats=false) - end -end - -# If a cache of tuned parameters already exists, use it, otherwise, tune and cache -# the benchmark parameters. Reusing cached parameters is faster and more reliable -# than re-tuning `suite` every time the file is included. -paramspath = joinpath(dirname(@__FILE__), "params.json") - -if isfile(paramspath) - loadparams!(suite, BenchmarkTools.load(paramspath)[1], :evals); -else - tune!(suite) - BenchmarkTools.save(paramspath, params(suite)); -end - -# -# Perform benchmarks and print results -# - -results = run(suite) - -for trial in results - ctx = IOContext(stdout, :verbose => true, :compact => false) - println(ctx) - println(ctx, trial.first) - println(ctx, trial.second) -end diff --git a/bench/profile.jl b/bench/profile.jl deleted file mode 100644 index d4c5b45..0000000 --- a/bench/profile.jl +++ /dev/null @@ -1,12 +0,0 @@ -using DistMesh -using GeometryBasics -using PProf -using Profile - -fn_sphere(v) = sqrt(sum(v.^2)) -1 -algo = DistMeshSetup(distribution=:packed) - -distmesh(fn_sphere,HUniform(),0.15,algo,origin = GeometryBasics.Point{3,Float64}(-1),widths = GeometryBasics.Point{3,Float64}(2),stats=false) - -Profile.clear() -@pprof distmesh(fn_sphere,HUniform(),0.15,algo,origin = GeometryBasics.Point{3,Float64}(-1),widths = GeometryBasics.Point{3,Float64}(2),stats=false) diff --git a/bench/util.jl b/bench/util.jl deleted file mode 100644 index b4388a0..0000000 --- a/bench/util.jl +++ /dev/null @@ -1,31 +0,0 @@ - -function plotout(statsdata, qualities, folder, name) - - qual_hist = Plots.histogram(qualities, title = "Quality", bins=30, legend=false) - # avg_plt = Plots.plot(statsdata.average_qual, title = "Average Tri Quality", legend=false, ylabel="Quality") - # vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - # med_plt = Plots.plot(statsdata.median_qual, title = "Median Tri Quality", legend=false, ylabel="Quality") - # vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - # min_plt = Plots.plot(statsdata.minimum_qual, title = "Minimum Tri Quality", legend=false, ylabel="Quality") - # vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - # max_plt = Plots.plot(statsdata.maximum_qual, title = "Maximum Tri Quality", legend=false, ylabel="Quality") - # vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - data = hcat(statsdata.average_volume_edge_ratio, statsdata.min_volume_edge_ratio, statsdata.max_volume_edge_ratio) - - tq_plt = Plots.plot(data, title = "Tet Quality", legend=true, label=["Avg","Min","Max"], ylabel="Vol/Edge Ratio") - vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - maxdp_plt = Plots.plot(statsdata.maxdp, title = "Max Displacement", legend=false, ylabel="Edge Displacement") - vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - maxmove_plt = Plots.plot(statsdata.maxmove, title = "Max Move", legend=false, ylabel="Point Displacement") - vline!(statsdata.retriangulations, line=(0.2, :dot, [:red])) - - plt = Plots.plot(tq_plt,maxdp_plt,maxmove_plt,layout=(3,1), xlabel="Iteration") - - savefig(plt, "$folder/result_stat$name.svg") - savefig(qual_hist, "$folder/result_qual$name.svg") -end diff --git a/docs/Project.toml b/docs/Project.toml index eed229d..7c86727 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,3 +1,11 @@ [deps] +CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +DistMesh = "f7ee28b6-bfbf-11e9-3e31-8961b86f052c" Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +Literate = "98b081ad-f1c9-55d3-8b20-4c87d4299306" +StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + +[compat] +CairoMakie = "0.15" +Documenter = "1" diff --git a/docs/make.jl b/docs/make.jl index 3d25b72..7ce5b6c 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -1,15 +1,80 @@ -using Documenter, DistMesh +using Documenter +using DistMesh +using Literate + +# --- 1. Automation Script: Build the "Examples" Page --- + +# Define paths +examples_dir = joinpath(@__DIR__, "..", "examples") +docs_src = joinpath(@__DIR__, "src") +master_file = joinpath(docs_src, "examples.md") + +# Define a preprocessing function +function replace_gl_with_cairo(content) + return replace(content, "using GLMakie" => "using CairoMakie\nCairoMakie.activate!(type=\"png\", px_per_unit=1.0); # hide") +end +# update_theme!(size=(600, 450)) # For setting figure size instead of px_per_unit + +# Initialize the master "Examples" page +open(master_file, "w") do io + write(io, "# Examples\n\nA collection of 2D meshing examples. Note that all the codes are available in the `examples` directory.\n\n") +end + +# Find all .jl files and sort them +jl_files = sort(filter(f -> endswith(f, ".jl"), readdir(examples_dir))) + +for file in jl_files + source_path = joinpath(examples_dir, file) + dest_path = joinpath(docs_src, file) # Copy directly to docs/src/ + + # 1. Copy the .jl file to docs/src/ + # This satisfies Documenter, which looks for the source file next to examples.md + cp(source_path, dest_path, force=true) + + # 2. Run Literate + # We output the .md file to the same folder (docs/src/) to keep paths simple. + # We use name=... to ensure unique scope. + Literate.markdown(dest_path, docs_src; + documenter=true, + credit=false, + name=replace(file, ".jl"=>""), + preprocess = replace_gl_with_cairo + ) + + # 3. Read the generated markdown + md_file = replace(file, ".jl" => ".md") + generated_md_path = joinpath(docs_src, md_file) + content = read(generated_md_path, String) + + # 4. Append it to the master examples.md file + open(master_file, "a") do io + write(io, "\n\n" * content) + end + + # 5. Cleanup the individual .md file (we don't need it anymore, it's in examples.md) + # Note: We KEEP the .jl file in docs/src/ so the "Source" links work. + rm(generated_md_path) +end + +# --- 2. Build Documentation --- makedocs( - modules=[DistMesh], - format=Documenter.HTML(), - pages=[ + sitename = "DistMesh.jl", + modules = [DistMesh], + authors = "Per-Olof Persson ", + pages = [ "Home" => "index.md", + "Examples" => "examples.md", + "API Reference" => "api.md" ], - sitename="DistMesh.jl", - authors="Steve Kelly ", + warnonly = [:missing_docs], + format = Documenter.HTML( + prettyurls = get(ENV, "CI", nothing) == "true" + ) ) deploydocs( - repo="github.com/JuliaGeometry/DistMesh.jl", + repo = "github.com/JuliaGeometry/DistMesh.jl.git", + push_preview = true ) + diff --git a/docs/src/api.md b/docs/src/api.md new file mode 100644 index 0000000..eec30b0 --- /dev/null +++ b/docs/src/api.md @@ -0,0 +1,72 @@ +# API Reference + +## Core Meshing & Types + +The primary interface for generating meshes and handling the resulting data structures. + +```@docs +distmesh2d +DMesh +as_arrays + +``` + +## Distance Functions: Basic Shapes + +Pre-defined signed distance functions for common primitives in 2D and 3D. + +```@docs +dcircle +drectangle +dhypersphere +dsphere +dblock + +``` + +## Distance Functions: Polygons & Lines + +Utilities for working with polygonal boundaries and line segments. + +```@docs +dpoly +dline +DistMesh.inpolygon + +``` + +## Distance Functions: Boolean Operations (CSG) + +Constructive Solid Geometry operations to combine multiple distance functions. + +```@docs +ddiff +dunion +dintersect + +``` + +## Distance Functions: Special Functions + +Helper functions for element sizing and specific test cases (like airfoils). + +```@docs +dnaca + +``` + +## Mesh utilities: Size functions + +```@docs +huniform + +``` + +## Mesh utilities: General + +```@docs +element_volumes +element_qualities +cleanup_mesh + +``` diff --git a/docs/src/assets/circle_mesh.png b/docs/src/assets/circle_mesh.png new file mode 100644 index 0000000..03c05b6 Binary files /dev/null and b/docs/src/assets/circle_mesh.png differ diff --git a/docs/src/index.md b/docs/src/index.md index c80d268..ecab0c4 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -1,53 +1,244 @@ # DistMesh.jl +**DistMesh.jl** is a Julia package for generating unstructured triangular and tetrahedral meshes. It uses [Signed Distance Functions](https://en.wikipedia.org/wiki/Signed_distance_function) (SDFs) to define geometries, enabling the generation of high-quality, isotropic meshes for complex shapes defined by simple mathematical functions. -DistMesh.jl implements simplex refinement on signed distance functions, or anything that -has a sign, distance, and called like a function. The algorithm was first presented -in 2004 by Per-Olof Persson, and was initially a port of the corresponding Matlab Code. +--- -## What is Simplex Refinement? +## Installation -In layman's terms, a simplex is either a triangle in the 2D case, or a tetrahedra in the 3D case. +```julia +using Pkg +Pkg.add("DistMesh") -When simulating, you other want a few things from a mesh of simplices: - - Accurate approximation of boundaries and features - - Adaptive mesh sizes to improve accuracy - - Near-Regular Simplicies +``` + +--- + +## Introduction + +### A Simple Example Mesh + +The primary entry point for 2D meshing is `distmesh2d`. It generates a mesh based on: + +* A **distance function** `fd(p)` (negative inside, positive outside). In this example, we represent the unit circle by $d(x,y) = \sqrt{x^2+y^2} - 1$. +* A **relative size function** `fh(p)`. For a uniform mesh, we can simply set $h(x,y)=1$. +* An **initial element edge length** `h0`. Since our size function is uniform, this will also be roughly the final size of the generated elements. +* A **bounding box** `bbox` for the domain. For the unit circle, we use the coordinates `((-1,-1), (1,1))`. + +The code below demonstrates how to implement this using DistMesh in Julia. + +```@example introduction +using DistMesh +using CairoMakie # or Plots, or GLMakie (optional) +CairoMakie.activate!(type="png", px_per_unit=1.0) # hide + +fd(p) = sqrt(sum(p.^2)) - 1 # or dcircle(p) - unit circle geometry +fh(p) = 1.0 # or huniform(p) - uniform size function +hmin = 0.2 # initial edge lengths +bbox = ((-1,-1), (1,1)) # bounding box for unit circle + +msh = distmesh2d(fd, fh, hmin, bbox) + +``` + +The resulting mesh can be visualized with the `plot` command. + +```@example introduction +plot(msh) + +``` + +### Accessing the generated mesh + +The `msh` object contains the node coordinates `p` and the triangle indices `t`, stored as vectors of static vectors (for efficiency). + +```@example introduction +# Access the nodes and connectivity as vectors of static vectors +p, t = msh +p[1:3] # First 3 nodes + +``` + +```@example introduction +t[1:3] # First 3 triangles (indices) + +``` + +```@example introduction +p[t[1]] # x,y-coordinates of the first triangle + +``` + +If you prefer a matrix-based representation (similar to the original MATLAB DistMesh, except transposed), the utility function `as_arrays` creates a zero-allocation view for this. Note that if you modify these matrices, the original versions in `msh` will also be changed! + +```@example introduction +# Access the nodes and connectivity as matrices +p_mat, t_mat = as_arrays(msh) +p_mat[:, 1:3] # First 3 nodes + +``` + +```@example introduction +t_mat[:, 1:3] # First 3 triangles (indices) + +``` + +```@example introduction +p_mat[:, t_mat[:, 1]] # x,y-coordinates of the first triangle + +``` + +If you want separate re-allocated versions of these matrices, use `collect`. + +### Fixed points + +An optional argument to `distmesh2d` is `pfix` - a vector of frozen points that are forced to be part of the generated mesh. These are typically required for boundaries with sharp corners, since the implicit geometry representation as a signed distance function does not explicitly provide them. + +Here is a simple example of a mesh of a rectangle, where we include the four corner points in `pfix`. + +```@example introduction +fd(p) = drectangle(p, 0, 1, 0, 1) +pfix = ((0,0), (1,0), (0,1), (1,1)) +msh = distmesh2d(fd, huniform, 0.1, ((0,0), (1,1)), pfix) +plot(msh) + +``` + +### Implicit Geometry vs Distance Function + +Although the original version of DistMesh required actual signed distance functions for the geometry, this condition was relaxed in later versions. The algorithm actually accepts any smooth function with an implicitly defined zero level-set. + +This can be very convenient when defining non-trivial geometries. For example, an ellipse with semi-axes 2 and 1 can now be represented as the zero level-set of $d(x,y)=(x/2)^2 + (y/1)^2 - 1$. Note that this is not the actual Euclidean distance function for the ellipse. + +```@example introduction +fd(p) = (p[1]/2)^2 + (p[2]/1)^2 - 1 +bbox = ((-2,-1), (2,1)) +msh = distmesh2d(fd, huniform, 0.2, bbox) +plot(msh) + +``` + +### Non-uniform size function + +For non-uniform element sizes, we provide a (relative) size function $h(x,y)$. In general, it is best to make this an absolute size function that gives the actual desired edge lengths at point . To achieve this, you set the initial edge lengths `hmin` to the smallest value of $h(x,y)$ in the domain. + +For example, to set the element sizes to at a source and let the element sizes increase linearly away from the source, we use a size function $h(x,y)=h_\mathrm{min} + 0.3d(x,y)$ where $d(x,y)$ is the distance function of the source. + +```@example introduction +# Point source +hmin = 0.01 +fh(p) = hmin + 0.3 * dcircle(p, r=0) +msh = distmesh2d(dcircle, fh, hmin, ((-1,-1), (1,1))) +plot(msh) -DistMesh is designed to address the above. +``` -## Algorithm Overview +Multiple size function sources can be combined using the `min` function: -The basic processes is as follows: +```@example introduction +# Point and line sources +fd(p) = drectangle(p, 0, 1, 0, 1) +fh(p) = min(min(0.01 + 0.3*abs(dcircle(p, r=0)), + 0.025 + 0.3*abs(dpoly(p, [(0.3,0.7), (0.7,0.5)]))), + 0.15) +# Note: we explicitly add corners to pfix for the rectangle +pfix = ((0,0), (1,0), (0,1), (1,1)) +msh = distmesh2d(fd, fh, 0.01, ((0,0), (1,1)), pfix) +plot(msh) +``` +### Randomness and Reproducibility -## Comparison to other refinements +The DistMesh algorithm is notoriously *chaotic*, or sensitive to initial conditions. This means that very small perturbations in the mesh calculations can grow to large changes in the mesh (resulting in completely different meshes). -DistMesh generally has a very low memory footprint, and can refine without additional -memory allocation. Similarly, since the global state of simplex qualities is accounted for -in each refinement iteration, this leads to very high quality meshes. +However, running on the same deterministic computer, if you repeat a `distmesh2d` call twice with uniform size functions, it usually gives two identical meshes because it uses a deterministic grid-based initialization: -Aside from the above, since DistMesh works on signed distance functions it can handle -complex and varied input data that are not in the form of surface meshes (Piecewise Linear Complicies). +```@example introduction +msh1 = distmesh2d(dcircle, huniform, 0.2, ((-1,-1), (1,1))) +msh2 = distmesh2d(dcircle, huniform, 0.2, ((-1,-1), (1,1))) +msh1.p == msh2.p && msh1.t == msh2.t -## Difference from the MatLab implementation +``` -Given the same parameters, the Julia implementation of DistMesh will generally perform -4-60 times faster than the MatLab implementation. Delaunay Triangulation in MatLab uses -QHull, whereas DistMesh.jl uses TetGen. +For **non-uniform size functions**, DistMesh uses the `rand` function for the initial point distribution (rejection sampling). This means two meshes with identical inputs will in general not be the same: -## How do I get a Signed Distance Function? +```@example introduction +fh(p) = 0.01 + 0.3 * dcircle(p, r=0) +msh1 = distmesh2d(dcircle, fh, 0.01, ((-1,-1), (1,1))) -Here are some libraries that turn gridded and level set data into an approximate signed -distance function: +``` -- Interpolations.jl -- AdaptiveDistanceFields.jl +```@example introduction +msh2 = distmesh2d(dcircle, fh, 0.01, ((-1,-1), (1,1))) -```@index ``` -```@autodocs -Modules = [DistMesh] +```@example introduction +# Check if they are identical (likely false) +msh1.p == msh2.p && msh1.t == msh2.t + ``` + +Many times this is undesirable (e.g., for regression testing or debugging). You can seed the random number generator to make the meshes identical: + +```@example introduction +using Random +fh(p) = 0.01 + 0.3 * dcircle(p, r=0) + +Random.seed!(1234) +msh1 = distmesh2d(dcircle, fh, 0.01, ((-1,-1), (1,1))) + +``` + +Now we generate the second mesh with the same seed: + +```@example introduction +Random.seed!(1234) +msh2 = distmesh2d(dcircle, fh, 0.01, ((-1,-1), (1,1))) + +``` + +Finally, we verify they are identical: + +```@example introduction +msh1.p == msh2.p && msh1.t == msh2.t + +``` + +### Save/export meshes + +DistMesh does not provide built-in mesh export functionality to external formats. However, it is easy to write specialized routines, e.g., based on text files. + +A common format is to have an initial line with metadata (number of nodes and elements), followed by comma-separated rows for node positions and element connectivities: + +```@example introduction +using DelimitedFiles + +function savemesh(msh::DMesh, fname) + open(fname, "w") do io + p, t = as_arrays(msh) + println(io, "$(length(p)) $(length(t)) # nbr_nodes nbr_elems") + writedlm(io, p', ',') + writedlm(io, t', ',') + end +end + +msh = distmesh2d(dcircle, huniform, 0.2, ((-1,-1), (1,1))) +fname = joinpath(tempdir(), "mesh.dat") +savemesh(msh, fname) +println("Mesh saved to file $fname") + +``` + +--- + +## More about Distance Functions + +TODO + +--- + +## More about Size Functions + +TODO diff --git a/examples/001-polygon.jl b/examples/001-polygon.jl new file mode 100644 index 0000000..cfd673f --- /dev/null +++ b/examples/001-polygon.jl @@ -0,0 +1,28 @@ +# ## Polygon Mesh + +using DistMesh +using GLMakie + +# First, define the vertices of the polygon as a list of points (tuples) +pv = [(-0.4, -0.5), (0.4, -0.2), (0.4, -0.7), (1.5, -0.4), + (0.9, 0.1), (1.6, 0.8), (0.5, 0.5), (0.2, 1.0), + (0.1, 0.4), (-0.7, 0.7), (-0.4, -0.5)]; + +# Next, use the `dpoly` function and these vertices to define the distance function +fd(p) = dpoly(p, pv) + +# We use a uniform mesh size function, with a given desired edge length +hmin = 0.15 +fh = huniform + +# DistMesh also needs a bounding box, which must enclose the polygon +bbox = ((-1,-1), (2,1)) + +# Sharp corners have to be provided in the `pfix` argument +pfix = pv + +# Generate the mesh +msh = distmesh2d(fd, fh, hmin, bbox, pfix) + +# Finally, plot the resulting mesh +plot(msh) diff --git a/examples/002-naca_airfoil.jl b/examples/002-naca_airfoil.jl new file mode 100644 index 0000000..38a9969 --- /dev/null +++ b/examples/002-naca_airfoil.jl @@ -0,0 +1,66 @@ +# ## NACA Airfoil Mesh +# +# This example shows how to generate a mesh around a NACA0012 airfoil. + +# First, load the required packages and define a convenient short-hand +# for static 2D points. + +using DistMesh +using GLMakie +using StaticArrays + +const Point2d = SVector{2, Float64} + +# First, we define the size function for the NACA airfoil. It consists of the minimum of several point sources and constants: +# * A point source at the tip of the airfoil, with size `hlead` +# * A point source at the trailing edge of the airfoil, with size `htrail` +# * A maximum element size in the entire domain `hmax` + +function hnaca(p; hlead=0.01, htrail=0.04, hmax=2.0) + minimum((hlead + 0.3 * dcircle(p, c=(0, 0), r=0), + htrail + 0.3 * dcircle(p, c=(1, 0), r=0), + hmax)) +end + +# Next, we define the fix points. This could be as simple as just the trailing edge at `(1,0)`. However, the mesh quality is improved by providing several points along the surface, spread out consistently with the size function above. Therefore, this function also needs the edge length `htrail` from before. We also add the symmetry point `(0,0)`. + +function fixnaca(; htrail=0.04) + a0, a14... = naca_coeffs + fixx = 1 .- htrail * cumsum(1.3 .^ (0:4)) + fixy = a0 * sqrt.(fixx) .+ fixx .^ (1:4)' * a14 + fix = vcat(Point2d[(0,0),(1,0)], [ Point2d[(x,y),(x,-y)] for (x,y) in zip(fixx,fixy) ]...) +end + +# Finally, we can define a function for generating the arguments to `distmesh2d` for generating the NACA mesh. The parameters are the sizes from before, as well as a center point `(circx,0)` and a radius for the far-field circle boundary. + +function dm_naca(; hlead=0.01, htrail=0.04, hmax=2.0, circx=2.0, circr=4.0) + ## Distance function: Difference between the outer circle and the NACA airfoil + dfcn(p) = ddiff(dcircle(p, c=(circx, 0), r=circr), dnaca(p)) + + ## Size function: Given by `hnaca` above + hfcn(p) = hnaca(p; hlead=hlead, htrail=htrail, hmax=hmax) + + ## Fix points: Add symmetry points for the circle plus the ones from `fixnaca` + fix = Point2d[(1,0),(0,1),(-1,0),(0,-1)] .* circr .+ Point2d[(circx,0)] + fix = vcat(fix, fixnaca(htrail=htrail)) + + ## Bounding box: Determined by the far-field circle + bbox = [(circx - circr, -circr), (circx + circr, circr)] + + ## The `hmin` parameter needs to be the smallest element size in the domain + hmin = minimum((hlead, htrail, hmax)) + + dfcn, hfcn, hmin, bbox, fix +end + +# Now we can generate and plot the default mesh +msh = distmesh2d(dm_naca()...) +plot(msh) + +# We can modify the mesh, e.g. by shrinking the farfield circle +msh = distmesh2d(dm_naca(circx=1, circr=1.5)...) +plot(msh) + +# Finally, we can increase the element sizes at the sources +msh = distmesh2d(dm_naca(circx=1, circr=1.5, hlead=0.05, htrail=0.1)...) +plot(msh) diff --git a/examples/Project.toml b/examples/Project.toml new file mode 100644 index 0000000..006f1dc --- /dev/null +++ b/examples/Project.toml @@ -0,0 +1,5 @@ +[deps] +DistMesh = "f7ee28b6-bfbf-11e9-3e31-8961b86f052c" +GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" diff --git a/ext/DistMeshCairoMakieExt.jl b/ext/DistMeshCairoMakieExt.jl new file mode 100644 index 0000000..7d4c41c --- /dev/null +++ b/ext/DistMeshCairoMakieExt.jl @@ -0,0 +1,30 @@ +module DistMeshCairoMakieExt + +using DistMesh +using CairoMakie + +const MESH_COLOR = "#DDEEFF" + +function CairoMakie.plot(m::DMesh{2}; args...) + f = Figure() # size=(600, 600) + ax = Axis(f[1,1], aspect=DataAspect()) + + p, t = as_arrays(m) + poly!(ax, p', t', color=MESH_COLOR, strokewidth=1) + return f +end + +const _has_warned_live = Ref(false) + +function DistMesh.live_plot(m::DMesh) + if !_has_warned_live[] + @warn "Live plotting disabled for CairoMakie. \n" * + "CairoMakie is for static plots (PDF/PNG). \n" * + "Switch to `using GLMakie` for animations." + _has_warned_live[] = true + end + return nothing +end + +end + diff --git a/ext/DistMeshGLMakieExt.jl b/ext/DistMeshGLMakieExt.jl new file mode 100644 index 0000000..e1a2447 --- /dev/null +++ b/ext/DistMeshGLMakieExt.jl @@ -0,0 +1,96 @@ +module DistMeshGLMakieExt + +using DistMesh +using GLMakie +using GeometryBasics + +const MESH_COLOR = "#DDEEFF" + +# --------------------------------------------------------- +# 1. Helpers +# --------------------------------------------------------- + +""" + get_canvas(; aspect=DataAspect()) + +Gets the current figure/axis if they exist, or creates new ones. +""" +function get_canvas(; aspect=DataAspect()) + fig = current_figure() + if isnothing(fig) + fig = Figure() # size=(600, 600) + ax = Axis(fig[1,1], aspect=aspect) + return fig, ax + else + ax = current_axis() + if isnothing(ax) + ax = Axis(fig[1,1], aspect=aspect) + end + return fig, ax + end +end + +""" + to_gl_mesh(m::DMesh) + +Converts a DistMesh DMesh object into a GeometryBasics.normal_mesh +suitable for high-performance GLMakie plotting and updates. +""" +function to_gl_mesh(m::DMesh{2}) + p, t = as_arrays(m) + + # 1. strict conversion to Float32 Points (GL standard) + pts = Point2f[Point2f(col) for col in eachcol(p)] + + # 2. strict conversion to standard Triangle Faces + faces = GLTriangleFace[GLTriangleFace(col...) for col in eachcol(t)] + + # 3. Create Mesh and compute Normals + # (Required because Makie initializes with normals by default; + # we must match that type for updates to work) + return GeometryBasics.normal_mesh(GeometryBasics.Mesh(pts, faces)) +end + +# --------------------------------------------------------- +# 2. Standard Plot (Static) +# --------------------------------------------------------- + +function GLMakie.plot(m::DMesh{2}; args...) + f, ax = get_canvas() + + # Standard plot: Clear the axis and draw fresh + empty!(ax) + + gl_mesh = to_gl_mesh(m) + poly!(ax, gl_mesh, color=MESH_COLOR, strokewidth=1) + + return f +end + +# --------------------------------------------------------- +# 3. Live Plot (Dynamic / Animation) +# --------------------------------------------------------- + +function DistMesh.live_plot(m::DMesh{2}) + f, ax = get_canvas() + + # Always convert the incoming data to the strict GL mesh format + gl_mesh = to_gl_mesh(m) + + if isempty(ax.scene.plots) + # --- INITIALIZATION --- + poly!(ax, gl_mesh, color=MESH_COLOR, strokewidth=1) + autolimits!(ax) + display(f) + else + # --- UPDATE --- + plt = ax.scene.plots[1] + plt[1][] = gl_mesh + # autolimits!(ax) # technically needed, but makes animation non-smooth + end + + sleep(0.01) + return f +end + +end diff --git a/ext/DistMeshPlotsExt.jl b/ext/DistMeshPlotsExt.jl new file mode 100644 index 0000000..7f7793e --- /dev/null +++ b/ext/DistMeshPlotsExt.jl @@ -0,0 +1,20 @@ +module DistMeshPlotsExt + +using DistMesh +using Plots + +const MESH_COLOR = Plots.RGBX(0.8, 0.9, 1.0) + +function Plots.plot(m::DMesh{2,T,N,I}; args...) where {T,N,I} + pxy(d) = [ tix==0 ? NaN : m.p[tt[tix]][d] for tix in (1,2,3,1,0), tt in m.t ] + args = (args..., + seriestype=:shape, + aspect_ratio=:equal, + leg=false, + fillcolor=MESH_COLOR) + h = Plots.plot(vec(pxy(1)), vec(pxy(2)); args...) +end + +DistMesh.live_plot(m::DMesh; args...) = display(plot(m)) + +end diff --git a/src/DistMesh.jl b/src/DistMesh.jl index f134cb5..4bb38af 100644 --- a/src/DistMesh.jl +++ b/src/DistMesh.jl @@ -1,125 +1,28 @@ module DistMesh -using LinearAlgebra, - TetGen -using GeometryBasics -using GeometryBasics: Triangle, Tetrahedron, Mesh, Polytope, Point +using StaticArrays +using LinearAlgebra +using Delaunator -const tetpairs = ((1,2),(1,3),(1,4),(2,3),(2,4),(3,4)) -const tettriangles = ((1,2,3),(1,2,4),(2,3,4),(1,3,4)) +# --- Load Types --- +include("dmesh.jl") -abstract type AbstractDistMeshAlgorithm end +# --- Load Utilities and 2D Implementation --- +include("distfuncs.jl") +include("meshutils.jl") +include("distmesh2d.jl") -""" - DistMeshSetup +# --- Exports --- -Takes Keyword arguments as follows: +export DMesh, as_arrays +export distmesh2d - iso (default: 0): Value of which to extract the isosurface, inside surface is negative - deltat (default: 0.1): the fraction of edge displacement to apply each iteration - sort (default:false): If true and no fixed points, sort points using a hilbert sort. - sort_interval (default:20) Use hilbert sort after the specified retriangulations - distribution (default: :regular) Initial point distribution, either :regular or :packed. -""" -struct DistMeshSetup{T} <: AbstractDistMeshAlgorithm - iso::T - deltat::T - ttol::T - ptol::T - sort::Bool # use hilbert sort to cache-localize points - sort_interval::Int # retriangulations before resorting - nonlinear::Bool # uses nonlinear edge force - distribution::Symbol # intial point distribution -end +export dhypersphere, dcircle, dsphere, drectangle, dblock +export dline, dsegment, dpoly +export ddiff, dunion, dintersect +export huniform +export naca_coeffs, dnaca -function DistMeshSetup(;iso=0, - ptol=.001, - deltat=0.05, - ttol=0.02, - sort=false, - sort_interval=20, - nonlinear=false, - distribution=:regular) - T = promote_type(typeof(iso),typeof(ptol),typeof(deltat), typeof(ttol)) - DistMeshSetup{T}(iso, - deltat, - ttol, - ptol, - sort, - sort_interval, - nonlinear, - distribution) -end - -""" - DistMeshQuality - -Use Tetrahedral quality analysis to control the meshing process - - iso (default: 0): Value of which to extract the iso surface, inside negative - deltat (default: 0.1): the fraction of edge displacement to apply each iteration -""" -struct DistMeshQuality{T} <: AbstractDistMeshAlgorithm - iso::T - deltat::T - filter_less_than::T # Remove tets less than the given quality - #allow_n_regressions::Int # Might want this - termination_quality::T # Once achieved, terminate - sort::Bool # use hilbert sort to cache-localize points - sort_interval::Int # retriangulations before resorting - nonlinear::Bool # uses nonlinear edge force - distribution::Symbol # intial point distribution -end - -function DistMeshQuality(;iso=0, - deltat=0.05, - filter_less_than=0.02, - termination_quality=0.3, - sort=false, - sort_interval=20, - nonlinear=true, - distribution=:regular) - DistMeshQuality(iso, - deltat, - filter_less_than, - termination_quality, - sort, - sort_interval, - nonlinear, - distribution) -end - -""" - DistMeshStatistics - - Statistics about the convergence between iterations -""" -struct DistMeshStatistics{T} - maxmove::Vector{T} # max point move in an iteration - maxdp::Vector{T} # max displacmeent induced by an edge - min_volume_edge_ratio::Vector{T} - max_volume_edge_ratio::Vector{T} - average_volume_edge_ratio::Vector{T} - retriangulations::Vector{Int} # Iteration num where retriangulation occured -end - -DistMeshStatistics() = DistMeshStatistics{Float64}([],[],[],[],[],[]) - -""" -Uniform edge length function. -""" -struct HUniform end - - -include("diff.jl") -include("pointdistribution.jl") -include("distmeshnd.jl") -include("tetgen.jl") -include("quality.jl") -include("decompositions.jl") -include("hilbertsort.jl") - -#export distmeshsurface -export distmesh, DistMeshSetup, DistMeshStatistics, HUniform +export element_qualities, element_volumes, cleanup_mesh end # module diff --git a/src/decompositions.jl b/src/decompositions.jl deleted file mode 100644 index 1e8f5f3..0000000 --- a/src/decompositions.jl +++ /dev/null @@ -1,74 +0,0 @@ - -""" -convert tets to tris, -returned sorted and unique -""" -function tets_to_tris!(tris, triset, tets) - empty!(triset) - for i in eachindex(tets) - for j in 1:4 - tp = tettriangles[j] - p1 = tets[i][tp[1]] - p2 = tets[i][tp[2]] - p3 = tets[i][tp[3]] - # sort indices - if p1 <= p2 <= p3 - push!(triset, (p1,p2,p3)) - elseif p1 <= p3 <= p2 - push!(triset, (p1,p3,p2)) - elseif p2 <= p3 <= p1 - push!(triset, (p2,p3,p1)) - elseif p2 <= p1 <= p3 - push!(triset, (p2,p1,p3)) - elseif p3 <= p1 <= p2 - push!(triset, (p3,p1,p2)) - elseif p3 <= p2 <= p1 - push!(triset, (p3,p2,p1)) - end - end - end - resize!(tris, length(triset)) - #copy elements to tri - i = 1 - for elt in triset - tris[i] = elt - i = i + 1 - end - sort!(tris) - tris -end - -function tets_to_tris!(tris::Vector, tets::Vector) - tets_to_tris!(tris, Set{eltype(tris)}(), tets) -end - -""" - Decompose tets to edges, using a pre-allocated array and set. - Set ensures uniqueness, and result will be sorted. -""" -function tet_to_edges!(pair::Vector, pair_set::Set, t) - empty!(pair_set) - length(pair) < length(t)*6 && resize!(pair, length(t)*6) - num_pair = 0 - @inbounds for i in eachindex(t) - for ep in 1:6 - p1 = t[i][tetpairs[ep][1]] - p2 = t[i][tetpairs[ep][2]] - elt = p1 > p2 ? (p2,p1) : (p1,p2) - if !in(elt, pair_set) - push!(pair_set, elt) - num_pair += 1 - pair[num_pair] = elt - end - end - end - - # sort the edge pairs for better point lookup - sort!(view(pair, 1:num_pair)) - - return num_pair # return the number of pairs -end - -function bitpack(xi,yi) - (unsafe_trunc(UInt64, xi) << 32) | unsafe_trunc(UInt64, yi) -end diff --git a/src/diff.jl b/src/diff.jl deleted file mode 100644 index c0e11ea..0000000 --- a/src/diff.jl +++ /dev/null @@ -1,7 +0,0 @@ -function centraldiff(f::Function,p::VT) where VT - deps = sqrt(eps(eltype(VT))) - dx = (f(p.+VT(deps,0,0)) - f(p.-VT(deps,0,0))) - dy = (f(p.+VT(0,deps,0)) - f(p.-VT(0,deps,0))) - dz = (f(p.+VT(0,0,deps)) - f(p.-VT(0,0,deps))) - grad = VT(dx,dy,dz)./(2deps) #normalize? -end diff --git a/src/distfuncs.jl b/src/distfuncs.jl new file mode 100644 index 0000000..b7801fe --- /dev/null +++ b/src/distfuncs.jl @@ -0,0 +1,151 @@ +################################################################################ +### 1. Basic Shapes (Circles, Rectangles) +################################################################################ + +""" + dhypersphere(p, c, r) + +Signed distance function for a hypersphere of radius `r` centered at `c`. +Works for any dimension, provided `p` and `c` have matching lengths. +""" +dhypersphere(p, c, r) = norm(p - c) - r + +""" + dcircle(p; c=(0, 0), r=1.0) + +Signed distance function for a 2D circle. +Wrapper around `dhypersphere` that enforces 2D inputs. +""" +dcircle(p; c=(0, 0), r=1) = dhypersphere(SVector{2}(p), SVector{2}(c), r) + +""" + dsphere(p; c=(0, 0, 0), r=1.0) + +Signed distance function for a 3D sphere. +Wrapper around `dhypersphere` that enforces 3D inputs. +""" +dsphere(p; c=(0, 0, 0), r=1) = dhypersphere(SVector{3}(p), SVector{3}(c), r) + +""" + drectangle(p, x1, x2, y1, y2) + +Signed distance function for a 2D axis-aligned rectangle. +Returns negative values inside the region `[x1, x2] × [y1, y2]`. +""" +drectangle(p, x1, x2, y1, y2) = -minimum((-y1 + p[2], y2 - p[2], -x1 + p[1], x2 - p[1])) + +""" + dblock(p, x1, x2, y1, y2, z1, z2) + +Signed distance function for a 3D axis-aligned block (cuboid). +Returns negative values inside the region `[x1, x2] × [y1, y2] × [z1, z2]`. +""" +dblock(p, x1, x2, y1, y2, z1, z2) = -minimum((-z1 + p[3], z2 - p[3], + -y1 + p[2], y2 - p[2], + -x1 + p[1], x2 - p[1])) + +################################################################################ +### 2. Polygons & Lines +################################################################################ + +""" + dline(p, p1, p2) + +Distance from point `p` to the finite line segment defined by endpoints `p1` and `p2`. +Returns the Euclidean distance (always non-negative). +""" +function dline(p, p1, p2) + p,p1,p2 = SVector{2}.((p,p1,p2)) + + v = p2 - p1 + w = p - p1 + c1 = dot(v, w) + c2 = dot(v, v) + if c1 <= 0 + return norm(p - p1) + elseif c1 >= c2 + return norm(p - p2) + else + return norm(p - (p1 + c1 / c2 * v)) + end +end + +""" + inpolygon(p, pv) + +Point-in-polygon test using the Ray Casting algorithm. +Returns `true` if `p` is inside the polygon defined by vertices `pv`. +""" +function inpolygon(p, pv) + cn = 0 # Crossing number counter + for i = 1:length(pv)-1 # Loop over all edges of the polygon + if pv[i][2] <= p[2] && pv[i+1][2] > p[2] || # Upward crossing + pv[i][2] > p[2] && pv[i+1][2] <= p[2] # Downward crossing + vt = (p[2] - pv[i][2]) / (pv[i+1][2] - pv[i][2]) # Intersection + if p[1] < pv[i][1] + vt * (pv[i+1][1] - pv[i][1]) + cn += 1 # A valid cross right of p[1] + end + end + end + return cn % 2 == 1 +end + +# Internal helper (not typically exported, so no docstring needed unless you want one) +dsegment(p, pv) = (dline(p, pv[i+1], pv[i]) for i in 1:length(pv)-1) + +""" + dpoly(p, pv) + +Signed distance function for a polygon defined by vertices `pv`. +**Note:** `pv` must be a closed loop (i.e., `pv[end] == pv[1]`). +Returns negative values inside, positive outside. +""" +function dpoly(p, pv) + d = minimum(dsegment(p, pv)) + inpolygon(p, pv) ? -d : d +end + +################################################################################ +### 3. Boolean Operations (CSG) +################################################################################ + +""" + ddiff(d1, d2) + +Difference of two regions (Region 1 minus Region 2). +`d1` and `d2` are signed distances. +""" +ddiff(d1, d2) = max(d1, -d2) + +""" + dunion(d1, d2) + +Union of two regions. +`d1` and `d2` are signed distances. +""" +dunion(d1, d2) = min(d1, d2) + +""" + dintersect(d1, d2) + +Intersection of two regions. +`d1` and `d2` are signed distances. +""" +dintersect(d1, d2) = max(d1, d2) + +################################################################################ +### 4. Special Functions +################################################################################ + +const naca_coeffs = 0.12 / 0.2 * SVector(0.2969, -0.1260, -0.3516, 0.2843, -0.1036) + +""" + dnaca(p) + +Implicit level-set function for a NACA 0012 airfoil. +Zero contour defines the airfoil boundary. +""" +function dnaca(p) + a0, a14... = naca_coeffs + (abs(p[2]) - sum(a14 .* p[1] .^ SVector(1, 2, 3, 4))) .^ 2 - a0^2 * p[1] +end diff --git a/src/distmesh2d.jl b/src/distmesh2d.jl new file mode 100644 index 0000000..39e8c0d --- /dev/null +++ b/src/distmesh2d.jl @@ -0,0 +1,227 @@ +######################################################################## +# Internal Type Aliases + +const Point2d = SVector{2, Float64} +const Index2 = SVector{2, Int32} # For Edges +const Index3 = SVector{3, Int32} # For Triangles + +######################################################################## +# Utility functions + +barvectors(p, bars) = [ p[bar[1]] - p[bar[2]] for bar in bars ] + +function init_nodes(bbox, h0) + # Create initial distribution in bounding box (equilateral triangles) + xx = bbox[1][1]:h0:bbox[2][1] + yy = bbox[1][2]:h0*√3/2:bbox[2][2] + p = [ Point2d(x + iseven(iy) * h0/2, y) for x in xx for (iy,y) in enumerate(yy) ] +end + +function nodes_rejection(p, pfix, dfcn, hfcn, geps) + # Remove nodes outside the region, apply the rejection method + p = p[dfcn.(p) .< geps] + r0 = [ 1 / hfcn(pp)^2 for pp in p ] + p = p[rand(length(r0)) .< r0./maximum(r0)] + p = vcat(pfix, setdiff(p, pfix)) +end + +function retriangulate(p, dfcn, geps) + # Retriangulation by the Delaunay algorithm, remove outside triangles + t = delaunay(p) + t = filter(tt -> dfcn(sum(p[tt]) / 3) < -geps, t) + # Find all bars as the unique triangle edges + bars = [ tt[ix] for tt in t for ix in Index2[(1,2),(2,3),(3,1)] ] + bars = unique(sort.(bars)) + t, bars +end + +function desiredlengths(p, bars, L, hfcn, Fscale) + # Scaled and normalized desired bar lengths + barmid = [ (p[bar[1]] + p[bar[2]]) / 2 for bar in bars ] + hbars = hfcn.(barmid) + L0 = hbars * Fscale * sqrt(sum(L .^ 2) / sum(hbars .^ 2)) +end + +function density_control(p, L, L0, bars, nfix) + # Density control - remove nodes that are too close + pkeep = trues(length(p)) + foreach(bar -> pkeep[bar] .= false, bars[L0[:].>2*L[:]]) + pkeep[1:nfix] .= true + p = p[pkeep] +end + +function total_node_forces(L, L0, barvec, bars, np, nfix) + # Find all bar forces and accumulate at all nodes + F = max.(L0 .- L, 0.0) + Fvec = F ./ L .* barvec + Ftot = [ Point2d(0.0,0.0) for ip = 1:np ] + for ibar in eachindex(bars) + Ftot[bars[ibar][1]] += Fvec[ibar] + Ftot[bars[ibar][2]] -= Fvec[ibar] + end + Ftot[1:nfix] .*= 0.0 + Ftot +end + +function project_nodes!(p, dfcn, deps) + d = dfcn.(p) + ix = findall(d .> 0) + numgrad(f,x,fx) = (Point2d(f(x + Point2d(deps,0)), f(x + Point2d(0,deps))) .- fx) / deps + dgrad = [ numgrad(dfcn, p[i], d[i]) for i in ix ] + @. p[ix] -= d[ix] * dgrad / norm(dgrad)^2 + d +end + +######################################################################## +# Main function + +""" + distmesh2d(dfcn, hfcn, h0, bbox, pfix=[]; kwargs...) -> (p, t) + +Generate a 2D unstructured triangular mesh using a signed distance function. + +This function implements the DistMesh algorithm (Persson/Strang), which treats the mesh generation +as a physical equilibrium problem. A system of truss bars (edges) is relaxed until the force +equilibrium is reached, constrained by the signed distance function `dfcn` to stay within the domain. + +# Arguments +- `dfcn::Function`: Signed distance function `d(p)`. Returns negative values inside the region, + positive outside. The input `p` is a 2-element coordinate vector (e.g., `Vector`, `Tuple`, or `SVector`). +- `hfcn::Function`: Element size function `h(p)`. Returns target edge length at point `p`. +- `h0::Real`: Initial nominal edge length (scaling factor for `hfcn`). +- `bbox`: Bounding box tuple `((xmin, ymin), (xmax, ymax))` defining the initial grid generation area. +- `pfix::Vector`: (Optional) List of fixed node positions that must be part of the mesh (e.g., corners). + +# Keywords +- `plotting::Bool = false`: Enable live visualization of the relaxation process (Plots or GLMakie). +- `maxiter::Int = 10_000`: Maximum number of relaxation iterations. +- Several other parameters that are rarely modified + +# Returns +- `p::Vector{Point2d}`: The node positions. +- `t::Vector{Index3}`: The triangle connectivity indices. + +# Examples + +**Uniform Mesh on a Unit Circle** +```julia +using DistMesh + +fd(p) = sqrt(sum(p.^2)) - 1 # or dcircle(p) - unit circle geometry +fh(p) = 1.0 # or huniform(p) - uniform size function +hmin = 0.2 # initial edge lengths +bbox = ((-1,-1), (1,1)) # bounding box for unit circle + +msh = distmesh2d(fd, fh, hmin, bbox) + +# Optionally, the mesh can be visualized using various plotting packages: +using GLMakie # or Plots, or CairoMakie +plot(msh) +``` + +**Rectangle with Circular Hole (Refined at Boundary)** +```julia +using DistMesh +hmin = 0.05 +fd(p) = ddiff(drectangle(p, -1, 1, -1, 1), dcircle(p, r=0.5)) +fh(p) = hmin + 0.3*dcircle(p, r=0.5) +msh = distmesh2d(fd, fh, hmin, ((-1,-1), (1,1)), ((-1,-1), (-1,1), (1,-1), (1,1))) +``` + +**Polygon** +```julia +using DistMesh +pv = [(-0.4, -0.5), (0.4, -0.2), (0.4, -0.7), (1.5, -0.4), + (0.9, 0.1), (1.6, 0.8), (0.5, 0.5), (0.2, 1.0), + (0.1, 0.4), (-0.7, 0.7), (-0.4, -0.5)] +fd(p) = dpoly(p, pv) +bbox = ((-1,-1), (2,1)) +h0 = 0.15 +msh = distmesh2d(fd, huniform, h0, bbox, pv) +``` + +**Ellipse** +```julia +using DistMesh +fd(p) = (p[1]/2)^2 + (p[2]/1)^2 - 1 +bbox = ((-2,-1), (2,1)) +msh = distmesh2d(fd, huniform, 0.2, bbox) +``` + +**Square, with size function point and line sources** +```julia +using DistMesh +fd(p) = drectangle(p, 0, 1, 0, 1) +fh(p) = min(min(0.01 + 0.3*abs(dcircle(p, r=0)), + 0.025 + 0.3*abs(dpoly(p, [(0.3,0.7), (0.7,0.5)]))), + 0.15) +msh = distmesh2d(fd, fh, 0.01, ((0,0), (1,1)), ((0,0), (1,0), (0,1), (1,1))) +``` + +**NACA0012 airfoil** + +See `examples/002-naca_airfoil.jl` +""" +function distmesh2d(dfcn, hfcn, h0, bbox, pfix=Point2d[]; + plotting=false, # Optional live plotting + densityctrlfreq = 30, # Frequency of density controls + maxiter = 10_000, # When to terminate if no convergence + # Algorithmic parameters, defaults are normally good + Fscale = 1.2, # Force function parameter (compression) + deltat = 0.2, # Timestep + ttol = 0.1 * h0, # Retriangulation tolerance + geps = 0.001 * h0, # dfcn(p) tolerance for in/out points + dptol = geps, # Termination tolerance + deps = sqrt(eps()) * h0 # Finite difference stepsize + ) + + # Initializations + pfix = unique(Point2d.(pfix)) + nfix = length(pfix) + pold = [Point2d(Inf,Inf)] + t, bars = Index3[], Index2[] + converged = false + + # Initial nodes + p = init_nodes(bbox, h0) + p = nodes_rejection(p, pfix, dfcn, hfcn, geps) + + # Main loop + for iter = 1:maxiter + # If large relative movements, retriangulate and plot + if maximum(norm.(p .- pold)) > ttol + pold = copy(p) + t, bars = retriangulate(p, dfcn, geps) + plotting && live_plot(DMesh(p,t)) + end + + # All bars and lengths + barvec = barvectors(p, bars) + L = norm.(barvec) + L0 = desiredlengths(p, bars, L, hfcn, Fscale) + + # Density control - remove points that are too close to each other + if iter % densityctrlfreq == 0 + p = density_control(p, L, L0, bars, nfix) + pold = [Point2d(Inf,Inf)] + continue + end + + # Compute forces and update nodes + dp = deltat * total_node_forces(L, L0, barvec, bars, length(p), nfix) + p .+= dp + + # Project outside points back to boundary + d = project_nodes!(p, dfcn, deps) + + # Terminate if small (interior) node movements + converged = maximum(norm.(dp[d.<-geps]); init=0.0) < dptol + converged && break + end + + converged || @warn "No convergence in maxiter=$maxiter iterations" + + msh = DMesh(p, t) + plotting && live_plot(msh) + return msh +end diff --git a/src/distmeshnd.jl b/src/distmeshnd.jl deleted file mode 100644 index 251c44d..0000000 --- a/src/distmeshnd.jl +++ /dev/null @@ -1,266 +0,0 @@ -""" - distmesh - 3D Mesh Generator using Signed Distance Functions. - Arguments: - fdist: Distance function - fh: Edge length function - h: Smallest edge length - - Returns: - p: Node positions - t: Triangle indices - - - Example: Unit ball - d(p) = sqrt(sum(p.^2))-1 - p,t = distmeshnd(d,huniform,0.2) -""" -function distmesh(fdist::Function, - fh::Union{Function,HUniform}, - h::Number, - setup::AbstractDistMeshAlgorithm=DistMeshSetup(); - origin=GeometryBasics.Point{3,Float64}(-1,-1,-1), - widths=GeometryBasics.Point{3,Float64}(2,2,2), - fix=nothing, - stats=false) where {VertType} - # TODO: tetgen only handles Float64 - VT = GeometryBasics.Point{3,Float64} - if isa(fix, Nothing) - fp = nothing - else - fp = convert(Vector{VT}, fix) - end - o = VT(origin...) - w = VT(widths...) - distmesh(fdist, fh, h, setup, o, w, fp, Val(stats), VT) -end - -""" - DistMeshResult - -A struct returned from the `distmesh` function that includes point, simplex, -and interation statistics. -""" -struct DistMeshResult{PT, TT, STATS} - points::Vector{PT} - tetrahedra::Vector{TT} - stats::STATS -end - -function distmesh(fdist::Function, - fh, - h::Number, - setup::DistMeshSetup, - origin, - widths, - fix, - ::Val{stats}, - ::Type{VertType}) where {VertType, stats} - - geps=1e-1*h+setup.iso # parameter for filtering tets outside bounds and considering for max displacment of a node - - # static parameter info - non_uniform = isa(fh, Function) # so we can elide fh calls - have_fixed = !isa(fix, Nothing) - - #ptol=.001; ttol=.1; L0mult=1+.4/2^(dim-1); deltat=.2; geps=1e-1*h; - - # initialize Vertex Arrays - # the first N points in the array correspond to'fix' points that do not move - if have_fixed - p = copy(fix) - else - p = VertType[] - end - - pt_dists = eltype(VertType)[] - - # setup the initial point distribution specified in setup - point_distribution!(fdist,p,pt_dists,h, setup, origin, widths, VertType) - - # Result struct for holding points, simplices, and iteration statistics - result = DistMeshResult(p, - GeometryBasics.SimplexFace{4,Int32}[], - stats ? DistMeshStatistics() : nothing) - - # initialize arrays - pair_set = Set{Tuple{Int32,Int32}}() # set used for ensure we have a unique set of edges - pair = Tuple{Int32,Int32}[] # edge indices (Int32 since we use Tetgen) - dp = zeros(VertType, length(p)) # displacement at each node - bars = VertType[] # the vector of each edge - L = eltype(VertType)[] # vector length of each edge - L0 = non_uniform ? eltype(VertType)[] : nothing # desired edge length computed by dh (edge length function) - maxmove = typemax(eltype(VertType)) # stores an iteration max movement for retriangulation - - # information on each iteration - lcount = 0 # iteration counter - triangulationcount = 0 # triangulation counter - num_pairs = 0 - - @inbounds while true - # if large move, retriangulation - if maxmove>setup.ttol*h - - # compute a new delaunay triangulation - retriangulate!(fdist, result, geps, setup, triangulationcount, pt_dists) - - num_pairs = tet_to_edges!(pair, pair_set, result.tetrahedra) # Describe each edge by a unique pair of nodes - - # resize arrays for new pair count - if length(L) < num_pairs - resize!(bars, num_pairs) - resize!(L, num_pairs) - non_uniform && resize!(L0, num_pairs) - end - - triangulationcount += 1 - stats && push!(result.stats.retriangulations, lcount) - end - - compute_displacements!(fh, dp, pair, num_pairs, L, L0, bars, result.points, setup, VertType) - - # Zero out forces on fix points - if have_fixed - for i in eachindex(fix) - dp[i] = zero(VertType) - end - end - - # apply point forces and - # bring outside points back to the boundary - maxdp = typemin(eltype(VertType)) - maxmove = typemin(eltype(VertType)) - for i in eachindex(p) - - p0 = p[i] # store original point location - p[i] = p[i].+setup.deltat.*dp[i] # apply displacements to points - - # Check if we are verifiably within the bounds and use this value - # to avoid recomputing fdist. This increases performance greatly on - # complex distance functions and large node counts - move = sqrt(sum((p[i]-p0).^2)) # compute movement from the displacement - d_est = pt_dists[i] + move # apply the movement to our cache point - d = d_est < -geps ? d_est : fdist(result.points[i]) # determine if we need correct or approximate distance - - if d < -geps - maxdp = max(maxdp, setup.deltat*sqrt(sum(dp[i].^2))) - end - - if d <= setup.iso - pt_dists[i] = d # store distance - maxmove = max(move,maxmove) - else - # bring points back to boundary if outside using central difference - p[i] = p[i] .- centraldiff(fdist,p[i]).*(d+setup.iso) - maxmove = max(sqrt(sum((p[i]-p0).^2)), maxmove) - pt_dists[i] = setup.iso # ideally - end - end - - # increment iteration counter - lcount = lcount + 1 - - # save iteration stats - if stats - push!(result.stats.maxmove,maxmove) - push!(result.stats.maxdp,maxdp) - min_v_edge, avg_v_edge, max_v_edge = volume_edge_stats(result.points,result.tetrahedra) - push!(result.stats.min_volume_edge_ratio, min_v_edge) - push!(result.stats.average_volume_edge_ratio, avg_v_edge) - push!(result.stats.max_volume_edge_ratio, max_v_edge) - end - - # Termination criterion - if maxdp>>1] - i, j = lo, hi - while true - pivot_elt = pivot[coord] - while v[i][coord] < pivot_elt; i += 1; end - while pivot_elt < v[j][coord]; j -= 1; end - i <= j || break - v[i], v[j] = v[j], v[i] - if CT !== Nothing; carry[i], carry[j] = carry[j], carry[i]; end - i += 1; j -= 1 - end - if k <= j - hi = j - elseif i <= k - lo = i - else - return #pivot - end - end - else - @inbounds while lo < hi - if isone(hi-lo) - if v[hi][coord] > v[lo][coord] - v[lo], v[hi] = v[hi], v[lo] - if CT !== Nothing; carry[lo], carry[hi] = carry[hi], carry[lo]; end - end - return #v[k] - end - pivot = v[(lo+hi)>>>1] - i, j = lo, hi - while true - pivot_elt = pivot[coord] - while v[i][coord] > pivot_elt; i += 1; end - while pivot_elt > v[j][coord]; j -= 1; end - i <= j || break - v[i], v[j] = v[j], v[i] - if CT !== Nothing; carry[i], carry[j] = carry[j], carry[i]; end - i += 1; j -= 1 - end - if k <= j - hi = j - elseif i <= k - lo = i - else - return #pivot - end - end - end - #return v[lo] - nothing -end - - -# 2D version -# function hilbertsort!(directionx::AbstractDirection, directiony::AbstractDirection, coordinate::AbstractCoordinate, a::Array{T,1}, lo::Int64, hi::Int64, lim::Int64=4) where T<:AbstractPoint2D -# hi-lo <= lim && return a - -# i2 = (lo+hi)>>>1 -# i1 = (lo+i2)>>>1 -# i3 = (i2+hi)>>>1 - -# select!(directionx, coordinate, a, i2, lo, hi) -# select!(directiony, next2d(coordinate), a, i1, lo, i2) -# select!(!directiony, next2d(coordinate), a, i3, i2, hi) - -# hilbertsort!(directiony, directionx, next2d(coordinate), a, lo, i1, lim) -# hilbertsort!(directionx, directiony, coordinate, a, i1, i2, lim) -# hilbertsort!(directionx, directiony, coordinate, a, i2, i3, lim) -# hilbertsort!(!directiony, !directionx, next2d(coordinate), a, i3, hi, lim) - -# return a -# end - -function hilbertsort!(directionx, directiony, directionz, coordinate, a::Vector, lo::Integer, hi::Integer, lim::Integer, carry) - hi-lo <= lim && return a - - i4 = (lo+hi)>>>1 - i2 = (lo+i4)>>>1 - i1 = (lo+i2)>>>1 - i3 = (i2+i4)>>>1 - i6 = (i4+hi)>>>1 - i5 = (i4+i6)>>>1 - i7 = (i6+hi)>>>1 - - select!(directionx, coordinate, a, i4, lo, hi, carry) - select!(directiony, next3d(coordinate), a, i2, lo, i4, carry) - select!(directionz, nextnext3d(coordinate), a, i1, lo, i2, carry) - select!(!directionz, nextnext3d(coordinate), a, i3, i2, i4, carry) - select!(!directiony, next3d(coordinate), a, i6, i4, hi, carry) - select!(directionz, nextnext3d(coordinate), a, i5, i4, i6, carry) - select!(!directionz, nextnext3d(coordinate), a, i7, i6, hi, carry) - - hilbertsort!( directionz, directionx, directiony, nextnext3d(coordinate), a, lo, i1, lim, carry) - hilbertsort!( directiony, directionz, directionx, next3d(coordinate), a, i1, i2, lim, carry) - hilbertsort!( directiony, directionz, directionx, next3d(coordinate), a, i2, i3, lim, carry) - hilbertsort!( directionx, !directiony, !directionz, coordinate, a, i3, i4, lim, carry) - hilbertsort!( directionx, !directiony, !directionz, coordinate, a, i4, i5, lim, carry) - hilbertsort!(!directiony, directionz, !directionx, next3d(coordinate), a, i5, i6, lim, carry) - hilbertsort!(!directiony, directionz, !directionx, next3d(coordinate), a, i6, i7, lim, carry) - hilbertsort!(!directionz, !directionx, directiony, nextnext3d(coordinate), a, i7, hi, lim, carry) - - return a -end - -#hilbertsort!(a::Array{T,1}) where {T<:AbstractPoint2D} = hilbertsort!(backward, backward, coordinatey, a, 1, length(a)) -#hilbertsort!(a::Array{T,1}, lo::Int64, hi::Int64, lim::Int64) where {T<:AbstractPoint2D} = hilbertsort!(backward, backward, coordinatey, a, lo, hi, lim) -""" -Hilbert Sorting. If `carry` is specified, this array will be permuted in line with the -specified array. -""" -hilbertsort!(a::Vector, carry=nothing) = hilbertsort!(backward, backward, backward, coordinatez, a, 1, length(a), 8, carry) -hilbertsort!(a::Vector, lo::Int64, hi::Int64, lim::Int64) = hilbertsort!(backward, backward, backward, coordinatey, a, lo, hi, lim) diff --git a/src/meshutils.jl b/src/meshutils.jl new file mode 100644 index 0000000..ee767f8 --- /dev/null +++ b/src/meshutils.jl @@ -0,0 +1,180 @@ +################################################################################ +### Delaunator wrappers +################################################################################ + +extract_elements(tri::Delaunator.Triangulation{I}) where {I} = + reinterpret(SVector{3, I}, triangles(tri)) + +function fix_winding!(tri::Delaunator.Triangulation{I}) where {I} + tris = triangles(tri) + mat = reinterpret(reshape, I, tris) + + # Swap rows 2 and 3 (in-place) + @inbounds for c in axes(mat, 2) + mat[2, c], mat[3, c] = mat[3, c], mat[2, c] + end + return nothing +end + +function delaunay(p) + t = triangulate(p) + fix_winding!(t) + return extract_elements(t) +end + +################################################################################ +### Size function utilities +################################################################################ + +""" + huniform(p) + +Returns `1.0`. Default sizing function for uniform meshes. +""" +huniform(p) = 1 + + +################################################################################ +### Element properties +################################################################################ + +""" + element_volume(el) + +Compute the generalized volume (area in 2D, volume in 3D) of a single element. +`el` is a vector of coordinates (e.g. [[x1, y1], [x2, y2], [x3, y3]]). +""" +function element_volume(el) + # Generic simplex handling could go here later. + # For now, explicit checks for standard shapes: + + N = length(el) + D = N > 0 ? length(el[1]) : 0 + + if D == 2 && N == 3 # Triangle (2D) + p12 = el[2] - el[1] + p13 = el[3] - el[1] + return (p12[1] * p13[2] - p12[2] * p13[1]) / 2 + + elseif D == 3 && N == 4 # Tetrahedron (3D) + error("3D Tetrahedra not yet implemented") + + elseif D == 2 && N == 4 # Example: Quad (2D) logic check + # Quad logic + error("2D Quadrilaterals not yet implemented") + + else + error("Element type or dimension not supported") + end +end + +""" + element_quality(el) + +Compute a quality metric for a single element (normalized 0.0 to 1.0). +Currently implements 2*r/R (radius ratio) for triangles. +""" +function element_quality(el) + if length(el) == 3 # Triangle + # Lengths of the three edges + a = norm(el[2] - el[1]) + b = norm(el[3] - el[2]) + c = norm(el[1] - el[3]) + + # Semiperimeter + s = (a + b + c) / 2 + + # Area (Heron's formula) for inradius calculation + # area = sqrt(s * (s-a) * (s-b) * (s-c)) + # r = area / s + # R = a*b*c / (4*area) + # Quality = 2*r/R + + denom = (a * b * c) + if denom ≈ 0 + return 0.0 + end + + return 8 * (s - a) * (s - b) * (s - c) / denom + else + error("Dimension not implemented") + end +end + +# Helper to map a function over all elements +_map_elements(m::DMesh, f) = [f(m.p[indices]) for indices in m.t] + +""" + element_qualities(m::DMesh, quality_func=element_quality) + +Return a vector of quality metrics for every element in the mesh. +""" +element_qualities(m::DMesh, f=element_quality) = _map_elements(m, f) + +""" + element_volumes(m::DMesh) + +Return a vector of volumes (or areas) for every element in the mesh. +""" +element_volumes(m::DMesh) = _map_elements(m, element_volume) + +################################################################################ +### General mesh utilities +################################################################################ + +snap(x::T, scaling=1) where {T <: Real} = x +snap(x::T, scaling=1, tol=sqrt(eps(T))) where {T <: AbstractFloat} = + scaling*tol*round(x/scaling/tol) + zero(T) # Adding zero to uniquify -0.0 and 0.0 + + +""" + cleanup_mesh(msh::DMesh) -> (msh::DMesh, ix::Vector{Int}) + +Remove duplicate nodes from the mesh `msh` and re-index the connectivity. + +This function identifies nodes that are coincident (or within a very small tolerance relative to the mesh size) +and merges them. This is useful after mesh generation or modification operations that might create +overlapping vertices. + +# Arguments +- `msh::DMesh`: The input mesh containing nodes `p` and connectivity `t`. + +# Returns +A `NamedTuple` `(msh, ix)` where: +- `msh`: The cleaned `DMesh` with duplicate nodes removed. +- `ix`: An index vector mapping the **new** nodes to the **old** nodes (i.e., `new_p = old_p[ix]`). + +# Example +```julia +clean_msh, = cleanup_mesh(dirty_msh) # Ignoring the index output (ix) + +``` + +""" +function cleanup_mesh(msh::DMesh) + p, t = msh + + # 1. Snap nodes to a grid to identify duplicates (relative tolerance) + scaling = maximum(norm.(p)) + if scaling == 0.0 + scaling = 1.0 + end + pp = [snap.(p1, scaling) for p1 in p] + + # 2. Find unique nodes + ppp = unique(pp) + + # 3. Create mappings + # ix: Mapping from New -> Old (which old node did this new node come from?) + ix = Int.(indexin(ppp, pp)) + # jx: Mapping from Old -> New (where did this old node go?) + jx = Int.(indexin(pp, ppp)) + + # 4. Rebuild Mesh + new_p = p[ix] + # Broadcast the index lookup to preserve SVector/Tuple structure of triangles + new_t = [map(idx -> jx[idx], tri) for tri in t] + + return (msh=DMesh(new_p, new_t), ix=ix) + +end diff --git a/src/pointdistribution.jl b/src/pointdistribution.jl deleted file mode 100644 index 5b74d8b..0000000 --- a/src/pointdistribution.jl +++ /dev/null @@ -1,37 +0,0 @@ - -function simplecubic!(fdist, points, dists, h, iso, origin, widths, ::Type{VertType}) where VertType - @inbounds for xi = origin[1]:h:(origin[1]+widths[1]), yi = origin[2]:h:(origin[2]+widths[2]), zi = origin[3]:h:(origin[3]+widths[3]) - point = VertType(xi,yi,zi) - d = fdist(point) - if d < iso - push!(points,point) - push!(dists, d) - end - end -end - -function facecenteredcubic!(fdist, points, dists, h, iso, origin, widths, ::Type{VertType}) where VertType - # face-centered cubic point distribution - r = h/2 - counts = round.(widths./h).+2 - @inbounds for xi = -1:Int(counts[1]), yi = -1:Int(counts[2]), zi = -1:Int(counts[3]) - point = VertType(2xi+((yi+zi)%2), sqrt(3)*(yi+(zi%2)/3),2*sqrt(6)*zi/3).*r + origin - d = fdist(point) - if d < iso - push!(points,point) - push!(dists, d) - end - end -end - -function point_distribution!(fdist, p, pt_dists, h, setup, origin, widths, ::Type{VertType}) where VertType - map!(fdist, pt_dists, p) # cache to store point locations so we can minimize fdist calls - - # add points to p based on the initial distribution - if setup.distribution === :regular - simplecubic!(fdist, p, pt_dists, h, setup.iso, origin, widths, VertType) - elseif setup.distribution === :packed - # face-centered cubic point distribution - facecenteredcubic!(fdist, p, pt_dists, h, setup.iso, origin, widths, VertType) - end -end diff --git a/src/quality.jl b/src/quality.jl deleted file mode 100644 index 3ca45e6..0000000 --- a/src/quality.jl +++ /dev/null @@ -1,137 +0,0 @@ -""" -Determine the quality of a triangle given 3 points. - -Points must be 3D. -""" -function triqual(p1, p2, p3) - d12 = p2 - p1 - d13 = p3 - p1 - d23 = p3 - p2 - n = cross(d12,d13) - vol = sqrt(sum(n.^2)) - den = dot(d12,d12) + dot(d13,d13) + dot(d23,d23) - return sqrt(3)*2*vol/den -end - -function triangle_qualities(p,tets) - tris = NTuple{3,Int}[] - tets_to_tris!(tris, tets) - qualities = Vector{Float64}(undef,length(tris)) - triangle_qualities!(tris,qualities,p,tets) -end - -function triangle_qualities!(tris,triset,qualities,p,tets) - tets_to_tris!(tris,triset,tets) - resize!(qualities, length(tris)) - for i in eachindex(tris) - tp = tris[i] - qualities[i] = triqual(p[tp[1]], p[tp[2]], p[tp[3]]) - end - qualities -end - -function triangle_qualities!(tris::Vector,qualities::Vector,p,tets) - triangle_qualities!(tris,Set{eltype(tris)}(),qualities,p,tets) -end - -const ⋅ = dot -const × = cross - -function dihedral(p0,p1,p2,p3) - b1 = p1 - p0 - b2 = p2 - p1 - b3 = p3 - p2 - - abs(atan(((b1×b2)×(b2×b3))⋅normalize(b2), (b1×b2)⋅(b2×b3))) -end - -""" - Compute dihedral angles within a tetrahedra - radians -""" -function dihedral_angles(p,t) - AT = eltype(eltype(p)) - nangs = length(t)*6 - a = fill(zero(AT), nangs) - for i in 1:length(t) - t1, t2, t3, t4 = t[i] - a[i*6-5] = dihedral(p[t1],p[t2],p[t3],p[t4]) - a[i*6-4] = dihedral(p[t1],p[t2],p[t4],p[t3]) - a[i*6-3] = dihedral(p[t2],p[t1],p[t4],p[t3]) - a[i*6-2] = dihedral(p[t2],p[t3],p[t4],p[t1]) - a[i*6-1] = dihedral(p[t2],p[t1],p[t3],p[t4]) - a[i*6] = dihedral(p[t3],p[t1],p[t2],p[t4]) - end - a -end - -""" - Compute the minimum dihedral angle within a tetrahedra - radians -""" -function min_dihedral_angles(p,t) - AT = eltype(eltype(p)) - nangs = length(t) - a = fill(zero(AT), nangs) - for i in 1:length(t) - t1, t2, t3, t4 = t[i] - d = (dihedral(p[t1],p[t2],p[t3],p[t4]), - dihedral(p[t1],p[t2],p[t4],p[t3]), - dihedral(p[t2],p[t1],p[t4],p[t3]), - dihedral(p[t2],p[t3],p[t4],p[t1]), - dihedral(p[t2],p[t1],p[t3],p[t4]), - dihedral(p[t3],p[t1],p[t2],p[t4])) - a[i] = minimum(d) - end - a -end - -""" - Computes the volume and edge-length ratio from four given points -""" -function volume_edge_ratio(a,b,c,d) - t = a .- d - u = b .- d - v = c .- d - volume = t[1]*(u[2]*v[3]-v[2]*u[3])-u[1]*(t[2]*v[3]-v[2]*t[3])+v[1]*(t[2]*u[3]-u[2]*t[3]) - edges = (t,u,v,a.-b,b.-c,a.-c) - lengths = dot.(edges,edges) - l_rms = sqrt(sum(lengths)/6) - return sqrt(2)*abs(volume)/(l_rms^3) -end - -""" - -returns the extrema elements (min, max) of the sampled qualities -""" -function volume_edge_extrema(points::Vector{T},tets) where {T} - n = length(tets) - min_q = typemax(eltype(T)) - max_q = typemin(eltype(T)) - @inbounds for i = 1:n - tet = tets[i] - q = volume_edge_ratio(points[tet[1]],points[tet[2]],points[tet[3]],points[tet[4]]) - min_q = min(q,min_q) - max_q = max(q,max_q) - end - min_q, max_q -end - -""" - -returns the (min, avg, max) of the sampled qualities -""" -function volume_edge_stats(points::Vector{T},tets) where {T} - n = length(tets) - min_q = typemax(eltype(T)) - max_q = typemin(eltype(T)) - sum_q = zero(eltype(T)) - @inbounds for i = 1:n - tet = tets[i] - q = volume_edge_ratio(points[tet[1]],points[tet[2]],points[tet[3]],points[tet[4]]) - min_q = min(q,min_q) - max_q = max(q,max_q) - sum_q += q - end - min_q, sum_q/n, max_q -end diff --git a/src/tetgen.jl b/src/tetgen.jl deleted file mode 100644 index cdc750f..0000000 --- a/src/tetgen.jl +++ /dev/null @@ -1,22 +0,0 @@ -function delaunayn(points) - # M - no merge of close facets - # J - no jettison of points - # B - No boundary info - # N - No node output - # F - No face and edge info - # I - No mesh iteration numbers - # Q - Quiet - tetio = tetrahedralize(TetGen.JLTetGenIO(points), "JBNFIQ") - tetio -end - -function delaunayn_nosort(points) - tetio = tetrahedralize(TetGen.JLTetGenIO(points), "Qb/1") # Q- Quiet - tetio -end - -# needs some tweaks, gives garbage results, might need to twek the julia wrapper? -function reconstruct!(points, tets) - tetio = tetrahedralize(TetGen.JLTetGenIO(points,tetrahedrons=tets), "Qr") # Q- Quiet, r- retriangulate - tetio -end diff --git a/test/runtests.jl b/test/runtests.jl index 221afb4..7ca9a56 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,113 +1,85 @@ using DistMesh using Test -using GeometryBasics +using CairoMakie -include("vals.jl") +# ------------------------------------------------------------------------------ +# DistMesh 2D Tests +# ------------------------------------------------------------------------------ +""" + check_mesh(p, t; np, nt, area, areatol, minqual) +Validates a 2D mesh against expected properties. +- `np`: Expected number of nodes. +- `nt`: Expected number of triangles. +- `area`: Expected total area of the domain. +- `areatol`: Tolerance for total area check. +- `minqual`: Minimum allowable triangle quality (0.0 to 1.0). +""" +function check_mesh(msh::DMesh; np::Int=0, nt::Int=0, area::Real=0.0, areatol::Real=1e-6, minqual::Real=0.1) + @testset "Mesh Validation" begin + + # 1. Check Counts + np > 0 && @test length(msh.p) == np + nt > 0 && @test length(msh.t) == nt -@testset "point distributions" begin - vlen(a,b) = sqrt(sum((a-b).^2)) - @testset "simple cubic" begin - pts = [] - dists = [] - f(x) = -1 - DistMesh.simplecubic!(f, pts, dists, 0.5, 0, Point{3,Float64}(0),Point{3,Float64}(1),Point{3,Float64}) - @test length(pts) == 27 - @test length(dists) == 27 - @test isapprox(vlen(pts[1],pts[2]),0.5) - @test length(pts) == length(unique(pts)) - end - - @testset "face centered cubic" begin - pts = [] - dists = [] - f(x) = -1 - DistMesh.facecenteredcubic!(f, pts, dists, 0.5, 0, Point{3,Float64}(0),Point{3,Float64}(1),Point{3,Float64}) - @test length(pts) == 216 - @test length(dists) == 216 - @test isapprox(vlen(pts[1],pts[2]),0.5) - @test length(pts) == length(unique(pts)) - end - -end + # 2. Compute Geometric Properties + total_area = sum(element_volumes(msh)) + min_q = minimum(element_qualities(msh)) + has_negative_area = minimum(element_volumes(msh)) < 0.0 -@testset "quality analysis" begin - @testset "triangles" begin - @test DistMesh.triqual([0,0,0],[1,0,0],[0,1,0]) == DistMesh.triqual([0,0,0],[2,0,0],[0,2,0]) - @test DistMesh.triqual([0,0,0],[1,0,1],[0,1,1]) == DistMesh.triqual([0,0,0],[2,0,2],[0,2,2]) - @test DistMesh.triqual([0,0,0],[2,0,0],[1,sqrt(3),0]) ≈ 1 - @test DistMesh.triqual([0,0,0],[1,sqrt(3),0],[2,0,0]) ≈ 1 - end - @testset "volume-length" begin - pts = ([1,0,-1/sqrt(2)], [-1,0,-1/sqrt(2)], [0,1,1/sqrt(2)], [0,-1,1/sqrt(2)]) - pts2 = ([1,1,1], [1,-1,-1], [-1,1,-1], [-1,-1,1]) - pts_degenerate = ([1,1,1], [1,1,1], [-1,1,-1], [-1,-1,1]) - @test DistMesh.volume_edge_ratio(pts...) ≈ 1 - @test DistMesh.volume_edge_ratio((pts.*2)...) ≈ 1 - @test DistMesh.volume_edge_ratio((pts.*1e-6)...) ≈ 1 - @test isnan(DistMesh.volume_edge_ratio((pts.*0)...)) - @test DistMesh.volume_edge_ratio(pts2...) ≈ 1 - @test DistMesh.volume_edge_ratio((pts2.*2)...) ≈ 1 - @test DistMesh.volume_edge_ratio(pts_degenerate...) == 0 + # 3. Check Winding / Topology + @test !has_negative_area - end -end + # 4. Check Total Area + area > 0.0 && @test isapprox(total_area, area, atol=areatol) -@testset "decompositions" begin - @testset "tets to triangles" begin - simps = [[4,3,2,1],[5,4,3,2],[1,2,3,4]] - tris = Tuple{Int,Int,Int}[] - DistMesh.tets_to_tris!(tris,simps) - @test tris == [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)] + # 5. Check Element Quality + @test min_q >= minqual end end -@testset "hilbert sort" begin - rng = 0:0.3:1 - a = Vector{Vector{Float64}}(undef,length(rng)^3) - i = 1 - for xi in rng, yi in rng, zi in rng - a[i] = [xi,yi,zi] - i += 1 +@testset "Unit Circle Mesh" begin + msh = distmesh2d(dcircle, huniform, 0.2, ((-1,-1), (1,1))) + check_mesh(msh, np=88, nt=143) + + for h in (0.01, 0.02, 0.05, 0.10, 0.15, 0.2) + msh = distmesh2d(dcircle, huniform, h, ((-1,-1), (1,1))) + check_mesh(msh, + area=pi, + areatol=h^2, # Not an exact circle + minqual=0.6 + ) end - DistMesh.hilbertsort!(a) - @test a == hilbert_a end -@testset "distmesh 3D" begin - d(p) = sqrt(sum(p.^2))-1 - result = distmesh(d,HUniform(),0.2) - @test length(result.points) == 485 - @test length(result.tetrahedra) == 2207 - result = distmesh(d,HUniform(),0.2, DistMeshSetup(distribution=:packed)) - @test length(result.points) == 742 - @test length(result.tetrahedra) == 3472 +# ------------------------------------------------------------------------------ +# Run all scripts in the examples/ directory - # test stats is not messing - result = distmesh(d,HUniform(),0.2, stats=true) - @test length(result.points) == 485 - @test length(result.tetrahedra) == 2207 +const EXAMPLES_DIR = joinpath(@__DIR__, "..", "examples") - result = distmesh(d,HUniform(),0.4, stats=true) - @test length(result.points) == 56 - @test length(result.tetrahedra) == 186 - #for fn in fieldnames(typeof(result.stats)) - # @test isapprox(getproperty(result.stats,fn), getproperty(stat_04,fn)) - #end -end +@testset "Examples" begin + # Get all .jl files + files = filter(f -> endswith(f, ".jl"), readdir(EXAMPLES_DIR)) + + for file in files + @testset "$file" begin + # Read the example file + path = joinpath(EXAMPLES_DIR, file) + content = read(path, String) + + # Swap GLMakie -> CairoMakie (for Headless tests) + content = replace(content, "using GLMakie" => "using CairoMakie") -@testset "dihedral metrics" begin - d(p) = sqrt(sum(p.^2))-1 - result = distmesh(d,HUniform(),0.2) - p = result.points - t = result.tetrahedra - all_angs = DistMesh.dihedral_angles(p,t) - min_angs = DistMesh.min_dihedral_angles(p,t) - ax = extrema(all_angs) - mx = extrema(min_angs) - @test ax[1] == mx[1] - @test all(ax .≈ (0.023502688273828173, 3.104396619996953)) - @test all(mx .≈ (0.023502688273828173, 1.2044902180168893)) + # Run the code + try + include_string(Main, content, path) + @test true + catch e + @error "Example $file failed to run" exception=(e, catch_backtrace()) + @test false + end + end + end end diff --git a/test/vals.jl b/test/vals.jl deleted file mode 100644 index 193aa30..0000000 --- a/test/vals.jl +++ /dev/null @@ -1,4 +0,0 @@ -#stat_04 = DistMeshStatistics{Float64}([0.015861808197171447, 0.04333997993833317, 0.030539364290593892, 0.03136281119397018, 0.02563981053478331, 0.013146443917954281, 0.01175223918624788, 0.010072460884465097, 0.010095555217344735, 0.01013796999511984, 0.010140632643274205, 0.010304587497854923, 0.010462582532303984, 0.010716139899621396, 0.011021054862975449, 0.011240323884294448, 0.01142232855445764, 0.011612249108897528, 0.011811272270023909, 0.012034107769143534, 0.012056898531952622, 0.012293750640801487, 0.01253910968482863, 0.013004095618999076, 0.013252841175879744, 0.013917719093503656, 0.013396847948485273, 0.003189020157222165, 0.001562109707501573, 0.0009931741145458414, 0.0006511321515956363, 0.0004797453102939885, 0.00037832020260625596], [0.01586180819717149, 0.043339979938333134, 0.030539364290593937, 0.025048818294013803, 0.025639810534783355, 0.013146443917954269, 0.011752239186247897, 0.010072460884465097, 0.010095555217344726, 0.0101379699951199, 0.010140632643274243, 0.010304587497854942, 0.01046258253230403, 0.010716139899621346, 0.011021054862975494, 0.011240323884294462, 0.011422328554457682, 0.01161224910889749, 0.011811272270023897, 0.012034107769143534, 0.012056898531952602, 0.012293750640801451, 0.012539109684828593, 0.012245282734261766, 0.0023300852630041935, 0.002447933509399279, 0.0025695121186121712, 0.002338682036472209, 0.0015621097075015642, 0.0009931741145458226, 0.0006511321515956257, 0.00044189161676361335, 0.00031167049211313627], [0.8513479333014904, 0.7999266605934156, 0.8237832569578655, 0.817521012694373, 0.8296223294441304, 0.8782925269541574, 0.8923366367078434, 0.8927651653134971, 0.8945352521480744, 0.8976771953430919, 0.9006192563827091, 0.9015511578835772, 0.9023325838482263, 0.9021231128462143, 0.9013980826173323, 0.9013870765654909, 0.9016622807520963, 0.9018313595924459, 0.9018918673592288, 0.9018399155548923, 0.9017386119698663, 0.9014401063090378, 0.9010116089076747, 0.8993122456162714, 0.8985981708401958, 0.8955172651439618, 0.8942894809739554, 0.8907754718921969, 0.8909268818143122, 0.8910108579548632, 0.8910571422908532, 0.8910820499895338, 0.8910946964871009], [0.8652080743786591, 0.8543837234573923, 0.8623250243903223, 0.8600554459902974, 0.8623728487909205, 0.8675526892316004, 0.86813448792801, 0.867886604152207, 0.8683165255416818, 0.8741409899736776, 0.8874376497339312, 0.8871929206150294, 0.8868023977155903, 0.8862767476859909, 0.8855800788413576, 0.8847996249062478, 0.883963567834448, 0.8830513999087894, 0.8820448631022926, 0.8809192341868274, 0.8797024210613953, 0.8783238518802771, 0.8767724740675475, 0.8749410864744815, 0.872938454517967, 0.8706218244939238, 0.8702910360100947, 0.8684338642874472, 0.8683585516484286, 0.8682860253670031, 0.8682092206857535, 0.8681310653003876, 0.8680532945221214], [0.8042665470208608, 0.030882544034837138, 0.031205915063413674, 0.039027484580454345, 0.043185620349155414, 0.7801798146155217, 0.7757327592563474, 0.7895610286647429, 0.7982628961615663, 0.8019173511962595, 0.8080797261120612, 0.8113232071425015, 0.8141475611173873, 0.8164017608524986, 0.8162646723007843, 0.8161431245874965, 0.8160398512387739, 0.8159572530416423, 0.8158854172957702, 0.8158108155078492, 0.8157818549664978, 0.8157456416732362, 0.8157018839829728, 0.8155656386618806, 0.8154254644984282, 0.8152833339192274, 0.8151391827922918, 0.7527856381383334, 0.7513436255829244, 0.7502417424228109, 0.749393575220651, 0.7487360804668232, 0.7482227724278689], [1.0000000000000002, 1.0, 0.9999999999288185, 0.9999999997538248, 0.9999999998746554, 0.9999999996769505, 0.9999999998056341, 0.9999999998989167, 0.9999999999633605, 0.9999999999958346, 0.9999999999853654, 0.9999999999148561, 0.9999999997622445, 0.9999999995007761, 0.9999999991000814, 0.999999999251637, 0.9999999989511745, 0.9999999983301885, 0.9999999974434121, 0.9999999963425825, 0.9999999951246715, 0.9999999937977475, 0.9999999924659485, 0.9999999911705475, 0.9999999900045999, 0.9999999889813795, 0.9999999881198527, 0.999999983355277, 0.9999999885253779, 0.9999999920525013, 0.9999999944812701, 0.999999996164262, 0.9999999973343159], [0.567656495859004, 0.001208133246415821, 5.807412554687958e-5, 0.0007585537896351211, 0.005144029841366791, 1.8622515759872645e-5, 0.0010187380481615181, 0.00472431489407814, 0.0044099961715646846, 0.004097353626958525, 0.0037928020570145785, 0.0035002143173518386, 0.0032400946364245587, 0.0010802784097499337, 0.0009467684016039907, 0.0008722065889398544, 0.0015103488748075698, 0.0016375144330289203, 0.0012347159490814106, 0.0008279310464794467, 0.004262842381860203, 0.004971613172964763, 0.005683081137010508, 0.0023835115478611003, 0.002942999395935075, 0.0018751049144915893, 0.001311668048234658, 0.0003334346940654691, 0.000338146509556331, 0.0003375729016325274, 0.00033346089771292493, 0.0003270922983339331, 0.0003193882554204471] -#,[0.9993197499803357, 0.996275531043326, 0.9935584654924047, 0.9886977699392009, 0.9901266852334549, 0.9905268840250959, 0.9925334319042799, 0.9942877035837783, 0.9952835828669422, 0.9958803224524336, 0.9962760032478873, 0.9966123241717426, 0.9969339673790191, 0.9972731371313256, 0.9976289891233671, 0.9979765868142796, 0.9983021513556015, 0.998608051528163, 0.9988921395426992, 0.9991511627731727, 0.9994013273534111, 0.9996092165494008, 0.9997746356452248, 0.9998898901508024, 0.9999685361050338, 0.9999993773318173, 0.9999883870491219, 0.9999811777994916, 0.9999449029670939, 0.9999048076517231, 0.9998698615833159, 0.9998419637859888, 0.9998207131917966] -#, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]) -hilbert_a = Array{Float64,1}[[0.9, 0.9, 0.9], [0.6, 0.6, 0.9], [0.6, 0.9, 0.9], [0.6, 0.6, 0.6], [0.9, 0.9, 0.6], [0.9, 0.6, 0.6], [0.6, 0.9, 0.6], [0.9, 0.6, 0.9], [0.6, 0.3, 0.9], [0.9, 0.3, 0.9], [0.6, 0.3, 0.6], [0.9, 0.0, 0.9], [0.9, 0.0, 0.6], [0.9, 0.3, 0.6], [0.6, 0.0, 0.9], [0.6, 0.0, 0.6], [0.3, 0.0, 0.6], [0.0, 0.0, 0.6], [0.0, 0.0, 0.9], [0.0, 0.3, 0.6], [0.0, 0.3, 0.9], [0.3, 0.3, 0.9], [0.3, 0.0, 0.9], [0.3, 0.3, 0.6], [0.0, 0.6, 0.6], [0.0, 0.6, 0.9], [0.3, 0.6, 0.6], [0.3, 0.9, 0.9], [0.3, 0.6, 0.9], [0.0, 0.9, 0.6], [0.3, 0.9, 0.6], [0.3, 0.9, 0.3], [0.3, 0.9, 0.0], [0.0, 0.9, 0.9], [0.0, 0.9, 0.3], [0.3, 0.6, 0.3], [0.0, 0.9, 0.0], [0.3, 0.6, 0.0], [0.0, 0.6, 0.3], [0.0, 0.6, 0.0], [0.3, 0.3, 0.0], [0.0, 0.3, 0.3], [0.3, 0.0, 0.0], [0.3, 0.3, 0.3], [0.0, 0.0, 0.0], [0.0, 0.0, 0.3], [0.0, 0.3, 0.0], [0.3, 0.0, 0.3], [0.9, 0.0, 0.3], [0.6, 0.0, 0.3], [0.9, 0.3, 0.3], [0.6, 0.0, 0.0], [0.6, 0.3, 0.3], [0.9, 0.0, 0.0], [0.6, 0.3, 0.0], [0.9, 0.3, 0.0], [0.6, 0.6, 0.3], [0.6, 0.6, 0.0], [0.9, 0.6, 0.0], [0.9, 0.6, 0.3], [0.6, 0.9, 0.3], [0.9, 0.9, 0.0], [0.9, 0.9, 0.3], [0.6, 0.9, 0.0]]