Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e83b9bd158 | ||
|
|
2d0c705839 | ||
|
|
b36ec2ce0e | ||
|
|
b8d143dd72 | ||
|
|
be022a58e4 | ||
|
|
30e0af942a | ||
|
|
8c77a6aa05 | ||
|
|
54fa822408 | ||
|
|
7d564cfbc1 | ||
|
|
bc0bded294 | ||
|
|
d52decc4f1 | ||
|
|
8060376e12 | ||
|
|
eba866d266 | ||
|
|
cc4966f062 | ||
|
|
3216a24be8 | ||
|
|
5e566c8c36 | ||
|
|
80edfee978 | ||
|
|
0e0d1c4f69 | ||
|
|
e15f4cf375 | ||
|
|
c9322ca63a | ||
|
|
45826d6c47 | ||
|
|
dd781cdbdf | ||
|
|
638badaf9b | ||
|
|
0149e482bc | ||
|
|
f683e8c9c0 | ||
|
|
1f8e8037f1 | ||
|
|
10a15c1dd4 | ||
|
|
6e1629ddce | ||
|
|
e273f6b09d | ||
|
|
67c468211d | ||
|
|
01c38e42ca | ||
|
|
1991232eb7 | ||
|
|
4551288f95 | ||
|
|
2e29784449 | ||
|
|
2a2cb6f88e | ||
|
|
1a91d8db2a | ||
|
|
82b98d9353 | ||
|
|
7273c9bf0f | ||
|
|
4ff3f7cf68 | ||
|
|
fafe4792da | ||
|
|
b439603eb9 | ||
|
|
b6eea01021 | ||
|
|
b9f7228064 | ||
|
|
0ef5f70434 | ||
|
|
bb6acf1f6e | ||
|
|
5930b5c09d | ||
|
|
a842de97c6 | ||
|
|
2942229b49 | ||
|
|
0856539bfc | ||
|
|
621835683f | ||
|
|
bec8164120 | ||
|
|
062399c1c7 | ||
|
|
d51ee709c2 | ||
|
|
206871ac11 | ||
|
|
2055b9c412 | ||
|
|
5e103931f1 | ||
|
|
77051ead35 | ||
|
|
83b78f8356 | ||
|
|
6c6193c25b | ||
|
|
e79d343bec | ||
|
|
1d6a89ac87 | ||
|
|
8651bf8bd5 | ||
|
|
1514c15184 | ||
|
|
cc83e1b7aa | ||
|
|
111350f1ef | ||
|
|
b4f583fcae | ||
|
|
8011fb6072 | ||
|
|
9290d420b0 | ||
|
|
fca66380f5 | ||
|
|
8497e44915 | ||
|
|
a7eac92087 | ||
|
|
15399474fa | ||
|
|
2d513446f7 | ||
|
|
abff7e8ed3 | ||
|
|
7c454dc7a4 | ||
|
|
ffdd97d4d3 | ||
|
|
7facd0ecc0 | ||
|
|
59760b3369 | ||
|
|
5f9b484b6c | ||
|
|
18edefc6c4 | ||
|
|
93e06a2de8 | ||
|
|
047159e2c4 |
@@ -0,0 +1,59 @@
|
||||
name: build_wheels
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build_wheels:
|
||||
name: Build wheels on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04, windows-latest, macos-latest]
|
||||
steps:
|
||||
- run: |
|
||||
git config --global submodule.fetchJobs 8
|
||||
git config --global core.longpaths true
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Build wheels
|
||||
uses: pypa/cibuildwheel@v2.15.0
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
path: ./wheelhouse/*.whl
|
||||
|
||||
make_sdist:
|
||||
name: Make SDist
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Optional, use if you use setuptools_scm
|
||||
submodules: true # Optional, use if you have submodules
|
||||
|
||||
- name: Build SDist
|
||||
run: pipx run build --sdist
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
path: dist/*.tar.gz
|
||||
|
||||
pypi-publish:
|
||||
name: Upload release to PyPI
|
||||
needs: [build_wheels, make_sdist]
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: pypi
|
||||
url: https://pypi.org/p/manifold3d
|
||||
permissions:
|
||||
id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
|
||||
steps:
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifact
|
||||
path: dist
|
||||
- name: Publish package distributions to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
@@ -17,5 +17,8 @@ jobs:
|
||||
source: '.'
|
||||
exclude: '*/third_party'
|
||||
extensions: 'h,cpp,js,ts,html'
|
||||
clangFormatVersion: 12
|
||||
|
||||
clangFormatVersion: 11
|
||||
- uses: psf/black@stable
|
||||
with:
|
||||
options: "--check --verbose"
|
||||
src: "./bindings/python/examples"
|
||||
|
||||
@@ -15,47 +15,43 @@ jobs:
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
matrix:
|
||||
cuda_support: [ON, OFF]
|
||||
parallel_backend: [NONE, OMP, TBB]
|
||||
parallel_backend: [NONE, TBB]
|
||||
runs-on: ubuntu-22.04
|
||||
if: github.event.pull_request.draft == false
|
||||
container:
|
||||
image: docker://nvidia/cuda:12.0.1-devel-ubuntu22.04
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt-get -y update
|
||||
DEBIAN_FRONTEND=noninteractive apt install -y libomp-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip lcov
|
||||
pip install trimesh
|
||||
sudo apt-get -y update
|
||||
DEBIAN_FRONTEND=noninteractive sudo apt install -y libglm-dev libgtest-dev libassimp-dev git libtbb-dev libthrust-dev pkg-config libpython3-dev python3 python3-distutils python3-pip lcov
|
||||
pip install trimesh pytest
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: jwlawson/actions-setup-cmake@v1.12
|
||||
- name: Build ${{matrix.backend}}
|
||||
if: matrix.parallel_backend != 'NONE' || matrix.cuda_support != 'OFF'
|
||||
if: matrix.parallel_backend != 'NONE'
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_DEBUG=ON -DMANIFOLD_EXPORT=ON -DMANIFOLD_PAR=${{matrix.parallel_backend}} -DMANIFOLD_USE_CUDA=${{matrix.cuda_support}} .. && make
|
||||
- name: Test ${{matrix.parallel_backend}} with CUDA ${{matrix.cuda_support}}
|
||||
# note that the test for CUDA backend does not really test CUDA, as we
|
||||
# don't have CUDA GPU on GitHub Action
|
||||
if: matrix.parallel_backend != 'NONE' || matrix.cuda_support != 'OFF'
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_DEBUG=ON -DMANIFOLD_EXPORT=ON -DMANIFOLD_PAR=${{matrix.parallel_backend}} .. && make
|
||||
- name: Test ${{matrix.parallel_backend}}
|
||||
if: matrix.parallel_backend != 'NONE'
|
||||
run: |
|
||||
export PYTHONPATH=$PYTHONPATH:$(pwd)/build/bindings/python
|
||||
cd build/test
|
||||
./manifold_test
|
||||
cd ../../
|
||||
python3 bindings/python/examples/run_all.py
|
||||
python3 bindings/python/examples/run_all.py -e
|
||||
python3 -m pytest
|
||||
- name: Coverage Report
|
||||
# only do code coverage for default sequential backend, it seems that TBB
|
||||
# backend will cause failure
|
||||
# perhaps issue related to invalid memory access?
|
||||
if: matrix.parallel_backend == 'NONE' && matrix.cuda_support == 'OFF'
|
||||
if: matrix.parallel_backend == 'NONE'
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_PAR=${{matrix.parallel_backend}} -DMANIFOLD_USE_CUDA=${{matrix.cuda_support}} -DCODE_COVERAGE=ON .. && make
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_PAR=${{matrix.parallel_backend}} -DCODE_COVERAGE=ON .. && make
|
||||
lcov --capture --initial --directory . --output-file ./code_coverage_init.info
|
||||
cd test
|
||||
./manifold_test
|
||||
@@ -64,35 +60,31 @@ jobs:
|
||||
lcov --add-tracefile ./code_coverage_init.info --add-tracefile ./code_coverage_test.info --output-file ./code_coverage_total.info
|
||||
lcov --remove ./code_coverage_total.info '/usr/*' '*/third_party/*' '*/test/*' '*/extras/*' '*/bindings/*' --output-file ./code_coverage.info
|
||||
- uses: codecov/codecov-action@v2
|
||||
if: matrix.parallel_backend == 'NONE' && matrix.cuda_support == 'OFF'
|
||||
if: matrix.parallel_backend == 'NONE'
|
||||
with:
|
||||
files: build/code_coverage.info
|
||||
fail_ci_if_error: false
|
||||
name: ${{matrix.parallel_backend}}-${{matrix.cuda_support}}
|
||||
name: ${{matrix.parallel_backend}}
|
||||
|
||||
build_cbind:
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-22.04
|
||||
if: github.event.pull_request.draft == false
|
||||
container:
|
||||
image: docker://nvidia/cuda:12.0.1-devel-ubuntu22.04
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt-get -y update
|
||||
DEBIAN_FRONTEND=noninteractive apt install -y libomp-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip
|
||||
sudo apt-get -y update
|
||||
DEBIAN_FRONTEND=noninteractive sudo apt install -y libgtest-dev libglm-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: jwlawson/actions-setup-cmake@v1.12
|
||||
- name: Build C bindings with OMP and CUDA
|
||||
- name: Build C bindings with TBB
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_DEBUG=ON -DMANIFOLD_CBIND=ON -DMANIFOLD_PAR=OMP -DMANIFOLD_USE_CUDA=ON .. && make
|
||||
- name: Test ${{matrix.parallel_backend}} with CUDA ${{matrix.cuda_support}}
|
||||
# note that the test for CUDA backend does not really test CUDA, as we
|
||||
# don't have CUDA GPU on GitHub Action
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_DEBUG=ON -DMANIFOLD_CBIND=ON -DMANIFOLD_PAR=TBB .. && make
|
||||
- name: Test ${{matrix.parallel_backend}}
|
||||
run: |
|
||||
cd build/test
|
||||
./manifold_test --gtest_filter=CBIND.*
|
||||
@@ -105,7 +97,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get -y update
|
||||
DEBIAN_FRONTEND=noninteractive sudo apt install -y nodejs
|
||||
DEBIAN_FRONTEND=noninteractive sudo apt install -y nodejs libglm-dev
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
@@ -114,8 +106,8 @@ jobs:
|
||||
# setup emscripten
|
||||
git clone https://github.com/emscripten-core/emsdk.git
|
||||
cd emsdk
|
||||
./emsdk install latest
|
||||
./emsdk activate latest
|
||||
./emsdk install 3.1.45
|
||||
./emsdk activate 3.1.45
|
||||
- uses: jwlawson/actions-setup-cmake@v1.12
|
||||
- name: Build WASM
|
||||
run: |
|
||||
@@ -133,6 +125,7 @@ jobs:
|
||||
npm ci
|
||||
npm run build
|
||||
npm test
|
||||
cp ../manifold.* ./dist/
|
||||
- name: Upload WASM files
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
@@ -144,8 +137,7 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
parallel_backend: [NONE]
|
||||
cuda_support: [OFF]
|
||||
parallel_backend: [NONE, TBB]
|
||||
max-parallel: 1
|
||||
runs-on: windows-2019
|
||||
if: github.event.pull_request.draft == false
|
||||
@@ -155,35 +147,40 @@ jobs:
|
||||
submodules: recursive
|
||||
- uses: jwlawson/actions-setup-cmake@v1.12
|
||||
- uses: ilammy/msvc-dev-cmd@v1
|
||||
- name: Install CUDA
|
||||
if: matrix.backend == 'CUDA'
|
||||
env:
|
||||
cuda: "11.3.0"
|
||||
visual_studio: "Visual Studio 16 2019"
|
||||
shell: powershell
|
||||
run: |
|
||||
Invoke-RestMethod https://raw.githubusercontent.com/ptheywood/cuda-cmake-github-actions/21811d232fc775fa8d44dddf7f8c5ce2cf8d2b81/scripts/actions/install_cuda_windows.ps1 -OutFile install_cuda_windows.ps1
|
||||
.\install_cuda_windows.ps1
|
||||
- name: nvcc check
|
||||
if: matrix.backend == 'CUDA'
|
||||
shell: powershell
|
||||
run: |
|
||||
nvcc -V
|
||||
ls $env:CUDA_PATH
|
||||
ls $env:CUDA_PATH\bin
|
||||
ls $env:CUDA_PATH\include
|
||||
- name: Build ${{matrix.backend}}
|
||||
shell: powershell
|
||||
run: |
|
||||
cmake . -DCMAKE_BUILD_TYPE=Release -B build -DMANIFOLD_DEBUG=ON -DPYBIND11_FINDPYTHON=OFF -DMANIFOLD_PAR=${{matrix.parallel_backend}} -DMANIFOLD_USE_CUDA=${{matrix.cuda_support}} -A x64
|
||||
cmake . -DCMAKE_BUILD_TYPE=Release -B build -DMANIFOLD_DEBUG=ON -DPYBIND11_FINDPYTHON=OFF -DMANIFOLD_PAR=${{matrix.parallel_backend}} -A x64
|
||||
cd build
|
||||
cmake --build . --target ALL_BUILD --config Release
|
||||
- name: Test ${{matrix.parallel_backend}} with CUDA ${{matrix.cuda_support}}
|
||||
- name: Test ${{matrix.parallel_backend}}
|
||||
shell: bash
|
||||
run: |
|
||||
cd build/test
|
||||
./Release/manifold_test.exe
|
||||
|
||||
build_mxe:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
parallel_backend: [NONE, TBB]
|
||||
max-parallel: 1
|
||||
runs-on: ubuntu-latest
|
||||
container: openscad/mxe-x86_64-gui:latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Build
|
||||
run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DMANIFOLD_PYBIND=OFF -DMANIFOLD_DEBUG=ON -DMANIFOLD_PAR=${{matrix.parallel_backend}} .. && make
|
||||
- name: Test
|
||||
run: |
|
||||
cd build/test
|
||||
./manifold_test
|
||||
|
||||
build_mac:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -194,11 +191,8 @@ jobs:
|
||||
steps:
|
||||
- name: Install common dependencies
|
||||
run: |
|
||||
brew install pkg-config assimp
|
||||
pip install trimesh
|
||||
- name: Install OpenMP
|
||||
if: matrix.parallel_backend == 'OMP'
|
||||
run: brew install libomp
|
||||
brew install pkg-config googletest assimp
|
||||
pip install trimesh pytest
|
||||
- name: Install TBB
|
||||
if: matrix.parallel_backend == 'TBB'
|
||||
run: brew install tbb
|
||||
@@ -220,12 +214,23 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
variant: [none, omp, tbb, none-cuda, omp-cuda, tbb-cuda, js]
|
||||
variant: [none, tbb, js]
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.pull_request.draft == false
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: cachix/install-nix-action@v15
|
||||
- uses: cachix/install-nix-action@v22
|
||||
- run: nix build -L '.?submodules=1#manifold-${{matrix.variant}}'
|
||||
|
||||
build_nix_python:
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.pull_request.draft == false
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: cachix/install-nix-action@v22
|
||||
- run: nix build -L '.?submodules=1#manifold3d'
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
name: publish_npm
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish_npm:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: '20.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Download built examples
|
||||
uses: dawidd6/action-download-artifact@v2
|
||||
with:
|
||||
workflow: manifold.yml
|
||||
workflow_conclusion: completed
|
||||
name: wasm
|
||||
path: ./bindings/wasm/
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
cd ./bindings/wasm/
|
||||
npm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
+3
-13
@@ -1,19 +1,9 @@
|
||||
[submodule "third_party/thrust"]
|
||||
path = src/third_party/thrust
|
||||
url = https://github.com/NVIDIA/thrust
|
||||
[submodule "third_party/glm"]
|
||||
path = src/third_party/glm
|
||||
url = https://github.com/g-truc/glm
|
||||
[submodule "third_party/google_test"]
|
||||
path = test/third_party/google_test
|
||||
url = https://github.com/google/googletest.git
|
||||
[submodule "third_party/pybind11"]
|
||||
path = bindings/python/third_party/pybind11
|
||||
url = https://github.com/pybind/pybind11
|
||||
branch = stable
|
||||
[submodule "src/third_party/clipper2"]
|
||||
path = src/third_party/clipper2
|
||||
url = https://github.com/AngusJohnson/clipper2
|
||||
[submodule "src/third_party/quickhull"]
|
||||
path = src/third_party/quickhull
|
||||
url = https://github.com/akuukka/quickhull
|
||||
[submodule "bindings/python/third_party/nanobind"]
|
||||
path = bindings/python/third_party/nanobind
|
||||
url = https://github.com/wjakob/nanobind
|
||||
|
||||
Vendored
+6
-1
@@ -118,7 +118,7 @@
|
||||
"-DMANIFOLD_EXPORT=ON",
|
||||
"-DMANIFOLD_DEBUG=ON",
|
||||
"-DMANIFOLD_USE_CUDA=OFF",
|
||||
"-DMANIFOLD_PAR=NONE",
|
||||
"-DMANIFOLD_PAR=TBB",
|
||||
"-DCODE_COVERAGE=OFF",
|
||||
"-DCMAKE_CXX_FLAGS=''" //'-fsanitize=address,undefined'"
|
||||
],
|
||||
@@ -140,4 +140,9 @@
|
||||
"Verts"
|
||||
],
|
||||
"javascript.format.semicolons": "insert",
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
"python.formatting.provider": "none",
|
||||
"clang-format.executable": "clang-format",
|
||||
}
|
||||
+57
-39
@@ -16,68 +16,86 @@ cmake_minimum_required(VERSION 3.18)
|
||||
project(manifold LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_VERBOSE_MAKEFILE ON)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
set(MANIFOLD_PAR "NONE" CACHE STRING "Parallel backend, either \"TBB\" or \"NONE\"")
|
||||
set(MANIFOLD_FLAGS "" CACHE STRING "Manifold compiler flags")
|
||||
option(MANIFOLD_EXPORT "Build mesh export (via assimp) utility library" OFF)
|
||||
option(MANIFOLD_TEST "Enable testing suite" ON)
|
||||
# fuzztest is a rather large dependency
|
||||
option(MANIFOLD_FUZZ "Enable fuzzing tests" OFF)
|
||||
option(MANIFOLD_DEBUG "Enable debug tracing/timing" OFF)
|
||||
option(MANIFOLD_USE_CUDA "Enable GPU support via CUDA" OFF)
|
||||
option(MANIFOLD_PYBIND "Build python bindings" ON)
|
||||
option(MANIFOLD_CBIND "Build C (FFI) bindings" OFF)
|
||||
set(MANIFOLD_PAR "NONE" CACHE STRING "Parallel backend, either \"TBB\" or \"OpenMP\" or \"NONE\"")
|
||||
set(MANIFOLD_FLAGS -O3)
|
||||
option(MANIFOLD_JSBIND "Build js binding" ${EMSCRIPTEN})
|
||||
|
||||
if(MANIFOLD_FUZZ)
|
||||
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
message(FATAL_ERROR "fuzztest only supports clang" )
|
||||
endif()
|
||||
# we should enable debug checks
|
||||
set(MANIFOLD_DEBUG ON)
|
||||
# enable fuzztest fuzzing mode
|
||||
set(FUZZTEST_FUZZING_MODE ON)
|
||||
# address sanitizer required
|
||||
set(CMAKE_CXX_FLAGS "$CMAKE_CXX_FLAGS -fsanitize=address")
|
||||
endif()
|
||||
|
||||
option(TRACY_ENABLE "Use tracy profiling" OFF)
|
||||
option(TRACY_MEMORY_USAGE "Track memory allocation with tracy (expensive)" OFF)
|
||||
option(BUILD_TEST_CGAL "Build CGAL performance comparisons" OFF)
|
||||
if(TRACY_ENABLE)
|
||||
option(CMAKE_BUILD_TYPE "Build type" RelWithDebInfo)
|
||||
if(TRACY_MEMORY_USAGE)
|
||||
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} -DTRACY_MEMORY_USAGE)
|
||||
endif()
|
||||
if(NOT MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-omit-frame-pointer")
|
||||
endif()
|
||||
else()
|
||||
option(CMAKE_BUILD_TYPE "Build type" Release)
|
||||
endif()
|
||||
|
||||
if(EMSCRIPTEN)
|
||||
message("Building for Emscripten")
|
||||
set(MANIFOLD_FLAGS -fexceptions -D_LIBCUDACXX_HAS_THREAD_API_EXTERNAL -D_LIBCUDACXX_HAS_THREAD_API_CUDA)
|
||||
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -sALLOW_MEMORY_GROWTH=1)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sALLOW_MEMORY_GROWTH=1 -fexceptions -sDISABLE_EXCEPTION_CATCHING=0")
|
||||
set(MANIFOLD_PYBIND OFF)
|
||||
endif()
|
||||
|
||||
option(PYBIND11_FINDPYTHON "Enable PyBind to perform FindPython for you" ON)
|
||||
|
||||
option(BUILD_TEST_CGAL "Build CGAL performance comparisons" OFF)
|
||||
|
||||
option(BUILD_SHARED_LIBS "Build dynamic/shared libraries" OFF)
|
||||
set(PYBIND11_DIR ${PROJECT_SOURCE_DIR}/bindings/python/third_party/pybind11)
|
||||
set(THRUST_INC_DIR ${PROJECT_SOURCE_DIR}/src/third_party/thrust)
|
||||
|
||||
if(BUILD_SHARED_LIBS OR MANIFOLD_CBIND)
|
||||
# Allow shared libraries to be relocatable (add Place Independent Code flag).
|
||||
# Also include when statically linking C bindings to avoid issues with bundling
|
||||
# artefacts in host languages using them for FFI.
|
||||
add_compile_options(-fPIC)
|
||||
if(MANIFOLD_PYBIND)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
if(Python_VERSION VERSION_LESS 3.12)
|
||||
find_package(Python COMPONENTS Interpreter Development.Module REQUIRED)
|
||||
else()
|
||||
find_package(Python COMPONENTS Interpreter Development.SABIModule REQUIRED)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(MANIFOLD_USE_CUDA)
|
||||
enable_language(CUDA)
|
||||
find_package(CUDA REQUIRED)
|
||||
|
||||
# we cannot set THRUST_INC_DIR when building with CUDA, otherwise the
|
||||
# compiler will not use the system CUDA headers which causes incompatibility
|
||||
# clear THRUST_INC_DIR, we use the one from nvcc
|
||||
set(THRUST_INC_DIR "")
|
||||
set(MANIFOLD_NVCC_RELEASE_FLAGS -O3 -lineinfo)
|
||||
set(MANIFOLD_NVCC_DEBUG_FLAGS -G)
|
||||
set(MANIFOLD_NVCC_FLAGS -Xcudafe --diag_suppress=esa_on_defaulted_function_ignored --extended-lambda --expt-relaxed-constexpr
|
||||
"$<$<CONFIG:RELEASE>:${MANIFOLD_NVCC_RELEASE_FLAGS}>"
|
||||
"$<$<CONFIG:DEBUG>:${MANIFOLD_NVCC_DEBUG_FLAGS}>")
|
||||
if(CMAKE_EXPORT_COMPILE_COMMANDS AND NOT EMSCRIPTEN)
|
||||
# for nixos
|
||||
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
|
||||
${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES})
|
||||
endif()
|
||||
|
||||
if(NOT MSVC)
|
||||
set(WARNING_FLAGS -Werror -Wall -Wno-sign-compare -Wno-unused)
|
||||
add_compile_options(
|
||||
"$<$<COMPILE_LANGUAGE:CXX>:${WARNING_FLAGS}>"
|
||||
"$<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=${WARNING_FLAGS}>")
|
||||
if (MSVC)
|
||||
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} /DNOMINMAX)
|
||||
else()
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
set(WARNING_FLAGS -Werror -Wall -Wno-sign-compare -Wno-unused -Wno-array-bounds -Wno-stringop-overflow)
|
||||
else()
|
||||
set(WARNING_FLAGS -Werror -Wall -Wno-sign-compare -Wno-unused)
|
||||
endif()
|
||||
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} ${WARNING_FLAGS} -O3)
|
||||
endif()
|
||||
|
||||
if(CODE_COVERAGE AND NOT MSVC)
|
||||
set(COVERAGE_FLAGS -coverage -fno-inline-small-functions -fkeep-inline-functions -fkeep-static-functions)
|
||||
add_compile_options(
|
||||
"$<$<COMPILE_LANGUAGE:CXX>:${COVERAGE_FLAGS}>"
|
||||
"$<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=-coverage>")
|
||||
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} ${COVERAGE_FLAGS})
|
||||
add_link_options("-coverage")
|
||||
endif()
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
add_subdirectory(src)
|
||||
add_subdirectory(bindings)
|
||||
|
||||
|
||||
@@ -1,41 +1,46 @@
|
||||
[](https://codecov.io/github/elalish/manifold)
|
||||
[](https://badge.fury.io/py/manifold3d)
|
||||
[](https://badge.fury.io/js/manifold-3d)
|
||||
[](https://twitter.com/intent/follow?screen_name=manifoldcad)
|
||||
|
||||
## Users
|
||||
|
||||
[OpenSCAD](https://openscad.org/), [IFCjs](https://ifcjs.github.io/info/), [Grid.Space](https://grid.space/), and [OCADml](https://github.com/OCADml/OManifold) have all integrated our Manifold geometry kernel! Why? Because its reliability is guaranteed and it's 1,000 times faster than other libraries. See our [usage](https://github.com/elalish/manifold/discussions/340) and [performance](https://github.com/elalish/manifold/discussions/383) discussions for all the latest and to add your own projects & analyses.
|
||||
|
||||
For example, here is a log-log plot of Manifold's performance vs. earlier OpenSCAD geometry backends:
|
||||
## Manifold Frontend Sandboxes
|
||||
|
||||
<img src="https://elalish.github.io/manifold/samples/models/perfSpheres.png" width="350px"/>
|
||||
### [ManifoldCAD.org](https://manifoldcad.org)
|
||||
|
||||
## [ManifoldCAD.org](https://manifoldcad.org)
|
||||
If you like OpenSCAD / JSCAD, you might also like ManifoldCAD - our own solid modelling web app where you script in JS/TS. This uses our npm package, [manifold-3d](https://www.npmjs.com/package/manifold-3d), built via WASM. It's not quite as fast as our raw C++, but it's hard to beat for interoperability.
|
||||
|
||||
If you like OpenSCAD / JSCAD, you might also like ManifoldCAD - our own solid modelling web app. Our WASM is not GPU-accelerated, but it's still quite fast and a good way to test out our Manifold library.
|
||||
*Note for Firefox users: If you find the editor is stuck on **Loading...**, setting
|
||||
`dom.workers.modules.enabled: true` in your `about:config`, as mentioned in
|
||||
[issue#328](https://github.com/elalish/manifold/issues/328#issuecomment-1473847102)
|
||||
may solve the problem.*
|
||||
|
||||
### [Python Colab Example](https://colab.research.google.com/drive/1VxrFYHPSHZgUbl9TeWzCeovlpXrPQ5J5?usp=sharing)
|
||||
|
||||
If you prefer Python to JS/TS, make your own copy of the example notebook above. It demonstrates interop between our [`manifold3d`](https://pypi.org/project/manifold3d/) PyPI library and the popular [`trimesh`](https://pypi.org/project/trimesh/) library, including showing the interactive model right in the notebook and saving 3D model output.
|
||||
|
||||

|
||||
|
||||
### Note for Firefox users
|
||||
|
||||
If you find the editor is stuck on **Loading...**, setting
|
||||
`dom.workers.modules.enabled: true` in your `about:config`, as mentioned in the
|
||||
discussion of the
|
||||
[issue#328](https://github.com/elalish/manifold/issues/328#issuecomment-1473847102)
|
||||
of this repository may solve the problem.
|
||||
|
||||
# Manifold
|
||||
|
||||
[**API Documentation**](https://elalish.github.io/manifold/docs/html/modules.html) | [**Algorithm Documentation**](https://github.com/elalish/manifold/wiki/Manifold-Library) | [**Blog Posts**](https://elalish.blogspot.com/search/label/Manifold) | [**Web Examples**](https://elalish.github.io/manifold/model-viewer.html)
|
||||
|
||||
[Manifold](https://github.com/elalish/manifold) is a geometry library dedicated to creating and operating on manifold triangle meshes. A [manifold mesh](https://github.com/elalish/manifold/wiki/Manifold-Library#manifoldness) is a mesh that represents a solid object, and so is very important in manufacturing, CAD, structural analysis, etc. Further information can be found on the [wiki](https://github.com/elalish/manifold/wiki/Manifold-Library).
|
||||
|
||||
This is a modern C++ library that Github's CI verifies builds and runs on a variety of platforms. Additionally, we build bindings for JavaScript ([manifold-3d](https://www.npmjs.com/package/manifold-3d) on npm), Python, and C to make this library more portable and easy to use.
|
||||
This is a modern C++ library that Github's CI verifies builds and runs on a variety of platforms. Additionally, we build bindings for JavaScript ([manifold-3d](https://www.npmjs.com/package/manifold-3d) on npm), Python ([manifold3d](https://pypi.org/project/manifold3d/)), and C to make this library more portable and easy to use.
|
||||
|
||||
We have four core dependencies, making use of submodules to ensure compatibility:
|
||||
- `graphlite`: connected components algorithm
|
||||
- `Clipper2`: provides our 2D subsystem
|
||||
- `GLM`: a compact vector library
|
||||
- `Thrust`: Nvidia's parallel algorithms library (basically a superset of C++17 std::parallel_algorithms)
|
||||
System Dependencies (note that we will automatically download the dependency if there is no such package on the system):
|
||||
- [`GLM`](https://github.com/g-truc/glm/): A compact header-only vector library.
|
||||
- [`Thrust`](https://github.com/NVIDIA/thrust): NVIDIA's parallel algorithms library (basically a superset of C++17 std::parallel_algorithms)
|
||||
- [`tbb`](https://github.com/oneapi-src/oneTBB/): Intel's thread building blocks library. (only when `MANIFOLD_PAR=TBB` is enabled)
|
||||
- [`gtest`](https://github.com/google/googletest/): Google test library (only when test is enabled, i.e. `MANIFOLD_TEST=ON`)
|
||||
|
||||
Other dependencies:
|
||||
- [`Clipper2`](https://github.com/AngusJohnson/Clipper2): provides our 2D subsystem
|
||||
- [`quickhull`](https://github.com/akuukka/quickhull): 3D convex hull algorithm.
|
||||
|
||||
## What's here
|
||||
|
||||
@@ -43,7 +48,9 @@ This library is fast with guaranteed manifold output. As such you need manifold
|
||||
|
||||
The most significant contribution here is a guaranteed-manifold [mesh Boolean](https://github.com/elalish/manifold/wiki/Manifold-Library#mesh-boolean) algorithm, which I believe is the first of its kind. If you know of another, please open a discussion - a mesh Boolean algorithm robust to edge cases has been an open problem for many years. Likewise, if the Boolean here ever fails you, please submit an issue! This Boolean forms the basis of a CAD kernel, as it allows simple shapes to be combined into more complex ones.
|
||||
|
||||
To aid in speed, this library makes extensive use of parallelization, generally through Nvidia's Thrust library. You can switch between the CUDA, OMP, TBB, and serial C++ backends by setting a CMake flag. Not everything is so parallelizable, for instance a [polygon triangulation](https://github.com/elalish/manifold/wiki/Manifold-Library#polygon-triangulation) algorithm is included which is serial. Even if compiled for CUDA, the code will still run without a GPU, falling back to the serial version of the algorithms. The WASM build is serial-only for now, but still fast.
|
||||
To aid in speed, this library makes extensive use of parallelization, generally through Nvidia's Thrust library. You can switch between the TBB, and serial C++ backends by setting a CMake flag. Not everything is so parallelizable, for instance a [polygon triangulation](https://github.com/elalish/manifold/wiki/Manifold-Library#polygon-triangulation) algorithm is included which is serial. Even if compiled with parallel backend, the code will still fall back to the serial version of the algorithms if the problem size is small. The WASM build is serial-only for now, but still fast.
|
||||
|
||||
> Note: OMP and CUDA backends are now removed
|
||||
|
||||
Look in the [samples](https://github.com/elalish/manifold/tree/master/samples) directory for examples of how to use this library to make interesting 3D models. You may notice that some of these examples bare a certain resemblance to my OpenSCAD designs on [Thingiverse](https://www.thingiverse.com/emmett), which is no accident. Much as I love OpenSCAD, my library is dramatically faster and the code is more flexible.
|
||||
|
||||
@@ -61,16 +68,30 @@ cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON .. && make
|
||||
test/manifold_test
|
||||
```
|
||||
|
||||
CMake flags (usage e.g. `-DMANIFOLD_USE_CUDA=ON`):
|
||||
- `MANIFOLD_USE_CUDA=[<OFF>, ON]`: Provides Nvidia GPU parallelization, requires CUDA Toolkit and its nvcc compiler.
|
||||
- `MANIFOLD_PAR=[<NONE>, OMP, TBB]`: Provides multi-thread parallelization, requires `libomp-dev` or `libtbb-dev`.
|
||||
CMake flags (usage e.g. `-DMANIFOLD_DEBUG=ON`):
|
||||
- `MANIFOLD_JSBIND=[OFF, <ON>]`: Build js binding when using emscripten.
|
||||
- `MANIFOLD_CBIND=[<OFF>, ON]`: Build C FFI binding.
|
||||
- `MANIFOLD_PYBIND=[OFF, <ON>]`: Build python binding.
|
||||
- `MANIFOLD_PAR=[<NONE>, TBB]`: Provides multi-thread parallelization, requires `libtbb-dev` if `TBB` backend is selected.
|
||||
- `MANIFOLD_EXPORT=[<OFF>, ON]`: Enables GLB export of 3D models from the tests, requires `libassimp-dev`.
|
||||
- `MANIFOLD_DEBUG=[<OFF>, ON]`: Enables internal assertions and exceptions.
|
||||
- `MANIFOLD_TEST=[OFF, <ON>]`: Build unittests.
|
||||
- `TRACY_ENABLE=[<OFF>, ON]`: Enable integration with tracy profiler.
|
||||
See profiling section below.
|
||||
- `BUILD_TEST_CGAL=[<OFF>, ON]`: Builds a CGAL-based performance [comparison](https://github.com/elalish/manifold/tree/master/extras), requires `libcgal-dev`.
|
||||
|
||||
Offline building:
|
||||
- `FETCHCONTENT_SOURCE_DIR_GLM`: path to glm source.
|
||||
- `FETCHCONTENT_SOURCE_DIR_GOOGLETEST`: path to googletest source.
|
||||
- `FETCHCONTENT_SOURCE_DIR_THRUST`: path to NVIDIA thrust source.
|
||||
|
||||
The build instructions used by our CI are in [manifold.yml](https://github.com/elalish/manifold/blob/master/.github/workflows/manifold.yml), which is a good source to check if something goes wrong and for instructions specific to other platforms, like Windows.
|
||||
|
||||
### WASM
|
||||
|
||||
> Note that we have only tested emscripten version 3.1.45. It is known that
|
||||
3.1.48 has some issues compiling manifold.
|
||||
|
||||
To build the JS WASM library, first install NodeJS and set up emscripten:
|
||||
|
||||
(on Mac):
|
||||
@@ -99,12 +120,12 @@ node test/manifold_test.js
|
||||
### Python
|
||||
|
||||
The CMake script will build the python binding `manifold3d` automatically. To
|
||||
use the extension, please add `$BUILD_DIR/tools` to your `PYTHONPATH`, where
|
||||
use the extension, please add `$BUILD_DIR/bindings/python` to your `PYTHONPATH`, where
|
||||
`$BUILD_DIR` is the build directory for CMake. Examples using the python binding
|
||||
can be found in `bindings/python/examples`. To see exported samples, run:
|
||||
```
|
||||
sudo apt install pkg-config libpython3-dev python3 python3-distutils python3-pip
|
||||
pip install trimesh
|
||||
pip install trimesh pytest
|
||||
python3 run_all.py -e
|
||||
```
|
||||
|
||||
@@ -122,6 +143,31 @@ For more detailed documentation, please refer to the C++ API.
|
||||
|
||||
Contributions are welcome! A lower barrier contribution is to simply make a PR that adds a test, especially if it repros an issue you've found. Simply name it prepended with DISABLED_, so that it passes the CI. That will be a very strong signal to me to fix your issue. However, if you know how to fix it yourself, then including the fix in your PR would be much appreciated!
|
||||
|
||||
### Formatting
|
||||
|
||||
There is a formatting script `format.sh` that automatically formats everything.
|
||||
It requires clang-format 11 and black formatter for python.
|
||||
|
||||
If you have clang-format installed but without clang-11, you can specify the
|
||||
clang-format executable by setting the `CLANG_FORMAT` environment variable.
|
||||
|
||||
### Profiling
|
||||
|
||||
There is now basic support for the [Tracy profiler](https://github.com/wolfpld/tracy) for our tests.
|
||||
To enable tracing, compile with `-DTRACY_ENABLE=on` cmake option, and run the test with Tracy server running.
|
||||
To enable memory profiling in addition to tracing, compile with `-DTRACY_MEMORY_USAGE=ON` in addition to `-DTRACY_ENABLE=ON`.
|
||||
|
||||
### Fuzzing Support
|
||||
|
||||
We use https://github.com/google/fuzztest for fuzzing the triangulator.
|
||||
|
||||
To enable fuzzing, make sure that you are using clang compiler (`-DCMAKE_CXX_COMPILER=clang -DCMAKE_C_COMPILER=clang`), running Linux, and enable fuzzing support by setting `-DMANIFOLD_FUZZ=ON`.
|
||||
|
||||
To run the fuzzer and minimize testcase, do
|
||||
```
|
||||
../minimizer.sh ./test/polygon_fuzz --fuzz=PolygonFuzz.TriangulationNoCrash
|
||||
```
|
||||
|
||||
## About the author
|
||||
|
||||
This library was started by [Emmett Lalish](https://elalish.blogspot.com/). I am currently a Google employee and this is my 20% project, not an official Google project. At my day job I'm the maintainer of [\<model-viewer\>](https://modelviewer.dev/). I was the first employee at a 3D video startup, [Omnivor](https://www.omnivor.io/), and before that I worked on 3D printing at Microsoft, including [3D Builder](https://www.microsoft.com/en-us/p/3d-builder/9wzdncrfj3t6?activetab=pivot%3Aoverviewtab). Originally an aerospace engineer, I started at a small DARPA contractor doing seedling projects, one of which became [Sea Hunter](https://en.wikipedia.org/wiki/Sea_Hunter). I earned my doctorate from the University of Washington in control theory and published some [papers](https://www.researchgate.net/scientific-contributions/75011026_Emmett_Lalish).
|
||||
|
||||
@@ -20,6 +20,6 @@ if(NOT EMSCRIPTEN AND MANIFOLD_PYBIND)
|
||||
add_subdirectory(python)
|
||||
endif()
|
||||
|
||||
if(EMSCRIPTEN)
|
||||
if(EMSCRIPTEN AND MANIFOLD_JSBIND)
|
||||
add_subdirectory(wasm)
|
||||
endif()
|
||||
|
||||
@@ -14,9 +14,20 @@ endif()
|
||||
|
||||
target_link_libraries(
|
||||
${PROJECT_NAME}
|
||||
PRIVATE manifold sdf graphlite cross_section
|
||||
PRIVATE manifold sdf cross_section
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17)
|
||||
|
||||
install(
|
||||
TARGETS ${PROJECT_NAME}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT bindings
|
||||
)
|
||||
install(
|
||||
FILES include/manifoldc.h include/types.h
|
||||
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
|
||||
COMPONENT devel
|
||||
)
|
||||
|
||||
+16
-3
@@ -1,7 +1,20 @@
|
||||
#include <conv.h>
|
||||
#include <manifold.h>
|
||||
#include <public.h>
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "conv.h"
|
||||
#include "manifold.h"
|
||||
#include "public.h"
|
||||
#include "types.h"
|
||||
|
||||
ManifoldBox *manifold_box(void *mem, float x1, float y1, float z1, float x2,
|
||||
|
||||
+17
-4
@@ -1,12 +1,25 @@
|
||||
#include <conv.h>
|
||||
#include <manifold.h>
|
||||
#include <sdf.h>
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "conv.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "include/types.h"
|
||||
#include "manifold.h"
|
||||
#include "public.h"
|
||||
#include "sdf.h"
|
||||
#include "types.h"
|
||||
|
||||
ManifoldManifold *to_c(manifold::Manifold *m) {
|
||||
|
||||
+40
-3
@@ -1,10 +1,23 @@
|
||||
#include <conv.h>
|
||||
#include <manifold.h>
|
||||
#include <public.h>
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "conv.h"
|
||||
#include "cross_section.h"
|
||||
#include "manifold.h"
|
||||
#include "public.h"
|
||||
#include "types.h"
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_empty(void *mem) {
|
||||
@@ -106,6 +119,30 @@ ManifoldCrossSection *manifold_cross_section_intersection(
|
||||
return to_c(new (mem) CrossSection(cs));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_hull(void *mem,
|
||||
ManifoldCrossSection *cs) {
|
||||
auto hulled = from_c(cs)->Hull();
|
||||
return to_c(new (mem) CrossSection(hulled));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_batch_hull(
|
||||
void *mem, ManifoldCrossSectionVec *css) {
|
||||
auto hulled = CrossSection::Hull(*from_c(css));
|
||||
return to_c(new (mem) CrossSection(hulled));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_hull_simple_polygon(
|
||||
void *mem, ManifoldSimplePolygon *ps) {
|
||||
auto hulled = CrossSection::Hull(*from_c(ps));
|
||||
return to_c(new (mem) CrossSection(hulled));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_hull_polygons(
|
||||
void *mem, ManifoldPolygons *ps) {
|
||||
auto hulled = CrossSection::Hull(*from_c(ps));
|
||||
return to_c(new (mem) CrossSection(hulled));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_translate(void *mem,
|
||||
ManifoldCrossSection *cs,
|
||||
float x, float y) {
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
#pragma once
|
||||
#include <manifold.h>
|
||||
#include <public.h>
|
||||
#include <sdf.h>
|
||||
#include <types.h>
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "manifold.h"
|
||||
#include "public.h"
|
||||
#include "sdf.h"
|
||||
#include "types.h"
|
||||
|
||||
using namespace manifold;
|
||||
using ManifoldVec = std::vector<Manifold>;
|
||||
using CrossSectionVec = std::vector<CrossSection>;
|
||||
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <types.h>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include <cstdint>
|
||||
@@ -8,6 +23,7 @@ extern "C" {
|
||||
#endif
|
||||
|
||||
// Polygons
|
||||
|
||||
ManifoldSimplePolygon *manifold_simple_polygon(void *mem, ManifoldVec2 *ps,
|
||||
size_t length);
|
||||
ManifoldPolygons *manifold_polygons(void *mem, ManifoldSimplePolygon **ps,
|
||||
@@ -24,6 +40,7 @@ ManifoldVec2 manifold_polygons_get_point(ManifoldPolygons *ps, int simple_idx,
|
||||
int pt_idx);
|
||||
|
||||
// Mesh Construction
|
||||
|
||||
ManifoldMeshGL *manifold_meshgl(void *mem, float *vert_props, size_t n_verts,
|
||||
size_t n_props, uint32_t *tri_verts,
|
||||
size_t n_tris);
|
||||
@@ -94,7 +111,20 @@ ManifoldManifold *manifold_trim_by_plane(void *mem, ManifoldManifold *m,
|
||||
float normal_x, float normal_y,
|
||||
float normal_z, float offset);
|
||||
|
||||
// 3D to 2D
|
||||
|
||||
ManifoldCrossSection *manifold_slice(void *mem, ManifoldManifold *m,
|
||||
float height);
|
||||
ManifoldCrossSection *manifold_project(void *mem, ManifoldManifold *m);
|
||||
|
||||
// Convex Hulls
|
||||
|
||||
ManifoldManifold *manifold_hull(void *mem, ManifoldManifold *m);
|
||||
ManifoldManifold *manifold_batch_hull(void *mem, ManifoldManifoldVec *ms);
|
||||
ManifoldManifold *manifold_hull_pts(void *mem, ManifoldVec3 *ps, size_t length);
|
||||
|
||||
// Manifold Transformations
|
||||
|
||||
ManifoldManifold *manifold_translate(void *mem, ManifoldManifold *m, float x,
|
||||
float y, float z);
|
||||
ManifoldManifold *manifold_rotate(void *mem, ManifoldManifold *m, float x,
|
||||
@@ -112,6 +142,7 @@ ManifoldManifold *manifold_warp(void *mem, ManifoldManifold *m,
|
||||
ManifoldManifold *manifold_refine(void *mem, ManifoldManifold *m, int refine);
|
||||
|
||||
// Manifold Shapes / Constructors
|
||||
|
||||
ManifoldManifold *manifold_empty(void *mem);
|
||||
ManifoldManifold *manifold_copy(void *mem, ManifoldManifold *m);
|
||||
ManifoldManifold *manifold_tetrahedron(void *mem);
|
||||
@@ -137,6 +168,7 @@ ManifoldManifoldVec *manifold_decompose(void *mem, ManifoldManifold *m);
|
||||
ManifoldManifold *manifold_as_original(void *mem, ManifoldManifold *m);
|
||||
|
||||
// Manifold Info
|
||||
|
||||
int manifold_is_empty(ManifoldManifold *m);
|
||||
ManifoldError manifold_status(ManifoldManifold *m);
|
||||
int manifold_num_vert(ManifoldManifold *m);
|
||||
@@ -204,6 +236,17 @@ ManifoldCrossSection *manifold_cross_section_difference(
|
||||
ManifoldCrossSection *manifold_cross_section_intersection(
|
||||
void *mem, ManifoldCrossSection *a, ManifoldCrossSection *b);
|
||||
|
||||
// CrossSection Convex Hulls
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_hull(void *mem,
|
||||
ManifoldCrossSection *cs);
|
||||
ManifoldCrossSection *manifold_cross_section_batch_hull(
|
||||
void *mem, ManifoldCrossSectionVec *css);
|
||||
ManifoldCrossSection *manifold_cross_section_hull_simple_polygon(
|
||||
void *mem, ManifoldSimplePolygon *ps);
|
||||
ManifoldCrossSection *manifold_cross_section_hull_polygons(
|
||||
void *mem, ManifoldPolygons *ps);
|
||||
|
||||
// CrossSection Transformation
|
||||
|
||||
ManifoldCrossSection *manifold_cross_section_translate(void *mem,
|
||||
@@ -264,10 +307,9 @@ ManifoldRect *manifold_rect_mul(void *mem, ManifoldRect *r, float x, float y);
|
||||
int manifold_rect_does_overlap_rect(ManifoldRect *a, ManifoldRect *r);
|
||||
int manifold_rect_is_empty(ManifoldRect *r);
|
||||
int manifold_rect_is_finite(ManifoldRect *r);
|
||||
ManifoldCrossSection *manifold_rect_as_cross_section(void *mem,
|
||||
ManifoldRect *r);
|
||||
|
||||
// Bounding Box
|
||||
|
||||
ManifoldBox *manifold_box(void *mem, float x1, float y1, float z1, float x2,
|
||||
float y2, float z2);
|
||||
ManifoldVec3 manifold_box_min(ManifoldBox *b);
|
||||
@@ -292,11 +334,13 @@ int manifold_box_does_overlap_box(ManifoldBox *a, ManifoldBox *b);
|
||||
int manifold_box_is_finite(ManifoldBox *b);
|
||||
|
||||
// Static Quality Globals
|
||||
|
||||
void manifold_set_min_circular_angle(float degrees);
|
||||
void manifold_set_min_circular_edge_length(float length);
|
||||
void manifold_set_circular_segments(int number);
|
||||
|
||||
// Manifold Mesh Extraction
|
||||
|
||||
int manifold_meshgl_num_prop(ManifoldMeshGL *m);
|
||||
int manifold_meshgl_num_vert(ManifoldMeshGL *m);
|
||||
int manifold_meshgl_num_tri(ManifoldMeshGL *m);
|
||||
@@ -319,6 +363,7 @@ uint32_t *manifold_meshgl_face_id(void *mem, ManifoldMeshGL *m);
|
||||
float *manifold_meshgl_halfedge_tangent(void *mem, ManifoldMeshGL *m);
|
||||
|
||||
// memory size
|
||||
|
||||
size_t manifold_manifold_size();
|
||||
size_t manifold_manifold_vec_size();
|
||||
size_t manifold_cross_section_size();
|
||||
@@ -332,6 +377,7 @@ size_t manifold_rect_size();
|
||||
size_t manifold_curvature_size();
|
||||
|
||||
// destruction
|
||||
|
||||
void manifold_destruct_manifold(ManifoldManifold *m);
|
||||
void manifold_destruct_manifold_vec(ManifoldManifoldVec *ms);
|
||||
void manifold_destruct_cross_section(ManifoldCrossSection *m);
|
||||
@@ -343,6 +389,7 @@ void manifold_destruct_box(ManifoldBox *b);
|
||||
void manifold_destruct_rect(ManifoldRect *b);
|
||||
|
||||
// pointer free + destruction
|
||||
|
||||
void manifold_delete_manifold(ManifoldManifold *m);
|
||||
void manifold_delete_manifold_vec(ManifoldManifoldVec *ms);
|
||||
void manifold_delete_cross_section(ManifoldCrossSection *cs);
|
||||
@@ -354,6 +401,7 @@ void manifold_delete_box(ManifoldBox *b);
|
||||
void manifold_delete_rect(ManifoldRect *b);
|
||||
|
||||
// MeshIO / Export
|
||||
|
||||
#ifdef MANIFOLD_EXPORT
|
||||
ManifoldMaterial *manifold_material(void *mem);
|
||||
void manifold_material_set_roughness(ManifoldMaterial *mat, float roughness);
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <conv.h>
|
||||
#include <cross_section.h>
|
||||
#include <manifold.h>
|
||||
@@ -29,8 +43,7 @@ ManifoldMeshGL *level_set(void *mem, float (*sdf)(float, float, float),
|
||||
std::function<float(glm::vec3)> fun = [sdf](glm::vec3 v) {
|
||||
return (sdf(v.x, v.y, v.z));
|
||||
};
|
||||
auto pol = seq ? std::make_optional(ExecutionPolicy::Seq) : std::nullopt;
|
||||
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, pol);
|
||||
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, !seq);
|
||||
return to_c(new (mem) MeshGL(mesh));
|
||||
}
|
||||
ManifoldMeshGL *level_set_context(
|
||||
@@ -43,8 +56,7 @@ ManifoldMeshGL *level_set_context(
|
||||
std::function<float(glm::vec3)> fun = [sdf](glm::vec3 v) {
|
||||
return (sdf(v.x, v.y, v.z));
|
||||
};
|
||||
auto pol = seq ? std::make_optional(ExecutionPolicy::Seq) : std::nullopt;
|
||||
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, pol);
|
||||
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, !seq);
|
||||
return to_c(new (mem) MeshGL(mesh));
|
||||
}
|
||||
} // namespace
|
||||
@@ -190,6 +202,37 @@ ManifoldManifold *manifold_trim_by_plane(void *mem, ManifoldManifold *m,
|
||||
return to_c(new (mem) Manifold(trimmed));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_slice(void *mem, ManifoldManifold *m,
|
||||
float height) {
|
||||
auto poly = from_c(m)->Slice(height);
|
||||
return to_c(new (mem) CrossSection(poly));
|
||||
}
|
||||
|
||||
ManifoldCrossSection *manifold_project(void *mem, ManifoldManifold *m) {
|
||||
auto poly = from_c(m)->Project();
|
||||
return to_c(new (mem) CrossSection(poly));
|
||||
}
|
||||
|
||||
ManifoldManifold *manifold_hull(void *mem, ManifoldManifold *m) {
|
||||
auto hulled = from_c(m)->Hull();
|
||||
return to_c(new (mem) Manifold(hulled));
|
||||
}
|
||||
|
||||
ManifoldManifold *manifold_batch_hull(void *mem, ManifoldManifoldVec *ms) {
|
||||
auto hulled = Manifold::Hull(*from_c(ms));
|
||||
return to_c(new (mem) Manifold(hulled));
|
||||
}
|
||||
|
||||
ManifoldManifold *manifold_hull_pts(void *mem, ManifoldVec3 *ps,
|
||||
size_t length) {
|
||||
std::vector<glm::vec3> vec(length);
|
||||
for (int i = 0; i < length; ++i) {
|
||||
vec[i] = {ps[i].x, ps[i].y, ps[i].z};
|
||||
}
|
||||
auto hulled = Manifold::Hull(vec);
|
||||
return to_c(new (mem) Manifold(hulled));
|
||||
}
|
||||
|
||||
ManifoldManifold *manifold_translate(void *mem, ManifoldManifold *m, float x,
|
||||
float y, float z) {
|
||||
auto v = glm::vec3(x, y, z);
|
||||
|
||||
+16
-3
@@ -1,8 +1,21 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "meshIO.h"
|
||||
|
||||
#include <conv.h>
|
||||
|
||||
#include "include/types.h"
|
||||
#include "conv.h"
|
||||
#include "types.h"
|
||||
|
||||
// C <-> C++ conversions
|
||||
|
||||
|
||||
+16
-9
@@ -1,8 +1,21 @@
|
||||
#include <conv.h>
|
||||
#include <manifold.h>
|
||||
#include <public.h>
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "conv.h"
|
||||
#include "cross_section.h"
|
||||
#include "manifold.h"
|
||||
#include "public.h"
|
||||
#include "types.h"
|
||||
|
||||
ManifoldRect *manifold_rect(void *mem, float x1, float y1, float x2, float y2) {
|
||||
@@ -85,9 +98,3 @@ int manifold_rect_does_overlap_rect(ManifoldRect *a, ManifoldRect *r) {
|
||||
int manifold_rect_is_empty(ManifoldRect *r) { return from_c(r)->IsEmpty(); }
|
||||
|
||||
int manifold_rect_is_finite(ManifoldRect *r) { return from_c(r)->IsFinite(); }
|
||||
|
||||
ManifoldCrossSection *manifold_rect_as_cross_section(void *mem,
|
||||
ManifoldRect *r) {
|
||||
auto cs = from_c(r)->AsCrossSection();
|
||||
return to_c(new (mem) CrossSection(cs));
|
||||
}
|
||||
|
||||
@@ -15,10 +15,36 @@
|
||||
project(python)
|
||||
|
||||
add_subdirectory(third_party)
|
||||
pybind11_add_module(manifold3d manifold3d.cpp)
|
||||
target_link_libraries(manifold3d PRIVATE manifold)
|
||||
target_compile_options(manifold3d PRIVATE ${MANIFOLD_FLAGS})
|
||||
nanobind_add_module(
|
||||
manifold3d
|
||||
NB_STATIC STABLE_ABI LTO
|
||||
manifold3d.cpp)
|
||||
target_link_libraries(manifold3d PRIVATE manifold sdf polygon)
|
||||
target_compile_options(manifold3d PRIVATE ${MANIFOLD_FLAGS} -DMODULE_NAME=manifold3d)
|
||||
target_compile_features(manifold3d PUBLIC cxx_std_17)
|
||||
target_include_directories(manifold3d
|
||||
PRIVATE ${PYBIND11_DIR}/include
|
||||
set_target_properties(manifold3d PROPERTIES OUTPUT_NAME "manifold3d")
|
||||
|
||||
message(Python_EXECUTABLE = ${Python_EXECUTABLE})
|
||||
add_custom_target(
|
||||
autogen_docstrings
|
||||
${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/gen_docs.py
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
BYPRODUCTS autogen_docstrings.inl
|
||||
)
|
||||
target_include_directories(manifold3d PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
add_dependencies(autogen_docstrings manifold sdf polygon)
|
||||
add_dependencies(manifold3d autogen_docstrings)
|
||||
|
||||
if(SKBUILD)
|
||||
install(
|
||||
TARGETS manifold3d
|
||||
LIBRARY DESTINATION ${SKBUILD_PLATLIB_DIR}
|
||||
COMPONENT bindings
|
||||
)
|
||||
else()
|
||||
install(
|
||||
TARGETS manifold3d
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT bindings
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Python Bindings
|
||||
|
||||
## Autogenerated Doc-Strings
|
||||
|
||||
Doc-strings for the python API wrapper are generated by gen_docs.py
|
||||
The script is run automatically during the build to keep python
|
||||
doc strings fully up-to-date with c++ sources.
|
||||
|
||||
It scrapes documentation comments and c++ function signatures
|
||||
from the manifold c++ sources, in order to generate a c++ header file
|
||||
exposing the comments as string variables named by function names.
|
||||
This allows python bindings to re-use the c++ comments directly.
|
||||
|
||||
Some snake-casing of params is applied for python use case.
|
||||
|
||||
---
|
||||
|
||||
When modifying the Manifold C++ sources, you may need to update
|
||||
gen_docs.py. For example, top-level free functions are white-listed,
|
||||
so if you add a new one, you will need to add it in gen_docs.py.
|
||||
|
||||
Similarly, the list of source files to parse is also white listed,
|
||||
so if you define functions in new files that need python wrappers,
|
||||
you will also need to up gen_docs.py.
|
||||
|
||||
To verify that python docs are correct after changes, you can
|
||||
run the following commends from the manifold repo root:
|
||||
```
|
||||
pip install .
|
||||
python -c 'import manifold3d; help(manifold3d)'
|
||||
```
|
||||
|
||||
Alternateively you could generate stubs with roughly the same info
|
||||
```
|
||||
pip install nanobind-stubgen
|
||||
pip install .
|
||||
nanobind-stubgen manifold3d
|
||||
```
|
||||
It will emit some warnings and write a file `manifold3d.pyi`
|
||||
which will show all the function signatures and docstrings.
|
||||
@@ -0,0 +1,101 @@
|
||||
from manifold3d import *
|
||||
import numpy as np
|
||||
|
||||
|
||||
def all_root_level():
|
||||
set_min_circular_angle(10)
|
||||
set_min_circular_edge_length(1)
|
||||
set_circular_segments(22)
|
||||
n = get_circular_segments(1)
|
||||
assert n == 22
|
||||
poly = [[0, 0], [1, 0], [1, 1]]
|
||||
tris = triangulate([poly])
|
||||
tris = triangulate([np.array(poly)])
|
||||
|
||||
|
||||
def all_cross_section():
|
||||
poly = [[0, 0], [1, 0], [1, 1]]
|
||||
c = CrossSection([np.array(poly)])
|
||||
c = CrossSection([poly])
|
||||
c = CrossSection() + c
|
||||
a = c.area()
|
||||
c = CrossSection.batch_hull([c, c.translate((1, 0))])
|
||||
b = c.bounds()
|
||||
c = CrossSection.circle(1)
|
||||
cs = c.decompose()
|
||||
m = c.extrude(1)
|
||||
c = c.hull()
|
||||
c = CrossSection.hull_points(poly)
|
||||
c = CrossSection.hull_points(np.array(poly))
|
||||
e = c.is_empty()
|
||||
c = c.mirror((0, 1))
|
||||
n = c.num_contour()
|
||||
n = c.num_vert()
|
||||
c = c.offset(1, JoinType.Round)
|
||||
m = c.revolve()
|
||||
c = c.rotate(90)
|
||||
c = c.scale((2, 2))
|
||||
c = c.simplify()
|
||||
c = CrossSection.square((1, 1))
|
||||
p = c.to_polygons()
|
||||
c = c.transform([[1, 0, 0], [0, 1, 0]])
|
||||
c = c.translate((1, 1))
|
||||
c = c.warp(lambda p: (p[0] + 1, p[1] / 2))
|
||||
c = c.warp_batch(lambda ps: ps * [1, 0.5] + [1, 0])
|
||||
|
||||
|
||||
def all_manifold():
|
||||
mesh = Manifold.sphere(1).to_mesh()
|
||||
m = Manifold(mesh)
|
||||
m = Manifold() + m
|
||||
m = m.as_original()
|
||||
m = Manifold.batch_hull([m, m.translate((0, 0, 1))])
|
||||
b = m.bounding_box()
|
||||
m = m.calculate_curvature(4, 5)
|
||||
m = Manifold.compose([m, m.translate((5, 0, 0))])
|
||||
m = Manifold.cube((1, 1, 1))
|
||||
m = Manifold.cylinder(1, 1)
|
||||
ms = m.decompose()
|
||||
g = m.genus()
|
||||
a = m.surface_area()
|
||||
v = m.volume()
|
||||
m = m.hull()
|
||||
m = m.hull_points(mesh.vert_properties)
|
||||
e = m.is_empty()
|
||||
m = m.mirror((0, 0, 1))
|
||||
n = m.num_edge()
|
||||
n = m.num_prop()
|
||||
n = m.num_prop_vert()
|
||||
n = m.num_tri()
|
||||
n = m.num_vert()
|
||||
i = m.original_id()
|
||||
p = m.precision()
|
||||
c = m.project()
|
||||
m = m.refine(2)
|
||||
i = Manifold.reserve_ids(1)
|
||||
m = m.scale((1, 2, 3))
|
||||
m = m.set_properties(3, lambda pos, prop: pos)
|
||||
c = m.slice(0.5)
|
||||
m = Manifold.smooth(mesh, [0], [0.5])
|
||||
m = Manifold.sphere(1)
|
||||
m, n = m.split(m.translate((1, 0, 0)))
|
||||
m, n = m.split_by_plane((0, 0, 1), 0)
|
||||
e = m.status()
|
||||
m = Manifold.tetrahedron()
|
||||
mesh = m.to_mesh()
|
||||
m = m.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
|
||||
m = m.translate((0, 0, 0))
|
||||
m = m.trim_by_plane((0, 0, 1), 0)
|
||||
m = m.warp(lambda p: (p[0] + 1, p[1] / 2, p[2] * 2))
|
||||
m = m.warp_batch(lambda ps: ps * [1, 0.5, 2] + [1, 0, 0])
|
||||
|
||||
|
||||
def run():
|
||||
all_root_level()
|
||||
all_cross_section()
|
||||
all_manifold()
|
||||
return Manifold()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -20,60 +20,82 @@ from manifold3d import Manifold
|
||||
|
||||
INCHES = 25.4
|
||||
|
||||
brick_depth = (3 + 5/8) * INCHES
|
||||
brick_height = (2 + 1/4) * INCHES
|
||||
brick_length = (7 + 5/8) * INCHES
|
||||
brick_depth = (3 + 5 / 8) * INCHES
|
||||
brick_height = (2 + 1 / 4) * INCHES
|
||||
brick_length = (7 + 5 / 8) * INCHES
|
||||
|
||||
mortar_gap = (3/8) * INCHES
|
||||
mortar_gap = (3 / 8) * INCHES
|
||||
|
||||
|
||||
def brick():
|
||||
return Manifold.cube(brick_length, brick_depth, brick_height)
|
||||
return Manifold.cube([brick_length, brick_depth, brick_height])
|
||||
|
||||
|
||||
def halfbrick():
|
||||
return Manifold.cube((brick_length - mortar_gap)/2, brick_depth, brick_height)
|
||||
return Manifold.cube([(brick_length - mortar_gap) / 2, brick_depth, brick_height])
|
||||
|
||||
|
||||
def row(length):
|
||||
bricks = [brick().translate((brick_length + mortar_gap)*x, 0, 0)
|
||||
for x in range(length)]
|
||||
return Manifold(bricks)
|
||||
bricks = [
|
||||
brick().translate([(brick_length + mortar_gap) * x, 0, 0])
|
||||
for x in range(length)
|
||||
]
|
||||
return sum(bricks, Manifold())
|
||||
|
||||
|
||||
def wall(length, height, alternate=0):
|
||||
bricks = [row(length).translate(
|
||||
((z+alternate) % 2)*(brick_depth+mortar_gap), 0,
|
||||
(brick_height+mortar_gap)*z) for z in range(height)]
|
||||
return Manifold(bricks)
|
||||
bricks = [
|
||||
row(length).translate(
|
||||
[
|
||||
((z + alternate) % 2) * (brick_depth + mortar_gap),
|
||||
0,
|
||||
(brick_height + mortar_gap) * z,
|
||||
]
|
||||
)
|
||||
for z in range(height)
|
||||
]
|
||||
return sum(bricks, Manifold())
|
||||
|
||||
|
||||
def walls(length, width, height):
|
||||
return Manifold([
|
||||
wall(length, height),
|
||||
wall(width, height, 1).rotate(0, 0, 90).translate(brick_depth, 0, 0),
|
||||
wall(length, height, 1).translate(
|
||||
0, (width)*(brick_length+mortar_gap), 0),
|
||||
wall(width, height).rotate(0, 0, 90)
|
||||
.translate((length+0.5)*(brick_length+mortar_gap) - mortar_gap, 0, 0),
|
||||
])
|
||||
return sum(
|
||||
[
|
||||
wall(length, height),
|
||||
wall(width, height, 1).rotate([0, 0, 90]).translate([brick_depth, 0, 0]),
|
||||
wall(length, height, 1).translate(
|
||||
[0, (width) * (brick_length + mortar_gap), 0]
|
||||
),
|
||||
wall(width, height)
|
||||
.rotate([0, 0, 90])
|
||||
.translate(
|
||||
[(length + 0.5) * (brick_length + mortar_gap) - mortar_gap, 0, 0]
|
||||
),
|
||||
],
|
||||
Manifold(),
|
||||
)
|
||||
|
||||
|
||||
def floor(length, width):
|
||||
results = [walls(length, width, 1)]
|
||||
if length > 1 and width > 1:
|
||||
results.append(floor(length-1, width-1).translate(brick_depth +
|
||||
mortar_gap, brick_depth+mortar_gap, 0))
|
||||
results.append(
|
||||
floor(length - 1, width - 1).translate(
|
||||
[brick_depth + mortar_gap, brick_depth + mortar_gap, 0]
|
||||
)
|
||||
)
|
||||
if length == 1 and width > 1:
|
||||
results.append(row(width-1).rotate(0, 0, 90))
|
||||
results.append(row(width - 1).rotate(0, 0, 90))
|
||||
if width == 1 and length > 1:
|
||||
results.append(row(length-1).translate(2*(brick_depth +
|
||||
mortar_gap), brick_depth+mortar_gap, 0))
|
||||
results.append(halfbrick().translate(
|
||||
brick_depth+mortar_gap, brick_depth+mortar_gap, 0))
|
||||
return Manifold(results)
|
||||
results.append(
|
||||
row(length - 1).translate(
|
||||
[2 * (brick_depth + mortar_gap), brick_depth + mortar_gap, 0]
|
||||
)
|
||||
)
|
||||
results.append(
|
||||
halfbrick().translate([brick_depth + mortar_gap, brick_depth + mortar_gap, 0])
|
||||
)
|
||||
return sum(results, Manifold())
|
||||
|
||||
|
||||
def run(width=10, length=10, height=10):
|
||||
return walls(length, width, height) + floor(length, width)
|
||||
|
||||
|
||||
@@ -13,18 +13,21 @@
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
|
||||
|
||||
from manifold3d import Manifold
|
||||
from functools import reduce
|
||||
|
||||
# https://gist.github.com/ochafik/2db96400e3c1f73558fcede990b8a355#file-cube-with-half-spheres-dents-scad
|
||||
|
||||
|
||||
def run(n=5, overlap=True):
|
||||
a = Manifold.cube(n, n, 0.5).translate(-0.5, -0.5, -0.5)
|
||||
a = Manifold.cube([n, n, 0.5]).translate([-0.5, -0.5, -0.5])
|
||||
|
||||
spheres = [Manifold.sphere(0.45 if overlap else 0.55, 50).translate(i, j, 0)
|
||||
for i in range(n) for j in range(n)]
|
||||
spheres = reduce(lambda a, b: a + b, spheres)
|
||||
|
||||
return a - spheres
|
||||
spheres = [
|
||||
Manifold.sphere(0.45 if overlap else 0.55, 50).translate([i, j, 0])
|
||||
for i in range(n)
|
||||
for j in range(n)
|
||||
]
|
||||
# spheres = reduce(lambda a, b: a + b, spheres)
|
||||
|
||||
return a - sum(spheres, Manifold())
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from manifold3d import CrossSection, FillRule
|
||||
from manifold3d import CrossSection
|
||||
|
||||
|
||||
def run():
|
||||
@@ -10,29 +10,37 @@ def run():
|
||||
cross_section = CrossSection(polygons_points)
|
||||
polygons = cross_section.to_polygons()
|
||||
polygon = polygons[0]
|
||||
if set(polygon) != set(polygon_points):
|
||||
raise Exception(f"{polygon=} differs from {polygon_points=}")
|
||||
if set([tuple(p) for p in polygon]) != set(polygon_points):
|
||||
raise Exception(
|
||||
f"polygon={polygon} differs from polygon_points={polygon_points}"
|
||||
)
|
||||
|
||||
# extrude a polygon to create a manifold
|
||||
extruded_polygon = cross_section.extrude(10.0)
|
||||
eps = 0.001
|
||||
observed_volume = extruded_polygon.get_volume()
|
||||
observed_volume = extruded_polygon.volume()
|
||||
expected_volume = 10.0
|
||||
if abs(observed_volume - expected_volume) > eps:
|
||||
raise Exception(f"{observed_volume=} differs from {expected_volume=}")
|
||||
observed_surface_area = extruded_polygon.get_surface_area()
|
||||
raise Exception(
|
||||
f"observed_volume={observed_volume} differs from expected_volume={expected_volume}"
|
||||
)
|
||||
observed_surface_area = extruded_polygon.surface_area()
|
||||
expected_surface_area = 42.0
|
||||
if abs(observed_surface_area - expected_surface_area) > eps:
|
||||
raise Exception(f"{observed_surface_area=} differs from {expected_surface_area=}")
|
||||
raise Exception(
|
||||
f"observed_surface_area={observed_surface_area} differs from expected_surface_area={expected_surface_area}"
|
||||
)
|
||||
|
||||
# get bounding box from manifold
|
||||
observed_bbox = extruded_polygon.bounding_box
|
||||
observed_bbox = extruded_polygon.bounding_box()
|
||||
expected_bbox = (0.0, 0.0, 0.0, 1.0, 1.0, 10.0)
|
||||
if observed_bbox != expected_bbox:
|
||||
raise Exception(f"{observed_bbox=} differs from {expected_bbox=}")
|
||||
raise Exception(
|
||||
f"observed_bbox={observed_bbox} differs from expected_bbox={expected_bbox}"
|
||||
)
|
||||
|
||||
return extruded_polygon
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
run()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
Copyright 2023 The Manifold Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
|
||||
import math
|
||||
import numpy as np
|
||||
from manifold3d import Mesh, Manifold
|
||||
|
||||
|
||||
def gyroid(x, y, z):
|
||||
xi = x - math.pi / 4.0
|
||||
yi = y - math.pi / 4.0
|
||||
zi = z - math.pi / 4.0
|
||||
return (
|
||||
math.cos(xi) * math.sin(yi)
|
||||
+ math.cos(yi) * math.sin(zi)
|
||||
+ math.cos(zi) * math.sin(xi)
|
||||
)
|
||||
|
||||
|
||||
def gyroid_levelset(level, period, size, n):
|
||||
return Manifold(
|
||||
Mesh.level_set(
|
||||
gyroid,
|
||||
[-period, -period, -period, period, period, period],
|
||||
period / n,
|
||||
level,
|
||||
)
|
||||
).scale([size / period] * 3)
|
||||
|
||||
|
||||
def rhombic_dodecahedron(size):
|
||||
box = Manifold.cube(size * math.sqrt(2.0) * np.array([1, 1, 2]), True)
|
||||
result = box.rotate([90, 45, 0]) ^ box.rotate([90, 45, 90])
|
||||
return result ^ box.rotate([0, 0, 45])
|
||||
|
||||
|
||||
def gyroid_module(size=20, n=15):
|
||||
period = math.pi * 2.0
|
||||
result = (
|
||||
gyroid_levelset(-0.4, period, size, n) ^ rhombic_dodecahedron(size)
|
||||
) - gyroid_levelset(0.4, period, size, n)
|
||||
return result.rotate([-45, 0, 90]).translate([0, 0, size / math.sqrt(2.0)])
|
||||
|
||||
|
||||
def run(size=20, n=15):
|
||||
return gyroid_module(size, n)
|
||||
+2007
-2005
File diff suppressed because it is too large
Load Diff
@@ -24,10 +24,9 @@ from time import time
|
||||
if __name__ == "__main__":
|
||||
current_file = pathlib.Path(__file__)
|
||||
current_dir = current_file.parent
|
||||
files = [f.parts[-1][:-3]
|
||||
for f in current_dir.glob('*.py') if f != current_file]
|
||||
files = [f.parts[-1][:-3] for f in current_dir.glob("*.py") if f != current_file]
|
||||
|
||||
export_models = len(sys.argv) == 2 and sys.argv[-1] == '-e'
|
||||
export_models = len(sys.argv) == 2 and sys.argv[-1] == "-e"
|
||||
|
||||
for f in files:
|
||||
module = importlib.import_module(f)
|
||||
@@ -36,11 +35,15 @@ if __name__ == "__main__":
|
||||
mesh = model.to_mesh()
|
||||
if export_models:
|
||||
if mesh.vert_properties.shape[1] > 3:
|
||||
vertices = np.hsplit(mesh.vert_properties, 3)[0]
|
||||
vertices = mesh.vert_properties[:, :3]
|
||||
colors = (mesh.vert_properties[:, 3:] * 255).astype(np.uint8)
|
||||
else:
|
||||
vertices = mesh.vert_properties
|
||||
meshOut = trimesh.Trimesh(vertices=vertices, faces=mesh.tri_verts)
|
||||
trimesh.exchange.export.export_mesh(meshOut, f'{f}.glb', 'glb')
|
||||
print(f'Exported model to {f}.glb')
|
||||
colors = None
|
||||
meshOut = trimesh.Trimesh(
|
||||
vertices=vertices, faces=mesh.tri_verts, vertex_colors=colors
|
||||
)
|
||||
trimesh.exchange.export.export_mesh(meshOut, f"{f}.glb", "glb")
|
||||
print(f"Exported model to {f}.glb")
|
||||
t1 = time()
|
||||
print(f'Took {(t1-t0)*1000:.1f}ms for {f}')
|
||||
print(f"Took {(t1-t0)*1000:.1f}ms for {f}")
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
Copyright 2023 The Manifold Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
|
||||
from manifold3d import Manifold, Mesh
|
||||
import numpy as np
|
||||
|
||||
|
||||
def run():
|
||||
# A smoothed manifold demonstrating selective edge sharpening with
|
||||
# smooth() and refine(), see more details at:
|
||||
# https://elalish.blogspot.com/2022/03/smoothing-triangle-meshes.html
|
||||
|
||||
height = 10
|
||||
radius = 30
|
||||
offset = 20
|
||||
wiggles = 12
|
||||
sharpness = 0.8
|
||||
n = 50
|
||||
|
||||
triangles = []
|
||||
positions = [[-offset, 0, height], [-offset, 0, -height]]
|
||||
sharpenedEdges = []
|
||||
|
||||
delta = np.pi / wiggles
|
||||
for i in range(2 * wiggles):
|
||||
theta = (i - wiggles) * delta
|
||||
amp = 0.5 * height * max(np.cos(0.8 * theta), 0)
|
||||
|
||||
positions.append(
|
||||
[
|
||||
radius * np.cos(theta),
|
||||
radius * np.sin(theta),
|
||||
amp * (1 if i % 2 == 0 else -1),
|
||||
]
|
||||
)
|
||||
|
||||
j = i + 1
|
||||
if j == 2 * wiggles:
|
||||
j = 0
|
||||
|
||||
smoothness = 1 - sharpness * np.cos((theta + delta / 2) / 2)
|
||||
halfedge = 3 * len(triangles) + 1
|
||||
sharpenedEdges.append((halfedge, smoothness))
|
||||
triangles.append([0, 2 + i, 2 + j])
|
||||
|
||||
halfedge = 3 * len(triangles) + 1
|
||||
sharpenedEdges.append((halfedge, smoothness))
|
||||
triangles.append([1, 2 + j, 2 + i])
|
||||
|
||||
scallop = Mesh(
|
||||
tri_verts=np.array(triangles, np.int32),
|
||||
vert_properties=np.array(positions, np.float32),
|
||||
)
|
||||
|
||||
def colorCurvature(_pos, oldProp):
|
||||
a = max(0, min(1, oldProp[0] / 3 + 0.5))
|
||||
b = a * a * (3 - 2 * a)
|
||||
red = [1, 0, 0]
|
||||
blue = [0, 0, 1]
|
||||
return [(1 - b) * blue[i] + b * red[i] for i in range(3)]
|
||||
|
||||
edges, smoothing = zip(*sharpenedEdges)
|
||||
return (
|
||||
Manifold.smooth(scallop, edges, smoothing)
|
||||
.refine(n)
|
||||
.calculate_curvature(-1, 0)
|
||||
.set_properties(3, colorCurvature)
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
Copyright 2022 The Manifold Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
|
||||
from manifold3d import Manifold
|
||||
|
||||
|
||||
def run():
|
||||
a = Manifold.cube([1.0, 1.0, 1.0])
|
||||
b = Manifold.cube([1.0, 1.0, 1.0]).rotate([45.0, 45.0, 45.0])
|
||||
return a.split(b)[0]
|
||||
@@ -0,0 +1,43 @@
|
||||
from manifold3d import Manifold
|
||||
import numpy as np
|
||||
|
||||
|
||||
def fractal(holes, hole, w, position, depth, maxDepth):
|
||||
w /= 3
|
||||
holes.append(hole.scale([w, w, 1.0]).translate([position[0], position[1], 0.0]))
|
||||
if depth == maxDepth:
|
||||
return
|
||||
offsets = np.array(
|
||||
[
|
||||
[-w, -w],
|
||||
[-w, 0.0],
|
||||
[-w, w],
|
||||
[0.0, w],
|
||||
[w, w],
|
||||
[w, 0.0],
|
||||
[w, -w],
|
||||
[0.0, -w],
|
||||
]
|
||||
)
|
||||
for offset in offsets:
|
||||
fractal(holes, hole, w, position + offset, depth + 1, maxDepth)
|
||||
|
||||
|
||||
def posColors(pos, _):
|
||||
return [-p + 0.5 for p in pos] + [1.0]
|
||||
|
||||
|
||||
def run(n=1):
|
||||
result = Manifold.cube([1, 1, 1], True)
|
||||
holes = []
|
||||
fractal(holes, result, 1.0, np.array([0.0, 0.0]), 1, n)
|
||||
|
||||
hole = Manifold.compose(holes)
|
||||
|
||||
result -= hole
|
||||
result -= hole.rotate([90, 0, 0])
|
||||
result -= hole.rotate([0, 90, 0])
|
||||
|
||||
return (
|
||||
result.trim_by_plane([1, 1, 1], 0).set_properties(4, posColors).scale([100] * 3)
|
||||
)
|
||||
@@ -0,0 +1,98 @@
|
||||
from manifold3d import *
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
# Creates a classic torus knot, defined as a string wrapping periodically
|
||||
# around the surface of an imaginary donut. If p and q have a common
|
||||
# factor then you will get multiple separate, interwoven knots. This is
|
||||
# an example of using the warp() method, thus avoiding any direct
|
||||
# handling of triangles.
|
||||
|
||||
|
||||
def run(warp_single=False):
|
||||
# The number of times the thread passes through the donut hole.
|
||||
p = 1
|
||||
# The number of times the thread circles the donut.
|
||||
q = 3
|
||||
# Radius of the interior of the imaginary donut.
|
||||
majorRadius = 25
|
||||
# Radius of the small cross-section of the imaginary donut.
|
||||
minorRadius = 10
|
||||
# Radius of the small cross-section of the actual object.
|
||||
threadRadius = 3.75
|
||||
# Number of linear segments making up the threadRadius circle. Default is
|
||||
# getCircularSegments(threadRadius).
|
||||
circularSegments = -1
|
||||
# Number of segments along the length of the knot. Default makes roughly
|
||||
# square facets.
|
||||
linearSegments = -1
|
||||
|
||||
# These default values recreate Matlab Knot by Emmett Lalish:
|
||||
# https://www.thingiverse.com/thing:7080
|
||||
|
||||
kLoops = np.gcd(p, q)
|
||||
pk = p / kLoops
|
||||
qk = q / kLoops
|
||||
n = (
|
||||
circularSegments
|
||||
if circularSegments > 2
|
||||
else get_circular_segments(threadRadius)
|
||||
)
|
||||
m = linearSegments if linearSegments > 2 else n * qk * majorRadius / threadRadius
|
||||
|
||||
offset = 2
|
||||
circle = CrossSection.circle(1, n).translate([offset, 0])
|
||||
|
||||
def ax_rotate(x, theta):
|
||||
a, b = (x + 1) % 3, (x + 2) % 3
|
||||
s, c = np.sin(theta), np.cos(theta)
|
||||
m = np.zeros((len(theta), 4, 4), dtype=np.float32)
|
||||
m[:, a, a], m[:, a, b] = c, s
|
||||
m[:, b, a], m[:, b, b] = -s, c
|
||||
m[:, x, x], m[:, 3, 3] = 1, 1
|
||||
return m
|
||||
|
||||
def func(pts):
|
||||
npts = pts.shape[0]
|
||||
x, y, z = pts[:, 0], pts[:, 1], pts[:, 2]
|
||||
psi = qk * np.arctan2(x, y)
|
||||
theta = psi * pk / qk
|
||||
x1 = np.sqrt(x * x + y * y)
|
||||
phi = np.arctan2(x1 - offset, z)
|
||||
|
||||
v = np.zeros((npts, 4), dtype=np.float32)
|
||||
v[:, 0] = threadRadius * np.cos(phi)
|
||||
v[:, 2] = threadRadius * np.sin(phi)
|
||||
v[:, 3] = 1
|
||||
r = majorRadius + minorRadius * np.cos(theta)
|
||||
|
||||
m1 = ax_rotate(0, -np.arctan2(pk * minorRadius, qk * r))
|
||||
m1[:, 3, 0] = minorRadius
|
||||
m2 = ax_rotate(1, theta)
|
||||
m2[:, 3, 0] = majorRadius
|
||||
m3 = ax_rotate(2, psi)
|
||||
|
||||
v = v[:, None, :] @ m1 @ m2 @ m3
|
||||
pts[:] = v[:, 0, :3]
|
||||
|
||||
def func_single(v):
|
||||
pts = np.array([v])
|
||||
func(pts)
|
||||
return pts[0]
|
||||
|
||||
if warp_single:
|
||||
return circle.revolve(int(m)).warp(func_single)
|
||||
else:
|
||||
return circle.revolve(int(m)).warp_batch(func)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("warp_single", [True, False])
|
||||
def test_warp(warp_single):
|
||||
m = run(warp_single=warp_single)
|
||||
assert m.volume() == pytest.approx(20785.76)
|
||||
assert m.surface_area() == pytest.approx(11176.8)
|
||||
assert m.genus() == 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -1,7 +1,8 @@
|
||||
from manifold3d import Manifold
|
||||
|
||||
|
||||
def run():
|
||||
# for some reason this causes collider error
|
||||
obj = Manifold.cube()
|
||||
obj += Manifold([Manifold.cube()]).rotate(0, 0, 45+180)
|
||||
obj += Manifold.cube().rotate([0, 0, 45 + 180])
|
||||
return obj
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
from os.path import dirname
|
||||
from hashlib import md5
|
||||
import re
|
||||
|
||||
base = dirname(dirname(dirname(__file__)))
|
||||
|
||||
def snake_case(name):
|
||||
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower()
|
||||
|
||||
|
||||
def python_param_modifier(comment):
|
||||
# p = f":{snake_case(m[0][1:])}:"
|
||||
comment = re.sub(r"@(param \w+)", lambda m: f':{snake_case(m[1])}:', comment)
|
||||
# python API renames `MeshGL` to `Mesh`
|
||||
comment = re.sub('mesh_gl', 'mesh', comment)
|
||||
comment = re.sub('MeshGL', 'Mesh', comment)
|
||||
return comment
|
||||
|
||||
|
||||
def method_key(name):
|
||||
name = re.sub("\+", "_plus", name)
|
||||
name = re.sub("\-", "_minus", name)
|
||||
name = re.sub("\^", "_xor", name)
|
||||
name = re.sub("\=", "_eq", name)
|
||||
name = re.sub("\:", "_", name)
|
||||
name = re.sub("\~", "destroy_", name)
|
||||
return name
|
||||
|
||||
|
||||
parens_re = re.compile(r"[^(]+\(([^(]*(\(.*\))*[^(]*\))", flags=re.DOTALL)
|
||||
args_re = re.compile(
|
||||
r"^[^,^\(^\)]*(\(.*\))*[^,^\(^\)]*[\s\&\*]([0-9\w]+)\s*[,\)]", flags=re.DOTALL
|
||||
)
|
||||
|
||||
|
||||
def parse_args(s):
|
||||
par = parens_re.match(s)
|
||||
if not par:
|
||||
return None
|
||||
out = []
|
||||
arg_str = par[1]
|
||||
while m := re.search(args_re, arg_str):
|
||||
out += [snake_case(m[2])]
|
||||
arg_str = arg_str[m.span()[1] :]
|
||||
return out
|
||||
|
||||
|
||||
def collect(fname, matcher, param_modifier=python_param_modifier):
|
||||
comment = ""
|
||||
with open(fname) as f:
|
||||
for line in f:
|
||||
line = line.lstrip()
|
||||
if line.startswith("/**"):
|
||||
comment = ""
|
||||
elif line.startswith("*/"):
|
||||
pass
|
||||
elif line.startswith("*") and comment is not None:
|
||||
comment += line[1:].lstrip()
|
||||
elif comment and (m := matcher(line)):
|
||||
while (args := parse_args(line)) is None:
|
||||
line += next(f)
|
||||
if len(line) > 500:
|
||||
break
|
||||
|
||||
method = method_key(snake_case(m[1]))
|
||||
# comment = re.sub(param_re, param_modifier, comment)
|
||||
comment = param_modifier(comment)
|
||||
method = "__".join([method, *args])
|
||||
assert method not in comments
|
||||
comments[method] = comment
|
||||
comment = ""
|
||||
|
||||
|
||||
comments = {}
|
||||
|
||||
method_re = re.compile(r"(\w+::[\w\-\+\^\=\:]+)\(")
|
||||
function_re = re.compile(r"([\w\-\+\^\=\:]+)\(")
|
||||
|
||||
|
||||
# we don't handle inline functions in classes properly
|
||||
# so instead just white-list functions we want
|
||||
def select_functions(s):
|
||||
m = function_re.search(s)
|
||||
if m and "Triangulate" in m[0]:
|
||||
return m
|
||||
if m and "Circular" in m[0]:
|
||||
return m
|
||||
return None
|
||||
|
||||
|
||||
collect(f"{base}/src/manifold/src/manifold.cpp", lambda s: method_re.search(s))
|
||||
collect(f"{base}/src/manifold/src/constructors.cpp", lambda s: method_re.search(s))
|
||||
collect(
|
||||
f"{base}/src/cross_section/src/cross_section.cpp", lambda s: method_re.search(s)
|
||||
)
|
||||
collect(f"{base}/src/polygon/src/polygon.cpp", select_functions)
|
||||
collect(f"{base}/src/utilities/include/public.h", select_functions)
|
||||
|
||||
comments = dict(sorted(comments.items()))
|
||||
|
||||
gen_h = f"autogen_docstrings.inl"
|
||||
with open(gen_h, "w") as f:
|
||||
f.write("#pragma once\n\n")
|
||||
f.write("// --- AUTO GENERATED ---\n")
|
||||
f.write("// gen_docs.py is run by cmake build\n\n")
|
||||
f.write("namespace manifold_docstrings {\n")
|
||||
for key, doc in comments.items():
|
||||
f.write(f'const char* {key} = R"___({doc.strip()})___";\n')
|
||||
f.write("} // namespace manifold_docs")
|
||||
+544
-754
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1 +1 @@
|
||||
add_subdirectory(pybind11)
|
||||
add_subdirectory(nanobind)
|
||||
|
||||
+1
Submodule bindings/python/third_party/nanobind added at 23ea320229
Vendored
-1
Submodule bindings/python/third_party/pybind11 deleted from 12852cd33b
@@ -32,13 +32,21 @@ add_custom_target(js_deps ALL
|
||||
DEPENDS manifoldjs
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/manifold*.d.ts)
|
||||
|
||||
# copy WASM build back here for publishing to npm
|
||||
add_custom_command(
|
||||
TARGET js_deps POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy
|
||||
${CMAKE_CURRENT_BINARY_DIR}/manifold.*
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/manifold*.d.ts
|
||||
${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# copy WASM build and TS declarations for Vite to package into ManifoldCAD.org
|
||||
add_custom_command(
|
||||
TARGET js_deps POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/manifold*
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/examples/built/)
|
||||
|
||||
# copy TS declarations to public so they can be accessed by our editor
|
||||
add_custom_command(
|
||||
TARGET js_deps POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -24,7 +24,7 @@ Since Manifold is a WASM module, it does not automatically garbage-collect like
|
||||
|
||||
## Examples
|
||||
|
||||
Please see our usage [examples](https://github.com/elalish/manifold/tree/master/bindings/wasm/examples) to see how to interface this library with `three.js`, `<model-viewer>`, and `glTF`. Of particular note are the included libraries for lossless roundtrip of manifold meshes through glTF files, via a new extension: [EXT_manifold](https://github.com/KhronosGroup/glTF/pull/2286).
|
||||
Please see our usage [examples](https://github.com/elalish/manifold/tree/master/bindings/wasm/examples) to see how to interface this library with `three.js`, `<model-viewer>`, and `glTF`. Of particular note are the included libraries for lossless roundtrip of manifold meshes through glTF files, via a new extension: [EXT_mesh_manifold](https://github.com/KhronosGroup/glTF/pull/2286).
|
||||
|
||||
## About the author
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@
|
||||
|
||||
#include <emscripten/bind.h>
|
||||
#include <emscripten/val.h>
|
||||
#include <manifold.h>
|
||||
#include <polygon.h>
|
||||
#include <sdf.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "helpers.cpp"
|
||||
#include "manifold.h"
|
||||
#include "polygon.h"
|
||||
#include "sdf.h"
|
||||
|
||||
using namespace emscripten;
|
||||
using namespace manifold;
|
||||
@@ -125,6 +125,10 @@ EMSCRIPTEN_BINDINGS(whatever) {
|
||||
function("_crossSectionUnionN", &cross_js::UnionN);
|
||||
function("_crossSectionDifferenceN", &cross_js::DifferenceN);
|
||||
function("_crossSectionIntersectionN", &cross_js::IntersectionN);
|
||||
function("_crossSectionCollectVertices", &cross_js::CollectVertices);
|
||||
function("_crossSectionHullPoints",
|
||||
select_overload<CrossSection(std::vector<glm::vec2>)>(
|
||||
&CrossSection::Hull));
|
||||
|
||||
class_<Manifold>("Manifold")
|
||||
.constructor(&man_js::FromMeshJS)
|
||||
@@ -134,6 +138,9 @@ EMSCRIPTEN_BINDINGS(whatever) {
|
||||
.function("_Split", &man_js::Split)
|
||||
.function("_SplitByPlane", &man_js::SplitByPlane)
|
||||
.function("_TrimByPlane", &Manifold::TrimByPlane)
|
||||
.function("slice", &Manifold::Slice)
|
||||
.function("project", &Manifold::Project)
|
||||
.function("hull", select_overload<Manifold() const>(&Manifold::Hull))
|
||||
.function("_GetMeshJS", &js::GetMeshJS)
|
||||
.function("refine", &Manifold::Refine)
|
||||
.function("_Warp", &man_js::Warp)
|
||||
@@ -176,6 +183,10 @@ EMSCRIPTEN_BINDINGS(whatever) {
|
||||
function("_manifoldUnionN", &man_js::UnionN);
|
||||
function("_manifoldDifferenceN", &man_js::DifferenceN);
|
||||
function("_manifoldIntersectionN", &man_js::IntersectionN);
|
||||
function("_manifoldCollectVertices", &man_js::CollectVertices);
|
||||
function("_manifoldHullPoints",
|
||||
select_overload<Manifold(const std::vector<glm::vec3>&)>(
|
||||
&Manifold::Hull));
|
||||
|
||||
// Quality Globals
|
||||
function("setMinCircularAngle", &Quality::SetMinCircularAngle);
|
||||
|
||||
@@ -472,6 +472,36 @@ Module.setup = function() {
|
||||
Module.CrossSection.difference = crossSectionBatchbool('DifferenceN');
|
||||
Module.CrossSection.intersection = crossSectionBatchbool('IntersectionN');
|
||||
|
||||
function pushVec2(vec, ps) {
|
||||
toVec(vec, ps, p => {
|
||||
if (p instanceof Array) return {x: p[0], y: p[1]};
|
||||
return p;
|
||||
})
|
||||
}
|
||||
|
||||
Module.CrossSection.hull = function(...args) {
|
||||
if (args.length == 1) args = args[0];
|
||||
let pts = new Module.Vector_vec2();
|
||||
for (const cs of args) {
|
||||
if (cs instanceof CrossSectionCtor) {
|
||||
Module._crossSectionCollectVertices(pts, cs);
|
||||
} else if (
|
||||
cs instanceof Array && cs.length == 2 && typeof cs[0] == 'number') {
|
||||
pts.push_back({x: cs[0], y: cs[1]});
|
||||
} else if (cs.x) {
|
||||
pts.push_back(cs);
|
||||
} else {
|
||||
const wrap =
|
||||
((cs[0].length == 2 && typeof cs[0][0] == 'number') || cs[0].x);
|
||||
const polys = wrap ? [cs] : cs;
|
||||
for (const poly of polys) pushVec2(pts, poly);
|
||||
}
|
||||
}
|
||||
const result = Module._crossSectionHullPoints(pts);
|
||||
pts.delete();
|
||||
return result;
|
||||
};
|
||||
|
||||
Module.CrossSection.prototype = Object.create(CrossSectionCtor.prototype);
|
||||
|
||||
// Because the constructor and prototype are being replaced, instanceof will
|
||||
@@ -596,6 +626,33 @@ Module.setup = function() {
|
||||
return out;
|
||||
};
|
||||
|
||||
function pushVec3(vec, ps) {
|
||||
toVec(vec, ps, p => {
|
||||
if (p instanceof Array) return {x: p[0], y: p[1], z: p[2]};
|
||||
return p;
|
||||
})
|
||||
}
|
||||
|
||||
Module.Manifold.hull = function(...args) {
|
||||
if (args.length == 1) args = args[0];
|
||||
let pts = new Module.Vector_vec3();
|
||||
for (const m of args) {
|
||||
if (m instanceof ManifoldCtor) {
|
||||
Module._manifoldCollectVertices(pts, m);
|
||||
} else if (
|
||||
m instanceof Array && m.length == 3 && typeof m[0] == 'number') {
|
||||
pts.push_back({x: m[0], y: m[1], z: m[2]});
|
||||
} else if (m.x) {
|
||||
pts.push_back(m);
|
||||
} else {
|
||||
pushVec3(pts, m);
|
||||
}
|
||||
}
|
||||
const result = Module._manifoldHullPoints(pts);
|
||||
pts.delete();
|
||||
return result;
|
||||
};
|
||||
|
||||
Module.Manifold.prototype = Object.create(ManifoldCtor.prototype);
|
||||
|
||||
// Because the constructor and prototype are being replaced, instanceof will
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
declare module '@jscadui/3mf-export';
|
||||
@@ -65,7 +65,7 @@ button:hover {
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
|
||||
input {
|
||||
.name {
|
||||
border: none;
|
||||
height: 36px;
|
||||
background-color: transparent;
|
||||
@@ -77,7 +77,7 @@ input {
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
.name:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -130,18 +130,14 @@ model-viewer {
|
||||
|
||||
.header .margin {
|
||||
font-size: 16px;
|
||||
margin: 1em;
|
||||
}
|
||||
|
||||
#file {
|
||||
width: 250px;
|
||||
margin: 1em 0.5em;
|
||||
}
|
||||
|
||||
.dropdown {
|
||||
display: none;
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
width: 250px;
|
||||
width: 100%;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
@@ -150,6 +146,10 @@ model-viewer {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.hide {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.uparrow {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
@@ -174,6 +174,7 @@ model-viewer {
|
||||
position: absolute;
|
||||
width: 36px;
|
||||
top: 0px;
|
||||
right: 0px;
|
||||
background-size: 20px;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
@@ -193,7 +194,14 @@ model-viewer {
|
||||
|
||||
.trash {
|
||||
background-image: url(/icons/trash.png);
|
||||
right: 0px;
|
||||
}
|
||||
|
||||
.play {
|
||||
background-image: url(/icons/play.png);
|
||||
}
|
||||
|
||||
.pause {
|
||||
background-image: url(/icons/pause.png);
|
||||
}
|
||||
|
||||
.icon:hover {
|
||||
@@ -212,6 +220,60 @@ model-viewer {
|
||||
background-color: rgb(255, 177, 177);
|
||||
}
|
||||
|
||||
#file-margin {
|
||||
position: relative;
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
#save {
|
||||
width: 125px;
|
||||
}
|
||||
|
||||
#animation {
|
||||
display: none;
|
||||
align-items: center;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
bottom: 0px;
|
||||
margin: 2px;
|
||||
}
|
||||
|
||||
#play {
|
||||
position: relative;
|
||||
background-color: #ccc;
|
||||
margin: 8px;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: relative;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
margin-right: 16px;
|
||||
background: #ffffff55;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.slider::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
border-radius: 50%;
|
||||
background: #ccc;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.slider::-moz-range-thumb {
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
border-radius: 50%;
|
||||
background: #ccc;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 600px) {
|
||||
.container {
|
||||
flex-direction: column;
|
||||
@@ -220,5 +282,31 @@ model-viewer {
|
||||
|
||||
.col {
|
||||
width: 100%;
|
||||
height: 50%;
|
||||
}
|
||||
|
||||
#file-margin {
|
||||
width: calc(100% - 32px);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: .2em 1em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.header .margin {
|
||||
margin: 0.2em 16px;
|
||||
}
|
||||
|
||||
#button-container {
|
||||
flex-direction: row;
|
||||
margin-left: 8px;
|
||||
margin-right: 8px;
|
||||
width: calc(100% - 16px);
|
||||
}
|
||||
|
||||
#button-container .margin {
|
||||
width: calc(50% - 16px);
|
||||
margin: 8px;
|
||||
}
|
||||
}
|
||||
@@ -26,20 +26,31 @@ let editor = undefined;
|
||||
|
||||
// File UI ------------------------------------------------------------
|
||||
const fileButton = document.querySelector('#file');
|
||||
const currentElement = document.querySelector('#current');
|
||||
const arrow = document.querySelector('.uparrow');
|
||||
const dropdown = document.querySelector('.dropdown');
|
||||
const currentFileElement = document.querySelector('#current');
|
||||
const fileArrow = document.querySelector('#file .uparrow');
|
||||
const fileDropdown = document.querySelector('#fileDropdown');
|
||||
const saveContainer = document.querySelector('#save');
|
||||
const saveDropdown = document.querySelector('#saveDropdown');
|
||||
const saveArrow = document.querySelector('#save .uparrow');
|
||||
|
||||
const hideDropdown = function() {
|
||||
dropdown.classList.remove('show');
|
||||
arrow.classList.remove('down');
|
||||
fileDropdown.classList.remove('show');
|
||||
saveDropdown.classList.remove('show');
|
||||
fileArrow.classList.remove('down');
|
||||
saveArrow.classList.remove('down');
|
||||
};
|
||||
const toggleDropdown = function(event) {
|
||||
const toggleFileDropdown = function(event) {
|
||||
event.stopPropagation();
|
||||
dropdown.classList.toggle('show');
|
||||
arrow.classList.toggle('down');
|
||||
fileDropdown.classList.toggle('show');
|
||||
fileArrow.classList.toggle('down');
|
||||
};
|
||||
fileButton.onclick = toggleDropdown;
|
||||
const toggleSaveDropdown = function(event) {
|
||||
event.stopPropagation();
|
||||
saveDropdown.classList.toggle('show');
|
||||
saveArrow.classList.toggle('down');
|
||||
};
|
||||
fileButton.onclick = toggleFileDropdown;
|
||||
saveArrow.parentElement.onclick = toggleSaveDropdown;
|
||||
document.body.onclick = hideDropdown;
|
||||
|
||||
const prefix = 'ManifoldCAD';
|
||||
@@ -62,7 +73,7 @@ function nthKey(n) {
|
||||
|
||||
function saveCurrent() {
|
||||
if (editor) {
|
||||
const currentName = currentElement.textContent;
|
||||
const currentName = currentFileElement.textContent;
|
||||
if (!exampleFunctions.get(currentName)) {
|
||||
setScript(currentName, editor.getValue());
|
||||
}
|
||||
@@ -77,11 +88,11 @@ let isExample = true;
|
||||
function switchTo(scriptName) {
|
||||
if (editor) {
|
||||
switching = true;
|
||||
currentElement.textContent = scriptName;
|
||||
currentFileElement.textContent = scriptName;
|
||||
setScript('currentName', scriptName);
|
||||
const code =
|
||||
exampleFunctions.get(scriptName) ?? getScript(scriptName) ?? '';
|
||||
isExample = exampleFunctions.get(scriptName) != null;
|
||||
const code = isExample ? exampleFunctions.get(scriptName).substring(1) :
|
||||
getScript(scriptName) ?? '';
|
||||
editor.setValue(code);
|
||||
}
|
||||
}
|
||||
@@ -99,6 +110,8 @@ function createDropdownItem(name) {
|
||||
|
||||
button.onclick = function() {
|
||||
saveCurrent();
|
||||
window.location.hash = `#${label.textContent}`;
|
||||
window.location.search = '';
|
||||
switchTo(label.textContent);
|
||||
};
|
||||
// Stop text input spaces from triggering the button
|
||||
@@ -135,6 +148,7 @@ function addEdit(button) {
|
||||
const code = getScript(oldName);
|
||||
const form = document.createElement('form');
|
||||
const inputElement = document.createElement('input');
|
||||
inputElement.classList.add('name');
|
||||
inputElement.value = oldName;
|
||||
label.textContent = '';
|
||||
button.appendChild(form);
|
||||
@@ -148,8 +162,8 @@ function addEdit(button) {
|
||||
if (!input) return;
|
||||
const newName = uniqueName(input);
|
||||
label.textContent = newName;
|
||||
if (currentElement.textContent == oldName) {
|
||||
currentElement.textContent = newName;
|
||||
if (currentFileElement.textContent == oldName) {
|
||||
currentFileElement.textContent = newName;
|
||||
}
|
||||
removeScript(oldName);
|
||||
setScript(newName, code);
|
||||
@@ -182,8 +196,9 @@ function addEdit(button) {
|
||||
}, {once: true});
|
||||
} else if (performance.now() - lastClick > 500) {
|
||||
removeScript(label.textContent);
|
||||
if (currentElement.textContent == label.textContent) {
|
||||
if (currentFileElement.textContent == label.textContent) {
|
||||
switchTo('Intro');
|
||||
window.location.hash = '#Intro';
|
||||
}
|
||||
const container = button.parentElement;
|
||||
container.parentElement.removeChild(container);
|
||||
@@ -192,16 +207,16 @@ function addEdit(button) {
|
||||
}
|
||||
|
||||
const newButton = document.querySelector('#new');
|
||||
function newItem(code) {
|
||||
const name = uniqueName('New Script');
|
||||
function newItem(code, scriptName = undefined) {
|
||||
const name = uniqueName(scriptName ?? 'New Script');
|
||||
setScript(name, code);
|
||||
const nextButton = createDropdownItem(name);
|
||||
newButton.insertAdjacentElement('afterend', nextButton.parentElement);
|
||||
addEdit(nextButton);
|
||||
nextButton.click();
|
||||
return {button: nextButton, name};
|
||||
};
|
||||
newButton.onclick = function() {
|
||||
newItem('');
|
||||
newItem('').button.click();
|
||||
};
|
||||
|
||||
const runButton = document.querySelector('#compile');
|
||||
@@ -269,10 +284,10 @@ require(['vs/editor/editor.main'], async function() {
|
||||
|
||||
for (const [name] of exampleFunctions) {
|
||||
const button = createDropdownItem(name);
|
||||
dropdown.appendChild(button.parentElement);
|
||||
fileDropdown.appendChild(button.parentElement);
|
||||
}
|
||||
|
||||
let currentName = currentElement.textContent;
|
||||
let currentName = currentFileElement.textContent;
|
||||
|
||||
for (let i = 0; i < window.localStorage.length; i++) {
|
||||
const key = nthKey(i);
|
||||
@@ -287,7 +302,20 @@ require(['vs/editor/editor.main'], async function() {
|
||||
addEdit(button);
|
||||
}
|
||||
}
|
||||
switchTo(currentName);
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (window.location.hash.length > 0) {
|
||||
const name = unescape(window.location.hash.substring(1));
|
||||
switchTo(name);
|
||||
} else if (params.get('script') != null) {
|
||||
console.log(`Fetching ${params.get('script')}`);
|
||||
autoExecute = false;
|
||||
const response = await fetch(params.get('script'));
|
||||
const code = await response.text();
|
||||
switchTo(newItem(code, params.get('name')).name);
|
||||
} else {
|
||||
switchTo(currentName);
|
||||
window.location.hash = `#${currentName}`;
|
||||
}
|
||||
|
||||
if (manifoldInitialized) {
|
||||
initializeRun();
|
||||
@@ -301,7 +329,7 @@ require(['vs/editor/editor.main'], async function() {
|
||||
}
|
||||
if (isExample) {
|
||||
const cursor = editor.getPosition();
|
||||
newItem(editor.getValue());
|
||||
newItem(editor.getValue()).button.click();
|
||||
editor.setPosition(cursor);
|
||||
}
|
||||
});
|
||||
@@ -311,6 +339,51 @@ require(['vs/editor/editor.main'], async function() {
|
||||
};
|
||||
});
|
||||
|
||||
// Animation ------------------------------------------------------------
|
||||
const mv = document.querySelector('model-viewer');
|
||||
const animationContainer = document.querySelector('#animation');
|
||||
const playButton = document.querySelector('#play');
|
||||
const scrubber = document.querySelector('#scrubber');
|
||||
let paused = false;
|
||||
|
||||
mv.addEventListener('load', () => {
|
||||
const hasAnimation = mv.availableAnimations.length > 0;
|
||||
animationContainer.style.display = hasAnimation ? 'flex' : 'none';
|
||||
if (hasAnimation) {
|
||||
play();
|
||||
}
|
||||
});
|
||||
|
||||
function play() {
|
||||
mv.play();
|
||||
playButton.classList.remove('play');
|
||||
playButton.classList.add('pause');
|
||||
paused = false;
|
||||
scrubber.classList.add('hide');
|
||||
}
|
||||
|
||||
function pause() {
|
||||
mv.pause();
|
||||
playButton.classList.remove('pause');
|
||||
playButton.classList.add('play');
|
||||
paused = true;
|
||||
scrubber.max = mv.duration;
|
||||
scrubber.value = mv.currentTime;
|
||||
scrubber.classList.remove('hide');
|
||||
}
|
||||
|
||||
playButton.onclick = function() {
|
||||
if (paused) {
|
||||
play();
|
||||
} else {
|
||||
pause();
|
||||
}
|
||||
};
|
||||
|
||||
scrubber.oninput = function() {
|
||||
mv.currentTime = scrubber.value;
|
||||
};
|
||||
|
||||
// Execution ------------------------------------------------------------
|
||||
const consoleElement = document.querySelector('#console');
|
||||
const oldLog = console.log;
|
||||
@@ -346,8 +419,10 @@ function finishRun() {
|
||||
`Took ${(Math.round((t1 - t0) / 10) / 100).toLocaleString()} seconds`);
|
||||
}
|
||||
|
||||
const mv = document.querySelector('model-viewer');
|
||||
let objectURL = null;
|
||||
const output = {
|
||||
glbURL: null,
|
||||
threeMFURL: null
|
||||
};
|
||||
let manifoldWorker = null;
|
||||
|
||||
function createWorker() {
|
||||
@@ -370,10 +445,16 @@ function createWorker() {
|
||||
finishRun();
|
||||
runButton.disabled = true;
|
||||
|
||||
URL.revokeObjectURL(objectURL);
|
||||
objectURL = e.data.objectURL;
|
||||
mv.src = objectURL;
|
||||
if (objectURL == null) {
|
||||
if (output.threeMFURL != null) {
|
||||
URL.revokeObjectURL(output.threeMFURL);
|
||||
output.threeMFURL = null;
|
||||
}
|
||||
URL.revokeObjectURL(output.glbURL);
|
||||
output.glbURL = e.data.glbURL;
|
||||
output.threeMFURL = e.data.threeMFURL;
|
||||
threemfButton.disabled = output.threeMFURL == null;
|
||||
mv.src = output.glbURL;
|
||||
if (output.glbURL == null) {
|
||||
mv.showPoster();
|
||||
poster.textContent = 'Error';
|
||||
createWorker();
|
||||
@@ -411,10 +492,24 @@ runButton.onclick = function() {
|
||||
}
|
||||
};
|
||||
|
||||
const downloadButton = document.querySelector('#download');
|
||||
downloadButton.onclick = function() {
|
||||
const link = document.createElement('a');
|
||||
link.download = 'manifold.glb';
|
||||
link.href = objectURL;
|
||||
link.click();
|
||||
};
|
||||
function clickSave(saveButton, filename, outputName) {
|
||||
const container = saveButton.parentElement;
|
||||
return () => {
|
||||
const oldSave = saveContainer.firstElementChild;
|
||||
if (oldSave !== container) {
|
||||
saveDropdown.insertBefore(oldSave, saveDropdown.firstElementChild);
|
||||
saveContainer.insertBefore(container, saveDropdown);
|
||||
container.appendChild(saveArrow.parentElement);
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
link.download = filename;
|
||||
link.href = output[outputName];
|
||||
link.click();
|
||||
};
|
||||
}
|
||||
|
||||
const glbButton = document.querySelector('#glb');
|
||||
glbButton.onclick = clickSave(glbButton, 'manifold.glb', 'glbURL');
|
||||
|
||||
const threemfButton = document.querySelector('#threemf');
|
||||
threemfButton.onclick = clickSave(threemfButton, 'manifold.3mf', 'threeMFURL');
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import {Accessor} from '@gltf-transform/core';
|
||||
|
||||
import {EXTManifold} from './manifold-gltf.js';
|
||||
|
||||
export const attributeDefs = {
|
||||
'POSITION': {type: Accessor.Type.VEC3, components: 3},
|
||||
'NORMAL': {type: Accessor.Type.VEC3, components: 3},
|
||||
'TANGENT': {type: Accessor.Type.VEC4, components: 4},
|
||||
'TEXCOORD_0': {type: Accessor.Type.VEC2, components: 2},
|
||||
'TEXCOORD_1': {type: Accessor.Type.VEC2, components: 2},
|
||||
'COLOR_0': {type: Accessor.Type.VEC3, components: 3},
|
||||
'JOINTS_0': {type: Accessor.Type.VEC4, components: 4},
|
||||
'WEIGHTS_0': {type: Accessor.Type.VEC4, components: 4},
|
||||
'SKIP_1': {type: null, components: 1},
|
||||
'SKIP_2': {type: null, components: 2},
|
||||
'SKIP_3': {type: null, components: 3},
|
||||
'SKIP_4': {type: null, components: 4},
|
||||
};
|
||||
|
||||
export function setupIO(io) {
|
||||
return io.registerExtensions([EXTManifold]);
|
||||
}
|
||||
|
||||
function readPrimitive(primitive, numProp, attributes) {
|
||||
const position = primitive.getAttribute('POSITION');
|
||||
const numVert = position.getCount();
|
||||
const vertProperties = [];
|
||||
let offset = 0;
|
||||
for (const attribute of attributes) {
|
||||
const size = attributeDefs[attribute].components;
|
||||
if (attribute === 'SKIP') {
|
||||
offset += size;
|
||||
continue;
|
||||
}
|
||||
const accessor = primitive.getAttribute(attribute);
|
||||
if (accessor) {
|
||||
const array = accessor.getArray();
|
||||
for (let i = 0; i < numVert; ++i) {
|
||||
for (let j = 0; j < size; ++j) {
|
||||
vertProperties[numProp * i + offset + j] = array[i * size + j];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < numVert; ++i) {
|
||||
for (let j = 0; j < size; ++j) {
|
||||
vertProperties[numProp * i + offset + j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += size;
|
||||
}
|
||||
return vertProperties;
|
||||
}
|
||||
|
||||
export function readMesh(mesh, attributes, materials) {
|
||||
const primitives = mesh.listPrimitives();
|
||||
if (primitives.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (attributes.length === 0) {
|
||||
const attributeSet = new Set();
|
||||
for (const primitive of primitives) {
|
||||
const semantics = primitive.listSemantics();
|
||||
for (const semantic of semantics) {
|
||||
attributeSet.add(semantic);
|
||||
}
|
||||
}
|
||||
for (const semantic in attributeDefs) {
|
||||
if (attributeSet.has(semantic)) {
|
||||
attributes.push(semantic);
|
||||
attributeSet.delete(semantic);
|
||||
}
|
||||
}
|
||||
for (const semantic of attributeSet.keys()) {
|
||||
attributes.push(semantic);
|
||||
}
|
||||
}
|
||||
|
||||
if (attributes.length < 1 || attributes[0] !== 'POSITION')
|
||||
throw new Error('First attribute must be "POSITION".');
|
||||
|
||||
const numProp = attributes.map((def) => attributeDefs[def].components)
|
||||
.reduce((a, b) => a + b);
|
||||
|
||||
const manifoldPrimitive = mesh.getExtension('EXT_manifold');
|
||||
|
||||
let vertPropArray = [];
|
||||
let triVertArray = [];
|
||||
const runIndexArray = [0];
|
||||
const mergeFromVert = [];
|
||||
const mergeToVert = [];
|
||||
if (manifoldPrimitive != null) {
|
||||
vertPropArray = readPrimitive(primitives[0], numProp, attributes);
|
||||
for (const primitive of primitives) {
|
||||
triVertArray = [...triVertArray, ...primitive.getIndices().getArray()];
|
||||
runIndexArray.push(triVertArray.length);
|
||||
materials.push(primitive.getMaterial());
|
||||
}
|
||||
const mergeTriVert = manifoldPrimitive.getMergeIndices()?.getArray() ?? [];
|
||||
const mergeTo = manifoldPrimitive.getMergeValues()?.getArray() ?? [];
|
||||
const vert2merge = new Map();
|
||||
for (const [i, idx] of mergeTriVert.entries()) {
|
||||
vert2merge.set(triVertArray[idx], mergeTo[i]);
|
||||
}
|
||||
for (const [from, to] of vert2merge.entries()) {
|
||||
mergeFromVert.push(from);
|
||||
mergeToVert.push(to);
|
||||
}
|
||||
} else {
|
||||
for (const primitive of primitives) {
|
||||
const numVert = vertPropArray.length / numProp;
|
||||
vertPropArray =
|
||||
[...vertPropArray, ...readPrimitive(primitive, numProp, attributes)];
|
||||
triVertArray = [
|
||||
...triVertArray,
|
||||
...primitive.getIndices().getArray().map((i) => i + numVert)
|
||||
];
|
||||
runIndexArray.push(triVertArray.length);
|
||||
materials.push(primitive.getMaterial());
|
||||
}
|
||||
}
|
||||
const vertProperties = new Float32Array(vertPropArray);
|
||||
const triVerts = new Uint32Array(triVertArray);
|
||||
const runIndex = new Uint32Array(runIndexArray);
|
||||
|
||||
return {
|
||||
numProp,
|
||||
triVerts,
|
||||
vertProperties,
|
||||
runIndex,
|
||||
mergeFromVert,
|
||||
mergeToVert
|
||||
};
|
||||
}
|
||||
|
||||
export function writeMesh(doc, manifoldMesh, attributes, materials) {
|
||||
if (doc.getRoot().listBuffers().length === 0) {
|
||||
doc.createBuffer();
|
||||
}
|
||||
const buffer = doc.getRoot().listBuffers()[0];
|
||||
const manifoldExtension = doc.createExtension(EXTManifold);
|
||||
|
||||
const attributeUnion = [];
|
||||
for (const matAttributes of attributes) {
|
||||
matAttributes.forEach((attribute, i) => {
|
||||
if (i >= attributeUnion.length) {
|
||||
attributeUnion.push(attribute);
|
||||
} else {
|
||||
const size = attributeDefs[attribute].components;
|
||||
const unionSize = attributeDefs[attributeUnion[i]].components;
|
||||
if (size != unionSize) {
|
||||
throw new Error(
|
||||
'Attribute sizes do not correspond: ', attribute, ' and ',
|
||||
attributeUnion[i]);
|
||||
}
|
||||
if (attributeDefs[attributeUnion[i]].type == null) {
|
||||
attributeUnion[i] = attribute;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (attributeUnion.length < 1 || attributeUnion[0] !== 'POSITION')
|
||||
throw new Error('First attribute must be "POSITION".');
|
||||
|
||||
const mesh = doc.createMesh();
|
||||
const numPrimitive = manifoldMesh.runIndex.length - 1;
|
||||
for (let run = 0; run < numPrimitive; ++run) {
|
||||
const indices = doc.createAccessor('indices')
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array());
|
||||
const primitive = doc.createPrimitive().setIndices(indices);
|
||||
const material = materials[run];
|
||||
if (material) {
|
||||
primitive.setMaterial(material);
|
||||
}
|
||||
mesh.addPrimitive(primitive);
|
||||
}
|
||||
|
||||
const numVert = manifoldMesh.numVert;
|
||||
const numProp = manifoldMesh.numProp;
|
||||
let offset = 0;
|
||||
attributeUnion.forEach((attribute, aIdx) => {
|
||||
if (attribute === 'SKIP') {
|
||||
++offset;
|
||||
return;
|
||||
}
|
||||
const def = attributeDefs[attribute];
|
||||
if (def == null)
|
||||
throw new Error(attribute + ' is not a recognized attribute.');
|
||||
|
||||
const n = def.components;
|
||||
if (offset + n > numProp) throw new Error('Too many attribute channels.');
|
||||
|
||||
const array = new Float32Array(n * numVert);
|
||||
for (let v = 0; v < numVert; ++v) {
|
||||
for (let i = 0; i < n; ++i) {
|
||||
array[n * v + i] =
|
||||
manifoldMesh.vertProperties[numProp * v + offset + i];
|
||||
}
|
||||
}
|
||||
|
||||
const accessor =
|
||||
doc.createAccessor().setBuffer(buffer).setType(def.type).setArray(
|
||||
array);
|
||||
|
||||
mesh.listPrimitives().forEach((primitive, pIdx) => {
|
||||
if (attributes[pIdx].length > aIdx &&
|
||||
attributeDefs[attributes[pIdx][aIdx]].type != null) {
|
||||
primitive.setAttribute(attribute, accessor);
|
||||
}
|
||||
});
|
||||
offset += n;
|
||||
});
|
||||
|
||||
const manifoldPrimitive = manifoldExtension.createManifoldPrimitive();
|
||||
mesh.setExtension('EXT_manifold', manifoldPrimitive);
|
||||
|
||||
const indices = doc.createAccessor('indices')
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(manifoldMesh.triVerts);
|
||||
manifoldPrimitive.setIndices(indices);
|
||||
manifoldPrimitive.setRunIndex(manifoldMesh.runIndex);
|
||||
|
||||
const vert2merge = [...Array(manifoldMesh.numVert).keys()];
|
||||
for (const [i, from] of manifoldMesh.mergeFromVert.entries()) {
|
||||
vert2merge[from] = manifoldMesh.mergeToVert[i];
|
||||
}
|
||||
const ind = [];
|
||||
const val = [];
|
||||
for (const [i, vert] of manifoldMesh.triVerts.entries()) {
|
||||
const newVert = vert2merge[vert];
|
||||
if (vert !== newVert) {
|
||||
ind.push(i);
|
||||
val.push(newVert);
|
||||
}
|
||||
}
|
||||
const indicesAccessor = doc.createAccessor()
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array(ind));
|
||||
const valuesAccessor = doc.createAccessor()
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array(val));
|
||||
manifoldPrimitive.setMerge(indicesAccessor, valuesAccessor);
|
||||
|
||||
return mesh;
|
||||
}
|
||||
|
||||
export function disposeMesh(mesh) {
|
||||
if (!mesh) return;
|
||||
const primitives = mesh.listPrimitives();
|
||||
for (const primitive of primitives) {
|
||||
primitive.getIndices()?.dispose();
|
||||
for (const accessor of primitive.listAttributes()) {
|
||||
accessor.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
mesh.dispose();
|
||||
}
|
||||
|
||||
export async function loadTexture(texture, uri) {
|
||||
const response = await fetch(uri);
|
||||
const blob = await response.blob();
|
||||
texture.setMimeType(blob.type);
|
||||
texture.setImage(new Uint8Array(await blob.arrayBuffer()));
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import {Accessor, Document, Material, Mesh, Primitive, Texture, WebIO} from '@gltf-transform/core';
|
||||
|
||||
import {EXTManifold, ManifoldPrimitive} from './manifold-gltf';
|
||||
import {Mesh as ManifoldMesh, MeshOptions} from './public/manifold-encapsulated-types';
|
||||
|
||||
export const attributeDefs = {
|
||||
'POSITION': {type: Accessor.Type.VEC3, components: 3},
|
||||
'NORMAL': {type: Accessor.Type.VEC3, components: 3},
|
||||
'TANGENT': {type: Accessor.Type.VEC4, components: 4},
|
||||
'TEXCOORD_0': {type: Accessor.Type.VEC2, components: 2},
|
||||
'TEXCOORD_1': {type: Accessor.Type.VEC2, components: 2},
|
||||
'COLOR_0': {type: Accessor.Type.VEC3, components: 3},
|
||||
'JOINTS_0': {type: Accessor.Type.VEC4, components: 4},
|
||||
'WEIGHTS_0': {type: Accessor.Type.VEC4, components: 4},
|
||||
'SKIP_1': {type: null, components: 1},
|
||||
'SKIP_2': {type: null, components: 2},
|
||||
'SKIP_3': {type: null, components: 3},
|
||||
'SKIP_4': {type: null, components: 4},
|
||||
};
|
||||
|
||||
export type Attribute = keyof(typeof attributeDefs);
|
||||
|
||||
export interface Properties {
|
||||
material: Material;
|
||||
attributes: Attribute[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this first to register the manifold extension so that readMesh and
|
||||
* writeMesh will work.
|
||||
*/
|
||||
export function setupIO(io: WebIO) {
|
||||
return io.registerExtensions([EXTManifold]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an input mesh into Manifold-compatible data structures, whether it
|
||||
* contains the EXT_mesh_manifold extension or not.
|
||||
*
|
||||
* @param mesh The Mesh to read.
|
||||
* @param attributes An array of attributes representing the order of desired
|
||||
* properties returned in the vertProperties array of the output mesh. If
|
||||
* omitted, this will be populated with the union of all attributes defined
|
||||
* in the primitives of the input mesh. If present, the first entry must be
|
||||
* 'POSITION', and any attributes in the primitives that are not included in
|
||||
* this list will be ignored, while those in the list but not defined in a
|
||||
* primitive will be populated with zeros.
|
||||
* @returns The returned mesh is suitable for initializing a Manifold or Mesh of
|
||||
* the Manifold library if desired. See Manifold documentation if you prefer
|
||||
* to use these GL arrays in a different library. The runProperties array
|
||||
* gives the Material and attributes list associated with each triangle run,
|
||||
* which in turn corresponds to a primitive of the input mesh. These
|
||||
* attributes are the intersection of the attributes present on the
|
||||
* primitive and those requested in the attributes input.
|
||||
*/
|
||||
export function readMesh(mesh: Mesh, attributes: Attribute[] = []):
|
||||
{mesh: MeshOptions, runProperties: Properties[]}|null {
|
||||
const primitives = mesh.listPrimitives();
|
||||
if (primitives.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (attributes.length === 0) {
|
||||
const attributeSet = new Set<Attribute>();
|
||||
for (const primitive of primitives) {
|
||||
const semantics = primitive.listSemantics() as Attribute[];
|
||||
for (const semantic of semantics) {
|
||||
attributeSet.add(semantic);
|
||||
}
|
||||
}
|
||||
let semantic: Attribute;
|
||||
for (semantic in attributeDefs) {
|
||||
if (attributeSet.has(semantic)) {
|
||||
attributes.push(semantic);
|
||||
attributeSet.delete(semantic);
|
||||
}
|
||||
}
|
||||
for (const semantic of attributeSet.keys()) {
|
||||
attributes.push(semantic);
|
||||
}
|
||||
}
|
||||
|
||||
if (attributes.length < 1 || attributes[0] !== 'POSITION')
|
||||
throw new Error('First attribute must be "POSITION".');
|
||||
|
||||
let numProp = 0;
|
||||
const attributeOffsets = attributes.map((numProp = 0, def => {
|
||||
const last = numProp;
|
||||
numProp += attributeDefs[def].components;
|
||||
return last;
|
||||
}));
|
||||
|
||||
const manifoldPrimitive =
|
||||
mesh.getExtension('EXT_mesh_manifold') as ManifoldPrimitive;
|
||||
|
||||
let vertPropArray: number[] = [];
|
||||
let triVertArray: number[] = [];
|
||||
const runIndexArray = [0];
|
||||
const mergeFromVertArray = [];
|
||||
const mergeToVertArray = [];
|
||||
const runProperties: Properties[] = [];
|
||||
if (manifoldPrimitive != null) {
|
||||
const numVert = primitives[0].getAttribute('POSITION')!.getCount();
|
||||
const foundAttribute = attributes.map((a) => attributeDefs[a].type == null);
|
||||
vertPropArray = new Array<number>(numProp * numVert);
|
||||
|
||||
for (const primitive of primitives) {
|
||||
const indices = primitive.getIndices();
|
||||
if (!indices) {
|
||||
console.log('Skipping non-indexed primitive ', primitive.getName());
|
||||
continue;
|
||||
}
|
||||
|
||||
const attributesIn = primitive.listSemantics() as Attribute[];
|
||||
|
||||
attributes.forEach((attributeOut, idx) => {
|
||||
if (foundAttribute[idx]) {
|
||||
return;
|
||||
}
|
||||
for (const attributeIn of attributesIn) {
|
||||
if (attributeIn === attributeOut) {
|
||||
foundAttribute[idx] = true;
|
||||
const accessor = primitive.getAttribute(attributeIn)!;
|
||||
writeProperties(
|
||||
vertPropArray, accessor, numProp, attributeOffsets[idx]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
triVertArray = [...triVertArray, ...indices.getArray()!];
|
||||
runIndexArray.push(triVertArray.length);
|
||||
runProperties.push({
|
||||
material: primitive.getMaterial()!,
|
||||
attributes: attributesIn.filter(b => attributes.some(a => a == b))
|
||||
});
|
||||
}
|
||||
const mergeTriVert = manifoldPrimitive.getMergeIndices()?.getArray() ?? [];
|
||||
const mergeTo = manifoldPrimitive.getMergeValues()?.getArray() ?? [];
|
||||
const vert2merge = new Map();
|
||||
for (const [i, idx] of mergeTriVert.entries()) {
|
||||
vert2merge.set(triVertArray[idx], mergeTo[i]);
|
||||
}
|
||||
for (const [from, to] of vert2merge.entries()) {
|
||||
mergeFromVertArray.push(from);
|
||||
mergeToVertArray.push(to);
|
||||
}
|
||||
} else {
|
||||
for (const primitive of primitives) {
|
||||
const indices = primitive.getIndices();
|
||||
if (!indices) {
|
||||
console.log('Skipping non-indexed primitive ', primitive.getName());
|
||||
continue;
|
||||
}
|
||||
const numVert = vertPropArray.length / numProp;
|
||||
vertPropArray =
|
||||
[...vertPropArray, ...readPrimitive(primitive, numProp, attributes)];
|
||||
triVertArray =
|
||||
[...triVertArray, ...indices.getArray()!.map((i) => i + numVert)];
|
||||
runIndexArray.push(triVertArray.length);
|
||||
|
||||
const attributesIn = primitive.listSemantics() as Attribute[];
|
||||
runProperties.push({
|
||||
material: primitive.getMaterial()!,
|
||||
attributes: attributesIn.filter(b => attributes.some(a => a == b))
|
||||
});
|
||||
}
|
||||
}
|
||||
const vertProperties = new Float32Array(vertPropArray);
|
||||
const triVerts = new Uint32Array(triVertArray);
|
||||
const runIndex = new Uint32Array(runIndexArray);
|
||||
const mergeFromVert = new Uint32Array(mergeFromVertArray);
|
||||
const mergeToVert = new Uint32Array(mergeToVertArray);
|
||||
|
||||
const meshOut =
|
||||
{numProp, triVerts, vertProperties, runIndex, mergeFromVert, mergeToVert};
|
||||
|
||||
return {mesh: meshOut, runProperties};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a Manifold Mesh into a glTF Mesh object, using the EXT_mesh_manifold
|
||||
* extension to allow for lossless roundtrip of the manifold mesh through the
|
||||
* glTF file.
|
||||
*
|
||||
* @param doc The glTF Document to which this Mesh will be added.
|
||||
* @param manifoldMesh The Manifold Mesh to convert to glTF.
|
||||
* @param id2properties A map from originalID to Properties that include the
|
||||
* glTF Material and the set of attributes to output. All triangle runs with
|
||||
* the same originalID will be combined into a single output primitive. Any
|
||||
* originalIDs not found in the map will have the glTF default material and
|
||||
* no attributes beyond 'POSITION'. Each attributes array must correspond to
|
||||
* the manifoldMesh vertProperties, thus the first attribute must always be
|
||||
* 'POSITION'. Any properties that should not be output for a given
|
||||
* primitive must use the 'SKIP_*' attributes.
|
||||
* @returns The glTF Mesh to add to the Document.
|
||||
*/
|
||||
export function writeMesh(
|
||||
doc: Document, manifoldMesh: ManifoldMesh,
|
||||
id2properties: Map<number, Properties>): Mesh {
|
||||
if (doc.getRoot().listBuffers().length === 0) {
|
||||
doc.createBuffer();
|
||||
}
|
||||
const buffer = doc.getRoot().listBuffers()[0];
|
||||
const manifoldExtension = doc.createExtension(EXTManifold);
|
||||
|
||||
const mesh = doc.createMesh();
|
||||
const runIndex = [];
|
||||
const attributeUnion: Attribute[] = [];
|
||||
const primitive2attributes = new Map<Primitive, Attribute[]>();
|
||||
const numRun = manifoldMesh.runIndex.length - 1;
|
||||
let lastID = -1;
|
||||
for (let run = 0; run < numRun; ++run) {
|
||||
const id = manifoldMesh.runOriginalID[run];
|
||||
if (id == lastID) {
|
||||
continue;
|
||||
}
|
||||
lastID = id;
|
||||
runIndex.push(manifoldMesh.runIndex[run]);
|
||||
|
||||
const indices = doc.createAccessor('primitive indices of ID ' + id)
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array(1));
|
||||
const primitive = doc.createPrimitive().setIndices(indices);
|
||||
|
||||
const properties = id2properties.get(id);
|
||||
if (properties) {
|
||||
const {material, attributes} = properties;
|
||||
if (attributes.length < 1 || attributes[0] !== 'POSITION')
|
||||
throw new Error('First attribute must be "POSITION".');
|
||||
|
||||
primitive.setMaterial(material);
|
||||
primitive2attributes.set(primitive, attributes);
|
||||
|
||||
properties.attributes.forEach((attribute, i) => {
|
||||
if (i >= attributeUnion.length) {
|
||||
attributeUnion.push(attribute);
|
||||
} else {
|
||||
const size = attributeDefs[attribute].components;
|
||||
const unionSize = attributeDefs[attributeUnion[i]].components;
|
||||
if (size != unionSize) {
|
||||
throw new Error(
|
||||
'Attribute sizes do not correspond: ' + attribute + ' and ' +
|
||||
attributeUnion[i]);
|
||||
}
|
||||
if (attributeDefs[attributeUnion[i]].type == null) {
|
||||
attributeUnion[i] = attribute;
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
primitive2attributes.set(primitive, ['POSITION']);
|
||||
}
|
||||
|
||||
mesh.addPrimitive(primitive);
|
||||
}
|
||||
runIndex.push(manifoldMesh.runIndex[numRun]);
|
||||
|
||||
const numVert = manifoldMesh.numVert;
|
||||
const numProp = manifoldMesh.numProp;
|
||||
let offset = 0;
|
||||
attributeUnion.forEach((attribute, aIdx) => {
|
||||
const def = attributeDefs[attribute];
|
||||
if (def == null)
|
||||
throw new Error(attribute + ' is not a recognized attribute.');
|
||||
|
||||
if (def.type == null) {
|
||||
++offset;
|
||||
return;
|
||||
}
|
||||
|
||||
const n = def.components;
|
||||
if (offset + n > numProp) throw new Error('Too many attribute channels.');
|
||||
|
||||
const array = new Float32Array(n * numVert);
|
||||
for (let v = 0; v < numVert; ++v) {
|
||||
for (let i = 0; i < n; ++i) {
|
||||
let x = manifoldMesh.vertProperties[numProp * v + offset + i];
|
||||
if (attribute == 'COLOR_0') {
|
||||
x = Math.max(0, Math.min(1, x));
|
||||
}
|
||||
array[n * v + i] = x;
|
||||
}
|
||||
}
|
||||
|
||||
const accessor = doc.createAccessor(attribute)
|
||||
.setBuffer(buffer)
|
||||
.setType(def.type)
|
||||
.setArray(array);
|
||||
|
||||
for (const primitive of mesh.listPrimitives()) {
|
||||
const attributes = primitive2attributes.get(primitive)!;
|
||||
if (attributes.length > aIdx &&
|
||||
attributeDefs[attributes[aIdx]].type != null) {
|
||||
primitive.setAttribute(attribute, accessor);
|
||||
}
|
||||
}
|
||||
offset += n;
|
||||
});
|
||||
|
||||
const manifoldPrimitive = manifoldExtension.createManifoldPrimitive();
|
||||
mesh.setExtension('EXT_mesh_manifold', manifoldPrimitive);
|
||||
|
||||
const indices = doc.createAccessor('manifold indices')
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(manifoldMesh.triVerts);
|
||||
manifoldPrimitive.setIndices(indices);
|
||||
manifoldPrimitive.setRunIndex(runIndex);
|
||||
|
||||
const vert2merge = [...Array(manifoldMesh.numVert).keys()];
|
||||
const ind = [];
|
||||
const val = [];
|
||||
if (manifoldMesh.mergeFromVert && manifoldMesh.mergeToVert) {
|
||||
for (const [i, from] of manifoldMesh.mergeFromVert.entries()) {
|
||||
vert2merge[from] = manifoldMesh.mergeToVert[i];
|
||||
}
|
||||
|
||||
for (const [i, vert] of manifoldMesh.triVerts.entries()) {
|
||||
const newVert = vert2merge[vert];
|
||||
if (vert !== newVert) {
|
||||
ind.push(i);
|
||||
val.push(newVert);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ind.length > 0) {
|
||||
const indicesAccessor = doc.createAccessor('merge from')
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array(ind));
|
||||
const valuesAccessor = doc.createAccessor('merge to')
|
||||
.setBuffer(buffer)
|
||||
.setType(Accessor.Type.SCALAR)
|
||||
.setArray(new Uint32Array(val));
|
||||
manifoldPrimitive.setMerge(indicesAccessor, valuesAccessor);
|
||||
}
|
||||
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to dispose of a Mesh, useful when replacing an existing Mesh
|
||||
* with one from writeMesh.
|
||||
*/
|
||||
export function disposeMesh(mesh: Mesh) {
|
||||
if (!mesh) return;
|
||||
const primitives = mesh.listPrimitives();
|
||||
for (const primitive of primitives) {
|
||||
primitive.getIndices()?.dispose();
|
||||
for (const accessor of primitive.listAttributes()) {
|
||||
accessor.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
const manifoldPrimitive =
|
||||
mesh.getExtension('EXT_mesh_manifold') as ManifoldPrimitive;
|
||||
if (manifoldPrimitive) {
|
||||
manifoldPrimitive.getIndices()?.dispose();
|
||||
manifoldPrimitive.getMergeIndices()?.dispose();
|
||||
manifoldPrimitive.getMergeValues()?.dispose();
|
||||
}
|
||||
|
||||
mesh.dispose();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to download an image and apply it to the given texture.
|
||||
*
|
||||
* @param texture The texture to update
|
||||
* @param uri The location of the image to download
|
||||
*/
|
||||
export async function loadTexture(texture: Texture, uri: string) {
|
||||
const response = await fetch(uri);
|
||||
const blob = await response.blob();
|
||||
texture.setMimeType(blob.type);
|
||||
texture.setImage(new Uint8Array(await blob.arrayBuffer()));
|
||||
}
|
||||
|
||||
function writeProperties(
|
||||
vertProperties: number[], accessor: Accessor, numProp: number,
|
||||
offset: number) {
|
||||
const array = accessor.getArray()!;
|
||||
const size = accessor.getElementSize();
|
||||
const numVert = accessor.getCount();
|
||||
for (let i = 0; i < numVert; ++i) {
|
||||
for (let j = 0; j < size; ++j) {
|
||||
vertProperties[numProp * i + offset + j] = array[i * size + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readPrimitive(
|
||||
primitive: Primitive, numProp: number, attributes: Attribute[]) {
|
||||
const vertProperties: number[] = [];
|
||||
let offset = 0;
|
||||
for (const attribute of attributes) {
|
||||
const size = attributeDefs[attribute].components;
|
||||
if (attributeDefs[attribute].type == null) {
|
||||
offset += size;
|
||||
continue;
|
||||
}
|
||||
const accessor = primitive.getAttribute(attribute);
|
||||
if (accessor) {
|
||||
writeProperties(vertProperties, accessor, numProp, offset);
|
||||
}
|
||||
offset += size;
|
||||
}
|
||||
return vertProperties;
|
||||
}
|
||||
@@ -40,15 +40,27 @@
|
||||
<div class="page">
|
||||
<div class="container header" style="background-color: #A288B3;">
|
||||
<p style="flex: 2;"><a target="_blank" href="https://github.com/elalish/manifold">Manifold</a>CAD </p>
|
||||
<div class="margin" style="position: relative;">
|
||||
<button type="button" id="file" class="blue"><b class="uparrow"></b> <span
|
||||
<div class="margin" id="file-margin">
|
||||
<button type="button" id="file" class="blue item"><b class="uparrow"></b> <span
|
||||
id="current">Intro</span></button>
|
||||
<div class="dropdown">
|
||||
<div class="dropdown" id="fileDropdown">
|
||||
<button type="button" class="green item" id="new">New</button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" id="compile" class="margin green" disabled><span>Run</span></button>
|
||||
<button type="button" id="download" class="blue margin">Save GLB</button>
|
||||
<div class="container" id="button-container">
|
||||
<button type="button" id="compile" class="margin green" disabled><span>Run</span></button>
|
||||
<div id="save" class="margin" style="position: relative; ">
|
||||
<div class="item">
|
||||
<button type="button" id="glb" class="blue item">Save GLB</button>
|
||||
<button type="button" class="icon"><b class="uparrow" style="right: 2px;"></b></button>
|
||||
</div>
|
||||
<div class="dropdown" id="saveDropdown">
|
||||
<div class="item">
|
||||
<button type="button" id="threemf" class="blue item">Save 3MF</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container" style="flex: 2;">
|
||||
<div id="editor" class="col"></div>
|
||||
@@ -58,6 +70,10 @@
|
||||
<div class="center" slot="poster">
|
||||
<p id="poster" style="text-align: center; line-height: 36px;"> Loading... </p>
|
||||
</div>
|
||||
<div id="animation">
|
||||
<button type="button" id="play" class="icon pause"></button>
|
||||
<input type="range" min="0" max="1" step="0.01" value="0" class="slider" id="scrubber">
|
||||
</div>
|
||||
</model-viewer>
|
||||
<div id="console"></div>
|
||||
</div>
|
||||
@@ -72,6 +88,6 @@
|
||||
integrity="sha512-iQEIc0rsSDujsfjtD+lfyJ1W23Bh/lbgriubKDAym6VlEIDRj9rrbSIyJRyshOrl8s0yRcQ0+gyrZfSLyjJGWQ=="
|
||||
crossorigin="anonymous" referrerpolicy="no-referrer">
|
||||
<script type="module" src="editor.js"></script>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.1.1/model-viewer.min.js"></script>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.3.0/model-viewer.min.js"></script>
|
||||
|
||||
</html>
|
||||
@@ -46,7 +46,7 @@
|
||||
<body>
|
||||
<p>Load a glTF/GLB model and our <a href="https://github.com/elalish/manifold">Manifold</a> library will attempt to
|
||||
merge it into a set of manifold objects. If the model is water-tight, you can download the new GLB which will have
|
||||
our <a href="https://github.com/KhronosGroup/glTF/pull/2286">EXT_manifold</a> extension, thus preserving the
|
||||
our <a href="https://github.com/KhronosGroup/glTF/pull/2286">EXT_mesh_manifold</a> extension, thus preserving the
|
||||
manifold data without losing any mesh properties.</p>
|
||||
<p> If the View Manifold GLB checkbox is enabled, then some meshes in the model have open edges and don't represent a
|
||||
solid object. Check this box to see only the manifold parts, which will also enable them to be downloaded. If the
|
||||
@@ -59,13 +59,13 @@
|
||||
<span id="poster" slot="poster">Drop a GLB here</span>
|
||||
</model-viewer>
|
||||
</body>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/2.0.1/model-viewer.min.js"></script>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.3.0/model-viewer.min.js"></script>
|
||||
<script type="module">
|
||||
import { WebIO } from '@gltf-transform/core';
|
||||
import { prune } from '@gltf-transform/functions';
|
||||
import { KHRONOS_EXTENSIONS } from '@gltf-transform/extensions';
|
||||
import { SimpleDropzone } from 'simple-dropzone';
|
||||
import { readMesh, writeMesh, setupIO } from './gltf-io.js';
|
||||
import { readMesh, writeMesh, setupIO, disposeMesh } from './gltf-io';
|
||||
import Module from './built/manifold.js';
|
||||
|
||||
const io = setupIO(new WebIO());
|
||||
@@ -147,31 +147,30 @@
|
||||
const docIn = await io.read(url);
|
||||
const nodes = docIn.getRoot().listNodes();
|
||||
for (const node of nodes) {
|
||||
const attributes = [];
|
||||
const mesh = node.getMesh();
|
||||
if (!mesh) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const materials = [];
|
||||
const tmpMesh = readMesh(mesh, attributes, materials);
|
||||
tmpMesh.runOriginalID = [];
|
||||
const firstID = Manifold.reserveIDs(materials.length);
|
||||
for (let i = 0; i < materials.length; ++i) {
|
||||
tmpMesh.runOriginalID.push(firstID + i);
|
||||
}
|
||||
const manifoldMesh = new Mesh(tmpMesh);
|
||||
mesh.dispose();
|
||||
const tmp = readMesh(mesh);
|
||||
|
||||
const matAttributes = [];
|
||||
materials.forEach(() => matAttributes.push(attributes));
|
||||
tmp.mesh.runOriginalID = [];
|
||||
const id2properties = new Map();
|
||||
const numID = tmp.runProperties.length;
|
||||
const firstID = Manifold.reserveIDs(numID);
|
||||
for (let i = 0; i < numID; ++i) {
|
||||
tmp.mesh.runOriginalID.push(firstID + i);
|
||||
id2properties.set(firstID + i, tmp.runProperties[i]);
|
||||
}
|
||||
const manifoldMesh = new Mesh(tmp.mesh);
|
||||
disposeMesh(mesh);
|
||||
|
||||
manifoldMesh.merge();
|
||||
|
||||
try {
|
||||
// Test manifoldness - will throw if not.
|
||||
const manifold = Manifold(manifoldMesh);
|
||||
node.setMesh(writeMesh(docIn, manifold.getMesh(), matAttributes, materials));
|
||||
node.setMesh(writeMesh(docIn, manifold.getMesh(), id2properties));
|
||||
manifold.delete();
|
||||
anyManifold = true;
|
||||
} catch (e) {
|
||||
|
||||
@@ -12,15 +12,32 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import {Extension, ExtensionProperty, PropertyType} from '@gltf-transform/core';
|
||||
import {Accessor, Extension, ExtensionProperty, GLTF, IProperty, PropertyType, ReaderContext, WriterContext} from '@gltf-transform/core';
|
||||
|
||||
const NAME = 'EXT_manifold';
|
||||
const NAME = 'EXT_mesh_manifold';
|
||||
const MERGE = 'MERGE';
|
||||
|
||||
export class ManifoldPrimitive extends ExtensionProperty {
|
||||
interface IManifoldPrimitive extends IProperty {
|
||||
mergeIndices: Accessor;
|
||||
mergeValues: Accessor;
|
||||
indices: Accessor;
|
||||
runIndex: number[]|Uint32Array;
|
||||
}
|
||||
|
||||
interface ManifoldDef {
|
||||
manifoldPrimitive: GLTF.IMeshPrimitive;
|
||||
mergeIndices: number;
|
||||
mergeValues: number;
|
||||
}
|
||||
|
||||
export class ManifoldPrimitive extends ExtensionProperty<IManifoldPrimitive> {
|
||||
static EXTENSION_NAME = NAME;
|
||||
public declare extensionName: typeof NAME;
|
||||
public declare propertyType: 'ManifoldPrimitive';
|
||||
public declare parentTypes: [PropertyType.MESH];
|
||||
|
||||
init() {
|
||||
this.EXTENSION_NAME = NAME;
|
||||
ManifoldPrimitive.EXTENSION_NAME = NAME;
|
||||
this.propertyType = 'ManifoldPrimitive';
|
||||
this.parentTypes = [PropertyType.MESH];
|
||||
}
|
||||
@@ -39,7 +56,7 @@ export class ManifoldPrimitive extends ExtensionProperty {
|
||||
return this.getRef('mergeValues');
|
||||
}
|
||||
|
||||
setMerge(indicesAccessor, valuesAccessor) {
|
||||
setMerge(indicesAccessor: Accessor, valuesAccessor: Accessor) {
|
||||
if (indicesAccessor.getCount() !== valuesAccessor.getCount())
|
||||
throw new Error('merge vectors must be the same length.');
|
||||
this.setRef('mergeIndices', indicesAccessor);
|
||||
@@ -50,28 +67,29 @@ export class ManifoldPrimitive extends ExtensionProperty {
|
||||
return this.get('runIndex');
|
||||
}
|
||||
|
||||
setRunIndex(runIndex) {
|
||||
setRunIndex(runIndex: number[]|Uint32Array) {
|
||||
return this.set('runIndex', runIndex);
|
||||
}
|
||||
|
||||
setIndices(indices) {
|
||||
setIndices(indices: Accessor) {
|
||||
return this.setRef('indices', indices);
|
||||
}
|
||||
|
||||
getIndices() {
|
||||
return this.getRef('indices');
|
||||
return this.getRef('indices')!;
|
||||
}
|
||||
}
|
||||
|
||||
export class EXTManifold extends Extension {
|
||||
extensionName = NAME;
|
||||
prewriteTypes = [PropertyType.ACCESSOR];
|
||||
static EXTENSION_NAME = NAME;
|
||||
|
||||
createManifoldPrimitive() {
|
||||
return new ManifoldPrimitive(this.document.getGraph());
|
||||
}
|
||||
|
||||
read(context) {
|
||||
read(context: ReaderContext) {
|
||||
const {json} = context.jsonDoc;
|
||||
const meshDefs = json.meshes || [];
|
||||
|
||||
@@ -82,20 +100,27 @@ export class EXTManifold extends Extension {
|
||||
const manifoldPrimitive = this.createManifoldPrimitive();
|
||||
mesh.setExtension(NAME, manifoldPrimitive);
|
||||
|
||||
const manifoldDef = meshDef.extensions[NAME];
|
||||
const manifoldDef = meshDef.extensions[NAME] as ManifoldDef;
|
||||
|
||||
if (manifoldDef.manifoldPrimitive) {
|
||||
let count = 0;
|
||||
const runIndex = [];
|
||||
runIndex.push(count);
|
||||
for (const primitive of mesh.listPrimitives()) {
|
||||
count += primitive.getIndices().getCount();
|
||||
const indices = primitive.getIndices();
|
||||
if (!indices) {
|
||||
console.log('Skipping non-indexed primitive ', primitive.getName());
|
||||
continue;
|
||||
}
|
||||
count += indices.getCount();
|
||||
runIndex.push(count);
|
||||
}
|
||||
manifoldPrimitive.setRunIndex(runIndex);
|
||||
manifoldPrimitive.setIndices(
|
||||
context.accessors[manifoldDef.manifoldPrimitive.indices!]);
|
||||
}
|
||||
|
||||
if (manifoldDef.mergeIndices && manifoldDef.mergeValues) {
|
||||
if (manifoldDef.mergeIndices != null && manifoldDef.mergeValues != null) {
|
||||
manifoldPrimitive.setMerge(
|
||||
context.accessors[manifoldDef.mergeIndices],
|
||||
context.accessors[manifoldDef.mergeValues]);
|
||||
@@ -105,15 +130,34 @@ export class EXTManifold extends Extension {
|
||||
return this;
|
||||
}
|
||||
|
||||
write(context) {
|
||||
prewrite(context: WriterContext) {
|
||||
this.document.getRoot().listMeshes().forEach((mesh) => {
|
||||
const manifoldPrimitive = mesh.getExtension(NAME) as ManifoldPrimitive;
|
||||
if (!manifoldPrimitive) return;
|
||||
|
||||
const indices = manifoldPrimitive.getIndices();
|
||||
context.addAccessorToUsageGroup(
|
||||
indices, WriterContext.BufferViewUsage.ELEMENT_ARRAY_BUFFER);
|
||||
|
||||
const mergeFrom = manifoldPrimitive.getMergeIndices();
|
||||
const mergeTo = manifoldPrimitive.getMergeValues();
|
||||
if (!mergeFrom || !mergeTo) return;
|
||||
|
||||
context.addAccessorToUsageGroup(mergeFrom, MERGE);
|
||||
context.addAccessorToUsageGroup(mergeTo, MERGE);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
write(context: WriterContext) {
|
||||
const {json} = context.jsonDoc;
|
||||
|
||||
this.document.getRoot().listMeshes().forEach((mesh) => {
|
||||
const manifoldPrimitive = mesh.getExtension(NAME);
|
||||
const manifoldPrimitive = mesh.getExtension(NAME) as ManifoldPrimitive;
|
||||
if (!manifoldPrimitive) return;
|
||||
|
||||
const meshIndex = context.meshIndexMap.get(mesh);
|
||||
const meshDef = json.meshes[meshIndex];
|
||||
const meshIndex = context.meshIndexMap.get(mesh)!;
|
||||
const meshDef = json.meshes![meshIndex];
|
||||
|
||||
const runIndex = manifoldPrimitive.getRunIndex();
|
||||
const numPrimitive = runIndex.length - 1;
|
||||
@@ -124,20 +168,20 @@ export class EXTManifold extends Extension {
|
||||
}
|
||||
|
||||
const mergeIndicesIndex =
|
||||
context.accessorIndexMap.get(manifoldPrimitive.getMergeIndices());
|
||||
context.accessorIndexMap.get(manifoldPrimitive.getMergeIndices()!)!;
|
||||
const mergeValuesIndex =
|
||||
context.accessorIndexMap.get(manifoldPrimitive.getMergeValues());
|
||||
const mergeIndices = json.accessors[mergeIndicesIndex];
|
||||
const mergeValues = json.accessors[mergeValuesIndex];
|
||||
context.accessorIndexMap.get(manifoldPrimitive.getMergeValues()!)!;
|
||||
const mergeIndices = json.accessors![mergeIndicesIndex];
|
||||
const mergeValues = json.accessors![mergeValuesIndex];
|
||||
|
||||
const existingPrimitive = meshDef.primitives[0];
|
||||
const primitive = {
|
||||
indices: context.accessorIndexMap.get(manifoldPrimitive.getIndices()),
|
||||
indices: context.accessorIndexMap.get(manifoldPrimitive.getIndices())!,
|
||||
mode: existingPrimitive.mode,
|
||||
attributes: {'POSITION': existingPrimitive.attributes['POSITION']}
|
||||
};
|
||||
|
||||
const indices = json.accessors[primitive.indices];
|
||||
const indices = json.accessors![primitive.indices];
|
||||
if (!indices) {
|
||||
return;
|
||||
}
|
||||
@@ -146,21 +190,21 @@ export class EXTManifold extends Extension {
|
||||
indices.sparse = {
|
||||
count: mergeIndices.count,
|
||||
indices: {
|
||||
bufferView: mergeIndices.bufferView,
|
||||
bufferView: mergeIndices.bufferView!,
|
||||
byteOffset: mergeIndices.byteOffset,
|
||||
componentType: mergeIndices.componentType
|
||||
},
|
||||
values: {
|
||||
bufferView: mergeValues.bufferView,
|
||||
bufferView: mergeValues.bufferView!,
|
||||
byteOffset: mergeValues.byteOffset,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
for (let i = 0; i < numPrimitive; ++i) {
|
||||
const accessor = json.accessors[meshDef.primitives[i].indices];
|
||||
const accessor = json.accessors![meshDef.primitives[i].indices!];
|
||||
accessor.bufferView = indices.bufferView;
|
||||
accessor.byteOffset = indices.byteOffset + 4 * runIndex[i];
|
||||
accessor.byteOffset = indices.byteOffset! + 4 * runIndex[i];
|
||||
accessor.count = runIndex[i + 1] - runIndex[i];
|
||||
}
|
||||
|
||||
@@ -48,11 +48,11 @@
|
||||
<button id="download">Download manifold GLB</button>
|
||||
<model-viewer camera-controls shadow-intensity="1" alt="Output of mesh Boolean operation"></model-viewer>
|
||||
</body>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/2.0.1/model-viewer.min.js"></script>
|
||||
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.3.0/model-viewer.min.js"></script>
|
||||
<script type="module">
|
||||
import { Document, WebIO } from '@gltf-transform/core';
|
||||
import { clearNodeTransform, flatten, prune } from '@gltf-transform/functions';
|
||||
import { loadTexture, readMesh, writeMesh, disposeMesh, setupIO } from './gltf-io.js';
|
||||
import { loadTexture, readMesh, writeMesh, disposeMesh, setupIO } from './gltf-io';
|
||||
import Module from './built/manifold.js';
|
||||
|
||||
const io = setupIO(new WebIO());
|
||||
@@ -63,10 +63,9 @@
|
||||
|
||||
const { Manifold, Mesh } = wasm;
|
||||
|
||||
const attributes = ['POSITION', 'TEXCOORD_0'];
|
||||
const materialMap = new Map();
|
||||
const id2properties = new Map();
|
||||
|
||||
async function readGLB(url, attributes, materialMap) {
|
||||
async function readGLB(url) {
|
||||
const manifolds = [];
|
||||
const docIn = await io.read(url);
|
||||
await docIn.transform(flatten());
|
||||
@@ -75,30 +74,33 @@
|
||||
for (const node of nodes) {
|
||||
clearNodeTransform(node);
|
||||
const materials = [];
|
||||
const manifoldMesh = readMesh(node.getMesh(), attributes, materials);
|
||||
manifoldMesh.runOriginalID = [];
|
||||
const firstID = Manifold.reserveIDs(materials.length);
|
||||
for (let i = 0; i < materials.length; ++i) {
|
||||
manifoldMesh.runOriginalID.push(firstID + i);
|
||||
const tmp = readMesh(node.getMesh());
|
||||
tmp.mesh.runOriginalID = [];
|
||||
const numID = tmp.runProperties.length;
|
||||
const firstID = Manifold.reserveIDs(numID);
|
||||
for (let i = 0; i < numID; ++i) {
|
||||
tmp.mesh.runOriginalID.push(firstID + i);
|
||||
ids.push(firstID + i);
|
||||
id2properties.set(firstID + i, tmp.runProperties[i]);
|
||||
}
|
||||
manifolds.push(Manifold(new Mesh(manifoldMesh)));
|
||||
manifolds.push(Manifold(new Mesh(tmp.mesh)));
|
||||
}
|
||||
// pull in materials, TODO: replace with transfer() when available
|
||||
const startIdx = doc.getRoot().listMaterials().length;
|
||||
doc.merge(docIn);
|
||||
doc.getRoot().listScenes().forEach((s) => s.dispose());
|
||||
doc.getRoot().listBuffers().forEach((s) => s.dispose());
|
||||
doc.getRoot().listAccessors().forEach((s) => s.dispose());
|
||||
for (const [i, id] of ids.entries()) {
|
||||
const material = doc.getRoot().listMaterials()[startIdx + i];
|
||||
materialMap.set(id, material);
|
||||
id2properties.get(id).material = material;
|
||||
}
|
||||
|
||||
return Manifold.union(manifolds);
|
||||
}
|
||||
|
||||
const space = await readGLB('/models/space.glb', attributes, materialMap);
|
||||
const moon = await readGLB('/models/moon.glb', attributes, materialMap);
|
||||
const space = await readGLB('/models/space.glb');
|
||||
const moon = await readGLB('/models/moon.glb');
|
||||
|
||||
const node = doc.createNode();
|
||||
doc.createScene().addChild(node);
|
||||
@@ -129,13 +131,7 @@
|
||||
const manifoldMesh = manifold.rotate([-90, 0, 0]).getMesh();
|
||||
|
||||
disposeMesh(node.getMesh());
|
||||
const materials = [];
|
||||
const matAttributes = [];
|
||||
for (const id of manifoldMesh.runOriginalID) {
|
||||
materials.push(materialMap.get(id));
|
||||
matAttributes.push(attributes);
|
||||
}
|
||||
const mesh = writeMesh(doc, manifoldMesh, matAttributes, materials);
|
||||
const mesh = writeMesh(doc, manifoldMesh, id2properties);
|
||||
node.setMesh(mesh);
|
||||
await doc.transform(prune());
|
||||
|
||||
|
||||
Generated
+740
-792
File diff suppressed because it is too large
Load Diff
@@ -8,23 +8,25 @@
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"build:watch": "vite build --watch",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest",
|
||||
"test": "vitest run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:run": "vitest run"
|
||||
"test:dev": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gltf-transform/core": "^3.2.1",
|
||||
"@gltf-transform/extensions": "^3.2.1",
|
||||
"@gltf-transform/functions": "^3.2.1",
|
||||
"@gltf-transform/core": "^3.8.0",
|
||||
"@gltf-transform/extensions": "^3.8.0",
|
||||
"@gltf-transform/functions": "^3.8.0",
|
||||
"@jscadui/3mf-export": "^0.5.0",
|
||||
"fflate": "^0.8.0",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"simple-dropzone": "0.8.3",
|
||||
"three": "0.151.2"
|
||||
"three": "0.158.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitest/ui": "^0.31.1",
|
||||
"@vitest/web-worker": "^0.31.1",
|
||||
"typescript": "5.0.4",
|
||||
"vite": "^4.3.2",
|
||||
"typescript": "5.2.2",
|
||||
"vite": "^4.5.0",
|
||||
"vitest": "^0.31.1"
|
||||
}
|
||||
}
|
||||
|
||||
+42
-6
@@ -25,8 +25,11 @@ declare class GLTFNode {
|
||||
clone(parent?: GLTFNode): GLTFNode;
|
||||
}
|
||||
|
||||
type Attribute = 'POSITION'|'NORMAL'|'TANGENT'|'TEXCOORD_0'|'TEXCOORD_1'|
|
||||
'COLOR_0'|'JOINTS_0'|'WEIGHTS_0'|'SKIP_1'|'SKIP_2'|'SKIP_3'|'SKIP_4';
|
||||
|
||||
declare class GLTFMaterial {
|
||||
attributes?: string[];
|
||||
attributes?: Attribute[];
|
||||
roughness?: number;
|
||||
metallic?: number;
|
||||
baseColorFactor?: [number, number, number];
|
||||
@@ -35,15 +38,48 @@ declare class GLTFMaterial {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
declare const globalDefaults: {
|
||||
roughness: number,
|
||||
metallic: number,
|
||||
baseColorFactor: [number, number, number],
|
||||
alpha: number,
|
||||
unlit: boolean,
|
||||
animationLength: number,
|
||||
animationMode: 'loop'|'ping-pong';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set material properties on the input manifold. They will be carried along
|
||||
* through operations.
|
||||
* Returns a shallow copy of the input manifold with the given material
|
||||
* properties applied. They will be carried along through operations.
|
||||
*
|
||||
* @param manifold The object to add properties to - returned for chaining.
|
||||
* @param manifold The input object.
|
||||
* @param material A set of material properties to apply to this manifold.
|
||||
*/
|
||||
declare function setMaterial(
|
||||
manifold: Manifold, material: GLTFMaterial): Manifold;
|
||||
declare function setMaterial(manifold: Manifold, material: GLTFMaterial):
|
||||
Manifold;
|
||||
|
||||
/**
|
||||
* Apply a morphing animation to the input manifold. Specify the start
|
||||
* function which will be applied to the vertex positions of the first frame and
|
||||
* linearly interpolated across the length of the overall animation. This
|
||||
* animation will only be shown if this manifold is used directly on a GLTFNode.
|
||||
*
|
||||
* @param manifold The object to add morphing animation to.
|
||||
* @param func A warping function to apply to the first animation frame.
|
||||
*/
|
||||
declare function setMorphStart(
|
||||
manifold: Manifold, func: (v: Vec3) => void): void;
|
||||
|
||||
/**
|
||||
* Apply a morphing animation to the input manifold. Specify the end
|
||||
* function which will be applied to the vertex positions of the last frame and
|
||||
* linearly interpolated across the length of the overall animation. This
|
||||
* animation will only be shown if this manifold is used directly on a GLTFNode.
|
||||
*
|
||||
* @param manifold The object to add morphing animation to.
|
||||
* @param func A warping function to apply to the last animation frame.
|
||||
*/
|
||||
declare function setMorphEnd(manifold: Manifold, func: (v: Vec3) => void): void;
|
||||
|
||||
/**
|
||||
* Wrap any shape object with this method to display it and any copies in
|
||||
|
||||
@@ -50,9 +50,9 @@ export const examples = {
|
||||
|
||||
TetrahedronPuzzle: function() {
|
||||
// A tetrahedron cut into two identical halves that can screw together as
|
||||
// a puzzle. This only outputs one of the halves. This demonstrates how
|
||||
// redundant points along a polygon can be used to make twisted extrusions
|
||||
// smoother. Based on the screw puzzle by George Hart:
|
||||
// a puzzle. This demonstrates how redundant points along a polygon can be
|
||||
// used to make twisted extrusions smoother. It also showcases animated
|
||||
// assemblies. Based on the screw puzzle by George Hart:
|
||||
// https://www.thingiverse.com/thing:186372
|
||||
|
||||
const edgeLength = 50; // Length of each edge of the overall tetrahedron.
|
||||
@@ -61,19 +61,21 @@ export const examples = {
|
||||
|
||||
const scale = edgeLength / (2 * Math.sqrt(2));
|
||||
|
||||
const tet = Manifold.tetrahedron().scale(scale);
|
||||
const tet = Manifold.tetrahedron().intersect(
|
||||
Manifold.tetrahedron().rotate([0, 0, 90]).scale(2.5));
|
||||
|
||||
const box = [];
|
||||
box.push([1, -1], [1, 1]);
|
||||
box.push([2, -2], [2, 2]);
|
||||
for (let i = 0; i <= nDivisions; ++i) {
|
||||
box.push([gap / (4 * scale), 1 - i * 2 / nDivisions]);
|
||||
box.push([gap / (2 * scale), 2 - i * 4 / nDivisions]);
|
||||
}
|
||||
|
||||
const cyan = [0, 1, 1];
|
||||
const magenta = [1, 0, 1];
|
||||
const fade = (color, pos) => {
|
||||
for (let i = 0; i < 3; ++i) {
|
||||
color[i] = cyan[i] * pos[2] + magenta[i] * (1 - pos[2]);
|
||||
const x = pos[2] / 2;
|
||||
color[i] = cyan[i] * x + magenta[i] * (1 - x);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -82,25 +84,43 @@ export const examples = {
|
||||
// channels as colors, and sets the factor to white, since our default is
|
||||
// yellow.
|
||||
const screw = setMaterial(
|
||||
Manifold.extrude(box, 1, nDivisions, 270).setProperties(3, fade),
|
||||
Manifold.extrude(box, 2, nDivisions, 270).setProperties(3, fade),
|
||||
{baseColorFactor: [1, 1, 1], attributes: ['COLOR_0']});
|
||||
|
||||
const result = tet.intersect(
|
||||
screw.rotate([0, 0, -45]).translate([0, 0, -0.5]).scale(2 * scale));
|
||||
const result =
|
||||
tet.intersect(screw.rotate([0, 0, -45]).translate([0, 0, -1]))
|
||||
.scale(scale);
|
||||
|
||||
// Assigned materials are only applied to a GLTFNode. Note that material
|
||||
// definitions cascade, applying recursively to all child surfaces, but
|
||||
// overridden by any materials defined lower down. Our default material:
|
||||
// {
|
||||
// roughness = 0.2,
|
||||
// metallic = 1,
|
||||
// baseColorFactor = [1, 1, 0],
|
||||
// alpha = 1,
|
||||
// unlit = false,
|
||||
// name = ''
|
||||
// }
|
||||
const node = new GLTFNode();
|
||||
node.manifold = result;
|
||||
// overridden by any materials defined lower down. The default material
|
||||
// properties, as well as animation parameters can be set via
|
||||
// globalDefaults.
|
||||
|
||||
const layFlat = new GLTFNode();
|
||||
layFlat.rotation =
|
||||
[45, -Math.atan(1 / Math.sqrt(2)) * 180 / Math.PI, 120];
|
||||
layFlat.translation = [0, 0, scale * Math.sqrt(3) / 3];
|
||||
|
||||
const fixed = new GLTFNode(layFlat);
|
||||
fixed.manifold = result;
|
||||
fixed.rotation = [0, 0, 180];
|
||||
|
||||
// For 3MF export, only top-level objects are independently arrangeable.
|
||||
const layFlat2 = layFlat.clone();
|
||||
|
||||
const moving = new GLTFNode(layFlat2);
|
||||
moving.manifold = result;
|
||||
// Use functions to create animation, which runs from t=0 to t=1.
|
||||
moving.translation = (t) => {
|
||||
const a = 1 - t;
|
||||
const x = a > 0.5 ? scale * 2 * (0.5 - a) : 0;
|
||||
return [x, x, -2 * x + scale * 4 * (0.5 - Math.abs(0.5 - a))];
|
||||
};
|
||||
moving.rotation = (t) => [0, 0, 270 * 2 * (1 - t)];
|
||||
|
||||
globalDefaults.animationLength = 10; // seconds
|
||||
globalDefaults.animationMode = 'ping-pong';
|
||||
return result;
|
||||
},
|
||||
|
||||
@@ -139,6 +159,7 @@ export const examples = {
|
||||
// Smooth, complex manifolds can be created using the warp() function.
|
||||
// This example recreates the Exploitable Heart by Emmett Lalish:
|
||||
// https://www.thingiverse.com/thing:6190
|
||||
// It also demonstrates the use of setMorph to animate a warping function.
|
||||
|
||||
const func = (v) => {
|
||||
const x2 = v[0] * v[0];
|
||||
@@ -174,9 +195,20 @@ export const examples = {
|
||||
};
|
||||
|
||||
const ball = Manifold.sphere(1, 200);
|
||||
|
||||
const heart = ball.warp(func);
|
||||
const box = heart.boundingBox();
|
||||
const result = heart.scale(100 / (box.max[0] - box.min[0]));
|
||||
const scale = 100 / (box.max[0] - box.min[0]);
|
||||
|
||||
setMorphStart(ball, func);
|
||||
const node = new GLTFNode();
|
||||
node.manifold = ball;
|
||||
node.scale = [scale, scale, scale];
|
||||
|
||||
globalDefaults.animationLength = 5; // seconds
|
||||
globalDefaults.animationMode = 'ping-pong';
|
||||
|
||||
const result = heart.scale(scale);
|
||||
return result;
|
||||
},
|
||||
|
||||
@@ -253,71 +285,68 @@ export const examples = {
|
||||
// an example of using the warp() method, thus avoiding any direct
|
||||
// handling of triangles.
|
||||
|
||||
// @param p The number of times the thread passes through the donut hole.
|
||||
// @param q The number of times the thread circles the donut.
|
||||
// @param majorRadius Radius of the interior of the imaginary donut.
|
||||
// @param minorRadius Radius of the small cross-section of the imaginary
|
||||
// donut.
|
||||
// @param threadRadius Radius of the small cross-section of the actual
|
||||
// object.
|
||||
// @param circularSegments Number of linear segments making up the
|
||||
// threadRadius circle. Default is getCircularSegments(threadRadius).
|
||||
// @param linearSegments Number of segments along the length of the knot.
|
||||
// Default makes roughly square facets.
|
||||
// The number of times the thread passes through the donut hole.
|
||||
const p = 1;
|
||||
// The number of times the thread circles the donut.
|
||||
const q = 3;
|
||||
// Radius of the interior of the imaginary donut.
|
||||
const majorRadius = 25;
|
||||
// Radius of the small cross-section of the imaginary donut.
|
||||
const minorRadius = 10;
|
||||
// Radius of the small cross-section of the actual object.
|
||||
const threadRadius = 3.75;
|
||||
// Number of linear segments making up the threadRadius circle. Default is
|
||||
// getCircularSegments(threadRadius).
|
||||
const circularSegments = -1;
|
||||
// Number of segments along the length of the knot. Default makes roughly
|
||||
// square facets.
|
||||
const linearSegments = -1;
|
||||
|
||||
function torusKnot(
|
||||
p, q, majorRadius, minorRadius, threadRadius, circularSegments = 0,
|
||||
linearSegments = 0) {
|
||||
const {vec3} = glMatrix;
|
||||
|
||||
function gcd(a, b) {
|
||||
return b == 0 ? a : gcd(b, a % b);
|
||||
}
|
||||
|
||||
const kLoops = gcd(p, q);
|
||||
p /= kLoops;
|
||||
q /= kLoops;
|
||||
const n = circularSegments > 2 ? circularSegments :
|
||||
getCircularSegments(threadRadius);
|
||||
const m = linearSegments > 2 ? linearSegments :
|
||||
n * q * majorRadius / threadRadius;
|
||||
|
||||
const offset = 2
|
||||
const circle = CrossSection.circle(1, n).translate([offset, 0]);
|
||||
|
||||
const func = (v) => {
|
||||
const psi = q * Math.atan2(v[0], v[1]);
|
||||
const theta = psi * p / q;
|
||||
const x1 = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
|
||||
const phi = Math.atan2(x1 - offset, v[2]);
|
||||
vec3.set(
|
||||
v, threadRadius * Math.cos(phi), 0, threadRadius * Math.sin(phi));
|
||||
const center = vec3.fromValues(0, 0, 0);
|
||||
const r = majorRadius + minorRadius * Math.cos(theta);
|
||||
vec3.rotateX(v, v, center, -Math.atan2(p * minorRadius, q * r));
|
||||
v[0] += minorRadius;
|
||||
vec3.rotateY(v, v, center, theta);
|
||||
v[0] += majorRadius;
|
||||
vec3.rotateZ(v, v, center, psi);
|
||||
};
|
||||
|
||||
let knot = Manifold.revolve(circle, m).warp(func);
|
||||
|
||||
if (kLoops > 1) {
|
||||
const knots = [];
|
||||
for (let k = 0; k < kLoops; ++k) {
|
||||
knots.push(knot.rotate([0, 0, 360 * (k / kLoops) * (q / p)]));
|
||||
}
|
||||
knot = Manifold.compose(knots);
|
||||
}
|
||||
|
||||
return knot;
|
||||
}
|
||||
|
||||
// This recreates Matlab Knot by Emmett Lalish:
|
||||
// These default values recreate Matlab Knot by Emmett Lalish:
|
||||
// https://www.thingiverse.com/thing:7080
|
||||
|
||||
const result = torusKnot(1, 3, 25, 10, 3.75);
|
||||
const {vec3} = glMatrix;
|
||||
|
||||
function gcd(a, b) {
|
||||
return b == 0 ? a : gcd(b, a % b);
|
||||
}
|
||||
|
||||
const kLoops = gcd(p, q);
|
||||
const pk = p / kLoops;
|
||||
const qk = q / kLoops;
|
||||
const n = circularSegments > 2 ? circularSegments :
|
||||
getCircularSegments(threadRadius);
|
||||
const m = linearSegments > 2 ? linearSegments :
|
||||
n * qk * majorRadius / threadRadius;
|
||||
|
||||
const offset = 2
|
||||
const circle = CrossSection.circle(1, n).translate([offset, 0]);
|
||||
|
||||
const func = (v) => {
|
||||
const psi = qk * Math.atan2(v[0], v[1]);
|
||||
const theta = psi * pk / qk;
|
||||
const x1 = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
|
||||
const phi = Math.atan2(x1 - offset, v[2]);
|
||||
vec3.set(
|
||||
v, threadRadius * Math.cos(phi), 0, threadRadius * Math.sin(phi));
|
||||
const center = vec3.fromValues(0, 0, 0);
|
||||
const r = majorRadius + minorRadius * Math.cos(theta);
|
||||
vec3.rotateX(v, v, center, -Math.atan2(pk * minorRadius, qk * r));
|
||||
v[0] += minorRadius;
|
||||
vec3.rotateY(v, v, center, theta);
|
||||
v[0] += majorRadius;
|
||||
vec3.rotateZ(v, v, center, psi);
|
||||
};
|
||||
|
||||
const result = Manifold.revolve(circle, m).warp(func);
|
||||
|
||||
for (let k = 0; k < kLoops; ++k) {
|
||||
const node = new GLTFNode();
|
||||
node.manifold = result;
|
||||
node.rotation = [0, 0, 360 * (k / kLoops) * (qk / pk)];
|
||||
node.translation = [0, 0, result.boundingBox().min[2]];
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
|
||||
@@ -350,12 +379,12 @@ export const examples = {
|
||||
|
||||
const hole = Manifold.compose(holes);
|
||||
|
||||
result = Manifold.difference(
|
||||
result,
|
||||
hole,
|
||||
hole.rotate([90, 0, 0]),
|
||||
hole.rotate([0, 90, 0]),
|
||||
);
|
||||
result = Manifold.difference([
|
||||
result,
|
||||
hole,
|
||||
hole.rotate([90, 0, 0]),
|
||||
hole.rotate([0, 90, 0]),
|
||||
]);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 240 B |
Binary file not shown.
|
After Width: | Height: | Size: 326 B |
Binary file not shown.
Binary file not shown.
@@ -18,7 +18,7 @@ import {WebIO} from '@gltf-transform/core';
|
||||
import {expect, suite, test} from 'vitest';
|
||||
|
||||
import Module from './built/manifold.js';
|
||||
import {readMesh, setupIO} from './gltf-io.js';
|
||||
import {readMesh, setupIO} from './gltf-io';
|
||||
import {examples} from './public/examples.js';
|
||||
import ManifoldWorker from './worker?worker';
|
||||
|
||||
@@ -39,7 +39,7 @@ function initialized(worker) {
|
||||
});
|
||||
}
|
||||
|
||||
let objectURL = null;
|
||||
let glbURL = null;
|
||||
|
||||
async function runExample(name) {
|
||||
const worker = new ManifoldWorker();
|
||||
@@ -55,26 +55,24 @@ async function runExample(name) {
|
||||
|
||||
worker.onmessage = async function(e) {
|
||||
try {
|
||||
URL.revokeObjectURL(objectURL);
|
||||
objectURL = e.data.objectURL;
|
||||
if (objectURL == null) {
|
||||
reject('no objectURL');
|
||||
URL.revokeObjectURL(glbURL);
|
||||
glbURL = e.data.glbURL;
|
||||
if (glbURL == null) {
|
||||
reject('no glbURL)');
|
||||
}
|
||||
const docIn = await io.read(objectURL);
|
||||
const docIn = await io.read(glbURL);
|
||||
const nodes = docIn.getRoot().listNodes();
|
||||
for (const node of nodes) {
|
||||
const mesh = node.getMesh();
|
||||
if (!mesh) {
|
||||
const docMesh = node.getMesh();
|
||||
if (!docMesh) {
|
||||
continue;
|
||||
}
|
||||
const attributes = [];
|
||||
const materials = [];
|
||||
const manifoldMesh = readMesh(mesh, attributes, materials);
|
||||
const manifold = wasm.Manifold(manifoldMesh);
|
||||
const {mesh} = readMesh(docMesh);
|
||||
const manifold = wasm.Manifold(mesh);
|
||||
const prop = manifold.getProperties();
|
||||
const genus = manifold.genus();
|
||||
console.log(genus);
|
||||
manifold.delete();
|
||||
// Return properties of first mesh encountered.
|
||||
resolve({...prop, genus});
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -97,8 +95,8 @@ suite('Examples', () => {
|
||||
test('Tetrahedron Puzzle', async () => {
|
||||
const result = await runExample('Tetrahedron Puzzle');
|
||||
expect(result.genus).to.equal(0, 'Genus');
|
||||
expect(result.volume).to.be.closeTo(7297, 1, 'Volume');
|
||||
expect(result.surfaceArea).to.be.closeTo(3303, 1, 'Surface Area');
|
||||
expect(result.volume).to.be.closeTo(7240, 1, 'Volume');
|
||||
expect(result.surfaceArea).to.be.closeTo(3235, 1, 'Surface Area');
|
||||
});
|
||||
|
||||
test('Rounded Frame', async () => {
|
||||
@@ -111,8 +109,8 @@ suite('Examples', () => {
|
||||
test('Heart', async () => {
|
||||
const result = await runExample('Heart');
|
||||
expect(result.genus).to.equal(0, 'Genus');
|
||||
expect(result.volume).to.be.closeTo(282743, 10, 'Volume');
|
||||
expect(result.surfaceArea).to.be.closeTo(22187, 1, 'Surface Area');
|
||||
expect(result.volume).to.be.closeTo(3.342, 0.001, 'Volume');
|
||||
expect(result.surfaceArea).to.be.closeTo(11.51, 0.01, 'Surface Area');
|
||||
});
|
||||
|
||||
test('Scallop', async () => {
|
||||
|
||||
@@ -12,25 +12,38 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import {Document, Material, Node, WebIO} from '@gltf-transform/core';
|
||||
import {Accessor, Animation, AnimationSampler, Document, mat4, Material, Mesh as GLTFMesh, Node, WebIO} from '@gltf-transform/core';
|
||||
import {KHRMaterialsUnlit, KHRONOS_EXTENSIONS} from '@gltf-transform/extensions';
|
||||
import {fileForContentTypes, FileForRelThumbnail, to3dmodel} from '@jscadui/3mf-export';
|
||||
import {strToU8, Zippable, zipSync} from 'fflate'
|
||||
import * as glMatrix from 'gl-matrix';
|
||||
|
||||
import Module from './built/manifold';
|
||||
//@ts-ignore
|
||||
import {setupIO, writeMesh} from './gltf-io';
|
||||
import type {GLTFMaterial, Quat} from './public/editor';
|
||||
import {Properties, setupIO, writeMesh} from './gltf-io';
|
||||
import {GLTFMaterial, Quat} from './public/editor';
|
||||
import type {CrossSection, Manifold, ManifoldToplevel, Mesh, Vec3} from './public/manifold';
|
||||
|
||||
interface GlobalDefaults {
|
||||
roughness: number;
|
||||
metallic: number;
|
||||
baseColorFactor: [number, number, number];
|
||||
alpha: number;
|
||||
unlit: boolean;
|
||||
animationLength: number;
|
||||
animationMode: 'loop'|'ping-pong';
|
||||
}
|
||||
|
||||
interface WorkerStatic extends ManifoldToplevel {
|
||||
GLTFNode: typeof GLTFNode;
|
||||
show(manifold: Manifold): Manifold;
|
||||
only(manifold: Manifold): Manifold;
|
||||
setMaterial(manifold: Manifold, material: GLTFMaterial): void;
|
||||
setMaterial(manifold: Manifold, material: GLTFMaterial): Manifold;
|
||||
setMorphStart(manifold: Manifold, func: (v: Vec3) => void): void;
|
||||
setMorphEnd(manifold: Manifold, func: (v: Vec3) => void): void;
|
||||
cleanup(): void;
|
||||
}
|
||||
|
||||
const module = await Module() as unknown as WorkerStatic;
|
||||
const module = await Module() as WorkerStatic;
|
||||
module.setup();
|
||||
|
||||
// Faster on modern browsers than Float32Array
|
||||
@@ -42,29 +55,30 @@ io.registerExtensions(KHRONOS_EXTENSIONS);
|
||||
// manifold static methods (that return a new manifold)
|
||||
const manifoldStaticFunctions = [
|
||||
'cube', 'cylinder', 'sphere', 'tetrahedron', 'extrude', 'revolve', 'compose',
|
||||
'union', 'difference', 'intersection', 'levelSet', 'smooth', 'ofMesh'
|
||||
'union', 'difference', 'intersection', 'levelSet', 'smooth', 'ofMesh', 'hull'
|
||||
];
|
||||
// manifold member functions (that return a new manifold)
|
||||
const manifoldMemberFunctions = [
|
||||
'add', 'subtract', 'intersect', 'decompose', 'warp', 'transform', 'translate',
|
||||
'rotate', 'scale', 'mirror', 'refine', 'setProperties', 'asOriginal',
|
||||
'trimByPlane', 'split', 'splitByPlane'
|
||||
'trimByPlane', 'split', 'splitByPlane', 'slice', 'project', 'hull'
|
||||
];
|
||||
// CrossSection static methods (that return a new cross-section)
|
||||
const crossSectionStaticFunctions = [
|
||||
'square', 'circle', 'union', 'difference', 'intersection', 'compose',
|
||||
'ofPolygons'
|
||||
'ofPolygons', 'hull'
|
||||
];
|
||||
// CrossSection member functions (that return a new cross-section)
|
||||
const crossSectionMemberFunctions = [
|
||||
'add', 'subtract', 'intersect', 'rectClip', 'decompose', 'transform',
|
||||
'translate', 'rotate', 'scale', 'mirror', 'simplify', 'offset'
|
||||
'translate', 'rotate', 'scale', 'mirror', 'simplify', 'offset', 'hull'
|
||||
];
|
||||
// top level functions that construct a new manifold/mesh
|
||||
const toplevelConstructors = ['show', 'only', 'setMaterial'];
|
||||
const toplevel = [
|
||||
'setMinCircularAngle', 'setMinCircularEdgeLength', 'setCircularSegments',
|
||||
'getCircularSegments', 'Mesh', 'GLTFNode', 'Manifold', 'CrossSection'
|
||||
'getCircularSegments', 'Mesh', 'GLTFNode', 'Manifold', 'CrossSection',
|
||||
'setMorphStart', 'setMorphEnd'
|
||||
];
|
||||
const exposedFunctions = toplevelConstructors.concat(toplevel);
|
||||
|
||||
@@ -81,15 +95,13 @@ function addMembers(
|
||||
const cls = module[className];
|
||||
const obj = areStatic ? cls : cls.prototype;
|
||||
for (const name of methodNames) {
|
||||
if (name != 'cylinder') {
|
||||
const originalFn = obj[name];
|
||||
obj[name] = function(...args: any) {
|
||||
//@ts-ignore
|
||||
const result = originalFn(...args);
|
||||
memoryRegistry.push(result);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
const originalFn = obj[name];
|
||||
obj[name] = function(...args: any) {
|
||||
//@ts-ignore
|
||||
const result = originalFn(...args);
|
||||
memoryRegistry.push(result);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +137,18 @@ let ghost = false;
|
||||
const shown = new Map<number, Mesh>();
|
||||
const singles = new Map<number, Mesh>();
|
||||
|
||||
const FPS = 30;
|
||||
|
||||
const GLOBAL_DEFAULTS = {
|
||||
roughness: 0.2,
|
||||
metallic: 1,
|
||||
baseColorFactor: [1, 1, 0] as [number, number, number],
|
||||
alpha: 1,
|
||||
unlit: false,
|
||||
animationLength: 1,
|
||||
animationMode: 'loop'
|
||||
};
|
||||
|
||||
const SHOW = {
|
||||
baseColorFactor: [1, 0, 0],
|
||||
alpha: 0.25,
|
||||
@@ -142,6 +166,15 @@ const GHOST = {
|
||||
const nodes = new Array<GLTFNode>();
|
||||
const id2material = new Map<number, GLTFMaterial>();
|
||||
const materialCache = new Map<GLTFMaterial, Material>();
|
||||
const object2globalID = new Map<GLTFNode|Manifold, number>();
|
||||
const manifold2morph = new Map<Manifold, Morph>();
|
||||
// lib3mf doesn't like objectid=0
|
||||
let nextGlobalID = 1;
|
||||
let animation: Animation;
|
||||
let timesAccessor: Accessor;
|
||||
let weightsAccessor: Accessor;
|
||||
let weightsSampler: AnimationSampler;
|
||||
let hasAnimation: boolean;
|
||||
|
||||
function cleanup() {
|
||||
ghost = false;
|
||||
@@ -150,14 +183,59 @@ function cleanup() {
|
||||
nodes.length = 0;
|
||||
id2material.clear();
|
||||
materialCache.clear();
|
||||
object2globalID.clear();
|
||||
manifold2morph.clear();
|
||||
nextGlobalID = 1;
|
||||
}
|
||||
|
||||
interface Morph {
|
||||
start?: (v: Vec3) => void;
|
||||
end?: (v: Vec3) => void;
|
||||
}
|
||||
|
||||
interface Mesh3MF {
|
||||
id: string;
|
||||
vertices: Float32Array;
|
||||
indices: Uint32Array;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface Child3MF {
|
||||
objectID: string;
|
||||
transform?: mat4;
|
||||
}
|
||||
|
||||
interface Component3MF {
|
||||
id: string;
|
||||
children: Array<Child3MF>;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface Header {
|
||||
unit?: 'micron'|'millimeter'|'centimeter'|'inch'|'foot'|'meter';
|
||||
title?: string;
|
||||
author?: string;
|
||||
description?: string;
|
||||
application?: string;
|
||||
creationDate?: string;
|
||||
license?: string;
|
||||
modificationDate?: string;
|
||||
}
|
||||
|
||||
interface To3MF {
|
||||
meshes: Array<Mesh3MF>;
|
||||
components: Array<Component3MF>;
|
||||
items: Array<Child3MF>;
|
||||
precision: number;
|
||||
header: Header;
|
||||
}
|
||||
|
||||
class GLTFNode {
|
||||
private _parent?: GLTFNode;
|
||||
manifold?: Manifold;
|
||||
translation?: Vec3;
|
||||
rotation?: Vec3;
|
||||
scale?: Vec3;
|
||||
translation?: Vec3|((t: number) => Vec3);
|
||||
rotation?: Vec3|((t: number) => Vec3);
|
||||
scale?: Vec3|((t: number) => Vec3);
|
||||
material?: GLTFMaterial;
|
||||
name?: string;
|
||||
|
||||
@@ -178,12 +256,32 @@ class GLTFNode {
|
||||
|
||||
module.GLTFNode = GLTFNode;
|
||||
|
||||
const globalDefaults = {...GLOBAL_DEFAULTS};
|
||||
|
||||
module.setMaterial = (manifold: Manifold, material: GLTFMaterial): Manifold => {
|
||||
const out = manifold.asOriginal();
|
||||
id2material.set(out.originalID(), material);
|
||||
return out;
|
||||
};
|
||||
|
||||
module.setMorphStart = (manifold: Manifold, func: (v: Vec3) => void): void => {
|
||||
const morph = manifold2morph.get(manifold);
|
||||
if (morph != null) {
|
||||
morph.start = func;
|
||||
} else {
|
||||
manifold2morph.set(manifold, {start: func});
|
||||
}
|
||||
};
|
||||
|
||||
module.setMorphEnd = (manifold: Manifold, func: (v: Vec3) => void): void => {
|
||||
const morph = manifold2morph.get(manifold);
|
||||
if (morph != null) {
|
||||
morph.end = func;
|
||||
} else {
|
||||
manifold2morph.set(manifold, {end: func});
|
||||
}
|
||||
};
|
||||
|
||||
function debug(manifold: Manifold, map: Map<number, Mesh>) {
|
||||
let result = manifold.asOriginal();
|
||||
map.set(result.originalID(), result.getMesh());
|
||||
@@ -228,13 +326,13 @@ function log(...args: any[]) {
|
||||
}
|
||||
|
||||
self.onmessage = async (e) => {
|
||||
const content = e.data +
|
||||
'\nreturn exportGLB(typeof result === "undefined" ? undefined : result);\n';
|
||||
const content = 'const globalDefaults = {};\n' + e.data +
|
||||
'\nreturn exportModels(globalDefaults, typeof result === "undefined" ? undefined : result);\n';
|
||||
try {
|
||||
const f = new Function(
|
||||
'exportGLB', 'glMatrix', 'module', ...exposedFunctions, content);
|
||||
'exportModels', 'glMatrix', 'module', ...exposedFunctions, content);
|
||||
await f(
|
||||
exportGLB, glMatrix, module, //@ts-ignore
|
||||
exportModels, glMatrix, module, //@ts-ignore
|
||||
...exposedFunctions.map(name => module[name]));
|
||||
} catch (error: any) {
|
||||
console.log(error.toString());
|
||||
@@ -245,23 +343,146 @@ self.onmessage = async (e) => {
|
||||
}
|
||||
};
|
||||
|
||||
function createGLTFnode(doc: Document, node: GLTFNode) {
|
||||
function euler2quat(rotation: Vec3): Quat {
|
||||
const {quat} = glMatrix;
|
||||
const deg2rad = Math.PI / 180;
|
||||
const q = quat.create() as Quat;
|
||||
quat.rotateZ(q, q, deg2rad * rotation[2]);
|
||||
quat.rotateY(q, q, deg2rad * rotation[1]);
|
||||
quat.rotateX(q, q, deg2rad * rotation[0]);
|
||||
return q;
|
||||
}
|
||||
|
||||
function addMotion(
|
||||
doc: Document, type: 'translation'|'rotation'|'scale', node: GLTFNode,
|
||||
out: Node): Vec3|null {
|
||||
const motion = node[type];
|
||||
if (motion == null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof motion !== 'function') {
|
||||
return motion;
|
||||
}
|
||||
|
||||
const nFrames = timesAccessor.getCount();
|
||||
const nEl = type == 'rotation' ? 4 : 3;
|
||||
const frames = new Float32Array(nEl * nFrames);
|
||||
for (let i = 0; i < nFrames; ++i) {
|
||||
const x = i / (nFrames - 1);
|
||||
const m = motion(
|
||||
globalDefaults.animationMode !== 'ping-pong' ?
|
||||
x :
|
||||
(1 - Math.cos(x * 2 * Math.PI)) / 2);
|
||||
frames.set(nEl === 4 ? euler2quat(m) : m, nEl * i);
|
||||
}
|
||||
|
||||
const framesAccessor =
|
||||
doc.createAccessor(node.name + ' ' + type + ' frames')
|
||||
.setBuffer(doc.getRoot().listBuffers()[0])
|
||||
.setArray(frames)
|
||||
.setType(nEl === 4 ? Accessor.Type.VEC4 : Accessor.Type.VEC3);
|
||||
const sampler = doc.createAnimationSampler()
|
||||
.setInput(timesAccessor)
|
||||
.setOutput(framesAccessor)
|
||||
.setInterpolation('LINEAR');
|
||||
const channel = doc.createAnimationChannel()
|
||||
.setTargetPath(type)
|
||||
.setTargetNode(out)
|
||||
.setSampler(sampler);
|
||||
animation.addSampler(sampler);
|
||||
animation.addChannel(channel);
|
||||
hasAnimation = true;
|
||||
return motion(0);
|
||||
}
|
||||
|
||||
function setMorph(doc: Document, node: Node, manifold: Manifold) {
|
||||
if (manifold2morph.has(manifold)) {
|
||||
const channel = doc.createAnimationChannel()
|
||||
.setTargetPath('weights')
|
||||
.setTargetNode(node)
|
||||
.setSampler(weightsSampler);
|
||||
animation.addChannel(channel);
|
||||
hasAnimation = true;
|
||||
}
|
||||
}
|
||||
|
||||
function morphStart(manifoldMesh: Mesh, morph?: Morph): number[] {
|
||||
const inputPositions: number[] = [];
|
||||
if (morph == null) {
|
||||
return inputPositions;
|
||||
}
|
||||
|
||||
for (let i = 0; i < manifoldMesh.numVert; ++i) {
|
||||
for (let j = 0; j < 3; ++j)
|
||||
inputPositions[i * 3 + j] =
|
||||
manifoldMesh.vertProperties[i * manifoldMesh.numProp + j];
|
||||
}
|
||||
if (morph.start) {
|
||||
for (let i = 0; i < manifoldMesh.numVert; ++i) {
|
||||
const vertProp = manifoldMesh.vertProperties;
|
||||
const offset = i * manifoldMesh.numProp;
|
||||
const pos = inputPositions.slice(offset, offset + 3) as Vec3;
|
||||
morph.start(pos);
|
||||
for (let j = 0; j < 3; ++j) vertProp[offset + j] = pos[j];
|
||||
}
|
||||
}
|
||||
return inputPositions;
|
||||
}
|
||||
|
||||
function morphEnd(
|
||||
doc: Document, manifoldMesh: Mesh, mesh: GLTFMesh, inputPositions: number[],
|
||||
morph?: Morph) {
|
||||
if (morph == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
mesh.setWeights([0]);
|
||||
|
||||
mesh.listPrimitives().forEach((primitive, i) => {
|
||||
if (morph.end) {
|
||||
for (let i = 0; i < manifoldMesh.numVert; ++i) {
|
||||
const pos = inputPositions.slice(3 * i, 3 * (i + 1)) as Vec3;
|
||||
morph.end(pos);
|
||||
inputPositions.splice(3 * i, 3, ...pos);
|
||||
}
|
||||
}
|
||||
|
||||
const startPosition = primitive.getAttribute('POSITION')!.getArray()!;
|
||||
const array = new Float32Array(startPosition.length);
|
||||
|
||||
const offset = manifoldMesh.runIndex[i];
|
||||
for (let j = 0; j < array.length; ++j) {
|
||||
array[j] = inputPositions[offset + j] - startPosition[j];
|
||||
}
|
||||
|
||||
const morphAccessor = doc.createAccessor(mesh.getName() + ' morph target')
|
||||
.setBuffer(doc.getRoot().listBuffers()[0])
|
||||
.setArray(array)
|
||||
.setType(Accessor.Type.VEC3);
|
||||
const morphTarget =
|
||||
doc.createPrimitiveTarget().setAttribute('POSITION', morphAccessor);
|
||||
primitive.addTarget(morphTarget);
|
||||
});
|
||||
}
|
||||
|
||||
function createGLTFnode(doc: Document, node: GLTFNode): Node {
|
||||
const out = doc.createNode(node.name);
|
||||
if (node.translation) {
|
||||
out.setTranslation(node.translation);
|
||||
|
||||
const pos = addMotion(doc, 'translation', node, out);
|
||||
if (pos != null) {
|
||||
out.setTranslation(pos);
|
||||
}
|
||||
if (node.rotation) {
|
||||
const {quat} = glMatrix;
|
||||
const deg2rad = Math.PI / 180;
|
||||
const q = quat.create() as Quat;
|
||||
quat.rotateX(q, q, deg2rad * node.rotation[0]);
|
||||
quat.rotateY(q, q, deg2rad * node.rotation[1]);
|
||||
quat.rotateZ(q, q, deg2rad * node.rotation[2]);
|
||||
out.setRotation(q);
|
||||
|
||||
const rot = addMotion(doc, 'rotation', node, out);
|
||||
if (rot != null) {
|
||||
out.setRotation(euler2quat(rot));
|
||||
}
|
||||
if (node.scale) {
|
||||
out.setScale(node.scale);
|
||||
|
||||
const scale = addMotion(doc, 'scale', node, out);
|
||||
if (scale != null) {
|
||||
out.setScale(scale);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -275,15 +496,13 @@ function getBackupMaterial(node?: GLTFNode): GLTFMaterial {
|
||||
return node.material;
|
||||
}
|
||||
|
||||
function makeDefaultedMaterial(doc: Document, {
|
||||
roughness = 0.2,
|
||||
metallic = 1,
|
||||
baseColorFactor = [1, 1, 0],
|
||||
alpha = 1,
|
||||
unlit = false,
|
||||
name = ''
|
||||
}: GLTFMaterial = {}): Material {
|
||||
const material = doc.createMaterial(name);
|
||||
function makeDefaultedMaterial(
|
||||
doc: Document, matIn: GLTFMaterial = {}): Material {
|
||||
const defaults = {...globalDefaults};
|
||||
Object.assign(defaults, matIn);
|
||||
const {roughness, metallic, baseColorFactor, alpha, unlit} = defaults;
|
||||
|
||||
const material = doc.createMaterial(matIn.name ?? '');
|
||||
|
||||
if (unlit) {
|
||||
const unlit = doc.createExtension(KHRMaterialsUnlit).createUnlit();
|
||||
@@ -307,7 +526,7 @@ function getCachedMaterial(doc: Document, matDef: GLTFMaterial): Material {
|
||||
}
|
||||
|
||||
function addMesh(
|
||||
doc: Document, node: Node, manifold: Manifold,
|
||||
doc: Document, to3mf: To3MF, node: Node, manifold: Manifold,
|
||||
backupMaterial: GLTFMaterial = {}) {
|
||||
const numTri = manifold.numTri();
|
||||
if (numTri == 0) {
|
||||
@@ -330,36 +549,51 @@ function addMesh(
|
||||
// From Z-up to Y-up (glTF)
|
||||
const manifoldMesh = manifold.getMesh();
|
||||
|
||||
const materials = new Array<GLTFMaterial>();
|
||||
const attributes = new Array<Array<string>>();
|
||||
const id2properties = new Map<number, Properties>();
|
||||
for (const id of manifoldMesh.runOriginalID!) {
|
||||
const material = id2material.get(id) || backupMaterial;
|
||||
materials.push(material);
|
||||
attributes.push(['POSITION', ...material.attributes ?? []]);
|
||||
id2properties.set(id, {
|
||||
material: getCachedMaterial(doc, ghost ? GHOST : material),
|
||||
attributes: ['POSITION', ...material.attributes ?? []]
|
||||
});
|
||||
}
|
||||
|
||||
const gltfMaterials = materials.map((matDef) => {
|
||||
return getCachedMaterial(doc, ghost ? GHOST : matDef);
|
||||
});
|
||||
const morph = manifold2morph.get(manifold);
|
||||
const inputPositions = morphStart(manifoldMesh, morph);
|
||||
|
||||
node.setMesh(writeMesh(doc, manifoldMesh, attributes, gltfMaterials));
|
||||
const mesh = writeMesh(doc, manifoldMesh, id2properties);
|
||||
mesh.setName(node.getName());
|
||||
node.setMesh(mesh);
|
||||
|
||||
morphEnd(doc, manifoldMesh, mesh, inputPositions, morph);
|
||||
|
||||
const vertices = manifoldMesh.numProp === 3 ?
|
||||
manifoldMesh.vertProperties :
|
||||
new Float32Array(manifoldMesh.numVert * 3);
|
||||
if (manifoldMesh.numProp > 3) {
|
||||
for (let i = 0; i < manifoldMesh.numVert; ++i) {
|
||||
for (let j = 0; j < 3; ++j)
|
||||
vertices[i * 3 + j] =
|
||||
manifoldMesh.vertProperties[i * manifoldMesh.numProp + j];
|
||||
}
|
||||
}
|
||||
object2globalID.set(manifold, nextGlobalID);
|
||||
to3mf.meshes.push(
|
||||
{vertices, indices: manifoldMesh.triVerts, id: `${nextGlobalID++}`});
|
||||
|
||||
for (const [run, id] of manifoldMesh.runOriginalID!.entries()) {
|
||||
let inMesh = shown.get(id);
|
||||
let single = false;
|
||||
if (inMesh == null) {
|
||||
single = true;
|
||||
inMesh = singles.get(id);
|
||||
}
|
||||
const show = shown.has(id);
|
||||
const inMesh = show ? shown.get(id) : singles.get(id);
|
||||
if (inMesh == null) {
|
||||
continue;
|
||||
}
|
||||
const mat = single ? materials[run] : SHOW;
|
||||
const debugNode =
|
||||
doc.createNode('debug')
|
||||
.setMesh(writeMesh(
|
||||
doc, inMesh, attributes, [getCachedMaterial(doc, mat)]))
|
||||
.setMatrix(manifoldMesh.transform(run));
|
||||
|
||||
id2properties.get(id)!.material = getCachedMaterial(
|
||||
doc, show ? SHOW : (id2material.get(id) || backupMaterial));
|
||||
|
||||
const debugNode = doc.createNode('debug')
|
||||
.setMesh(writeMesh(doc, inMesh, id2properties))
|
||||
.setMatrix(manifoldMesh.transform(run));
|
||||
node.addChild(debugNode);
|
||||
}
|
||||
}
|
||||
@@ -388,17 +622,19 @@ function cloneNodeNewMaterial(
|
||||
}
|
||||
|
||||
function createNodeFromCache(
|
||||
doc: Document, nodeDef: GLTFNode,
|
||||
doc: Document, to3MF: To3MF, nodeDef: GLTFNode,
|
||||
manifold2node: Map<Manifold, Map<GLTFMaterial, Node>>): Node {
|
||||
const node = createGLTFnode(doc, nodeDef);
|
||||
if (nodeDef.manifold != null) {
|
||||
const {manifold} = nodeDef;
|
||||
if (manifold != null) {
|
||||
setMorph(doc, node, manifold);
|
||||
const backupMaterial = getBackupMaterial(nodeDef);
|
||||
const cachedNodes = manifold2node.get(nodeDef.manifold);
|
||||
const cachedNodes = manifold2node.get(manifold);
|
||||
if (cachedNodes == null) {
|
||||
addMesh(doc, node, nodeDef.manifold, backupMaterial);
|
||||
addMesh(doc, to3MF, node, manifold, backupMaterial);
|
||||
const cache = new Map<GLTFMaterial, Node>();
|
||||
cache.set(backupMaterial, node);
|
||||
manifold2node.set(nodeDef.manifold, cache);
|
||||
manifold2node.set(manifold, cache);
|
||||
} else {
|
||||
const cachedNode = cachedNodes.get(backupMaterial);
|
||||
if (cachedNode == null) {
|
||||
@@ -412,10 +648,21 @@ function createNodeFromCache(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object2globalID.set(nodeDef, nextGlobalID);
|
||||
to3MF.components.push({
|
||||
id: `${nextGlobalID++}`,
|
||||
name: nodeDef.name,
|
||||
children:
|
||||
manifold == null ? [] : [{objectID: `${object2globalID.get(manifold)}`}]
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
async function exportGLB(manifold?: Manifold) {
|
||||
async function exportModels(defaults: GlobalDefaults, manifold?: Manifold) {
|
||||
Object.assign(globalDefaults, GLOBAL_DEFAULTS);
|
||||
Object.assign(globalDefaults, defaults);
|
||||
|
||||
const doc = new Document();
|
||||
const halfRoot2 = Math.sqrt(2) / 2;
|
||||
const mm2m = 1 / 1000;
|
||||
@@ -424,13 +671,53 @@ async function exportGLB(manifold?: Manifold) {
|
||||
.setScale([mm2m, mm2m, mm2m]);
|
||||
doc.createScene().addChild(wrapper);
|
||||
|
||||
animation = doc.createAnimation('');
|
||||
hasAnimation = false;
|
||||
const nFrames = Math.round(globalDefaults.animationLength * FPS) + 1;
|
||||
const times = new Float32Array(nFrames);
|
||||
const weights = new Float32Array(nFrames);
|
||||
for (let i = 0; i < nFrames; ++i) {
|
||||
const x = i / (nFrames - 1);
|
||||
times[i] = x * globalDefaults.animationLength;
|
||||
weights[i] = globalDefaults.animationMode !== 'ping-pong' ?
|
||||
x :
|
||||
(1 - Math.cos(x * 2 * Math.PI)) / 2;
|
||||
}
|
||||
timesAccessor = doc.createAccessor('animation times')
|
||||
.setBuffer(doc.createBuffer())
|
||||
.setArray(times)
|
||||
.setType(Accessor.Type.SCALAR);
|
||||
weightsAccessor = doc.createAccessor('animation weights')
|
||||
.setBuffer(doc.getRoot().listBuffers()[0])
|
||||
.setArray(weights)
|
||||
.setType(Accessor.Type.SCALAR);
|
||||
weightsSampler = doc.createAnimationSampler()
|
||||
.setInput(timesAccessor)
|
||||
.setOutput(weightsAccessor)
|
||||
.setInterpolation('LINEAR');
|
||||
animation.addSampler(weightsSampler);
|
||||
|
||||
const to3mf = {
|
||||
meshes: [],
|
||||
components: [],
|
||||
items: [],
|
||||
precision: 7,
|
||||
header: {
|
||||
unit: 'millimeter',
|
||||
title: 'ManifoldCAD.org model',
|
||||
description: 'ManifoldCAD.org model',
|
||||
application: 'ManifoldCAD.org',
|
||||
}
|
||||
} as To3MF;
|
||||
|
||||
if (nodes.length > 0) {
|
||||
const node2gltf = new Map<GLTFNode, Node>();
|
||||
const manifold2node = new Map<Manifold, Map<GLTFMaterial, Node>>();
|
||||
let leafNodes = 0;
|
||||
|
||||
for (const nodeDef of nodes) {
|
||||
node2gltf.set(nodeDef, createNodeFromCache(doc, nodeDef, manifold2node));
|
||||
node2gltf.set(
|
||||
nodeDef, createNodeFromCache(doc, to3mf, nodeDef, manifold2node));
|
||||
if (nodeDef.manifold) {
|
||||
++leafNodes;
|
||||
}
|
||||
@@ -438,10 +725,19 @@ async function exportGLB(manifold?: Manifold) {
|
||||
|
||||
for (const nodeDef of nodes) {
|
||||
const gltfNode = node2gltf.get(nodeDef)!;
|
||||
if (nodeDef.parent == null) {
|
||||
const child = {
|
||||
objectID: `${object2globalID.get(nodeDef)}`,
|
||||
transform: gltfNode.getMatrix()
|
||||
};
|
||||
const {parent} = nodeDef;
|
||||
if (parent == null) {
|
||||
wrapper.addChild(gltfNode);
|
||||
to3mf.items.push(child);
|
||||
} else {
|
||||
node2gltf.get(nodeDef.parent)!.addChild(gltfNode);
|
||||
node2gltf.get(parent)!.addChild(gltfNode);
|
||||
const parent3mf = to3mf.components.find(
|
||||
(comp) => comp.id == `${object2globalID.get(parent)}`)!;
|
||||
parent3mf.children.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,12 +749,36 @@ async function exportGLB(manifold?: Manifold) {
|
||||
return;
|
||||
}
|
||||
const node = doc.createNode();
|
||||
addMesh(doc, node, manifold);
|
||||
addMesh(doc, to3mf, node, manifold);
|
||||
wrapper.addChild(node);
|
||||
to3mf.items.push({objectID: `${object2globalID.get(manifold)}`});
|
||||
}
|
||||
|
||||
if (!hasAnimation) {
|
||||
timesAccessor.dispose();
|
||||
weightsAccessor.dispose();
|
||||
weightsSampler.dispose();
|
||||
animation.dispose();
|
||||
}
|
||||
|
||||
const glb = await io.writeBinary(doc);
|
||||
const blobGLB = new Blob([glb], {type: 'application/octet-stream'});
|
||||
|
||||
const blob = new Blob([glb], {type: 'application/octet-stream'});
|
||||
self.postMessage({objectURL: URL.createObjectURL(blob)});
|
||||
const fileForRelThumbnail = new FileForRelThumbnail();
|
||||
fileForRelThumbnail.add3dModel('3D/3dmodel.model')
|
||||
|
||||
const model = to3dmodel(to3mf);
|
||||
const files: Zippable = {};
|
||||
files['3D/3dmodel.model'] = strToU8(model);
|
||||
files[fileForContentTypes.name] = strToU8(fileForContentTypes.content);
|
||||
files[fileForRelThumbnail.name] = strToU8(fileForRelThumbnail.content);
|
||||
const zipFile = zipSync(files);
|
||||
const blob3MF = new Blob(
|
||||
[zipFile],
|
||||
{type: 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml'});
|
||||
|
||||
self.postMessage({
|
||||
glbURL: URL.createObjectURL(blobGLB),
|
||||
threeMFURL: URL.createObjectURL(blob3MF)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#include <emscripten/bind.h>
|
||||
#include <emscripten/val.h>
|
||||
#include <manifold.h>
|
||||
#include <polygon.h>
|
||||
#include <sdf.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "manifold.h"
|
||||
#include "polygon.h"
|
||||
#include "sdf.h"
|
||||
|
||||
using namespace emscripten;
|
||||
using namespace manifold;
|
||||
@@ -159,6 +159,11 @@ CrossSection Offset(CrossSection& cross_section, double delta, int join_type,
|
||||
: CrossSection::JoinType::Miter;
|
||||
return cross_section.Offset(delta, jt, miter_limit, arc_tolerance);
|
||||
}
|
||||
|
||||
void CollectVertices(std::vector<glm::vec2>& verts, const CrossSection& cs) {
|
||||
auto polys = cs.ToPolygons();
|
||||
for (auto poly : polys) verts.insert(verts.end(), poly.begin(), poly.end());
|
||||
}
|
||||
} // namespace cross_js
|
||||
|
||||
namespace man_js {
|
||||
@@ -219,4 +224,9 @@ std::vector<Manifold> SplitByPlane(Manifold& m, glm::vec3 normal,
|
||||
auto [a, b] = m.SplitByPlane(normal, originOffset);
|
||||
return {a, b};
|
||||
}
|
||||
|
||||
void CollectVertices(std::vector<glm::vec3>& verts, const Manifold& manifold) {
|
||||
Mesh mesh = manifold.GetMesh();
|
||||
verts.insert(verts.end(), mesh.vertPos.begin(), mesh.vertPos.end());
|
||||
}
|
||||
} // namespace man_js
|
||||
|
||||
+60
-19
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import {Box, FillRule, JoinType, Mat4, Polygons, Properties, Rect, SealedFloat32Array, SealedUint32Array, SimplePolygon, Smoothness, Vec2, Vec3} from './manifold-global-types';
|
||||
import {Box, FillRule, JoinType, Mat3, Mat4, Polygons, Properties, Rect, SealedFloat32Array, SealedUint32Array, SimplePolygon, Smoothness, Vec2, Vec3} from './manifold-global-types';
|
||||
|
||||
/**
|
||||
* Triangulates a set of /epsilon-valid polygons.
|
||||
@@ -111,6 +111,7 @@ export class CrossSection {
|
||||
* @param v The vector to add to every vertex.
|
||||
*/
|
||||
translate(v: Vec2): CrossSection;
|
||||
translate(x: number, y?: number): CrossSection;
|
||||
|
||||
/**
|
||||
* Applies a (Z-axis) rotation to the CrossSection, in degrees. This operation
|
||||
@@ -173,11 +174,6 @@ export class CrossSection {
|
||||
delta: number, joinType?: JoinType, miterLimit?: number,
|
||||
circularSegments?: number): CrossSection;
|
||||
|
||||
/**
|
||||
* Compute the convex hull of the contours in this CrossSection.
|
||||
*/
|
||||
hull(): CrossSection;
|
||||
|
||||
/**
|
||||
* Remove vertices from the contours in this CrossSection that are less than
|
||||
* the specified distance epsilon from an imaginary line that passes through
|
||||
@@ -246,6 +242,18 @@ export class CrossSection {
|
||||
*/
|
||||
static intersection(polygons: (CrossSection|Polygons)[]): CrossSection;
|
||||
|
||||
// Convex Hulls
|
||||
|
||||
/**
|
||||
* Compute the convex hull of the contours in this CrossSection.
|
||||
*/
|
||||
hull(): CrossSection;
|
||||
|
||||
/**
|
||||
* Compute the convex hull of all points in a list of polygons/cross-sections.
|
||||
*/
|
||||
static hull(polygons: (CrossSection|Polygons)[]): CrossSection;
|
||||
|
||||
// Topological Operations
|
||||
|
||||
/**
|
||||
@@ -507,6 +515,7 @@ export class Manifold {
|
||||
* @param v The vector to add to every vertex.
|
||||
*/
|
||||
translate(v: Vec3): Manifold;
|
||||
translate(x: number, y?: number, z?: number): Manifold;
|
||||
|
||||
/**
|
||||
* Applies an Euler angle rotation to the manifold, first about the X axis,
|
||||
@@ -519,6 +528,7 @@ export class Manifold {
|
||||
* @param v [X, Y, Z] rotation in degrees.
|
||||
*/
|
||||
rotate(v: Vec3): Manifold;
|
||||
rotate(x: number, y?: number, z?: number): Manifold;
|
||||
|
||||
/**
|
||||
* Scale this Manifold in space. This operation can be chained. Transforms are
|
||||
@@ -675,6 +685,35 @@ export class Manifold {
|
||||
*/
|
||||
trimByPlane(normal: Vec3, originOffset: number): Manifold;
|
||||
|
||||
/**
|
||||
* Returns the cross section of this object parallel to the X-Y plane at the
|
||||
* specified height. Using a height equal to the bottom
|
||||
* of the bounding box will return the bottom faces, while using a height
|
||||
* equal to the top of the bounding box will return empty.
|
||||
*
|
||||
* @param height Z-level of slice.
|
||||
*/
|
||||
slice(height: number): CrossSection;
|
||||
|
||||
/**
|
||||
* Returns a cross section representing the projected outline of this object
|
||||
* onto the X-Y plane.
|
||||
*/
|
||||
project(): CrossSection;
|
||||
|
||||
// Convex Hulls
|
||||
|
||||
/**
|
||||
* Compute the convex hull of all points in this Manifold.
|
||||
*/
|
||||
hull(): Manifold;
|
||||
|
||||
/**
|
||||
* Compute the convex hull of all points contained within a set of Manifolds
|
||||
* and point vectors.
|
||||
*/
|
||||
static hull(points: (Manifold|Vec3)[]): Manifold;
|
||||
|
||||
// Topological Operations
|
||||
|
||||
/**
|
||||
@@ -815,19 +854,7 @@ export class Manifold {
|
||||
delete(): void;
|
||||
}
|
||||
|
||||
export class Mesh {
|
||||
constructor(options: {
|
||||
numProp: number,
|
||||
vertProperties: Float32Array,
|
||||
triVerts: Uint32Array,
|
||||
mergeFromVert?: Uint32Array,
|
||||
mergeToVert?: Uint32Array,
|
||||
runIndex?: Uint32Array,
|
||||
runOriginalID?: Uint32Array,
|
||||
runTransform?: Float32Array,
|
||||
faceID?: Uint32Array,
|
||||
halfedgeTangent?: Float32Array
|
||||
});
|
||||
export interface MeshOptions {
|
||||
numProp: number;
|
||||
vertProperties: Float32Array;
|
||||
triVerts: Uint32Array;
|
||||
@@ -838,6 +865,20 @@ export class Mesh {
|
||||
runTransform?: Float32Array;
|
||||
faceID?: Uint32Array;
|
||||
halfedgeTangent?: Float32Array;
|
||||
}
|
||||
|
||||
export class Mesh {
|
||||
constructor(options: MeshOptions);
|
||||
numProp: number;
|
||||
vertProperties: Float32Array;
|
||||
triVerts: Uint32Array;
|
||||
mergeFromVert: Uint32Array;
|
||||
mergeToVert: Uint32Array;
|
||||
runIndex: Uint32Array;
|
||||
runOriginalID: Uint32Array;
|
||||
runTransform: Float32Array;
|
||||
faceID: Uint32Array;
|
||||
halfedgeTangent: Float32Array;
|
||||
get numTri(): number;
|
||||
get numVert(): number;
|
||||
get numRun(): number;
|
||||
|
||||
+12
@@ -22,6 +22,18 @@ export interface SealedFloat32Array<N extends number> extends Float32Array {
|
||||
|
||||
export type Vec2 = [number, number];
|
||||
export type Vec3 = [number, number, number];
|
||||
// 3x3 matrix stored in column-major order
|
||||
export type Mat3 = [
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
];
|
||||
// 4x4 matrix stored in column-major order
|
||||
export type Mat4 = [
|
||||
number,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "manifold-3d",
|
||||
"version": "2.1.0",
|
||||
"version": "2.3.0",
|
||||
"description": "Geometry library for topological robustness",
|
||||
"main": "manifold.js",
|
||||
"files": [
|
||||
|
||||
@@ -24,6 +24,13 @@ target_link_libraries(largeSceneTest manifold)
|
||||
target_compile_options(largeSceneTest PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(largeSceneTest PUBLIC cxx_std_17)
|
||||
|
||||
if(MANIFOLD_DEBUG)
|
||||
add_executable(minimizeTestcase minimize_testcase.cpp)
|
||||
target_link_libraries(minimizeTestcase polygon)
|
||||
target_compile_options(minimizeTestcase PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(minimizeTestcase PUBLIC cxx_std_17)
|
||||
endif()
|
||||
|
||||
if(MANIFOLD_EXPORT)
|
||||
add_executable(convertFile convert_file.cpp)
|
||||
target_link_libraries(convertFile manifold meshIO)
|
||||
@@ -34,9 +41,9 @@ endif()
|
||||
if(BUILD_TEST_CGAL)
|
||||
add_executable(perfTestCGAL perf_test_cgal.cpp)
|
||||
find_package(CGAL REQUIRED COMPONENTS Core)
|
||||
find_package(Boost REQUIRED COMPONENTS thread)
|
||||
target_compile_definitions(perfTestCGAL PRIVATE CGAL_USE_GMPXX)
|
||||
# target_compile_definitions(perfTestCGAL PRIVATE CGAL_DEBUG)
|
||||
target_link_libraries(perfTestCGAL manifold CGAL::CGAL CGAL::CGAL_Core)
|
||||
target_link_libraries(perfTestCGAL manifold CGAL::CGAL CGAL::CGAL_Core Boost::thread)
|
||||
target_compile_options(perfTestCGAL PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(perfTestCGAL PUBLIC cxx_std_17)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<pstl/glue_execution_defs.h>)
|
||||
#include <execution>
|
||||
#endif
|
||||
|
||||
#include "polygon.h"
|
||||
#include "utils.h"
|
||||
|
||||
using namespace manifold;
|
||||
|
||||
inline float cross(glm::vec2 p, glm::vec2 q) { return p.x * q.y - p.y * q.x; }
|
||||
|
||||
// return true if p intersects with q
|
||||
// note that we don't care about collinear, intersection in the ends etc.
|
||||
// https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
|
||||
inline bool intersect(glm::vec2 p0, glm::vec2 p1, glm::vec2 q0, glm::vec2 q1,
|
||||
float precision) {
|
||||
glm::vec2 r = p1 - p0;
|
||||
glm::vec2 s = q1 - q0;
|
||||
// allow some error in the intersection point
|
||||
float epsilon_r = 2.0 * precision / glm::length(r);
|
||||
float epsilon_s = 2.0 * precision / glm::length(s);
|
||||
float rxs = cross(r, s);
|
||||
// in case they are nearly collinear, ignore them...
|
||||
// this is to avoid treating degenerate triangles as intersecting
|
||||
//
|
||||
// note that this does not correspond to a fixed angle,
|
||||
// but seems to work well enough
|
||||
if (rxs < kTolerance && rxs > -kTolerance) {
|
||||
return false;
|
||||
}
|
||||
float u = cross(q0 - p0, r) / rxs;
|
||||
float t = cross(q0 - p0, s) / rxs;
|
||||
// we only care about intersection in the middle of both lines, excluding
|
||||
// their ends
|
||||
if (epsilon_r <= u && u <= (1 - epsilon_r) && //
|
||||
epsilon_s <= t && t <= (1 - epsilon_s)) {
|
||||
// there can be cases which r and s are close to collinear,
|
||||
// so even though the lines are not intersecting,
|
||||
// perturbation along r/s is not enough.
|
||||
//
|
||||
// in that case, apply perturbation perpendicular to r
|
||||
glm::vec2 r_orth = glm::normalize(glm::vec2(-r.y, r.x)) * precision;
|
||||
float u1 = cross(q0 - p0 + r_orth, r) / rxs;
|
||||
float u2 = cross(q0 - p0 - r_orth, r) / rxs;
|
||||
float t1 = cross(q0 - p0 + r_orth, s) / rxs;
|
||||
float t2 = cross(q0 - p0 - r_orth, s) / rxs;
|
||||
return 0 <= u1 && u1 <= 1 && //
|
||||
0 <= t1 && t1 <= 1 && //
|
||||
0 <= u2 && u2 <= 1 && //
|
||||
0 <= t2 && t2 <= 1;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// check if removing point j in polygon i will introduce self-intersection
|
||||
// this checks if the new edge j-1 <-> j+1 intersects with any other edges,
|
||||
// assuming the original polygon does not contain self-intersection
|
||||
bool safeToRemove(const Polygons &polys, int i, int j, float precision) {
|
||||
if (polys[i].size() == 3) return false;
|
||||
glm::vec2 prev = polys[i][j == 0 ? polys[i].size() - 1 : (j - 1)];
|
||||
glm::vec2 next = polys[i][j == (polys[i].size() - 1) ? 0 : (j + 1)];
|
||||
for (int k = 0; k < polys.size(); k++) {
|
||||
auto ll = [&](size_t l) {
|
||||
return l == (polys[k].size() - 1) ? 0 : (l + 1);
|
||||
};
|
||||
const glm::vec2 *polysk = polys[k].data();
|
||||
if (!std::all_of(
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<pstl/glue_execution_defs.h>)
|
||||
std::execution::par,
|
||||
#endif
|
||||
countAt((size_t)0), countAt(polys[k].size()), [=](size_t l) {
|
||||
if (i == k && (l == j || ll(l) == j)) return true;
|
||||
return !intersect(prev, next, polysk[l], polysk[ll(l)],
|
||||
precision);
|
||||
}))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::pair<int, int> findIndex(const Polygons &polys, int i) {
|
||||
int outer = 0;
|
||||
while (i >= polys[outer].size()) i -= polys[outer++].size();
|
||||
return std::make_pair(outer, i);
|
||||
}
|
||||
|
||||
void Dump(const Polygons &polys) {
|
||||
for (const SimplePolygon &poly : polys) {
|
||||
std::cout << "polys.push_back({" << std::setprecision(9) << std::endl;
|
||||
for (const glm::vec2 v : poly) {
|
||||
std::cout << " {" << v.x << ", " << v.y << "}, //" << std::endl;
|
||||
}
|
||||
std::cout << "});" << std::endl;
|
||||
}
|
||||
for (const SimplePolygon &poly : polys) {
|
||||
std::cout << "show(array([" << std::endl;
|
||||
for (const glm::vec2 v : poly) {
|
||||
std::cout << " [" << v.x << ", " << v.y << "]," << std::endl;
|
||||
}
|
||||
std::cout << "]))" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void DumpTriangulation(const Polygons &polys, float precision) {
|
||||
ExecutionParams oldParams = PolygonParams();
|
||||
manifold::PolygonParams().processOverlaps = true;
|
||||
std::vector<glm::ivec3> result = Triangulate(polys);
|
||||
PolygonParams() = oldParams;
|
||||
for (const glm::ivec3 &tri : result) {
|
||||
std::pair<int, int> xid = findIndex(polys, tri.x);
|
||||
std::pair<int, int> yid = findIndex(polys, tri.y);
|
||||
std::pair<int, int> zid = findIndex(polys, tri.z);
|
||||
glm::vec2 x = polys[xid.first][xid.second];
|
||||
glm::vec2 y = polys[yid.first][yid.second];
|
||||
glm::vec2 z = polys[zid.first][zid.second];
|
||||
printf("show(array([[%.7f, %.7f], [%.7f, %.7f], [%.7f, %.7f]]))\n", x.x,
|
||||
x.y, y.x, y.y, z.x, z.y);
|
||||
if (CCW(x, y, z, precision) == -1) {
|
||||
printf("^ not CCW\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// x direction ray
|
||||
// idk which direction, but it is a fixed direction...
|
||||
// https://stackoverflow.com/questions/11716268/point-in-polygon-algorithm
|
||||
bool rayHit(glm::vec2 point, glm::vec2 q0, glm::vec2 q1) {
|
||||
return ((q0.y >= point.y) != (q1.y >= point.y)) &&
|
||||
(point.x <= (q1.x - q0.x) * (point.y - q0.y) / (q1.y - q0.y) + q0.x);
|
||||
}
|
||||
|
||||
// get the list of polygons inside polygon i
|
||||
// this enumerates over the first point in all other polygons,
|
||||
// and check if they are inside the current polygon
|
||||
// this algorithm assumes that polygons are non-intersecting
|
||||
std::vector<int> getChildren(const Polygons &polys, int i) {
|
||||
std::vector<int> results;
|
||||
for (int j = 0; j < polys.size(); j++) {
|
||||
if (i == j) continue;
|
||||
glm::vec2 point = polys[j][0];
|
||||
auto k1 = [&](size_t k) {
|
||||
return k == (polys[i].size() - 1) ? 0 : (k + 1);
|
||||
};
|
||||
int count = std::count_if(
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<pstl/glue_execution_defs.h>)
|
||||
std::execution::par,
|
||||
#endif
|
||||
countAt((size_t)0), countAt(polys[i].size()),
|
||||
[&](size_t k) { return rayHit(point, polys[i][k], polys[i][k1(k)]); });
|
||||
if (count % 2) results.push_back(j);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// assuming polys is valid
|
||||
// we try to remove vertices from polys such that
|
||||
// 1. the updated polys is still valid (no overlapping edges, correct winding
|
||||
// direction)
|
||||
// 2. same error in triangulation (either geometryErr or overlapping triangles)
|
||||
void simplify(Polygons &polys, float precision = -1) {
|
||||
bool removedSomething = true;
|
||||
std::string msg;
|
||||
while (removedSomething) {
|
||||
int points = 0;
|
||||
for (const SimplePolygon &poly : polys) points += poly.size();
|
||||
std::cout << "trying to simplify " << points << " points" << std::endl;
|
||||
|
||||
removedSomething = false;
|
||||
// try to remove simple polygons
|
||||
for (int i = 0; i < polys.size(); i++) {
|
||||
std::vector<int> children = getChildren(polys, i);
|
||||
// if there are children, we can't remove it or we will mess up with
|
||||
// winding direction...
|
||||
if (!children.empty()) continue;
|
||||
SimplePolygon poly = std::move(polys[i]);
|
||||
polys.erase(polys.begin() + i);
|
||||
try {
|
||||
std::vector<glm::ivec3> result = Triangulate(polys, precision);
|
||||
polys.insert(polys.begin() + i, std::move(poly));
|
||||
} catch (geometryErr &e) {
|
||||
if (msg.size() > 0 && msg.compare(e.what()) != 0) {
|
||||
polys.insert(polys.begin() + i, std::move(poly));
|
||||
} else {
|
||||
removedSomething = true;
|
||||
msg = e.what();
|
||||
}
|
||||
} catch (topologyErr &e) {
|
||||
polys.insert(polys.begin() + i, std::move(poly));
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < polys.size(); i++) {
|
||||
std::vector<int> children = getChildren(polys, i);
|
||||
for (int j = 0; j < polys[i].size(); j++) {
|
||||
// removed vertex cannot change inclusion relation
|
||||
// we just check if the vertex
|
||||
// x: intersects with j0, j (original edge 1)
|
||||
// y: intersects with j, j1 (original edge 2)
|
||||
// z: intersects with j0, j1 (new edge)
|
||||
// if (x ^ y ^ z) is true, it means that the count % 2 is changed,
|
||||
// and we changed inclusion relation, so vertex j cannot be removed
|
||||
int j0 = j == 0 ? polys[i].size() - 1 : j - 1;
|
||||
int j1 = j == polys[i].size() - 1 ? 0 : j + 1;
|
||||
if (std::any_of(children.begin(), children.end(), [&](int k) {
|
||||
return rayHit(polys[k][0], polys[i][j0], polys[i][j]) ^
|
||||
rayHit(polys[k][0], polys[i][j], polys[i][j1]) ^
|
||||
rayHit(polys[k][0], polys[i][j0], polys[i][j1]);
|
||||
}))
|
||||
continue;
|
||||
|
||||
// removed vertex cannot introduce intersection
|
||||
if (!safeToRemove(polys, i, j, precision)) continue;
|
||||
glm::vec2 removed = polys[i][j];
|
||||
polys[i].erase(polys[i].begin() + j);
|
||||
try {
|
||||
std::vector<glm::ivec3> result = Triangulate(polys, precision);
|
||||
polys[i].insert(polys[i].begin() + j, removed);
|
||||
} catch (geometryErr &e) {
|
||||
if (msg.size() > 0 && msg.compare(e.what()) != 0) {
|
||||
polys[i].insert(polys[i].begin() + j, removed);
|
||||
} else {
|
||||
removedSomething = true;
|
||||
msg = e.what();
|
||||
}
|
||||
} catch (topologyErr &e) {
|
||||
polys[i].insert(polys[i].begin() + j, removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout << "Error message for triangulation:" << std::endl
|
||||
<< msg.c_str() << std::endl;
|
||||
}
|
||||
|
||||
struct Edge {
|
||||
glm::vec2 west; // -x side vertex
|
||||
glm::vec2 east; // +x side vertex
|
||||
size_t i, j; // indices of origin vertex
|
||||
bool operator<(const Edge &other) const {
|
||||
return west.x < other.west.x ||
|
||||
(west.x == other.west.x && east.x < other.east.x);
|
||||
}
|
||||
Edge(const Polygons &polys, size_t i, size_t j) : i(i), j(j) {
|
||||
size_t j1 = j == polys[i].size() - 1 ? 0 : j + 1;
|
||||
east = polys[i][j];
|
||||
west = polys[i][j1];
|
||||
if (west.x > east.x) std::swap(east, west);
|
||||
}
|
||||
};
|
||||
|
||||
int isValid(const Polygons &polys, float precision = -1) {
|
||||
size_t numEdge = 0;
|
||||
for (const SimplePolygon &poly : polys) numEdge += poly.size();
|
||||
std::vector<Edge> edges;
|
||||
edges.reserve(numEdge);
|
||||
for (size_t i = 0; i < polys.size(); i++)
|
||||
for (size_t j = 0; j < polys[i].size(); j++)
|
||||
edges.push_back(Edge(polys, i, j));
|
||||
std::sort(edges.begin(), edges.end());
|
||||
// check intersection
|
||||
std::mutex mutex;
|
||||
std::vector<std::pair<Edge, Edge>> overlappingPairs;
|
||||
|
||||
std::for_each( //
|
||||
countAt((size_t)0), countAt(edges.size()), [&](size_t i) {
|
||||
// check all subsequent edges e' until e'.west.x > e.east.x
|
||||
// this ensures we checked all edges e' where
|
||||
// e.west.x < e'.west.x < e.east.x
|
||||
Edge e = edges[i];
|
||||
for (size_t j = i + 1; j < edges.size() && edges[j].west.x < e.east.x;
|
||||
j++) {
|
||||
if (intersect(e.west, e.east, edges[j].west, edges[j].east,
|
||||
precision)) {
|
||||
mutex.lock();
|
||||
overlappingPairs.push_back(std::make_pair(e, edges[j]));
|
||||
mutex.unlock();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!overlappingPairs.empty()) {
|
||||
std::cout << "found " << overlappingPairs.size() << " self-intersection"
|
||||
<< std::endl;
|
||||
for (const std::pair<Edge, Edge> &pairs : overlappingPairs) {
|
||||
std::cout << pairs.first.i << " " << pairs.first.j << "<->" //
|
||||
<< pairs.second.i << " " << pairs.second.j << std::endl;
|
||||
printf("array([[%.7f, %.7f], [%.7f, %.7f]])\n", pairs.first.west.x,
|
||||
pairs.first.west.y, pairs.first.east.x, pairs.first.east.y);
|
||||
printf("array([[%.7f, %.7f], [%.7f, %.7f]])\n", pairs.second.west.x,
|
||||
pairs.second.west.y, pairs.second.east.x, pairs.second.east.y);
|
||||
}
|
||||
} else {
|
||||
std::cout << "No self-intersection" << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
PolygonParams().intermediateChecks = true;
|
||||
PolygonParams().processOverlaps = false;
|
||||
PolygonParams().suppressErrors = true;
|
||||
|
||||
if (argc < 2) {
|
||||
std::cerr << "Usage: " << argv[0] << " <input file>" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
std::ifstream fin(argv[1]);
|
||||
std::string line;
|
||||
float precision = -1;
|
||||
Polygons polys;
|
||||
SimplePolygon poly;
|
||||
// search for precision first
|
||||
while (std::getline(fin, line)) {
|
||||
int index = line.find("Precision = ");
|
||||
if (index != std::string::npos) {
|
||||
std::istringstream iss(line.substr(index + 12));
|
||||
if (!(iss >> precision)) {
|
||||
std::cerr << "Error parsing precision" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::cout << "Precision = " << precision << std::endl;
|
||||
// fill polygons
|
||||
while (std::getline(fin, line)) {
|
||||
if (line.length() > 5 && line.substr(0, 5).compare(" {") == 0) {
|
||||
std::istringstream iss(line.substr(5));
|
||||
float x, y;
|
||||
if (!(iss >> x)) {
|
||||
std::cerr << "Error parsing coordinate:" << std::endl;
|
||||
std::cerr << "Line: " << line << std::endl;
|
||||
return 1;
|
||||
}
|
||||
iss.ignore(2);
|
||||
if (!(iss >> y)) {
|
||||
std::cerr << "Error parsing coordinate:" << std::endl;
|
||||
std::cerr << "Line: " << line << std::endl;
|
||||
return 1;
|
||||
}
|
||||
poly.push_back(glm::vec2(x, y));
|
||||
} else if (line.length() >= 3 && line.substr(0, 3).compare("});") == 0) {
|
||||
if (poly.size() < 3) {
|
||||
std::cerr << "Error: empty/invalid polygon" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
polys.push_back(std::move(poly));
|
||||
poly.clear();
|
||||
} else if (line.length() >= 5 && line.substr(0, 5).compare("array") == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (polys.size() == 0) {
|
||||
std::cerr << "Error: empty polygon" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (precision == -1) {
|
||||
float bound = 0;
|
||||
for (const SimplePolygon &poly : polys) {
|
||||
for (const glm::vec2 &pt : poly) {
|
||||
bound = glm::max(bound, glm::abs(pt.x));
|
||||
bound = glm::max(bound, glm::abs(pt.y));
|
||||
}
|
||||
}
|
||||
precision = bound * kTolerance;
|
||||
}
|
||||
|
||||
std::cout << "------------" << std::endl;
|
||||
|
||||
isValid(polys, precision);
|
||||
|
||||
simplify(polys, precision);
|
||||
|
||||
std::cout << "------------" << std::endl;
|
||||
std::cout << "Final polygon:" << std::endl;
|
||||
Dump(polys);
|
||||
|
||||
std::cout << "------------" << std::endl;
|
||||
std::cout << "Erroneous triangulation:" << std::endl;
|
||||
DumpTriangulation(polys, precision);
|
||||
return 0;
|
||||
}
|
||||
@@ -57,10 +57,9 @@ void manifoldToCGALSurfaceMesh(Manifold &manifold, TriangleMesh &cgalMesh) {
|
||||
int main(int argc, char **argv) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
Manifold sphere = Manifold::Sphere(1, (8 << i) * 4);
|
||||
Manifold sphere2 = sphere;
|
||||
sphere2.Translate(glm::vec3(0.5));
|
||||
Manifold sphere2 = sphere.Translate(glm::vec3(0.5));
|
||||
|
||||
TriangleMesh cgalSphere, cgalSphere2, cgalOut;
|
||||
TriangleMesh cgalSphere, cgalSphere2;
|
||||
manifoldToCGALSurfaceMesh(sphere, cgalSphere);
|
||||
manifoldToCGALSurfaceMesh(sphere2, cgalSphere2);
|
||||
|
||||
|
||||
Generated
+42
-6
@@ -1,12 +1,15 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1649676176,
|
||||
"narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=",
|
||||
"lastModified": 1692799911,
|
||||
"narHash": "sha256-3eihraek4qL744EvQXsK1Ha6C3CR7nnT8X2qWap4RNk=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678",
|
||||
"rev": "f9e7cf818399d17d347f847525c5a5a8032e4e44",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -15,13 +18,30 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"gtest-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1690989893,
|
||||
"narHash": "sha256-t0RchAHTJbuI5YW4uyBPykTvcjy90JW9AOPNjIhwh6U=",
|
||||
"owner": "google",
|
||||
"repo": "googletest",
|
||||
"rev": "f8d7d77c06936315286eb55f8de22cd23c188571",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "google",
|
||||
"ref": "v1.14.0",
|
||||
"repo": "googletest",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1689008574,
|
||||
"narHash": "sha256-VFMgyHDiqsGDkRg73alv6OdHJAqhybryWHv77bSCGIw=",
|
||||
"lastModified": 1692734709,
|
||||
"narHash": "sha256-SCFnyHCyYjwEmgUsHDDuU0TsbVMKeU1vwkR+r7uS2Rg=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "4a729ce4b1fe5ec4fffc71c67c96aa5184ebb462",
|
||||
"rev": "b85ed9dcbf187b909ef7964774f8847d554fab3b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -33,8 +53,24 @@
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"gtest-src": "gtest-src",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
{
|
||||
inputs.flake-utils.url = "github:numtide/flake-utils";
|
||||
inputs.nixpkgs.url = "nixpkgs/nixos-unstable";
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils }:
|
||||
inputs.gtest-src = {
|
||||
url = "github:google/googletest/v1.14.0";
|
||||
flake = false;
|
||||
};
|
||||
outputs = { self, nixpkgs, flake-utils, gtest-src }:
|
||||
flake-utils.lib.eachDefaultSystem
|
||||
(system:
|
||||
let
|
||||
@@ -10,71 +13,84 @@
|
||||
inherit system;
|
||||
config.allowUnfree = true;
|
||||
};
|
||||
thrust-210 = pkgs.nvidia-thrust.overrideAttrs (_: _: {
|
||||
version = "24486a1";
|
||||
src = builtins.fetchGit {
|
||||
url = "https://github.com/NVIDIA/thrust.git";
|
||||
ref = "main";
|
||||
rev = "24486a169a62a58ef8f824d3dc9613c006b6f5a7";
|
||||
submodules = true;
|
||||
};
|
||||
cmakeFlags = [ "-DTHRUST_ENABLE_HEADER_TESTING=OFF" "-DTHRUST_ENABLE_TESTING=OFF" "-DTHRUST_ENABLE_EXAMPLES=OFF" "-DTHRUST_DEVICE_SYSTEM=CPP" ];
|
||||
fixupPhase = ''
|
||||
cat <<EOT > $out/lib/cmake/thrust/thrust-header-search.cmake
|
||||
# Parse version information from version.h in source tree
|
||||
set(_THRUST_VERSION_INCLUDE_DIR "$out/include")
|
||||
if(EXISTS "\''${_THRUST_VERSION_INCLUDE_DIR}/thrust/version.h")
|
||||
set(_THRUST_VERSION_INCLUDE_DIR "\''${_THRUST_VERSION_INCLUDE_DIR}" CACHE FILEPATH "" FORCE) # Clear old result
|
||||
set_property(CACHE _THRUST_VERSION_INCLUDE_DIR PROPERTY TYPE INTERNAL)
|
||||
endif()
|
||||
EOT
|
||||
cat <<EOT > $out/lib/cmake/libcudacxx/libcudacxx-header-search.cmake
|
||||
# Parse version information from version header:
|
||||
unset(_libcudacxx_VERSION_INCLUDE_DIR CACHE) # Clear old result to force search
|
||||
find_path(_libcudacxx_VERSION_INCLUDE_DIR cuda/std/detail/__config
|
||||
NO_DEFAULT_PATH # Only search explicit paths below:
|
||||
PATHS
|
||||
"\''${CMAKE_CURRENT_LIST_DIR}/../../../include" # Source tree
|
||||
)
|
||||
set_property(CACHE _libcudacxx_VERSION_INCLUDE_DIR PROPERTY TYPE INTERNAL)
|
||||
EOT
|
||||
'';
|
||||
enableParallelBuilding = false;
|
||||
});
|
||||
manifold =
|
||||
{ parallel-backend ? "none"
|
||||
, cuda-support ? false
|
||||
, doCheck ? true
|
||||
, build-tools ? [ ]
|
||||
, ...
|
||||
}: pkgs.stdenv.mkDerivation {
|
||||
inherit doCheck;
|
||||
pname =
|
||||
if cuda-support then
|
||||
"manifold-${parallel-backend}-cuda"
|
||||
else
|
||||
"manifold-${parallel-backend}";
|
||||
version = "beta";
|
||||
pname = "manifold-${parallel-backend}";
|
||||
version = "2.3.0";
|
||||
src = self;
|
||||
nativeBuildInputs = (with pkgs; [ cmake (python39.withPackages (ps: with ps; [ trimesh ])) ]) ++ build-tools ++
|
||||
(if cuda-support then with pkgs.cudaPackages; [ cuda_nvcc cuda_cudart cuda_cccl pkgs.addOpenGLRunpath ] else [ ]);
|
||||
nativeBuildInputs = (with pkgs; [
|
||||
cmake
|
||||
thrust-210
|
||||
glm
|
||||
ninja
|
||||
(python39.withPackages
|
||||
(ps: with ps; [ trimesh pytest ]))
|
||||
gtest
|
||||
]) ++ build-tools;
|
||||
cmakeFlags = [
|
||||
"-DMANIFOLD_PYBIND=ON"
|
||||
"-DMANIFOLD_CBIND=ON"
|
||||
"-DBUILD_SHARED_LIBS=ON"
|
||||
"-DMANIFOLD_PAR=${pkgs.lib.strings.toUpper parallel-backend}"
|
||||
"-DMANIFOLD_USE_CUDA=${if cuda-support then "ON" else "OFF"}"
|
||||
];
|
||||
checkPhase = ''
|
||||
cd test
|
||||
./manifold_test
|
||||
cd ../../
|
||||
PYTHONPATH=$PYTHONPATH:$(pwd)/build/bindings/python python3 bindings/python/examples/run_all.py
|
||||
PYTHONPATH=$PYTHONPATH:$(pwd)/build/bindings/python python3 -m pytest
|
||||
cd build
|
||||
'';
|
||||
installPhase = ''
|
||||
mkdir -p $out
|
||||
cp src/manifold/libmanifold.a $out/
|
||||
cp extras/perfTest $out
|
||||
cp bindings/python/manifold3d* $out
|
||||
'';
|
||||
};
|
||||
parallelBackends = [
|
||||
{ parallel-backend = "none"; }
|
||||
{
|
||||
parallel-backend = "omp";
|
||||
build-tools = [ pkgs.llvmPackages_13.openmp ];
|
||||
}
|
||||
{
|
||||
parallel-backend = "tbb";
|
||||
build-tools = with pkgs; [ tbb pkg-config ];
|
||||
build-tools = with pkgs; [ tbb_2021_8 pkg-config ];
|
||||
}
|
||||
];
|
||||
buildMatrix = with pkgs; with lib; lists.flatten (map
|
||||
(env: map
|
||||
(x: x // env)
|
||||
parallelBackends) [
|
||||
{ cuda-support = false; }
|
||||
{
|
||||
cuda-support = true;
|
||||
}
|
||||
]);
|
||||
devShell = { additional ? [ ] }: pkgs.mkShell {
|
||||
buildInputs = with pkgs; [
|
||||
cmake
|
||||
llvmPackages_13.openmp
|
||||
clang-tools
|
||||
clang_13
|
||||
emscripten
|
||||
tbb
|
||||
lcov
|
||||
tbb_2021_8
|
||||
thrust-210
|
||||
gtest
|
||||
] ++ additional;
|
||||
};
|
||||
in
|
||||
@@ -82,14 +98,13 @@
|
||||
packages = (builtins.listToAttrs
|
||||
(map
|
||||
(x: {
|
||||
name = "manifold-" + x.parallel-backend + (if
|
||||
x.cuda-support then "-cuda" else "");
|
||||
name = "manifold-" + x.parallel-backend;
|
||||
value = manifold x;
|
||||
})
|
||||
buildMatrix)) // {
|
||||
parallelBackends)) // {
|
||||
manifold-js = pkgs.buildEmscriptenPackage {
|
||||
name = "manifold-js";
|
||||
version = "beta";
|
||||
version = "2.3.0";
|
||||
src = self;
|
||||
nativeBuildInputs = (with pkgs; [ cmake python39 ]);
|
||||
buildInputs = [ pkgs.nodejs ];
|
||||
@@ -98,9 +113,10 @@
|
||||
export EM_CACHE=$(pwd)/.emscriptencache
|
||||
mkdir build
|
||||
cd build
|
||||
mkdir cache
|
||||
export EM_CACHE=$(pwd)/cache
|
||||
emcmake cmake -DCMAKE_BUILD_TYPE=Release ..
|
||||
emcmake cmake -DCMAKE_BUILD_TYPE=Release \
|
||||
-DFETCHCONTENT_SOURCE_DIR_GLM=${pkgs.glm.src} \
|
||||
-DFETCHCONTENT_SOURCE_DIR_GOOGLETEST=${gtest-src} \
|
||||
-DFETCHCONTENT_SOURCE_DIR_THRUST=${thrust-210.src} ..
|
||||
'';
|
||||
buildPhase = ''
|
||||
emmake make -j''${NIX_BUILD_CORES}
|
||||
@@ -116,15 +132,42 @@
|
||||
cp {extras,wasm}/*.wasm $out/
|
||||
'';
|
||||
};
|
||||
# but how should we make it work with other python versions?
|
||||
manifold3d = with pkgs.python3Packages; buildPythonPackage {
|
||||
pname = "manifold3d";
|
||||
version = "2.3.0";
|
||||
src = self;
|
||||
propagatedBuildInputs = [
|
||||
numpy
|
||||
];
|
||||
buildInputs = with pkgs; [
|
||||
tbb_2021_8
|
||||
thrust-210
|
||||
glm
|
||||
];
|
||||
nativeBuildInputs = with pkgs; [
|
||||
cmake
|
||||
ninja
|
||||
setuptools
|
||||
scikit-build-core
|
||||
pyproject-metadata
|
||||
pathspec
|
||||
pkg-config
|
||||
];
|
||||
checkInputs = [
|
||||
trimesh
|
||||
pytest
|
||||
];
|
||||
format = "pyproject";
|
||||
dontUseCmakeConfigure = true;
|
||||
doCheck = true;
|
||||
checkPhase = ''
|
||||
python3 bindings/python/examples/run_all.py
|
||||
python3 -m pytest
|
||||
'';
|
||||
};
|
||||
};
|
||||
devShell = devShell { };
|
||||
devShells.cuda = devShell {
|
||||
additional = with pkgs.cudaPackages; [
|
||||
cuda_nvcc
|
||||
cuda_cudart
|
||||
cuda_cccl
|
||||
];
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
shopt -s extglob
|
||||
if [ -z "$CLANG_FORMAT" ]; then
|
||||
CLANG_FORMAT=$(dirname $(which clang-11))/clang-format
|
||||
fi
|
||||
|
||||
$CLANG_FORMAT -i extras/*.cpp
|
||||
$CLANG_FORMAT -i meshIO/**/*.{h,cpp}
|
||||
$CLANG_FORMAT -i samples/**/*.{h,cpp}
|
||||
$CLANG_FORMAT -i test/*.{h,cpp}
|
||||
$CLANG_FORMAT -i bindings/*/*.cpp
|
||||
$CLANG_FORMAT -i bindings/c/include/*.h
|
||||
$CLANG_FORMAT -i bindings/wasm/**/*.{js,ts,html}
|
||||
$CLANG_FORMAT -i src/!(third_party)/*/*.{h,cpp}
|
||||
black bindings/python/examples/*.py
|
||||
@@ -29,3 +29,14 @@ target_link_libraries(${PROJECT_NAME}
|
||||
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)
|
||||
|
||||
install(
|
||||
TARGETS ${PROJECT_NAME}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT devel
|
||||
)
|
||||
install(
|
||||
DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
|
||||
COMPONENT devel
|
||||
)
|
||||
|
||||
@@ -234,6 +234,7 @@ void ExportMesh(const std::string& filename, const MeshGL& mesh,
|
||||
? 1
|
||||
: mesh.vertProperties[i * mesh.numProp +
|
||||
options.mat.colorChannels[j]];
|
||||
c = glm::saturate(c);
|
||||
mesh_out->mColors[0][i] = aiColor4D(c.r, c.g, c.b, c.a);
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Modified from https://github.com/google/fuzztest/blob/main/tools/minimizer.sh
|
||||
# If you want to use a specific reproducer, pass it in FUZZTEST_MINIMIZE_REPRODUCER
|
||||
# environment variable.
|
||||
# Otherwise, just run it as
|
||||
# $ ./minimizer.sh ./build/test/polygon_fuzz --fuzz=PolygonFuzz.TriangulationNoCrash
|
||||
# If you want to kill it, try SIGKILL, SIGTERM is not very useful
|
||||
# If you want to end the loop early, rename $(pwd)/reproducers into something
|
||||
# else...
|
||||
|
||||
if [ -z "${FUZZTEST_MINIMIZE_REPRODUCER}"]; then
|
||||
mkdir -p $(pwd)/reproducers
|
||||
FUZZTEST_REPRODUCERS_OUT_DIR=$(pwd)/reproducers "$@"
|
||||
wildcard="$(pwd)/reproducers/*"
|
||||
reproducers=($wildcard)
|
||||
FUZZTEST_MINIMIZE_REPRODUCER="${reproducers[0]}"
|
||||
fi
|
||||
readonly ORIGINAL_REPRODUCER="${FUZZTEST_MINIMIZE_REPRODUCER}"
|
||||
|
||||
for i in {0001..9999}; do
|
||||
echo
|
||||
echo "╔════════════════════════════════════════════════╗"
|
||||
echo "║ Minimization round: ${i} ║"
|
||||
echo "╚════════════════════════════════════════════════╝"
|
||||
echo "Note that to terminate early, simply move $ORIGINAL_REPRODUCER to somewhere else..."
|
||||
echo
|
||||
|
||||
if [ ! -f $ORIGINAL_REPRODUCER ]; then
|
||||
echo "Terminated by the user"
|
||||
break
|
||||
fi
|
||||
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
FUZZTEST_REPRODUCERS_OUT_DIR="${TEMP_DIR}" \
|
||||
FUZZTEST_MINIMIZE_REPRODUCER="${FUZZTEST_MINIMIZE_REPRODUCER}" \
|
||||
"$@"
|
||||
|
||||
if [ $? -eq 130 ]; then
|
||||
echo
|
||||
echo "╔═══════════════════════════════════════════════╗"
|
||||
echo "║ Minimization terminated. ║"
|
||||
echo "╚═══════════════════════════════════════════════╝"
|
||||
echo
|
||||
echo "Find the smallest reproducer at:"
|
||||
echo
|
||||
echo "${FUZZTEST_MINIMIZE_REPRODUCER}"
|
||||
|
||||
rm -rf "${TEMP_DIR}"
|
||||
break
|
||||
fi
|
||||
|
||||
SMALLER_REPRODUCER=$(find "${TEMP_DIR}" -type f)
|
||||
NEW_NAME="${ORIGINAL_REPRODUCER}-min-${i}"
|
||||
mv "${SMALLER_REPRODUCER}" "${NEW_NAME}"
|
||||
FUZZTEST_MINIMIZE_REPRODUCER="${NEW_NAME}"
|
||||
|
||||
rm -rf "${TEMP_DIR}"
|
||||
done
|
||||
@@ -0,0 +1,78 @@
|
||||
[project]
|
||||
name = "manifold3d"
|
||||
version = "2.3.0"
|
||||
authors = [
|
||||
{ name="Emmett Lalish", email="elalish@gmail.com" },
|
||||
]
|
||||
description = "Library for geometric robustness"
|
||||
readme = "README.md"
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: C++",
|
||||
"Topic :: Multimedia :: Graphics :: 3D Modeling",
|
||||
]
|
||||
requires-python = ">=3.8"
|
||||
|
||||
dependencies = [
|
||||
"numpy; python_version<'3.12'",
|
||||
"numpy>=1.26.0b1; python_version>='3.12'"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
"Homepage" = "https://github.com/elalish/manifold"
|
||||
"Bug Tracker" = "https://github.com/elalish/manifold/issues"
|
||||
|
||||
[build-system]
|
||||
requires = ["scikit-build-core"]
|
||||
build-backend = "scikit_build_core.build"
|
||||
|
||||
[tool.scikit-build]
|
||||
cmake.minimum-version = "3.18"
|
||||
sdist.exclude = [
|
||||
".github",
|
||||
"bindings/c",
|
||||
"bindings/wasm",
|
||||
"docs",
|
||||
"extras",
|
||||
"meshIO",
|
||||
"samples",
|
||||
"test",
|
||||
"oneTBB", # we may have this when we build with cibuildwheel
|
||||
"bindings/python/third_party/nanobind/tests/",
|
||||
"bindings/python/third_party/nanobind/docs/",
|
||||
"src/third_party/clipper2/CPP/Examples/",
|
||||
"src/third_party/clipper2/CPP/Tests/",
|
||||
"src/third_party/clipper2/CSharp/",
|
||||
"src/third_party/clipper2/Delphi/",
|
||||
"src/third_party/clipper2/DLL/",
|
||||
"src/third_party/clipper2/Tests/",
|
||||
]
|
||||
wheel.packages = ["manifold3d"]
|
||||
cmake.args = ["-DMANIFOLD_PAR=TBB", "-DMANIFOLD_TEST=OFF"]
|
||||
install.components = ["bindings"]
|
||||
|
||||
[tool.cibuildwheel]
|
||||
build-frontend = "build"
|
||||
test-requires = ["trimesh", "pytest"]
|
||||
test-command = "python {project}/bindings/python/examples/run_all.py"
|
||||
# Setuptools bug causes collision between pypy and cpython artifacts
|
||||
manylinux-x86_64-image = "manylinux_2_28"
|
||||
musllinux-x86_64-image = "musllinux_1_2"
|
||||
skip = ["*-win32", "*_i686", "pp*", "*-musllinux*"]
|
||||
|
||||
# only clone TBB once
|
||||
before-all = "git clone --depth 1 --branch v2021.10.0 https://github.com/oneapi-src/oneTBB.git"
|
||||
[tool.cibuildwheel.config-settings]
|
||||
"cmake.define.FETCHCONTENT_SOURCE_DIR_TBB" = "./oneTBB"
|
||||
"cmake.define.FETCHCONTENT_UPDATES_DISCONNECTED" = "ON"
|
||||
|
||||
[tool.cibuildwheel.macos]
|
||||
archs = ["x86_64", "arm64"]
|
||||
environment = "MACOSX_DEPLOYMENT_TARGET=10.14"
|
||||
test-skip = "*-macosx_arm64 *-macosx_universal2:arm64"
|
||||
|
||||
[tool.cibuildwheel.windows]
|
||||
before-build = "pip install delvewheel"
|
||||
repair-wheel-command = "delvewheel repair -w {dest_dir} {wheel}"
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths =
|
||||
bindings/python/examples
|
||||
+4
-24
@@ -14,37 +14,17 @@
|
||||
|
||||
project(samples)
|
||||
|
||||
add_library(samples src/bracelet.cpp src/knot.cpp src/menger_sponge.cpp src/rounded_frame.cpp src/scallop.cpp src/tet_puzzle.cpp)
|
||||
add_library(samples src/bracelet.cpp src/knot.cpp src/menger_sponge.cpp
|
||||
src/rounded_frame.cpp src/scallop.cpp src/tet_puzzle.cpp
|
||||
src/gyroid_module.cpp src/condensed_matter.cpp)
|
||||
|
||||
target_include_directories(samples
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_link_libraries(samples
|
||||
PUBLIC manifold
|
||||
PUBLIC manifold sdf
|
||||
)
|
||||
|
||||
target_compile_options(samples PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(samples PUBLIC cxx_std_17)
|
||||
|
||||
project(samplesGPU)
|
||||
|
||||
add_library(samplesGPU src/gyroid_module.cpp)
|
||||
|
||||
if(MANIFOLD_USE_CUDA)
|
||||
set_source_files_properties(src/gyroid_module.cpp PROPERTIES LANGUAGE CUDA)
|
||||
set_property(TARGET samplesGPU PROPERTY CUDA_ARCHITECTURES 61)
|
||||
endif()
|
||||
|
||||
target_include_directories(samplesGPU
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_link_libraries(samplesGPU
|
||||
PUBLIC manifold sdf
|
||||
)
|
||||
|
||||
target_compile_options(samplesGPU PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(samplesGPU
|
||||
PUBLIC cxx_std_17
|
||||
)
|
||||
|
||||
@@ -51,5 +51,7 @@ Manifold TetPuzzle(float edgeLength, float gap, int nDivisions);
|
||||
Manifold Scallop();
|
||||
|
||||
Manifold GyroidModule(float size = 20, int n = 20);
|
||||
|
||||
Manifold CondensedMatter(int fn = 16);
|
||||
/** @} */ // end of Samples
|
||||
} // namespace manifold
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 106 KiB |
@@ -0,0 +1,149 @@
|
||||
// Copyright 2023 The Manifold Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// From
|
||||
// https://gist.github.com/ochafik/70a6b15e982b7ccd5a79ff9afd99dbcf#file-condensed-matter-scad
|
||||
|
||||
#include "samples.h"
|
||||
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
using namespace glm;
|
||||
|
||||
constexpr float AtomicRadiusN2 = 0.65;
|
||||
constexpr float BondPairN2 = 1.197;
|
||||
constexpr float AtomicRadiusSi = 1.1;
|
||||
constexpr float LatticeCellSizeSi = 5.4309;
|
||||
constexpr float fccOffset = 0.25;
|
||||
constexpr float AtomicRadiusC = 0.7;
|
||||
constexpr float LatticeCellSizeC = 3.65;
|
||||
constexpr float cellLenA = 2.464;
|
||||
constexpr float cellLenB = cellLenA;
|
||||
constexpr float cellLenC = 6.711;
|
||||
constexpr float cellAngleA = 90;
|
||||
constexpr float cellAngleB = cellAngleA;
|
||||
constexpr float cellAngleC = 120;
|
||||
constexpr float LayerSeperationC = 3.364;
|
||||
|
||||
Manifold bond(int fn, vec3 p1 = {0, 0, 0}, vec3 p2 = {1, 1, 1}, float ar1 = 1.0,
|
||||
float ar2 = 2.0) {
|
||||
float cyR = std::min(ar1, ar2) / 5.0;
|
||||
float dist = length(p1 - p2);
|
||||
vec3 cyC = (p1 + p2) / 2.0f;
|
||||
float beta = degrees(acos((p1.z - p2.z) / dist));
|
||||
float gamma = degrees(atan2(p1.y - p2.y, p1.x - p2.x));
|
||||
vec3 rot = {0.0, beta, gamma};
|
||||
return Manifold::Cylinder(dist, cyR, -1, fn, true)
|
||||
.Rotate(rot.x, rot.y, rot.z)
|
||||
.Translate(cyC);
|
||||
}
|
||||
|
||||
Manifold bondPair(int fn, float d = 0.0, float ar = 1.0) {
|
||||
float axD = pow(d, 1.0 / 3.0);
|
||||
vec3 p1 = {+axD, -axD, -axD};
|
||||
vec3 p2 = {-axD, +axD, +axD};
|
||||
Manifold sphere = Manifold::Sphere(ar, fn);
|
||||
return sphere.Translate(p1) + sphere.Translate(p2) + bond(fn, p1, p2, ar, ar);
|
||||
}
|
||||
|
||||
Manifold hexagonalClosePacked(int fn, vec3 dst = {1.0, 1.0, 1.0},
|
||||
float ar = 1.0) {
|
||||
std::vector<Manifold> parts;
|
||||
vec3 p1 = {0, 0, 0};
|
||||
parts.push_back(Manifold::Sphere(ar, fn));
|
||||
float baseAg = 30;
|
||||
vec3 ag = {baseAg, baseAg + 120, baseAg + 240};
|
||||
vec3 points[] = {{cosd(ag.x) * dst.x, sind(ag.x) * dst.x, 0},
|
||||
{cosd(ag.y) * dst.y, sind(ag.y) * dst.y, 0},
|
||||
{cosd(ag.z) * dst.z, sind(ag.z) * dst.z, 0}};
|
||||
for (vec3 p2 : points) {
|
||||
parts.push_back(Manifold::Sphere(ar, fn).Translate(p2));
|
||||
parts.push_back(bond(fn, p1, p2, ar, ar));
|
||||
}
|
||||
return Manifold::BatchBoolean(parts, OpType::Add);
|
||||
}
|
||||
|
||||
Manifold fccDiamond(int fn, float ar = 1.0, float unitCell = 2.0,
|
||||
float fccOffset = 0.25) {
|
||||
std::vector<Manifold> parts;
|
||||
float huc = unitCell / 2.0;
|
||||
float od = fccOffset * unitCell;
|
||||
vec3 interstitial[] = {
|
||||
{+od, +od, +od}, {+od, -od, -od}, {-od, +od, -od}, {-od, -od, +od}};
|
||||
vec3 corners[] = {{+huc, +huc, +huc},
|
||||
{+huc, -huc, -huc},
|
||||
{-huc, +huc, -huc},
|
||||
{-huc, -huc, +huc}};
|
||||
vec3 fcc[] = {{+huc, 0, 0}, {-huc, 0, 0}, {0, +huc, 0},
|
||||
{0, -huc, 0}, {0, 0, +huc}, {0, 0, -huc}};
|
||||
for (auto p : corners) parts.push_back(Manifold::Sphere(ar, fn).Translate(p));
|
||||
|
||||
for (auto p : fcc) parts.push_back(Manifold::Sphere(ar, fn).Translate(p));
|
||||
for (auto p : interstitial)
|
||||
parts.push_back(Manifold::Sphere(ar, fn).Translate(p));
|
||||
|
||||
vec3 bonds[][2] = {{interstitial[0], corners[0]}, {interstitial[0], fcc[0]},
|
||||
{interstitial[0], fcc[2]}, {interstitial[0], fcc[4]},
|
||||
{interstitial[1], corners[1]}, {interstitial[1], fcc[0]},
|
||||
{interstitial[1], fcc[3]}, {interstitial[1], fcc[5]},
|
||||
{interstitial[2], corners[2]}, {interstitial[2], fcc[1]},
|
||||
{interstitial[2], fcc[2]}, {interstitial[2], fcc[5]},
|
||||
{interstitial[3], corners[3]}, {interstitial[3], fcc[1]},
|
||||
{interstitial[3], fcc[3]}, {interstitial[3], fcc[4]}};
|
||||
for (auto b : bonds) parts.push_back(bond(fn, b[0], b[1], ar, ar));
|
||||
|
||||
return Manifold::BatchBoolean(parts, OpType::Add);
|
||||
}
|
||||
|
||||
Manifold SiCell(int fn, float x = 1.0, float y = 1.0, float z = 1.0) {
|
||||
return fccDiamond(fn, AtomicRadiusSi, LatticeCellSizeSi, fccOffset)
|
||||
.Translate({LatticeCellSizeSi * x, LatticeCellSizeSi * y,
|
||||
LatticeCellSizeSi * z});
|
||||
}
|
||||
|
||||
Manifold SiN2Cell(int fn, float x = 1.0, float y = 1.0, float z = 1.0) {
|
||||
float n2Offset = LatticeCellSizeSi / 8;
|
||||
return bondPair(fn, BondPairN2, AtomicRadiusN2)
|
||||
.Translate({LatticeCellSizeSi * x - n2Offset,
|
||||
LatticeCellSizeSi * y + n2Offset,
|
||||
LatticeCellSizeSi * z + n2Offset}) +
|
||||
SiCell(fn, x, y, z);
|
||||
}
|
||||
|
||||
Manifold GraphiteCell(int fn, vec3 xyz = {1.0, 1.0, 1.0}) {
|
||||
vec3 loc = {(cellLenA * xyz.x * cosd(30) * 2),
|
||||
((cellLenB * sind(30)) + cellLenC) * xyz.y, xyz.z};
|
||||
return hexagonalClosePacked(fn, {cellLenA, cellLenB, cellLenC}, AtomicRadiusC)
|
||||
.Translate(loc);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace manifold {
|
||||
Manifold CondensedMatter(int fn) {
|
||||
std::vector<Manifold> parts;
|
||||
float siOffset = 3.0 * LatticeCellSizeSi / 8.0;
|
||||
for (int x = -3; x <= 3; x++)
|
||||
for (int y = -1; y <= 2; y++)
|
||||
parts.push_back(
|
||||
GraphiteCell(fn, {x + (y % 2 == 0 ? 0.0 : 0.5), y,
|
||||
LayerSeperationC * 0.5 + LatticeCellSizeSi * 1.5})
|
||||
.Translate({0, -siOffset, 0})
|
||||
.Rotate(0, 0, 45));
|
||||
|
||||
float xyPlane[] = {-2, -1, 0, +1, +2};
|
||||
for (float x : xyPlane)
|
||||
for (float y : xyPlane) parts.push_back(SiN2Cell(fn, x, y, 1));
|
||||
return Manifold::BatchBoolean(parts, OpType::Add);
|
||||
}
|
||||
} // namespace manifold
|
||||
@@ -12,13 +12,15 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "manifold.h"
|
||||
#include "samples.h"
|
||||
#include "sdf.h"
|
||||
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
|
||||
struct Gyroid {
|
||||
__host__ __device__ float operator()(glm::vec3 p) const {
|
||||
float operator()(glm::vec3 p) const {
|
||||
p -= glm::pi<float>() / 4;
|
||||
return cos(p.x) * sin(p.y) + cos(p.y) * sin(p.z) + cos(p.z) * sin(p.x);
|
||||
}
|
||||
@@ -54,4 +56,4 @@ Manifold GyroidModule(float size, int n) {
|
||||
|
||||
return result.Rotate(-45, 0, 90).Translate({0, 0, size / glm::sqrt(2.0f)});
|
||||
}
|
||||
} // namespace manifold
|
||||
} // namespace manifold
|
||||
|
||||
+2
-1
@@ -12,7 +12,8 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
add_subdirectory(third_party)
|
||||
# do not add third_party installations
|
||||
add_subdirectory(third_party EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(utilities)
|
||||
add_subdirectory(collider)
|
||||
add_subdirectory(cross_section)
|
||||
|
||||
@@ -15,16 +15,18 @@
|
||||
project (collider)
|
||||
|
||||
file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.cpp)
|
||||
add_library(${PROJECT_NAME} OBJECT ${SOURCE_FILES})
|
||||
|
||||
if(MANIFOLD_USE_CUDA)
|
||||
set_source_files_properties(${SOURCE_FILES} PROPERTIES LANGUAGE CUDA)
|
||||
set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES 61)
|
||||
endif()
|
||||
add_library(${PROJECT_NAME} ${SOURCE_FILES})
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)
|
||||
target_link_libraries(${PROJECT_NAME} PUBLIC utilities)
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
|
||||
|
||||
target_compile_features(${PROJECT_NAME}
|
||||
PUBLIC cxx_std_17
|
||||
)
|
||||
|
||||
install(
|
||||
TARGETS ${PROJECT_NAME}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT runtime
|
||||
)
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
#pragma once
|
||||
#include "public.h"
|
||||
#include "sparse.h"
|
||||
#include "vec_dh.h"
|
||||
#include "vec.h"
|
||||
|
||||
namespace manifold {
|
||||
|
||||
@@ -23,20 +23,24 @@ namespace manifold {
|
||||
class Collider {
|
||||
public:
|
||||
Collider() {}
|
||||
Collider(const VecDH<Box>& leafBB, const VecDH<uint32_t>& leafMorton);
|
||||
Collider(const VecView<const Box>& leafBB,
|
||||
const VecView<const uint32_t>& leafMorton);
|
||||
bool Transform(glm::mat4x3);
|
||||
void UpdateBoxes(const VecDH<Box>& leafBB);
|
||||
template <const bool selfCollision = false, typename T>
|
||||
SparseIndices Collisions(const VecDH<T>& queriesIn) const;
|
||||
void UpdateBoxes(const VecView<const Box>& leafBB);
|
||||
template <const bool selfCollision = false, const bool inverted = false,
|
||||
typename T>
|
||||
SparseIndices Collisions(const VecView<const T>& queriesIn) const;
|
||||
|
||||
private:
|
||||
VecDH<Box> nodeBBox_;
|
||||
VecDH<int> nodeParent_;
|
||||
Vec<Box> nodeBBox_;
|
||||
Vec<int> nodeParent_;
|
||||
// even nodes are leaves, odd nodes are internal, root is 1
|
||||
VecDH<thrust::pair<int, int>> internalChildren_;
|
||||
Vec<thrust::pair<int, int>> internalChildren_;
|
||||
|
||||
int NumInternal() const { return internalChildren_.size(); };
|
||||
int NumLeaves() const { return NumInternal() + 1; };
|
||||
int NumLeaves() const {
|
||||
return internalChildren_.empty() ? 0 : (NumInternal() + 1);
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace manifold
|
||||
|
||||
+127
-80
@@ -24,6 +24,7 @@
|
||||
// Adjustable parameters
|
||||
constexpr int kInitialLength = 128;
|
||||
constexpr int kLengthMultiple = 4;
|
||||
constexpr int kSequentialThreshold = 512;
|
||||
// Fundamental constants
|
||||
constexpr int kRoot = 1;
|
||||
|
||||
@@ -59,36 +60,30 @@ uint32_t __inline clz(uint32_t value) {
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
|
||||
__host__ __device__ bool IsLeaf(int node) { return node % 2 == 0; }
|
||||
__host__ __device__ bool IsInternal(int node) { return node % 2 == 1; }
|
||||
__host__ __device__ int Node2Internal(int node) { return (node - 1) / 2; }
|
||||
__host__ __device__ int Internal2Node(int internal) { return internal * 2 + 1; }
|
||||
__host__ __device__ int Node2Leaf(int node) { return node / 2; }
|
||||
__host__ __device__ int Leaf2Node(int leaf) { return leaf * 2; }
|
||||
bool IsLeaf(int node) { return node % 2 == 0; }
|
||||
bool IsInternal(int node) { return node % 2 == 1; }
|
||||
int Node2Internal(int node) { return (node - 1) / 2; }
|
||||
int Internal2Node(int internal) { return internal * 2 + 1; }
|
||||
int Node2Leaf(int node) { return node / 2; }
|
||||
int Leaf2Node(int leaf) { return leaf * 2; }
|
||||
|
||||
struct CreateRadixTree {
|
||||
int* nodeParent_;
|
||||
thrust::pair<int, int>* internalChildren_;
|
||||
const VecDc<uint32_t> leafMorton_;
|
||||
VecView<int> nodeParent_;
|
||||
VecView<thrust::pair<int, int>> internalChildren_;
|
||||
const VecView<const uint32_t> leafMorton_;
|
||||
|
||||
__host__ __device__ int PrefixLength(uint32_t a, uint32_t b) const {
|
||||
int PrefixLength(uint32_t a, uint32_t b) const {
|
||||
// count-leading-zeros is used to find the number of identical highest-order
|
||||
// bits
|
||||
#ifdef __CUDA_ARCH__
|
||||
return __clz(a ^ b);
|
||||
#else
|
||||
|
||||
#ifdef _MSC_VER
|
||||
// return __lzcnt(a ^ b);
|
||||
return clz(a ^ b);
|
||||
#else
|
||||
return __builtin_clz(a ^ b);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
__host__ __device__ int PrefixLength(int i, int j) const {
|
||||
int PrefixLength(int i, int j) const {
|
||||
if (j < 0 || j >= leafMorton_.size()) {
|
||||
return -1;
|
||||
} else {
|
||||
@@ -103,7 +98,7 @@ struct CreateRadixTree {
|
||||
}
|
||||
}
|
||||
|
||||
__host__ __device__ int RangeEnd(int i) const {
|
||||
int RangeEnd(int i) const {
|
||||
// Determine direction of range (+1 or -1)
|
||||
int dir = PrefixLength(i, i + 1) - PrefixLength(i, i - 1);
|
||||
dir = (dir > 0) - (dir < 0);
|
||||
@@ -121,7 +116,7 @@ struct CreateRadixTree {
|
||||
return i + dir * length;
|
||||
}
|
||||
|
||||
__host__ __device__ int FindSplit(int first, int last) const {
|
||||
int FindSplit(int first, int last) const {
|
||||
int commonPrefix = PrefixLength(first, last);
|
||||
// Find the furthest object that shares more than commonPrefix bits with the
|
||||
// first one, using binary search.
|
||||
@@ -138,7 +133,7 @@ struct CreateRadixTree {
|
||||
return split;
|
||||
}
|
||||
|
||||
__host__ __device__ void operator()(int internal) {
|
||||
void operator()(int internal) {
|
||||
int first = internal;
|
||||
// Find the range of objects with a common prefix
|
||||
int last = RangeEnd(first);
|
||||
@@ -157,36 +152,27 @@ struct CreateRadixTree {
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, const bool allocateOnly, const bool selfCollision>
|
||||
template <typename T, const bool selfCollision, typename Recorder>
|
||||
struct FindCollisions {
|
||||
thrust::pair<int*, int*> queryTri_;
|
||||
int* counts;
|
||||
const Box* nodeBBox_;
|
||||
const thrust::pair<int, int>* internalChildren_;
|
||||
VecView<const Box> nodeBBox_;
|
||||
VecView<const thrust::pair<int, int>> internalChildren_;
|
||||
Recorder recorder;
|
||||
|
||||
__host__ __device__ int RecordCollision(int node,
|
||||
thrust::tuple<T, int>& query) {
|
||||
int RecordCollision(int node, thrust::tuple<T, int>& query) {
|
||||
const T& queryObj = thrust::get<0>(query);
|
||||
const int queryIdx = thrust::get<1>(query);
|
||||
int& count = counts[queryIdx];
|
||||
|
||||
bool overlaps = nodeBBox_[node].DoesOverlap(queryObj);
|
||||
if (overlaps && IsLeaf(node)) {
|
||||
const int leafIdx = Node2Leaf(node);
|
||||
int leafIdx = Node2Leaf(node);
|
||||
if (!selfCollision || leafIdx != queryIdx) {
|
||||
if (allocateOnly) {
|
||||
count++;
|
||||
} else {
|
||||
int pos = count++;
|
||||
queryTri_.first[pos] = queryIdx;
|
||||
queryTri_.second[pos] = leafIdx;
|
||||
}
|
||||
recorder.record(queryIdx, leafIdx);
|
||||
}
|
||||
}
|
||||
return overlaps && IsInternal(node); // Should traverse into node
|
||||
}
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<T, int> query) {
|
||||
void operator()(thrust::tuple<T, int> query) {
|
||||
// stack cannot overflow because radix tree has max depth 30 (Morton code) +
|
||||
// 32 (index).
|
||||
int stack[64];
|
||||
@@ -195,7 +181,7 @@ struct FindCollisions {
|
||||
int node = kRoot;
|
||||
const int queryIdx = thrust::get<1>(query);
|
||||
// same implies that this query do not have any collision
|
||||
if (!allocateOnly && counts[queryIdx] == counts[queryIdx + 1]) return;
|
||||
if (recorder.earlyexit(queryIdx)) return;
|
||||
while (1) {
|
||||
int internal = Node2Internal(node);
|
||||
int child1 = internalChildren_[internal].first;
|
||||
@@ -214,16 +200,56 @@ struct FindCollisions {
|
||||
}
|
||||
}
|
||||
}
|
||||
recorder.end(queryIdx);
|
||||
}
|
||||
};
|
||||
|
||||
struct BuildInternalBoxes {
|
||||
Box* nodeBBox_;
|
||||
int* counter_;
|
||||
const int* nodeParent_;
|
||||
const thrust::pair<int, int>* internalChildren_;
|
||||
struct CountCollisions {
|
||||
VecView<int> counts;
|
||||
VecView<char> empty;
|
||||
void record(int queryIdx, int _leafIdx) { counts[queryIdx]++; }
|
||||
bool earlyexit(int _queryIdx) { return false; }
|
||||
void end(int queryIdx) {
|
||||
if (counts[queryIdx] == 0) empty[queryIdx] = 1;
|
||||
}
|
||||
};
|
||||
|
||||
__host__ __device__ void operator()(int leaf) {
|
||||
template <const bool inverted>
|
||||
struct SeqCollisionRecorder {
|
||||
SparseIndices& queryTri_;
|
||||
void record(int queryIdx, int leafIdx) const {
|
||||
if (inverted)
|
||||
queryTri_.Add(leafIdx, queryIdx);
|
||||
else
|
||||
queryTri_.Add(queryIdx, leafIdx);
|
||||
}
|
||||
bool earlyexit(int queryIdx) const { return false; }
|
||||
void end(int queryIdx) const {}
|
||||
};
|
||||
|
||||
template <const bool inverted>
|
||||
struct ParCollisionRecorder {
|
||||
SparseIndices& queryTri;
|
||||
VecView<int> counts;
|
||||
VecView<char> empty;
|
||||
void record(int queryIdx, int leafIdx) {
|
||||
int pos = counts[queryIdx]++;
|
||||
if (inverted)
|
||||
queryTri.Set(pos, leafIdx, queryIdx);
|
||||
else
|
||||
queryTri.Set(pos, queryIdx, leafIdx);
|
||||
}
|
||||
bool earlyexit(int queryIdx) const { return empty[queryIdx] == 1; }
|
||||
void end(int queryIdx) const {}
|
||||
};
|
||||
|
||||
struct BuildInternalBoxes {
|
||||
VecView<Box> nodeBBox_;
|
||||
VecView<int> counter_;
|
||||
const VecView<int> nodeParent_;
|
||||
const VecView<thrust::pair<int, int>> internalChildren_;
|
||||
|
||||
void operator()(int leaf) {
|
||||
int node = Leaf2Node(leaf);
|
||||
do {
|
||||
node = nodeParent_[node];
|
||||
@@ -237,9 +263,7 @@ struct BuildInternalBoxes {
|
||||
|
||||
struct TransformBox {
|
||||
const glm::mat4x3 transform;
|
||||
__host__ __device__ void operator()(Box& box) {
|
||||
box = box.Transform(transform);
|
||||
}
|
||||
void operator()(Box& box) { box = box.Transform(transform); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -250,8 +274,9 @@ namespace manifold {
|
||||
* bounding boxes and corresponding Morton codes. It is assumed these vectors
|
||||
* are already sorted by increasing Morton code.
|
||||
*/
|
||||
Collider::Collider(const VecDH<Box>& leafBB,
|
||||
const VecDH<uint32_t>& leafMorton) {
|
||||
Collider::Collider(const VecView<const Box>& leafBB,
|
||||
const VecView<const uint32_t>& leafMorton) {
|
||||
ZoneScoped;
|
||||
ASSERT(leafBB.size() == leafMorton.size(), userErr,
|
||||
"vectors must be the same length");
|
||||
int num_nodes = 2 * leafBB.size() - 1;
|
||||
@@ -261,8 +286,7 @@ Collider::Collider(const VecDH<Box>& leafBB,
|
||||
internalChildren_.resize(leafBB.size() - 1, thrust::make_pair(-1, -1));
|
||||
// organize tree
|
||||
for_each_n(autoPolicy(NumInternal()), countAt(0), NumInternal(),
|
||||
CreateRadixTree(
|
||||
{nodeParent_.ptrD(), internalChildren_.ptrD(), leafMorton}));
|
||||
CreateRadixTree({nodeParent_, internalChildren_, leafMorton}));
|
||||
UpdateBoxes(leafBB);
|
||||
}
|
||||
|
||||
@@ -274,47 +298,59 @@ Collider::Collider(const VecDH<Box>& leafBB,
|
||||
* the query vector is the leaf vector, set selfCollision to true, which will
|
||||
* then not report any collisions between an index and itself.
|
||||
*/
|
||||
template <const bool selfCollision, typename T>
|
||||
SparseIndices Collider::Collisions(const VecDH<T>& queriesIn) const {
|
||||
template <const bool selfCollision, const bool inverted, typename T>
|
||||
SparseIndices Collider::Collisions(const VecView<const T>& queriesIn) const {
|
||||
ZoneScoped;
|
||||
// note that the length is 1 larger than the number of queries so the last
|
||||
// element can store the sum when using exclusive scan
|
||||
VecDH<int> counts(queriesIn.size() + 1, 0);
|
||||
auto policy = autoPolicy(queriesIn.size());
|
||||
// compute the number of collisions to determine the size for allocation and
|
||||
// offset, this avoids the need for atomic
|
||||
for_each_n(policy, zip(queriesIn.cbegin(), countAt(0)), queriesIn.size(),
|
||||
FindCollisions<T, true, selfCollision>(
|
||||
{thrust::pair<int*, int*>(nullptr, nullptr), counts.ptrD(),
|
||||
nodeBBox_.ptrD(), internalChildren_.ptrD()}));
|
||||
// compute start index for each query and total count
|
||||
exclusive_scan(policy, counts.begin(), counts.end(), counts.begin());
|
||||
SparseIndices queryTri(counts.back());
|
||||
// actually recording collisions
|
||||
for_each_n(policy, zip(queriesIn.cbegin(), countAt(0)), queriesIn.size(),
|
||||
FindCollisions<T, false, selfCollision>(
|
||||
{queryTri.ptrDpq(), counts.ptrD(), nodeBBox_.ptrD(),
|
||||
internalChildren_.ptrD()}));
|
||||
return queryTri;
|
||||
if (queriesIn.size() < kSequentialThreshold) {
|
||||
SparseIndices queryTri;
|
||||
for_each_n(ExecutionPolicy::Seq, zip(queriesIn.cbegin(), countAt(0)),
|
||||
queriesIn.size(),
|
||||
FindCollisions<T, selfCollision, SeqCollisionRecorder<inverted>>{
|
||||
nodeBBox_, internalChildren_, {queryTri}});
|
||||
return queryTri;
|
||||
} else {
|
||||
// compute the number of collisions to determine the size for allocation and
|
||||
// offset, this avoids the need for atomic
|
||||
Vec<int> counts(queriesIn.size() + 1, 0);
|
||||
Vec<char> empty(queriesIn.size(), 0);
|
||||
for_each_n(ExecutionPolicy::Par, zip(queriesIn.cbegin(), countAt(0)),
|
||||
queriesIn.size(),
|
||||
FindCollisions<T, selfCollision, CountCollisions>{
|
||||
nodeBBox_, internalChildren_, {counts, empty}});
|
||||
// compute start index for each query and total count
|
||||
exclusive_scan(ExecutionPolicy::Par, counts.begin(), counts.end(),
|
||||
counts.begin(), 0, std::plus<int>());
|
||||
if (counts.back() == 0) return SparseIndices(0);
|
||||
SparseIndices queryTri(counts.back());
|
||||
// actually recording collisions
|
||||
for_each_n(ExecutionPolicy::Par, zip(queriesIn.cbegin(), countAt(0)),
|
||||
queriesIn.size(),
|
||||
FindCollisions<T, selfCollision, ParCollisionRecorder<inverted>>{
|
||||
nodeBBox_, internalChildren_, {queryTri, counts, empty}});
|
||||
return queryTri;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate the collider's internal bounding boxes without changing the
|
||||
* hierarchy.
|
||||
*/
|
||||
void Collider::UpdateBoxes(const VecDH<Box>& leafBB) {
|
||||
void Collider::UpdateBoxes(const VecView<const Box>& leafBB) {
|
||||
ZoneScoped;
|
||||
ASSERT(leafBB.size() == NumLeaves(), userErr,
|
||||
"must have the same number of updated boxes as original");
|
||||
// copy in leaf node Boxes
|
||||
strided_range<VecDH<Box>::Iter> leaves(nodeBBox_.begin(), nodeBBox_.end(), 2);
|
||||
strided_range<Vec<Box>::Iter> leaves(nodeBBox_.begin(), nodeBBox_.end(), 2);
|
||||
auto policy = autoPolicy(NumInternal());
|
||||
copy(policy, leafBB.cbegin(), leafBB.cend(), leaves.begin());
|
||||
// create global counters
|
||||
VecDH<int> counter(NumInternal(), 0);
|
||||
Vec<int> counter(NumInternal(), 0);
|
||||
// kernel over leaves to save internal Boxes
|
||||
for_each_n(
|
||||
policy, countAt(0), NumLeaves(),
|
||||
BuildInternalBoxes({nodeBBox_.ptrD(), counter.ptrD(), nodeParent_.cptrD(),
|
||||
internalChildren_.cptrD()}));
|
||||
BuildInternalBoxes({nodeBBox_, counter, nodeParent_, internalChildren_}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -322,6 +358,7 @@ void Collider::UpdateBoxes(const VecDH<Box>& leafBB) {
|
||||
* axis-aligned, abort and return false to indicate recalculation is necessary.
|
||||
*/
|
||||
bool Collider::Transform(glm::mat4x3 transform) {
|
||||
ZoneScoped;
|
||||
bool axisAligned = true;
|
||||
for (int row : {0, 1, 2}) {
|
||||
int count = 0;
|
||||
@@ -337,12 +374,22 @@ bool Collider::Transform(glm::mat4x3 transform) {
|
||||
return axisAligned;
|
||||
}
|
||||
|
||||
template SparseIndices Collider::Collisions<true, Box>(const VecDH<Box>&) const;
|
||||
template SparseIndices Collider::Collisions<true, false, Box>(
|
||||
const VecView<const Box>&) const;
|
||||
|
||||
template SparseIndices Collider::Collisions<false, Box>(
|
||||
const VecDH<Box>&) const;
|
||||
template SparseIndices Collider::Collisions<false, false, Box>(
|
||||
const VecView<const Box>&) const;
|
||||
|
||||
template SparseIndices Collider::Collisions<false, glm::vec3>(
|
||||
const VecDH<glm::vec3>&) const;
|
||||
template SparseIndices Collider::Collisions<false, false, glm::vec3>(
|
||||
const VecView<const glm::vec3>&) const;
|
||||
|
||||
template SparseIndices Collider::Collisions<true, true, Box>(
|
||||
const VecView<const Box>&) const;
|
||||
|
||||
template SparseIndices Collider::Collisions<false, true, Box>(
|
||||
const VecView<const Box>&) const;
|
||||
|
||||
template SparseIndices Collider::Collisions<false, true, glm::vec3>(
|
||||
const VecView<const glm::vec3>&) const;
|
||||
|
||||
} // namespace manifold
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
project (cross_section)
|
||||
|
||||
file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.cpp)
|
||||
add_library(${PROJECT_NAME} OBJECT ${SOURCE_FILES})
|
||||
add_library(${PROJECT_NAME} ${SOURCE_FILES})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/include
|
||||
@@ -26,3 +26,15 @@ target_link_libraries( ${PROJECT_NAME}
|
||||
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
|
||||
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)
|
||||
|
||||
install(
|
||||
TARGETS ${PROJECT_NAME}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT runtime
|
||||
)
|
||||
install(
|
||||
DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
|
||||
COMPONENT devel
|
||||
)
|
||||
|
||||
|
||||
@@ -14,27 +14,23 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <clipper2/clipper.h>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "clipper2/clipper.core.h"
|
||||
#include "clipper2/clipper.offset.h"
|
||||
#include "glm/ext/matrix_float3x2.hpp"
|
||||
#include "glm/ext/vector_float2.hpp"
|
||||
#include "public.h"
|
||||
|
||||
namespace C2 = Clipper2Lib;
|
||||
#include "vec_view.h"
|
||||
|
||||
namespace manifold {
|
||||
|
||||
class Rect;
|
||||
|
||||
/** @addtogroup Core
|
||||
* @{
|
||||
*/
|
||||
|
||||
struct PathImpl;
|
||||
|
||||
/**
|
||||
* Two-dimensional cross sections guaranteed to be without self-intersections,
|
||||
* or overlaps between polygons (from construction onwards). This class makes
|
||||
@@ -102,6 +98,8 @@ class CrossSection {
|
||||
CrossSection Mirror(const glm::vec2 ax) const;
|
||||
CrossSection Transform(const glm::mat3x2& m) const;
|
||||
CrossSection Warp(std::function<void(glm::vec2&)> warpFunc) const;
|
||||
CrossSection WarpBatch(
|
||||
std::function<void(VecView<glm::vec2>)> warpFunc) const;
|
||||
CrossSection Simplify(double epsilon = 1e-6) const;
|
||||
|
||||
// Adapted from Clipper2 docs:
|
||||
@@ -169,70 +167,10 @@ class CrossSection {
|
||||
///@}
|
||||
|
||||
private:
|
||||
mutable std::shared_ptr<const C2::PathsD> paths_;
|
||||
mutable std::shared_ptr<const PathImpl> paths_;
|
||||
mutable glm::mat3x2 transform_ = glm::mat3x2(1.0f);
|
||||
CrossSection(C2::PathsD paths);
|
||||
C2::PathsD GetPaths() const;
|
||||
};
|
||||
/** @} */
|
||||
|
||||
/** @addtogroup Connections
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Axis-aligned rectangular bounds.
|
||||
*/
|
||||
class Rect {
|
||||
public:
|
||||
glm::vec2 min = glm::vec2(0);
|
||||
glm::vec2 max = glm::vec2(0);
|
||||
|
||||
/** @name Creation
|
||||
* Constructors
|
||||
*/
|
||||
///@{
|
||||
Rect();
|
||||
~Rect();
|
||||
Rect(const Rect& other);
|
||||
Rect& operator=(const Rect& other);
|
||||
Rect(Rect&&) noexcept;
|
||||
Rect& operator=(Rect&&) noexcept;
|
||||
Rect(const glm::vec2 a, const glm::vec2 b);
|
||||
///@}
|
||||
|
||||
/** @name Information
|
||||
* Details of the rectangle
|
||||
*/
|
||||
///@{
|
||||
glm::vec2 Size() const;
|
||||
float Area() const;
|
||||
float Scale() const;
|
||||
glm::vec2 Center() const;
|
||||
bool Contains(const glm::vec2& pt) const;
|
||||
bool Contains(const Rect& other) const;
|
||||
bool DoesOverlap(const Rect& other) const;
|
||||
bool IsEmpty() const;
|
||||
bool IsFinite() const;
|
||||
///@}
|
||||
|
||||
/** @name Modification
|
||||
*/
|
||||
///@{
|
||||
void Union(const glm::vec2 p);
|
||||
Rect Union(const Rect& other) const;
|
||||
Rect operator+(const glm::vec2 shift) const;
|
||||
Rect& operator+=(const glm::vec2 shift);
|
||||
Rect operator*(const glm::vec2 scale) const;
|
||||
Rect& operator*=(const glm::vec2 scale);
|
||||
Rect Transform(const glm::mat3x2& m) const;
|
||||
///@}
|
||||
|
||||
/** @name Conversion
|
||||
*/
|
||||
///@{
|
||||
CrossSection AsCrossSection() const;
|
||||
///@}
|
||||
CrossSection(std::shared_ptr<const PathImpl> paths);
|
||||
std::shared_ptr<const PathImpl> GetPaths() const;
|
||||
};
|
||||
/** @} */
|
||||
} // namespace manifold
|
||||
|
||||
@@ -14,8 +14,22 @@
|
||||
|
||||
#include "cross_section.h"
|
||||
|
||||
#include "clipper2/clipper.core.h"
|
||||
#include "clipper2/clipper.h"
|
||||
#include "clipper2/clipper.offset.h"
|
||||
|
||||
namespace C2 = Clipper2Lib;
|
||||
|
||||
using namespace manifold;
|
||||
|
||||
namespace manifold {
|
||||
struct PathImpl {
|
||||
PathImpl(const C2::PathsD paths_) : paths_(paths_) {}
|
||||
operator const C2::PathsD&() const { return paths_; }
|
||||
const C2::PathsD paths_;
|
||||
};
|
||||
} // namespace manifold
|
||||
|
||||
namespace {
|
||||
const int precision_ = 8;
|
||||
|
||||
@@ -96,8 +110,8 @@ C2::PathsD transform(const C2::PathsD ps, const glm::mat3x2 m) {
|
||||
return transformed;
|
||||
}
|
||||
|
||||
std::shared_ptr<const C2::PathsD> shared_paths(const C2::PathsD& ps) {
|
||||
return std::make_shared<const C2::PathsD>(ps);
|
||||
std::shared_ptr<const PathImpl> shared_paths(const C2::PathsD& ps) {
|
||||
return std::make_shared<const PathImpl>(ps);
|
||||
}
|
||||
|
||||
// forward declaration for mutual recursion
|
||||
@@ -132,6 +146,18 @@ void decompose_hole(const C2::PolyTreeD* outline,
|
||||
}
|
||||
}
|
||||
|
||||
void flatten(const C2::PolyTreeD* tree, C2::PathsD& polys, int i) {
|
||||
auto n_outlines = tree->Count();
|
||||
if (i < n_outlines) {
|
||||
auto outline = tree->Child(i);
|
||||
flatten(outline, polys, 0);
|
||||
polys.push_back(outline->Polygon());
|
||||
if (i < n_outlines - 1) {
|
||||
flatten(tree, polys, i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool V2Lesser(glm::vec2 a, glm::vec2 b) {
|
||||
if (a.x == b.x) return a.y < b.y;
|
||||
return a.x < b.x;
|
||||
@@ -191,7 +217,9 @@ namespace manifold {
|
||||
/**
|
||||
* The default constructor is an empty cross-section (containing no contours).
|
||||
*/
|
||||
CrossSection::CrossSection() { paths_ = shared_paths(C2::PathsD()); }
|
||||
CrossSection::CrossSection() {
|
||||
paths_ = std::make_shared<const PathImpl>(C2::PathsD());
|
||||
}
|
||||
|
||||
CrossSection::~CrossSection() = default;
|
||||
CrossSection::CrossSection(CrossSection&&) noexcept = default;
|
||||
@@ -218,7 +246,7 @@ CrossSection& CrossSection::operator=(const CrossSection& other) {
|
||||
};
|
||||
|
||||
// Private, skips unioning.
|
||||
CrossSection::CrossSection(C2::PathsD ps) { paths_ = shared_paths(ps); }
|
||||
CrossSection::CrossSection(std::shared_ptr<const PathImpl> ps) { paths_ = ps; }
|
||||
|
||||
/**
|
||||
* Create a 2d cross-section from a single contour. A boolean union operation
|
||||
@@ -271,13 +299,13 @@ CrossSection::CrossSection(const Rect& rect) {
|
||||
// Private
|
||||
// All access to paths_ should be done through the GetPaths() method, which
|
||||
// applies the accumulated transform_
|
||||
C2::PathsD CrossSection::GetPaths() const {
|
||||
std::shared_ptr<const PathImpl> CrossSection::GetPaths() const {
|
||||
if (transform_ == glm::mat3x2(1.0f)) {
|
||||
return *paths_;
|
||||
return paths_;
|
||||
}
|
||||
paths_ = shared_paths(transform(*paths_, transform_));
|
||||
paths_ = shared_paths(::transform(paths_->paths_, transform_));
|
||||
transform_ = glm::mat3x2(1.0f);
|
||||
return *paths_;
|
||||
return paths_;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -309,7 +337,7 @@ CrossSection CrossSection::Square(const glm::vec2 size, bool center) {
|
||||
p[2] = C2::PointD(x, y);
|
||||
p[3] = C2::PointD(0.0, y);
|
||||
}
|
||||
return CrossSection(C2::PathsD{p});
|
||||
return CrossSection(shared_paths(C2::PathsD{p}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -330,7 +358,7 @@ CrossSection CrossSection::Circle(float radius, int circularSegments) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
circle[i] = C2::PointD(radius * cosd(dPhi * i), radius * sind(dPhi * i));
|
||||
}
|
||||
return CrossSection(C2::PathsD{circle});
|
||||
return CrossSection(shared_paths(C2::PathsD{circle}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -339,9 +367,9 @@ CrossSection CrossSection::Circle(float radius, int circularSegments) {
|
||||
CrossSection CrossSection::Boolean(const CrossSection& second,
|
||||
OpType op) const {
|
||||
auto ct = cliptype_of_op(op);
|
||||
auto res = C2::BooleanOp(ct, C2::FillRule::Positive, GetPaths(),
|
||||
second.GetPaths(), precision_);
|
||||
return CrossSection(res);
|
||||
auto res = C2::BooleanOp(ct, C2::FillRule::Positive, GetPaths()->paths_,
|
||||
second.GetPaths()->paths_, precision_);
|
||||
return CrossSection(shared_paths(res));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -358,19 +386,19 @@ CrossSection CrossSection::BatchBoolean(
|
||||
auto subjs = crossSections[0].GetPaths();
|
||||
int n_clips = 0;
|
||||
for (int i = 1; i < crossSections.size(); ++i) {
|
||||
n_clips += crossSections[i].GetPaths().size();
|
||||
n_clips += crossSections[i].GetPaths()->paths_.size();
|
||||
}
|
||||
auto clips = C2::PathsD();
|
||||
clips.reserve(n_clips);
|
||||
for (int i = 1; i < crossSections.size(); ++i) {
|
||||
auto ps = crossSections[i].GetPaths();
|
||||
clips.insert(clips.end(), ps.begin(), ps.end());
|
||||
clips.insert(clips.end(), ps->paths_.begin(), ps->paths_.end());
|
||||
}
|
||||
|
||||
auto ct = cliptype_of_op(op);
|
||||
auto res =
|
||||
C2::BooleanOp(ct, C2::FillRule::Positive, subjs, clips, precision_);
|
||||
return CrossSection(res);
|
||||
auto res = C2::BooleanOp(ct, C2::FillRule::Positive, subjs->paths_, clips,
|
||||
precision_);
|
||||
return CrossSection(shared_paths(res));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -441,7 +469,7 @@ std::vector<CrossSection> CrossSection::Decompose() const {
|
||||
}
|
||||
|
||||
C2::PolyTreeD tree;
|
||||
C2::BooleanOp(C2::ClipType::Union, C2::FillRule::Positive, GetPaths(),
|
||||
C2::BooleanOp(C2::ClipType::Union, C2::FillRule::Positive, GetPaths()->paths_,
|
||||
C2::PathsD(), tree, precision_);
|
||||
|
||||
auto polys = std::vector<C2::PathsD>();
|
||||
@@ -451,7 +479,7 @@ std::vector<CrossSection> CrossSection::Decompose() const {
|
||||
auto comps = std::vector<CrossSection>(n_polys);
|
||||
// reverse the stack while wrapping
|
||||
for (int i = 0; i < n_polys; ++i) {
|
||||
comps[n_polys - i - 1] = CrossSection(polys[i]);
|
||||
comps[n_polys - i - 1] = CrossSection(shared_paths(polys[i]));
|
||||
}
|
||||
|
||||
return comps;
|
||||
@@ -539,20 +567,42 @@ CrossSection CrossSection::Transform(const glm::mat3x2& m) const {
|
||||
*/
|
||||
CrossSection CrossSection::Warp(
|
||||
std::function<void(glm::vec2&)> warpFunc) const {
|
||||
auto paths = GetPaths();
|
||||
auto warped = C2::PathsD();
|
||||
warped.reserve(paths.size());
|
||||
for (auto path : paths) {
|
||||
auto sz = path.size();
|
||||
auto s = C2::PathD(sz);
|
||||
for (int i = 0; i < sz; ++i) {
|
||||
auto v = v2_of_pd(path[i]);
|
||||
warpFunc(v);
|
||||
s[i] = v2_to_pd(v);
|
||||
return WarpBatch([&warpFunc](VecView<glm::vec2> vecs) {
|
||||
for (glm::vec2& p : vecs) {
|
||||
warpFunc(p);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as CrossSection::Warp but calls warpFunc with
|
||||
* a VecView which is roughly equivalent to std::span
|
||||
* pointing to all vec2 elements to be modified in-place
|
||||
*
|
||||
* @param warpFunc A function that modifies multiple vertex positions.
|
||||
*/
|
||||
CrossSection CrossSection::WarpBatch(
|
||||
std::function<void(VecView<glm::vec2>)> warpFunc) const {
|
||||
std::vector<glm::vec2> tmp_verts;
|
||||
C2::PathsD paths = GetPaths()->paths_; // deep copy
|
||||
for (C2::PathD const& path : paths) {
|
||||
for (C2::PointD const& p : path) {
|
||||
tmp_verts.push_back(v2_of_pd(p));
|
||||
}
|
||||
warped.push_back(s);
|
||||
}
|
||||
return CrossSection(C2::Union(warped, C2::FillRule::Positive, precision_));
|
||||
|
||||
warpFunc(VecView<glm::vec2>(tmp_verts.data(), tmp_verts.size()));
|
||||
|
||||
auto cursor = tmp_verts.begin();
|
||||
for (C2::PathD& path : paths) {
|
||||
for (C2::PointD& p : path) {
|
||||
p = v2_to_pd(*cursor);
|
||||
++cursor;
|
||||
}
|
||||
}
|
||||
|
||||
return CrossSection(
|
||||
shared_paths(C2::Union(paths, C2::FillRule::Positive, precision_)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -568,8 +618,29 @@ CrossSection CrossSection::Warp(
|
||||
* offseting operations are to be performed, which would compound the issue.
|
||||
*/
|
||||
CrossSection CrossSection::Simplify(double epsilon) const {
|
||||
auto ps = SimplifyPaths(GetPaths(), epsilon, false);
|
||||
return CrossSection(ps);
|
||||
C2::PolyTreeD tree;
|
||||
C2::BooleanOp(C2::ClipType::Union, C2::FillRule::Positive, GetPaths()->paths_,
|
||||
C2::PathsD(), tree, precision_);
|
||||
|
||||
C2::PathsD polys;
|
||||
flatten(&tree, polys, 0);
|
||||
|
||||
// Filter out contours less than epsilon wide.
|
||||
C2::PathsD filtered;
|
||||
for (C2::PathD poly : polys) {
|
||||
auto area = C2::Area(poly);
|
||||
Rect box;
|
||||
for (auto vert : poly) {
|
||||
box.Union(glm::vec2(vert.x, vert.y));
|
||||
}
|
||||
glm::vec2 size = box.Size();
|
||||
if (glm::abs(area) > glm::max(size.x, size.y) * epsilon) {
|
||||
filtered.push_back(poly);
|
||||
}
|
||||
}
|
||||
|
||||
auto ps = SimplifyPaths(filtered, epsilon, true);
|
||||
return CrossSection(shared_paths(ps));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -607,11 +678,17 @@ CrossSection CrossSection::Offset(double delta, JoinType jointype,
|
||||
arc_tol = (std::cos(Clipper2Lib::PI / n) - 1) * -scaled_delta;
|
||||
}
|
||||
auto ps =
|
||||
C2::InflatePaths(GetPaths(), delta, jt(jointype), C2::EndType::Polygon,
|
||||
miter_limit, precision_, arc_tol);
|
||||
return CrossSection(ps);
|
||||
C2::InflatePaths(GetPaths()->paths_, delta, jt(jointype),
|
||||
C2::EndType::Polygon, miter_limit, precision_, arc_tol);
|
||||
return CrossSection(shared_paths(ps));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the convex hull enveloping a set of cross-sections.
|
||||
*
|
||||
* @param crossSections A vector of cross-sections over which to compute a
|
||||
* convex hull.
|
||||
*/
|
||||
CrossSection CrossSection::Hull(
|
||||
const std::vector<CrossSection>& crossSections) {
|
||||
int n = 0;
|
||||
@@ -619,24 +696,41 @@ CrossSection CrossSection::Hull(
|
||||
SimplePolygon pts;
|
||||
pts.reserve(n);
|
||||
for (auto cs : crossSections) {
|
||||
auto paths = cs.GetPaths();
|
||||
auto paths = cs.GetPaths()->paths_;
|
||||
for (auto path : paths) {
|
||||
for (auto p : path) {
|
||||
pts.push_back(v2_of_pd(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
return CrossSection(C2::PathsD{HullImpl(pts)});
|
||||
return CrossSection(shared_paths(C2::PathsD{HullImpl(pts)}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the convex hull of this cross-section.
|
||||
*/
|
||||
CrossSection CrossSection::Hull() const {
|
||||
return Hull(std::vector<CrossSection>{*this});
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the convex hull of a set of points. If the given points are fewer
|
||||
* than 3, an empty CrossSection will be returned.
|
||||
*
|
||||
* @param pts A vector of 2-dimensional points over which to compute a convex
|
||||
* hull.
|
||||
*/
|
||||
CrossSection CrossSection::Hull(SimplePolygon pts) {
|
||||
return CrossSection(C2::PathsD{HullImpl(pts)});
|
||||
return CrossSection(shared_paths(C2::PathsD{HullImpl(pts)}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the convex hull of a set of points/polygons. If the given points are
|
||||
* fewer than 3, an empty CrossSection will be returned.
|
||||
*
|
||||
* @param pts A vector of vectors of 2-dimensional points over which to compute
|
||||
* a convex hull.
|
||||
*/
|
||||
CrossSection CrossSection::Hull(const Polygons polys) {
|
||||
SimplePolygon pts;
|
||||
for (auto poly : polys) {
|
||||
@@ -651,14 +745,14 @@ CrossSection CrossSection::Hull(const Polygons polys) {
|
||||
* Return the total area covered by complex polygons making up the
|
||||
* CrossSection.
|
||||
*/
|
||||
double CrossSection::Area() const { return C2::Area(GetPaths()); }
|
||||
double CrossSection::Area() const { return C2::Area(GetPaths()->paths_); }
|
||||
|
||||
/**
|
||||
* Return the number of vertices in the CrossSection.
|
||||
*/
|
||||
int CrossSection::NumVert() const {
|
||||
int n = 0;
|
||||
auto paths = GetPaths();
|
||||
auto paths = GetPaths()->paths_;
|
||||
for (auto p : paths) {
|
||||
n += p.size();
|
||||
}
|
||||
@@ -669,19 +763,19 @@ int CrossSection::NumVert() const {
|
||||
* Return the number of contours (both outer and inner paths) in the
|
||||
* CrossSection.
|
||||
*/
|
||||
int CrossSection::NumContour() const { return GetPaths().size(); }
|
||||
int CrossSection::NumContour() const { return GetPaths()->paths_.size(); }
|
||||
|
||||
/**
|
||||
* Does the CrossSection contain any contours?
|
||||
*/
|
||||
bool CrossSection::IsEmpty() const { return GetPaths().empty(); }
|
||||
bool CrossSection::IsEmpty() const { return GetPaths()->paths_.empty(); }
|
||||
|
||||
/**
|
||||
* Returns the axis-aligned bounding rectangle of all the CrossSections'
|
||||
* vertices.
|
||||
*/
|
||||
Rect CrossSection::Bounds() const {
|
||||
auto r = C2::GetBounds(GetPaths());
|
||||
auto r = C2::GetBounds(GetPaths()->paths_);
|
||||
return Rect({r.left, r.bottom}, {r.right, r.top});
|
||||
}
|
||||
|
||||
@@ -690,7 +784,7 @@ Rect CrossSection::Bounds() const {
|
||||
*/
|
||||
Polygons CrossSection::ToPolygons() const {
|
||||
auto polys = Polygons();
|
||||
auto paths = GetPaths();
|
||||
auto paths = GetPaths()->paths_;
|
||||
polys.reserve(paths.size());
|
||||
for (auto p : paths) {
|
||||
auto sp = SimplePolygon();
|
||||
@@ -702,167 +796,4 @@ Polygons CrossSection::ToPolygons() const {
|
||||
}
|
||||
return polys;
|
||||
}
|
||||
|
||||
// Rect
|
||||
|
||||
/**
|
||||
* Default constructor is an empty rectangle..
|
||||
*/
|
||||
Rect::Rect() {}
|
||||
|
||||
Rect::~Rect() = default;
|
||||
Rect::Rect(Rect&&) noexcept = default;
|
||||
Rect& Rect::operator=(Rect&&) noexcept = default;
|
||||
Rect::Rect(const Rect& other) {
|
||||
min = glm::vec2(other.min);
|
||||
max = glm::vec2(other.max);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a rectangle that contains the two given points.
|
||||
*/
|
||||
Rect::Rect(const glm::vec2 a, const glm::vec2 b) {
|
||||
min = glm::min(a, b);
|
||||
max = glm::max(a, b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the dimensions of the rectangle.
|
||||
*/
|
||||
glm::vec2 Rect::Size() const { return max - min; }
|
||||
|
||||
/**
|
||||
* Return the area of the rectangle.
|
||||
*/
|
||||
float Rect::Area() const {
|
||||
auto sz = Size();
|
||||
return sz.x * sz.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute-largest coordinate value of any contained
|
||||
* point.
|
||||
*/
|
||||
float Rect::Scale() const {
|
||||
glm::vec2 absMax = glm::max(glm::abs(min), glm::abs(max));
|
||||
return glm::max(absMax.x, absMax.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the center point of the rectangle.
|
||||
*/
|
||||
glm::vec2 Rect::Center() const { return 0.5f * (max + min); }
|
||||
|
||||
/**
|
||||
* Does this rectangle contain (includes on border) the given point?
|
||||
*/
|
||||
bool Rect::Contains(const glm::vec2& p) const {
|
||||
return glm::all(glm::greaterThanEqual(p, min)) &&
|
||||
glm::all(glm::greaterThanEqual(max, p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this rectangle contain (includes equal) the given rectangle?
|
||||
*/
|
||||
bool Rect::Contains(const Rect& rect) const {
|
||||
return glm::all(glm::greaterThanEqual(rect.min, min)) &&
|
||||
glm::all(glm::greaterThanEqual(max, rect.max));
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this rectangle overlap the one given (including equality)?
|
||||
*/
|
||||
bool Rect::DoesOverlap(const Rect& rect) const {
|
||||
return min.x <= rect.max.x && min.y <= rect.max.y && max.x >= rect.min.x &&
|
||||
max.y >= rect.min.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the rectangle empty (containing no space)?
|
||||
*/
|
||||
bool Rect::IsEmpty() const { return max.y <= min.y || max.x <= min.x; };
|
||||
|
||||
/**
|
||||
* Does this recangle have finite bounds?
|
||||
*/
|
||||
bool Rect::IsFinite() const {
|
||||
return glm::all(glm::isfinite(min)) && glm::all(glm::isfinite(max));
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand this rectangle (in place) to include the given point.
|
||||
*/
|
||||
void Rect::Union(const glm::vec2 p) {
|
||||
min = glm::min(min, p);
|
||||
max = glm::max(max, p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand this rectangle to include the given Rect.
|
||||
*/
|
||||
Rect Rect::Union(const Rect& rect) const {
|
||||
Rect out;
|
||||
out.min = glm::min(min, rect.min);
|
||||
out.max = glm::max(max, rect.max);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift this rectangle by the given vector.
|
||||
*/
|
||||
Rect Rect::operator+(const glm::vec2 shift) const {
|
||||
Rect out;
|
||||
out.min = min + shift;
|
||||
out.max = max + shift;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift this rectangle in-place by the given vector.
|
||||
*/
|
||||
Rect& Rect::operator+=(const glm::vec2 shift) {
|
||||
min += shift;
|
||||
max += shift;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale this rectangle by the given vector.
|
||||
*/
|
||||
Rect Rect::operator*(const glm::vec2 scale) const {
|
||||
Rect out;
|
||||
out.min = min * scale;
|
||||
out.max = max * scale;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale this rectangle in-place by the given vector.
|
||||
*/
|
||||
Rect& Rect::operator*=(const glm::vec2 scale) {
|
||||
min *= scale;
|
||||
max *= scale;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the rectangle by the given axis-aligned affine transform.
|
||||
*
|
||||
* Ensure the transform passed in is axis-aligned (rotations are all
|
||||
* multiples of 90 degrees), or else the resulting rectangle will no longer
|
||||
* bound properly.
|
||||
*/
|
||||
Rect Rect::Transform(const glm::mat3x2& m) const {
|
||||
Rect rect;
|
||||
rect.min = m * glm::vec3(min, 1);
|
||||
rect.max = m * glm::vec3(max, 1);
|
||||
return rect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a CrossSection with an outline defined by this axis-aligned
|
||||
* rectangle.
|
||||
*/
|
||||
CrossSection Rect::AsCrossSection() const { return CrossSection(*this); }
|
||||
|
||||
} // namespace manifold
|
||||
|
||||
@@ -17,17 +17,26 @@ project (manifold)
|
||||
file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.cpp)
|
||||
add_library(${PROJECT_NAME} ${SOURCE_FILES})
|
||||
|
||||
if(MANIFOLD_USE_CUDA)
|
||||
set_source_files_properties(${SOURCE_FILES} PROPERTIES LANGUAGE CUDA)
|
||||
set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES 61)
|
||||
endif()
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC utilities cross_section
|
||||
PRIVATE collider polygon ${MANIFOLD_INCLUDE} graphlite Clipper2 quickhull
|
||||
PRIVATE collider polygon ${MANIFOLD_INCLUDE} Clipper2 quickhull
|
||||
)
|
||||
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
|
||||
|
||||
target_compile_features(${PROJECT_NAME}
|
||||
PUBLIC cxx_std_17
|
||||
)
|
||||
|
||||
install(
|
||||
TARGETS ${PROJECT_NAME}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
|
||||
COMPONENT runtime
|
||||
)
|
||||
install(
|
||||
DIRECTORY include/
|
||||
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
|
||||
COMPONENT devel
|
||||
)
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "public.h"
|
||||
#include "vec_view.h"
|
||||
|
||||
namespace manifold {
|
||||
|
||||
@@ -206,6 +207,7 @@ class Manifold {
|
||||
Manifold Transform(const glm::mat4x3&) const;
|
||||
Manifold Mirror(glm::vec3) const;
|
||||
Manifold Warp(std::function<void(glm::vec3&)>) const;
|
||||
Manifold WarpBatch(std::function<void(VecView<glm::vec3>)>) const;
|
||||
Manifold SetProperties(
|
||||
int, std::function<void(float*, glm::vec3, const float*)>) const;
|
||||
Manifold CalculateCurvature(int gaussianIdx, int meanIdx) const;
|
||||
@@ -234,9 +236,20 @@ class Manifold {
|
||||
Manifold TrimByPlane(glm::vec3 normal, float originOffset) const;
|
||||
///@}
|
||||
|
||||
/** @name 2D from 3D
|
||||
*/
|
||||
///@{
|
||||
CrossSection Slice(float height = 0) const;
|
||||
CrossSection Project() const;
|
||||
///@}
|
||||
|
||||
/** @name Convex hull
|
||||
*/
|
||||
///@{
|
||||
Manifold Hull() const;
|
||||
static Manifold Hull(const std::vector<Manifold>& manifolds);
|
||||
static Manifold Hull(const std::vector<glm::vec3>& pts);
|
||||
///@}
|
||||
|
||||
/** @name Testing hooks
|
||||
* These are just for internal testing.
|
||||
|
||||
+186
-175
@@ -27,7 +27,7 @@ namespace {
|
||||
// carefully designed to minimize rounding error and to eliminate it at edge
|
||||
// cases to ensure consistency.
|
||||
|
||||
__host__ __device__ glm::vec2 Interpolate(glm::vec3 pL, glm::vec3 pR, float x) {
|
||||
glm::vec2 Interpolate(glm::vec3 pL, glm::vec3 pR, float x) {
|
||||
float dxL = x - pL.x;
|
||||
float dxR = x - pR.x;
|
||||
#ifdef MANIFOLD_DEBUG
|
||||
@@ -42,10 +42,8 @@ __host__ __device__ glm::vec2 Interpolate(glm::vec3 pL, glm::vec3 pR, float x) {
|
||||
return yz;
|
||||
}
|
||||
|
||||
__host__ __device__ glm::vec4 Intersect(const glm::vec3 &pL,
|
||||
const glm::vec3 &pR,
|
||||
const glm::vec3 &qL,
|
||||
const glm::vec3 &qR) {
|
||||
glm::vec4 Intersect(const glm::vec3 &pL, const glm::vec3 &pR,
|
||||
const glm::vec3 &qL, const glm::vec3 &qR) {
|
||||
float dyL = qL.y - pL.y;
|
||||
float dyR = qR.y - pR.y;
|
||||
#ifdef MANIFOLD_DEBUG
|
||||
@@ -67,42 +65,44 @@ __host__ __device__ glm::vec4 Intersect(const glm::vec3 &pL,
|
||||
return xyzz;
|
||||
}
|
||||
|
||||
template <const bool inverted>
|
||||
struct CopyFaceEdges {
|
||||
const SparseIndices &p1q1;
|
||||
// const int *p1q1;
|
||||
// x can be either vert or edge (0 or 1).
|
||||
thrust::pair<int *, int *> pXq1;
|
||||
const Halfedge *halfedgesQ;
|
||||
SparseIndices &pXq1;
|
||||
VecView<const Halfedge> halfedgesQ;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<int, int, int> in) {
|
||||
void operator()(thrust::tuple<int, int> in) {
|
||||
int idx = 3 * thrust::get<0>(in);
|
||||
const int pX = thrust::get<1>(in);
|
||||
const int q2 = thrust::get<2>(in);
|
||||
int i = thrust::get<1>(in);
|
||||
int pX = p1q1.Get(i, inverted);
|
||||
int q2 = p1q1.Get(i, !inverted);
|
||||
|
||||
for (const int i : {0, 1, 2}) {
|
||||
pXq1.first[idx + i] = pX;
|
||||
const int q1 = 3 * q2 + i;
|
||||
for (const int j : {0, 1, 2}) {
|
||||
const int q1 = 3 * q2 + j;
|
||||
const Halfedge edge = halfedgesQ[q1];
|
||||
pXq1.second[idx + i] = edge.IsForward() ? q1 : edge.pairedHalfedge;
|
||||
int a = pX;
|
||||
int b = edge.IsForward() ? q1 : edge.pairedHalfedge;
|
||||
if (inverted) std::swap(a, b);
|
||||
pXq1.Set(idx + j, a, b);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SparseIndices Filter11(const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
const SparseIndices &p1q2, const SparseIndices &p2q1,
|
||||
ExecutionPolicy policy) {
|
||||
const SparseIndices &p1q2, const SparseIndices &p2q1) {
|
||||
ZoneScoped;
|
||||
SparseIndices p1q1(3 * p1q2.size() + 3 * p2q1.size());
|
||||
for_each_n(policy, zip(countAt(0), p1q2.begin(0), p1q2.begin(1)), p1q2.size(),
|
||||
CopyFaceEdges({p1q1.ptrDpq(), inQ.halfedge_.cptrD()}));
|
||||
|
||||
p1q1.SwapPQ();
|
||||
for_each_n(policy, zip(countAt(p1q2.size()), p2q1.begin(1), p2q1.begin(0)),
|
||||
p2q1.size(),
|
||||
CopyFaceEdges({p1q1.ptrDpq(), inP.halfedge_.cptrD()}));
|
||||
p1q1.SwapPQ();
|
||||
p1q1.Unique(policy);
|
||||
for_each_n(autoPolicy(p1q2.size()), zip(countAt(0), countAt(0)), p1q2.size(),
|
||||
CopyFaceEdges<false>({p1q2, p1q1, inQ.halfedge_}));
|
||||
for_each_n(autoPolicy(p2q1.size()), zip(countAt(p1q2.size()), countAt(0)),
|
||||
p2q1.size(), CopyFaceEdges<true>({p2q1, p1q1, inP.halfedge_}));
|
||||
p1q1.Unique();
|
||||
return p1q1;
|
||||
}
|
||||
|
||||
__host__ __device__ bool Shadows(float p, float q, float dir) {
|
||||
inline bool Shadows(float p, float q, float dir) {
|
||||
return p == q ? dir < 0 : p < q;
|
||||
}
|
||||
|
||||
@@ -117,10 +117,10 @@ __host__ __device__ bool Shadows(float p, float q, float dir) {
|
||||
* compiled function (they must agree on CPU or GPU). This is now taken care of
|
||||
* by the shared policy_ member.
|
||||
*/
|
||||
__host__ __device__ thrust::pair<int, glm::vec2> Shadow01(
|
||||
const int p0, const int q1, const glm::vec3 *vertPosP,
|
||||
const glm::vec3 *vertPosQ, const Halfedge *halfedgeQ, const float expandP,
|
||||
const glm::vec3 *normalP, const bool reverse) {
|
||||
inline thrust::pair<int, glm::vec2> Shadow01(
|
||||
const int p0, const int q1, VecView<const glm::vec3> vertPosP,
|
||||
VecView<const glm::vec3> vertPosQ, VecView<const Halfedge> halfedgeQ,
|
||||
const float expandP, VecView<const glm::vec3> normalP, const bool reverse) {
|
||||
const int q1s = halfedgeQ[q1].startVert;
|
||||
const int q1e = halfedgeQ[q1].endVert;
|
||||
const float p0x = vertPosP[p0].x;
|
||||
@@ -148,43 +148,59 @@ __host__ __device__ thrust::pair<int, glm::vec2> Shadow01(
|
||||
return thrust::make_pair(s01, yz01);
|
||||
}
|
||||
|
||||
__host__ __device__ int BinarySearch(
|
||||
const thrust::pair<const int *, const int *> keys, const int size,
|
||||
const thrust::pair<int, int> key) {
|
||||
if (size <= 0) return -1;
|
||||
int left = 0;
|
||||
int right = size - 1;
|
||||
int m;
|
||||
thrust::pair<int, int> keyM;
|
||||
while (1) {
|
||||
m = right - (right - left) / 2;
|
||||
keyM = thrust::make_pair(keys.first[m], keys.second[m]);
|
||||
if (left == right) break;
|
||||
if (keyM > key)
|
||||
right = m - 1;
|
||||
else
|
||||
left = m;
|
||||
}
|
||||
if (keyM == key)
|
||||
return m;
|
||||
else
|
||||
// https://github.com/scandum/binary_search/blob/master/README.md
|
||||
// much faster than standard binary search on large arrays
|
||||
int monobound_quaternary_search(VecView<const int64_t> array, int64_t key) {
|
||||
if (array.size() == 0) {
|
||||
return -1;
|
||||
}
|
||||
unsigned int bot = 0;
|
||||
unsigned int top = array.size();
|
||||
while (top >= 65536) {
|
||||
unsigned int mid = top / 4;
|
||||
top -= mid * 3;
|
||||
if (key < array[bot + mid * 2]) {
|
||||
if (key >= array[bot + mid]) {
|
||||
bot += mid;
|
||||
}
|
||||
} else {
|
||||
bot += mid * 2;
|
||||
if (key >= array[bot + mid]) {
|
||||
bot += mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (top > 3) {
|
||||
unsigned int mid = top / 2;
|
||||
if (key >= array[bot + mid]) {
|
||||
bot += mid;
|
||||
}
|
||||
top -= mid;
|
||||
}
|
||||
|
||||
while (top--) {
|
||||
if (key == array[bot + top]) {
|
||||
return bot + top;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct Kernel11 {
|
||||
const glm::vec3 *vertPosP;
|
||||
const glm::vec3 *vertPosQ;
|
||||
const Halfedge *halfedgeP;
|
||||
const Halfedge *halfedgeQ;
|
||||
VecView<const glm::vec3> vertPosP;
|
||||
VecView<const glm::vec3> vertPosQ;
|
||||
VecView<const Halfedge> halfedgeP;
|
||||
VecView<const Halfedge> halfedgeQ;
|
||||
float expandP;
|
||||
const glm::vec3 *normalP;
|
||||
VecView<const glm::vec3> normalP;
|
||||
const SparseIndices &p1q1;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
thrust::tuple<glm::vec4 &, int &, int, int> inout) {
|
||||
glm::vec4 &xyzz11 = thrust::get<0>(inout);
|
||||
int &s11 = thrust::get<1>(inout);
|
||||
const int p1 = thrust::get<2>(inout);
|
||||
const int q1 = thrust::get<3>(inout);
|
||||
void operator()(thrust::tuple<int, glm::vec4 &, int &> inout) {
|
||||
const int p1 = p1q1.Get(thrust::get<0>(inout), false);
|
||||
const int q1 = p1q1.Get(thrust::get<0>(inout), true);
|
||||
glm::vec4 &xyzz11 = thrust::get<1>(inout);
|
||||
int &s11 = thrust::get<2>(inout);
|
||||
|
||||
// For pRL[k], qRL[k], k==0 is the left and k==1 is the right.
|
||||
int k = 0;
|
||||
@@ -254,20 +270,18 @@ struct Kernel11 {
|
||||
}
|
||||
};
|
||||
|
||||
std::tuple<VecDH<int>, VecDH<glm::vec4>> Shadow11(SparseIndices &p1q1,
|
||||
const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ,
|
||||
float expandP,
|
||||
ExecutionPolicy policy) {
|
||||
VecDH<int> s11(p1q1.size());
|
||||
VecDH<glm::vec4> xyzz11(p1q1.size());
|
||||
std::tuple<Vec<int>, Vec<glm::vec4>> Shadow11(SparseIndices &p1q1,
|
||||
const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ,
|
||||
float expandP) {
|
||||
ZoneScoped;
|
||||
Vec<int> s11(p1q1.size());
|
||||
Vec<glm::vec4> xyzz11(p1q1.size());
|
||||
|
||||
for_each_n(policy,
|
||||
zip(xyzz11.begin(), s11.begin(), p1q1.begin(0), p1q1.begin(1)),
|
||||
p1q1.size(),
|
||||
Kernel11({inP.vertPos_.cptrD(), inQ.vertPos_.cptrD(),
|
||||
inP.halfedge_.cptrD(), inQ.halfedge_.cptrD(), expandP,
|
||||
inP.vertNormal_.cptrD()}));
|
||||
for_each_n(autoPolicy(p1q1.size()),
|
||||
zip(countAt(0), xyzz11.begin(), s11.begin()), p1q1.size(),
|
||||
Kernel11({inP.vertPos_, inQ.vertPos_, inP.halfedge_, inQ.halfedge_,
|
||||
expandP, inP.vertNormal_, p1q1}));
|
||||
|
||||
p1q1.KeepFinite(xyzz11, s11);
|
||||
|
||||
@@ -275,19 +289,19 @@ std::tuple<VecDH<int>, VecDH<glm::vec4>> Shadow11(SparseIndices &p1q1,
|
||||
};
|
||||
|
||||
struct Kernel02 {
|
||||
const glm::vec3 *vertPosP;
|
||||
const Halfedge *halfedgeQ;
|
||||
const glm::vec3 *vertPosQ;
|
||||
const bool forward;
|
||||
VecView<const glm::vec3> vertPosP;
|
||||
VecView<const Halfedge> halfedgeQ;
|
||||
VecView<const glm::vec3> vertPosQ;
|
||||
const float expandP;
|
||||
const glm::vec3 *vertNormalP;
|
||||
VecView<const glm::vec3> vertNormalP;
|
||||
const SparseIndices &p0q2;
|
||||
const bool forward;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
thrust::tuple<int &, float &, int, int> inout) {
|
||||
int &s02 = thrust::get<0>(inout);
|
||||
float &z02 = thrust::get<1>(inout);
|
||||
const int p0 = thrust::get<2>(inout);
|
||||
const int q2 = thrust::get<3>(inout);
|
||||
void operator()(thrust::tuple<int, int &, float &> inout) {
|
||||
const int p0 = p0q2.Get(thrust::get<0>(inout), !forward);
|
||||
const int q2 = p0q2.Get(thrust::get<0>(inout), forward);
|
||||
int &s02 = thrust::get<1>(inout);
|
||||
float &z02 = thrust::get<2>(inout);
|
||||
|
||||
// For yzzLR[k], k==0 is the left and k==1 is the right.
|
||||
int k = 0;
|
||||
@@ -351,22 +365,19 @@ struct Kernel02 {
|
||||
}
|
||||
};
|
||||
|
||||
std::tuple<VecDH<int>, VecDH<float>> Shadow02(const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ,
|
||||
SparseIndices &p0q2, bool forward,
|
||||
float expandP,
|
||||
ExecutionPolicy policy) {
|
||||
VecDH<int> s02(p0q2.size());
|
||||
VecDH<float> z02(p0q2.size());
|
||||
std::tuple<Vec<int>, Vec<float>> Shadow02(const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ,
|
||||
SparseIndices &p0q2, bool forward,
|
||||
float expandP) {
|
||||
ZoneScoped;
|
||||
Vec<int> s02(p0q2.size());
|
||||
Vec<float> z02(p0q2.size());
|
||||
|
||||
auto vertNormalP =
|
||||
forward ? inP.vertNormal_.cptrD() : inQ.vertNormal_.cptrD();
|
||||
for_each_n(
|
||||
policy,
|
||||
zip(s02.begin(), z02.begin(), p0q2.begin(!forward), p0q2.begin(forward)),
|
||||
p0q2.size(),
|
||||
Kernel02({inP.vertPos_.cptrD(), inQ.halfedge_.cptrD(),
|
||||
inQ.vertPos_.cptrD(), forward, expandP, vertNormalP}));
|
||||
auto vertNormalP = forward ? inP.vertNormal_ : inQ.vertNormal_;
|
||||
for_each_n(autoPolicy(p0q2.size()), zip(countAt(0), s02.begin(), z02.begin()),
|
||||
p0q2.size(),
|
||||
Kernel02({inP.vertPos_, inQ.halfedge_, inQ.vertPos_, expandP,
|
||||
vertNormalP, p0q2, forward}));
|
||||
|
||||
p0q2.KeepFinite(z02, s02);
|
||||
|
||||
@@ -374,25 +385,23 @@ std::tuple<VecDH<int>, VecDH<float>> Shadow02(const Manifold::Impl &inP,
|
||||
};
|
||||
|
||||
struct Kernel12 {
|
||||
const thrust::pair<const int *, const int *> p0q2;
|
||||
const int *s02;
|
||||
const float *z02;
|
||||
const int size02;
|
||||
const thrust::pair<const int *, const int *> p1q1;
|
||||
const int *s11;
|
||||
const glm::vec4 *xyzz11;
|
||||
const int size11;
|
||||
const Halfedge *halfedgesP;
|
||||
const Halfedge *halfedgesQ;
|
||||
const glm::vec3 *vertPosP;
|
||||
VecView<const int64_t> p0q2;
|
||||
VecView<const int> s02;
|
||||
VecView<const float> z02;
|
||||
VecView<const int64_t> p1q1;
|
||||
VecView<const int> s11;
|
||||
VecView<const glm::vec4> xyzz11;
|
||||
VecView<const Halfedge> halfedgesP;
|
||||
VecView<const Halfedge> halfedgesQ;
|
||||
VecView<const glm::vec3> vertPosP;
|
||||
const bool forward;
|
||||
const SparseIndices &p1q2;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
thrust::tuple<int &, glm::vec3 &, int, int> inout) {
|
||||
int &x12 = thrust::get<0>(inout);
|
||||
glm::vec3 &v12 = thrust::get<1>(inout);
|
||||
const int p1 = thrust::get<2>(inout);
|
||||
const int q2 = thrust::get<3>(inout);
|
||||
void operator()(thrust::tuple<int, int &, glm::vec3 &> inout) {
|
||||
int p1 = p1q2.Get(thrust::get<0>(inout), !forward);
|
||||
int q2 = p1q2.Get(thrust::get<0>(inout), forward);
|
||||
int &x12 = thrust::get<1>(inout);
|
||||
glm::vec3 &v12 = thrust::get<2>(inout);
|
||||
|
||||
// For xzyLR-[k], k==0 is the left and k==1 is the right.
|
||||
int k = 0;
|
||||
@@ -406,9 +415,9 @@ struct Kernel12 {
|
||||
const Halfedge edge = halfedgesP[p1];
|
||||
|
||||
for (int vert : {edge.startVert, edge.endVert}) {
|
||||
const auto key =
|
||||
forward ? thrust::make_pair(vert, q2) : thrust::make_pair(q2, vert);
|
||||
const int idx = BinarySearch(p0q2, size02, key);
|
||||
const int64_t key = forward ? SparseIndices::EncodePQ(vert, q2)
|
||||
: SparseIndices::EncodePQ(q2, vert);
|
||||
const int idx = monobound_quaternary_search(p0q2, key);
|
||||
if (idx != -1) {
|
||||
const int s = s02[idx];
|
||||
x12 += s * ((vert == edge.startVert) == forward ? 1 : -1);
|
||||
@@ -427,9 +436,9 @@ struct Kernel12 {
|
||||
const int q1 = 3 * q2 + i;
|
||||
const Halfedge edge = halfedgesQ[q1];
|
||||
const int q1F = edge.IsForward() ? q1 : edge.pairedHalfedge;
|
||||
const auto key =
|
||||
forward ? thrust::make_pair(p1, q1F) : thrust::make_pair(q1F, p1);
|
||||
const int idx = BinarySearch(p1q1, size11, key);
|
||||
const int64_t key = forward ? SparseIndices::EncodePQ(p1, q1F)
|
||||
: SparseIndices::EncodePQ(q1F, p1);
|
||||
const int idx = monobound_quaternary_search(p1q1, key);
|
||||
if (idx != -1) { // s is implicitly zero for anything not found
|
||||
const int s = s11[idx];
|
||||
x12 -= s * (edge.IsForward() ? 1 : -1);
|
||||
@@ -465,42 +474,46 @@ struct Kernel12 {
|
||||
}
|
||||
};
|
||||
|
||||
std::tuple<VecDH<int>, VecDH<glm::vec3>> Intersect12(
|
||||
const Manifold::Impl &inP, const Manifold::Impl &inQ, const VecDH<int> &s02,
|
||||
const SparseIndices &p0q2, const VecDH<int> &s11, const SparseIndices &p1q1,
|
||||
const VecDH<float> &z02, const VecDH<glm::vec4> &xyzz11,
|
||||
SparseIndices &p1q2, bool forward, ExecutionPolicy policy) {
|
||||
VecDH<int> x12(p1q2.size());
|
||||
VecDH<glm::vec3> v12(p1q2.size());
|
||||
std::tuple<Vec<int>, Vec<glm::vec3>> Intersect12(
|
||||
const Manifold::Impl &inP, const Manifold::Impl &inQ, const Vec<int> &s02,
|
||||
const SparseIndices &p0q2, const Vec<int> &s11, const SparseIndices &p1q1,
|
||||
const Vec<float> &z02, const Vec<glm::vec4> &xyzz11, SparseIndices &p1q2,
|
||||
bool forward) {
|
||||
ZoneScoped;
|
||||
Vec<int> x12(p1q2.size());
|
||||
Vec<glm::vec3> v12(p1q2.size());
|
||||
|
||||
for_each_n(
|
||||
policy,
|
||||
zip(x12.begin(), v12.begin(), p1q2.begin(!forward), p1q2.begin(forward)),
|
||||
autoPolicy(p1q2.size()), zip(countAt(0), x12.begin(), v12.begin()),
|
||||
p1q2.size(),
|
||||
Kernel12({p0q2.ptrDpq(), s02.ptrD(), z02.cptrD(), p0q2.size(),
|
||||
p1q1.ptrDpq(), s11.ptrD(), xyzz11.cptrD(), p1q1.size(),
|
||||
inP.halfedge_.cptrD(), inQ.halfedge_.cptrD(),
|
||||
inP.vertPos_.cptrD(), forward}));
|
||||
Kernel12({p0q2.AsVec64(), s02, z02, p1q1.AsVec64(), s11, xyzz11,
|
||||
inP.halfedge_, inQ.halfedge_, inP.vertPos_, forward, p1q2}));
|
||||
|
||||
p1q2.KeepFinite(v12, x12);
|
||||
|
||||
return std::make_tuple(x12, v12);
|
||||
};
|
||||
|
||||
VecDH<int> Winding03(const Manifold::Impl &inP, SparseIndices &p0q2,
|
||||
VecDH<int> &s02, bool reverse, ExecutionPolicy policy) {
|
||||
Vec<int> Winding03(const Manifold::Impl &inP, Vec<int> &vertices, Vec<int> &s02,
|
||||
bool reverse) {
|
||||
ZoneScoped;
|
||||
// verts that are not shadowed (not in p0q2) have winding number zero.
|
||||
VecDH<int> w03(inP.NumVert(), 0);
|
||||
|
||||
if (!is_sorted(policy, p0q2.begin(reverse), p0q2.end(reverse)))
|
||||
sort_by_key(policy, p0q2.begin(reverse), p0q2.end(reverse), s02.begin());
|
||||
VecDH<int> w03val(w03.size());
|
||||
VecDH<int> w03vert(w03.size());
|
||||
Vec<int> w03(inP.NumVert(), 0);
|
||||
// checking is slow, so just sort and reduce
|
||||
auto policy = autoPolicy(vertices.size());
|
||||
stable_sort(
|
||||
policy, zip(vertices.begin(), s02.begin()),
|
||||
zip(vertices.end(), s02.end()),
|
||||
[](const thrust::tuple<int, int> &a, const thrust::tuple<int, int> &b) {
|
||||
return thrust::get<0>(a) < thrust::get<0>(b);
|
||||
});
|
||||
Vec<int> w03val(w03.size());
|
||||
Vec<int> w03vert(w03.size());
|
||||
// sum known s02 values into w03 (winding number)
|
||||
auto endPair = reduce_by_key<
|
||||
thrust::pair<decltype(w03val.begin()), decltype(w03val.begin())>>(
|
||||
policy, p0q2.begin(reverse), p0q2.end(reverse), s02.begin(),
|
||||
w03vert.begin(), w03val.begin());
|
||||
policy, vertices.begin(), vertices.end(), s02.begin(), w03vert.begin(),
|
||||
w03val.begin());
|
||||
scatter(policy, w03val.begin(), endPair.second, w03vert.begin(), w03.begin());
|
||||
|
||||
if (reverse)
|
||||
@@ -513,10 +526,7 @@ VecDH<int> Winding03(const Manifold::Impl &inP, SparseIndices &p0q2,
|
||||
namespace manifold {
|
||||
Boolean3::Boolean3(const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
OpType op)
|
||||
: inP_(inP),
|
||||
inQ_(inQ),
|
||||
expandP_(op == OpType::Add ? 1.0 : -1.0),
|
||||
policy_(autoPolicy(glm::max(inP.NumEdge(), inQ.NumEdge()))) {
|
||||
: inP_(inP), inQ_(inQ), expandP_(op == OpType::Add ? 1.0 : -1.0) {
|
||||
// Symbolic perturbation:
|
||||
// Union -> expand inP
|
||||
// Difference, Intersection -> contract inP
|
||||
@@ -536,29 +546,26 @@ Boolean3::Boolean3(const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
// Level 3
|
||||
// Find edge-triangle overlaps (broad phase)
|
||||
p1q2_ = inQ_.EdgeCollisions(inP_);
|
||||
p2q1_ = inP_.EdgeCollisions(inQ_);
|
||||
p2q1_ = inP_.EdgeCollisions(inQ_, true); // inverted
|
||||
|
||||
policy_ = autoPolicy(glm::max(p1q2_.size(), p2q1_.size()));
|
||||
p1q2_.Sort(policy_);
|
||||
p1q2_.Sort();
|
||||
PRINT("p1q2 size = " << p1q2_.size());
|
||||
|
||||
p2q1_.SwapPQ();
|
||||
p2q1_.Sort(policy_);
|
||||
p2q1_.Sort();
|
||||
PRINT("p2q1 size = " << p2q1_.size());
|
||||
|
||||
// Level 2
|
||||
// Find vertices that overlap faces in XY-projection
|
||||
SparseIndices p0q2 = inQ.VertexCollisionsZ(inP.vertPos_);
|
||||
p0q2.Sort(policy_);
|
||||
p0q2.Sort();
|
||||
PRINT("p0q2 size = " << p0q2.size());
|
||||
|
||||
SparseIndices p2q0 = inP.VertexCollisionsZ(inQ.vertPos_);
|
||||
p2q0.SwapPQ();
|
||||
p2q0.Sort(policy_);
|
||||
SparseIndices p2q0 = inP.VertexCollisionsZ(inQ.vertPos_, true); // inverted
|
||||
p2q0.Sort();
|
||||
PRINT("p2q0 size = " << p2q0.size());
|
||||
|
||||
// Find involved edge pairs from Level 3
|
||||
SparseIndices p1q1 = Filter11(inP_, inQ_, p1q2_, p2q1_, policy_);
|
||||
SparseIndices p1q1 = Filter11(inP_, inQ_, p1q2_, p2q1_);
|
||||
PRINT("p1q1 size = " << p1q1.size());
|
||||
|
||||
#ifdef MANIFOLD_DEBUG
|
||||
@@ -570,39 +577,43 @@ Boolean3::Boolean3(const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
// Level 2
|
||||
// Build up XY-projection intersection of two edges, including the z-value for
|
||||
// each edge, keeping only those whose intersection exists.
|
||||
VecDH<int> s11;
|
||||
VecDH<glm::vec4> xyzz11;
|
||||
std::tie(s11, xyzz11) = Shadow11(p1q1, inP, inQ, expandP_, policy_);
|
||||
Vec<int> s11;
|
||||
Vec<glm::vec4> xyzz11;
|
||||
std::tie(s11, xyzz11) = Shadow11(p1q1, inP, inQ, expandP_);
|
||||
PRINT("s11 size = " << s11.size());
|
||||
|
||||
// Build up Z-projection of vertices onto triangles, keeping only those that
|
||||
// fall inside the triangle.
|
||||
VecDH<int> s02;
|
||||
VecDH<float> z02;
|
||||
std::tie(s02, z02) = Shadow02(inP, inQ, p0q2, true, expandP_, policy_);
|
||||
Vec<int> s02;
|
||||
Vec<float> z02;
|
||||
std::tie(s02, z02) = Shadow02(inP, inQ, p0q2, true, expandP_);
|
||||
PRINT("s02 size = " << s02.size());
|
||||
|
||||
VecDH<int> s20;
|
||||
VecDH<float> z20;
|
||||
std::tie(s20, z20) = Shadow02(inQ, inP, p2q0, false, expandP_, policy_);
|
||||
Vec<int> s20;
|
||||
Vec<float> z20;
|
||||
std::tie(s20, z20) = Shadow02(inQ, inP, p2q0, false, expandP_);
|
||||
PRINT("s20 size = " << s20.size());
|
||||
|
||||
// Level 3
|
||||
// Build up the intersection of the edges and triangles, keeping only those
|
||||
// that intersect, and record the direction the edge is passing through the
|
||||
// triangle.
|
||||
std::tie(x12_, v12_) = Intersect12(inP, inQ, s02, p0q2, s11, p1q1, z02,
|
||||
xyzz11, p1q2_, true, policy_);
|
||||
std::tie(x12_, v12_) =
|
||||
Intersect12(inP, inQ, s02, p0q2, s11, p1q1, z02, xyzz11, p1q2_, true);
|
||||
PRINT("x12 size = " << x12_.size());
|
||||
|
||||
std::tie(x21_, v21_) = Intersect12(inQ, inP, s20, p2q0, s11, p1q1, z20,
|
||||
xyzz11, p2q1_, false, policy_);
|
||||
std::tie(x21_, v21_) =
|
||||
Intersect12(inQ, inP, s20, p2q0, s11, p1q1, z20, xyzz11, p2q1_, false);
|
||||
PRINT("x21 size = " << x21_.size());
|
||||
|
||||
Vec<int> p0 = p0q2.Copy(false);
|
||||
p0q2.Resize(0);
|
||||
Vec<int> q0 = p2q0.Copy(true);
|
||||
p2q0.Resize(0);
|
||||
// Sum up the winding numbers of all vertices.
|
||||
w03_ = Winding03(inP, p0q2, s02, false, policy_);
|
||||
w03_ = Winding03(inP, p0, s02, false);
|
||||
|
||||
w30_ = Winding03(inQ, p2q0, s20, true, policy_);
|
||||
w30_ = Winding03(inQ, q0, s20, true);
|
||||
|
||||
#ifdef MANIFOLD_DEBUG
|
||||
intersections.Stop();
|
||||
|
||||
@@ -54,8 +54,7 @@ class Boolean3 {
|
||||
const Manifold::Impl &inP_, &inQ_;
|
||||
const float expandP_;
|
||||
SparseIndices p1q2_, p2q1_;
|
||||
VecDH<int> x12_, x21_, w03_, w30_;
|
||||
VecDH<glm::vec3> v12_, v21_;
|
||||
ExecutionPolicy policy_;
|
||||
Vec<int> x12_, x21_, w03_, w30_;
|
||||
Vec<glm::vec3> v12_, v21_;
|
||||
};
|
||||
} // namespace manifold
|
||||
|
||||
+269
-194
@@ -13,8 +13,21 @@
|
||||
// limitations under the License.
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <map>
|
||||
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_map.h>)
|
||||
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
|
||||
#include <tbb/concurrent_map.h>
|
||||
#include <tbb/parallel_for.h>
|
||||
|
||||
template <typename K, typename V>
|
||||
using concurrent_map = tbb::concurrent_map<K, V>;
|
||||
#else
|
||||
template <typename K, typename V>
|
||||
// not really concurrent when tbb is disabled
|
||||
using concurrent_map = std::map<K, V>;
|
||||
#endif
|
||||
#include "boolean3.h"
|
||||
#include "par.h"
|
||||
#include "polygon.h"
|
||||
@@ -22,16 +35,25 @@
|
||||
using namespace manifold;
|
||||
using namespace thrust::placeholders;
|
||||
|
||||
template <>
|
||||
struct std::hash<std::pair<int, int>> {
|
||||
size_t operator()(const std::pair<int, int> &p) const {
|
||||
return std::hash<int>()(p.first) ^ std::hash<int>()(p.second);
|
||||
}
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kParallelThreshold = 128;
|
||||
|
||||
struct AbsSum : public thrust::binary_function<int, int, int> {
|
||||
__host__ __device__ int operator()(int a, int b) { return abs(a) + abs(b); }
|
||||
int operator()(int a, int b) { return abs(a) + abs(b); }
|
||||
};
|
||||
|
||||
struct DuplicateVerts {
|
||||
glm::vec3 *vertPosR;
|
||||
VecView<glm::vec3> vertPosR;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<int, int, glm::vec3> in) {
|
||||
void operator()(thrust::tuple<int, int, glm::vec3> in) {
|
||||
int inclusion = abs(thrust::get<0>(in));
|
||||
int vertR = thrust::get<1>(in);
|
||||
glm::vec3 vertPosP = thrust::get<2>(in);
|
||||
@@ -43,23 +65,25 @@ struct DuplicateVerts {
|
||||
};
|
||||
|
||||
struct CountVerts {
|
||||
int *count;
|
||||
const int *inclusion;
|
||||
VecView<int> count;
|
||||
VecView<const int> inclusion;
|
||||
|
||||
__host__ __device__ void operator()(const Halfedge &edge) {
|
||||
void operator()(const Halfedge &edge) {
|
||||
AtomicAdd(count[edge.face], glm::abs(inclusion[edge.startVert]));
|
||||
}
|
||||
};
|
||||
|
||||
template <const bool inverted>
|
||||
struct CountNewVerts {
|
||||
int *countP;
|
||||
int *countQ;
|
||||
const Halfedge *halfedges;
|
||||
VecView<int> countP;
|
||||
VecView<int> countQ;
|
||||
const SparseIndices &pq;
|
||||
VecView<const Halfedge> halfedges;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<int, int, int> in) {
|
||||
int edgeP = thrust::get<0>(in);
|
||||
int faceQ = thrust::get<1>(in);
|
||||
int inclusion = glm::abs(thrust::get<2>(in));
|
||||
void operator()(thrust::tuple<int, int> in) {
|
||||
int edgeP = pq.Get(thrust::get<0>(in), inverted);
|
||||
int faceQ = pq.Get(thrust::get<0>(in), !inverted);
|
||||
int inclusion = glm::abs(thrust::get<1>(in));
|
||||
|
||||
AtomicAdd(countQ[faceQ], inclusion);
|
||||
const Halfedge half = halfedges[edgeP];
|
||||
@@ -69,59 +93,64 @@ struct CountNewVerts {
|
||||
};
|
||||
|
||||
struct NotZero : public thrust::unary_function<int, int> {
|
||||
__host__ __device__ int operator()(int x) const { return x > 0 ? 1 : 0; }
|
||||
int operator()(int x) const { return x > 0 ? 1 : 0; }
|
||||
};
|
||||
|
||||
std::tuple<VecDH<int>, VecDH<int>> SizeOutput(
|
||||
std::tuple<Vec<int>, Vec<int>> SizeOutput(
|
||||
Manifold::Impl &outR, const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
const VecDH<int> &i03, const VecDH<int> &i30, const VecDH<int> &i12,
|
||||
const VecDH<int> &i21, const SparseIndices &p1q2, const SparseIndices &p2q1,
|
||||
bool invertQ, ExecutionPolicy policy) {
|
||||
VecDH<int> sidesPerFacePQ(inP.NumTri() + inQ.NumTri(), 0);
|
||||
auto sidesPerFaceP = sidesPerFacePQ.ptrD();
|
||||
auto sidesPerFaceQ = sidesPerFacePQ.ptrD() + inP.NumTri();
|
||||
const Vec<int> &i03, const Vec<int> &i30, const Vec<int> &i12,
|
||||
const Vec<int> &i21, const SparseIndices &p1q2, const SparseIndices &p2q1,
|
||||
bool invertQ) {
|
||||
ZoneScoped;
|
||||
Vec<int> sidesPerFacePQ(inP.NumTri() + inQ.NumTri(), 0);
|
||||
auto sidesPerFaceP = sidesPerFacePQ.view(0, inP.NumTri());
|
||||
auto sidesPerFaceQ = sidesPerFacePQ.view(inP.NumTri(), inQ.NumTri());
|
||||
|
||||
for_each(policy, inP.halfedge_.begin(), inP.halfedge_.end(),
|
||||
CountVerts({sidesPerFaceP, i03.cptrD()}));
|
||||
for_each(policy, inQ.halfedge_.begin(), inQ.halfedge_.end(),
|
||||
CountVerts({sidesPerFaceQ, i30.cptrD()}));
|
||||
for_each(autoPolicy(inP.halfedge_.size()), inP.halfedge_.begin(),
|
||||
inP.halfedge_.end(), CountVerts({sidesPerFaceP, i03}));
|
||||
for_each(autoPolicy(inP.halfedge_.size()), inQ.halfedge_.begin(),
|
||||
inQ.halfedge_.end(), CountVerts({sidesPerFaceQ, i30}));
|
||||
for_each_n(autoPolicy(i12.size()), zip(countAt(0), i12.begin()), i12.size(),
|
||||
CountNewVerts<false>(
|
||||
{sidesPerFaceP, sidesPerFaceQ, p1q2, inP.halfedge_}));
|
||||
for_each_n(
|
||||
policy, zip(p1q2.begin(0), p1q2.begin(1), i12.begin()), i12.size(),
|
||||
CountNewVerts({sidesPerFaceP, sidesPerFaceQ, inP.halfedge_.cptrD()}));
|
||||
for_each_n(
|
||||
policy, zip(p2q1.begin(1), p2q1.begin(0), i21.begin()), i21.size(),
|
||||
CountNewVerts({sidesPerFaceQ, sidesPerFaceP, inQ.halfedge_.cptrD()}));
|
||||
autoPolicy(i21.size()), zip(countAt(0), i21.begin()), i21.size(),
|
||||
CountNewVerts<true>({sidesPerFaceQ, sidesPerFaceP, p2q1, inQ.halfedge_}));
|
||||
|
||||
VecDH<int> facePQ2R(inP.NumTri() + inQ.NumTri() + 1, 0);
|
||||
Vec<int> facePQ2R(inP.NumTri() + inQ.NumTri() + 1, 0);
|
||||
auto keepFace =
|
||||
thrust::make_transform_iterator(sidesPerFacePQ.begin(), NotZero());
|
||||
inclusive_scan(policy, keepFace, keepFace + sidesPerFacePQ.size(),
|
||||
facePQ2R.begin() + 1);
|
||||
inclusive_scan(autoPolicy(sidesPerFacePQ.size()), keepFace,
|
||||
keepFace + sidesPerFacePQ.size(), facePQ2R.begin() + 1);
|
||||
int numFaceR = facePQ2R.back();
|
||||
facePQ2R.resize(inP.NumTri() + inQ.NumTri());
|
||||
|
||||
outR.faceNormal_.resize(numFaceR);
|
||||
auto next = copy_if<decltype(outR.faceNormal_.begin())>(
|
||||
policy, inP.faceNormal_.begin(), inP.faceNormal_.end(), keepFace,
|
||||
outR.faceNormal_.begin(), thrust::identity<bool>());
|
||||
autoPolicy(inP.faceNormal_.size()), inP.faceNormal_.begin(),
|
||||
inP.faceNormal_.end(), keepFace, outR.faceNormal_.begin(),
|
||||
thrust::identity<bool>());
|
||||
if (invertQ) {
|
||||
auto start = thrust::make_transform_iterator(inQ.faceNormal_.begin(),
|
||||
thrust::negate<glm::vec3>());
|
||||
auto end = thrust::make_transform_iterator(inQ.faceNormal_.end(),
|
||||
thrust::negate<glm::vec3>());
|
||||
copy_if<decltype(inQ.faceNormal_.begin())>(policy, start, end,
|
||||
keepFace + inP.NumTri(), next,
|
||||
thrust::identity<bool>());
|
||||
copy_if<decltype(inQ.faceNormal_.begin())>(
|
||||
autoPolicy(inQ.faceNormal_.size()), start, end, keepFace + inP.NumTri(),
|
||||
next, thrust::identity<bool>());
|
||||
} else {
|
||||
copy_if<decltype(inQ.faceNormal_.begin())>(
|
||||
policy, inQ.faceNormal_.begin(), inQ.faceNormal_.end(),
|
||||
keepFace + inP.NumTri(), next, thrust::identity<bool>());
|
||||
autoPolicy(inQ.faceNormal_.size()), inQ.faceNormal_.begin(),
|
||||
inQ.faceNormal_.end(), keepFace + inP.NumTri(), next,
|
||||
thrust::identity<bool>());
|
||||
}
|
||||
|
||||
auto newEnd = remove<decltype(sidesPerFacePQ.begin())>(
|
||||
policy, sidesPerFacePQ.begin(), sidesPerFacePQ.end(), 0);
|
||||
VecDH<int> faceEdge(newEnd - sidesPerFacePQ.begin() + 1, 0);
|
||||
inclusive_scan(policy, sidesPerFacePQ.begin(), newEnd, faceEdge.begin() + 1);
|
||||
autoPolicy(sidesPerFacePQ.size()), sidesPerFacePQ.begin(),
|
||||
sidesPerFacePQ.end(), 0);
|
||||
Vec<int> faceEdge(newEnd - sidesPerFacePQ.begin() + 1, 0);
|
||||
inclusive_scan(autoPolicy(std::distance(sidesPerFacePQ.begin(), newEnd)),
|
||||
sidesPerFacePQ.begin(), newEnd, faceEdge.begin() + 1);
|
||||
outR.halfedge_.resize(faceEdge.back());
|
||||
|
||||
return std::make_tuple(faceEdge, facePQ2R);
|
||||
@@ -134,46 +163,72 @@ struct EdgePos {
|
||||
};
|
||||
|
||||
void AddNewEdgeVerts(
|
||||
std::map<int, std::vector<EdgePos>> &edgesP,
|
||||
std::map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
|
||||
const SparseIndices &p1q2, const VecDH<int> &i12, const VecDH<int> &v12R,
|
||||
const VecDH<Halfedge> &halfedgeP, bool forward) {
|
||||
// we need concurrent_map because we will be adding things concurrently
|
||||
concurrent_map<int, std::vector<EdgePos>> &edgesP,
|
||||
concurrent_map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
|
||||
const SparseIndices &p1q2, const Vec<int> &i12, const Vec<int> &v12R,
|
||||
const Vec<Halfedge> &halfedgeP, bool forward) {
|
||||
ZoneScoped;
|
||||
// For each edge of P that intersects a face of Q (p1q2), add this vertex to
|
||||
// P's corresponding edge vector and to the two new edges, which are
|
||||
// intersections between the face of Q and the two faces of P attached to the
|
||||
// edge. The direction and duplicity are given by i12, while v12R remaps to
|
||||
// the output vert index. When forward is false, all is reversed.
|
||||
const VecDH<int> &p1 = p1q2.Get(!forward);
|
||||
const VecDH<int> &q2 = p1q2.Get(forward);
|
||||
for (int i = 0; i < p1q2.size(); ++i) {
|
||||
const int edgeP = p1[i];
|
||||
const int faceQ = q2[i];
|
||||
auto process = [&](std::function<void(size_t)> lock,
|
||||
std::function<void(size_t)> unlock, int i) {
|
||||
const int edgeP = p1q2.Get(i, !forward);
|
||||
const int faceQ = p1q2.Get(i, forward);
|
||||
const int vert = v12R[i];
|
||||
const int inclusion = i12[i];
|
||||
|
||||
auto &edgePosP = edgesP[edgeP];
|
||||
|
||||
Halfedge halfedge = halfedgeP[edgeP];
|
||||
std::pair<int, int> key = {halfedgeP[halfedge.pairedHalfedge].face, faceQ};
|
||||
if (!forward) std::swap(key.first, key.second);
|
||||
auto &edgePosRight = edgesNew[key];
|
||||
std::pair<int, int> keyRight = {halfedgeP[halfedge.pairedHalfedge].face,
|
||||
faceQ};
|
||||
if (!forward) std::swap(keyRight.first, keyRight.second);
|
||||
|
||||
key = {halfedge.face, faceQ};
|
||||
if (!forward) std::swap(key.first, key.second);
|
||||
auto &edgePosLeft = edgesNew[key];
|
||||
std::pair<int, int> keyLeft = {halfedge.face, faceQ};
|
||||
if (!forward) std::swap(keyLeft.first, keyLeft.second);
|
||||
|
||||
EdgePos edgePos = {vert, 0.0f, inclusion < 0};
|
||||
EdgePos edgePosRev = edgePos;
|
||||
edgePosRev.isStart = !edgePos.isStart;
|
||||
|
||||
for (int j = 0; j < glm::abs(inclusion); ++j) {
|
||||
edgePosP.push_back(edgePos);
|
||||
edgePosRight.push_back(forward ? edgePos : edgePosRev);
|
||||
edgePosLeft.push_back(forward ? edgePosRev : edgePos);
|
||||
++edgePos.vert;
|
||||
++edgePosRev.vert;
|
||||
bool direction = inclusion < 0;
|
||||
std::hash<std::pair<int, int>> pairHasher;
|
||||
std::array<std::tuple<bool, size_t, std::vector<EdgePos> *>, 3> edges = {
|
||||
std::make_tuple(direction, std::hash<int>{}(edgeP), &edgesP[edgeP]),
|
||||
std::make_tuple(direction ^ !forward, // revert if not forward
|
||||
pairHasher(keyRight), &edgesNew[keyRight]),
|
||||
std::make_tuple(direction ^ forward, // revert if forward
|
||||
pairHasher(keyLeft), &edgesNew[keyLeft])};
|
||||
for (const auto &tuple : edges) {
|
||||
lock(std::get<1>(tuple));
|
||||
for (int j = 0; j < glm::abs(inclusion); ++j)
|
||||
std::get<2>(tuple)->push_back({vert + j, 0.0f, std::get<0>(tuple)});
|
||||
unlock(std::get<1>(tuple));
|
||||
direction = !direction;
|
||||
}
|
||||
};
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
|
||||
// parallelize operations, requires concurrent_map so we can only enable this
|
||||
// with tbb
|
||||
if (!ManifoldParams().deterministic && p1q2.size() > kParallelThreshold) {
|
||||
// ideally we should have 1 mutex per key, but kParallelThreshold is enough
|
||||
// to avoid contention for most of the cases
|
||||
std::array<std::mutex, kParallelThreshold> mutexes;
|
||||
static tbb::affinity_partitioner ap;
|
||||
auto processFun = std::bind(
|
||||
process, [&](size_t hash) { mutexes[hash % mutexes.size()].lock(); },
|
||||
[&](size_t hash) { mutexes[hash % mutexes.size()].unlock(); },
|
||||
std::placeholders::_1);
|
||||
tbb::parallel_for(
|
||||
tbb::blocked_range<int>(0, p1q2.size(), 32),
|
||||
[&](const tbb::blocked_range<int> &range) {
|
||||
for (int i = range.begin(); i != range.end(); i++) processFun(i);
|
||||
},
|
||||
ap);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
auto processFun = std::bind(
|
||||
process, [](size_t _) {}, [](size_t _) {}, std::placeholders::_1);
|
||||
for (int i = 0; i < p1q2.size(); ++i) processFun(i);
|
||||
}
|
||||
|
||||
std::vector<Halfedge> PairUp(std::vector<EdgePos> &edgePos) {
|
||||
@@ -189,28 +244,29 @@ std::vector<Halfedge> PairUp(std::vector<EdgePos> &edgePos) {
|
||||
[](EdgePos x) { return x.isStart; });
|
||||
ASSERT(middle - edgePos.begin() == nEdges, topologyErr, "Non-manifold edge!");
|
||||
auto cmp = [](EdgePos a, EdgePos b) { return a.edgePos < b.edgePos; };
|
||||
std::sort(edgePos.begin(), middle, cmp);
|
||||
std::sort(middle, edgePos.end(), cmp);
|
||||
std::stable_sort(edgePos.begin(), middle, cmp);
|
||||
std::stable_sort(middle, edgePos.end(), cmp);
|
||||
std::vector<Halfedge> edges;
|
||||
for (int i = 0; i < nEdges; ++i)
|
||||
edges.push_back({edgePos[i].vert, edgePos[i + nEdges].vert, -1, -1});
|
||||
return edges;
|
||||
}
|
||||
|
||||
void AppendPartialEdges(Manifold::Impl &outR, VecDH<char> &wholeHalfedgeP,
|
||||
VecDH<int> &facePtrR,
|
||||
std::map<int, std::vector<EdgePos>> &edgesP,
|
||||
VecDH<TriRef> &halfedgeRef, const Manifold::Impl &inP,
|
||||
const VecDH<int> &i03, const VecDH<int> &vP2R,
|
||||
const VecDH<int>::IterC faceP2R, bool forward) {
|
||||
void AppendPartialEdges(Manifold::Impl &outR, Vec<char> &wholeHalfedgeP,
|
||||
Vec<int> &facePtrR,
|
||||
concurrent_map<int, std::vector<EdgePos>> &edgesP,
|
||||
Vec<TriRef> &halfedgeRef, const Manifold::Impl &inP,
|
||||
const Vec<int> &i03, const Vec<int> &vP2R,
|
||||
const Vec<int>::IterC faceP2R, bool forward) {
|
||||
ZoneScoped;
|
||||
// Each edge in the map is partially retained; for each of these, look up
|
||||
// their original verts and include them based on their winding number (i03),
|
||||
// while remapping them to the output using vP2R. Use the verts position
|
||||
// projected along the edge vector to pair them up, then distribute these
|
||||
// edges to their faces.
|
||||
VecDH<Halfedge> &halfedgeR = outR.halfedge_;
|
||||
const VecDH<glm::vec3> &vertPosP = inP.vertPos_;
|
||||
const VecDH<Halfedge> &halfedgeP = inP.halfedge_;
|
||||
Vec<Halfedge> &halfedgeR = outR.halfedge_;
|
||||
const Vec<glm::vec3> &vertPosP = inP.vertPos_;
|
||||
const Vec<Halfedge> &halfedgeP = inP.halfedge_;
|
||||
|
||||
for (auto &value : edgesP) {
|
||||
const int edgeP = value.first;
|
||||
@@ -229,7 +285,6 @@ void AppendPartialEdges(Manifold::Impl &outR, VecDH<char> &wholeHalfedgeP,
|
||||
}
|
||||
|
||||
int inclusion = i03[vStart];
|
||||
bool reversed = inclusion < 0;
|
||||
EdgePos edgePos = {vP2R[vStart],
|
||||
glm::dot(outR.vertPos_[vP2R[vStart]], edgeVec),
|
||||
inclusion > 0};
|
||||
@@ -239,7 +294,6 @@ void AppendPartialEdges(Manifold::Impl &outR, VecDH<char> &wholeHalfedgeP,
|
||||
}
|
||||
|
||||
inclusion = i03[vEnd];
|
||||
reversed |= inclusion < 0;
|
||||
edgePos = {vP2R[vEnd], glm::dot(outR.vertPos_[vP2R[vEnd]], edgeVec),
|
||||
inclusion < 0};
|
||||
for (int j = 0; j < glm::abs(inclusion); ++j) {
|
||||
@@ -281,13 +335,13 @@ void AppendPartialEdges(Manifold::Impl &outR, VecDH<char> &wholeHalfedgeP,
|
||||
}
|
||||
|
||||
void AppendNewEdges(
|
||||
Manifold::Impl &outR, VecDH<int> &facePtrR,
|
||||
std::map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
|
||||
VecDH<TriRef> &halfedgeRef, const VecDH<int> &facePQ2R,
|
||||
const int numFaceP) {
|
||||
Manifold::Impl &outR, Vec<int> &facePtrR,
|
||||
concurrent_map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
|
||||
Vec<TriRef> &halfedgeRef, const Vec<int> &facePQ2R, const int numFaceP) {
|
||||
ZoneScoped;
|
||||
// Pair up each edge's verts and distribute to faces based on indices in key.
|
||||
VecDH<Halfedge> &halfedgeR = outR.halfedge_;
|
||||
VecDH<glm::vec3> &vertPosR = outR.vertPos_;
|
||||
Vec<Halfedge> &halfedgeR = outR.halfedge_;
|
||||
Vec<glm::vec3> &vertPosR = outR.vertPos_;
|
||||
|
||||
for (auto &value : edgesNew) {
|
||||
const int faceP = value.first.first;
|
||||
@@ -334,20 +388,19 @@ void AppendNewEdges(
|
||||
}
|
||||
|
||||
struct DuplicateHalfedges {
|
||||
Halfedge *halfedgesR;
|
||||
TriRef *halfedgeRef;
|
||||
int *facePtr;
|
||||
const Halfedge *halfedgesP;
|
||||
const int *i03;
|
||||
const int *vP2R;
|
||||
const int *faceP2R;
|
||||
VecView<Halfedge> halfedgesR;
|
||||
VecView<TriRef> halfedgeRef;
|
||||
VecView<int> facePtr;
|
||||
VecView<const Halfedge> halfedgesP;
|
||||
VecView<const int> i03;
|
||||
VecView<const int> vP2R;
|
||||
VecView<const int> faceP2R;
|
||||
const bool forward;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<bool, Halfedge, int> in) {
|
||||
void operator()(thrust::tuple<bool, Halfedge, int> in) {
|
||||
if (!thrust::get<0>(in)) return;
|
||||
Halfedge halfedge = thrust::get<1>(in);
|
||||
if (!halfedge.IsForward()) return;
|
||||
const int edgeP = thrust::get<2>(in);
|
||||
|
||||
const int inclusion = i03[halfedge.startVert];
|
||||
if (inclusion == 0) return;
|
||||
@@ -385,25 +438,26 @@ struct DuplicateHalfedges {
|
||||
}
|
||||
};
|
||||
|
||||
void AppendWholeEdges(Manifold::Impl &outR, VecDH<int> &facePtrR,
|
||||
VecDH<TriRef> &halfedgeRef, const Manifold::Impl &inP,
|
||||
const VecDH<char> wholeHalfedgeP, const VecDH<int> &i03,
|
||||
const VecDH<int> &vP2R, const int *faceP2R, bool forward,
|
||||
ExecutionPolicy policy) {
|
||||
for_each_n(policy,
|
||||
void AppendWholeEdges(Manifold::Impl &outR, Vec<int> &facePtrR,
|
||||
Vec<TriRef> &halfedgeRef, const Manifold::Impl &inP,
|
||||
const Vec<char> wholeHalfedgeP, const Vec<int> &i03,
|
||||
const Vec<int> &vP2R, VecView<const int> faceP2R,
|
||||
bool forward) {
|
||||
ZoneScoped;
|
||||
for_each_n(ManifoldParams().deterministic ? ExecutionPolicy::Seq
|
||||
: autoPolicy(inP.halfedge_.size()),
|
||||
zip(wholeHalfedgeP.begin(), inP.halfedge_.begin(), countAt(0)),
|
||||
inP.halfedge_.size(),
|
||||
DuplicateHalfedges({outR.halfedge_.ptrD(), halfedgeRef.ptrD(),
|
||||
facePtrR.ptrD(), inP.halfedge_.cptrD(),
|
||||
i03.cptrD(), vP2R.cptrD(), faceP2R, forward}));
|
||||
DuplicateHalfedges({outR.halfedge_, halfedgeRef, facePtrR,
|
||||
inP.halfedge_, i03, vP2R, faceP2R, forward}));
|
||||
}
|
||||
|
||||
struct MapTriRef {
|
||||
const TriRef *triRefP;
|
||||
const TriRef *triRefQ;
|
||||
VecView<const TriRef> triRefP;
|
||||
VecView<const TriRef> triRefQ;
|
||||
const int offsetQ;
|
||||
|
||||
__host__ __device__ void operator()(TriRef &triRef) {
|
||||
void operator()(TriRef &triRef) {
|
||||
const int tri = triRef.tri;
|
||||
const bool PQ = triRef.meshID == 0;
|
||||
triRef = PQ ? triRefP[tri] : triRefQ[tri];
|
||||
@@ -411,14 +465,13 @@ struct MapTriRef {
|
||||
}
|
||||
};
|
||||
|
||||
VecDH<TriRef> UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ, bool invertQ,
|
||||
ExecutionPolicy policy) {
|
||||
VecDH<TriRef> refPQ = outR.meshRelation_.triRef;
|
||||
void UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ, bool invertQ) {
|
||||
const int offsetQ = Manifold::Impl::meshIDCounter_;
|
||||
for_each_n(policy, outR.meshRelation_.triRef.begin(), outR.NumTri(),
|
||||
MapTriRef({inP.meshRelation_.triRef.cptrD(),
|
||||
inQ.meshRelation_.triRef.cptrD(), offsetQ}));
|
||||
for_each_n(
|
||||
autoPolicy(outR.NumTri()), outR.meshRelation_.triRef.begin(),
|
||||
outR.NumTri(),
|
||||
MapTriRef({inP.meshRelation_.triRef, inQ.meshRelation_.triRef, offsetQ}));
|
||||
|
||||
for (const auto &pair : inP.meshRelation_.meshIDtransform) {
|
||||
outR.meshRelation_.meshIDtransform[pair.first] = pair.second;
|
||||
@@ -428,20 +481,19 @@ VecDH<TriRef> UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
|
||||
outR.meshRelation_.meshIDtransform[pair.first + offsetQ].backSide ^=
|
||||
invertQ;
|
||||
}
|
||||
return refPQ;
|
||||
}
|
||||
|
||||
struct Barycentric {
|
||||
glm::vec3 *uvw;
|
||||
const glm::vec3 *vertPosP;
|
||||
const glm::vec3 *vertPosQ;
|
||||
const glm::vec3 *vertPosR;
|
||||
const Halfedge *halfedgeP;
|
||||
const Halfedge *halfedgeQ;
|
||||
const Halfedge *halfedgeR;
|
||||
VecView<glm::vec3> uvw;
|
||||
VecView<const glm::vec3> vertPosP;
|
||||
VecView<const glm::vec3> vertPosQ;
|
||||
VecView<const glm::vec3> vertPosR;
|
||||
VecView<const Halfedge> halfedgeP;
|
||||
VecView<const Halfedge> halfedgeQ;
|
||||
VecView<const Halfedge> halfedgeR;
|
||||
const float precision;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<int, TriRef> in) {
|
||||
void operator()(thrust::tuple<int, TriRef> in) {
|
||||
const int tri = thrust::get<0>(in);
|
||||
const TriRef refPQ = thrust::get<1>(in);
|
||||
if (halfedgeR[3 * tri].startVert < 0) return;
|
||||
@@ -462,9 +514,9 @@ struct Barycentric {
|
||||
}
|
||||
};
|
||||
|
||||
void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
|
||||
const Manifold::Impl &inP, const Manifold::Impl &inQ,
|
||||
ExecutionPolicy policy) {
|
||||
void CreateProperties(Manifold::Impl &outR, const Manifold::Impl &inP,
|
||||
const Manifold::Impl &inQ) {
|
||||
ZoneScoped;
|
||||
const int numPropP = inP.NumProp();
|
||||
const int numPropQ = inQ.NumProp();
|
||||
const int numProp = glm::max(numPropP, numPropQ);
|
||||
@@ -474,16 +526,19 @@ void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
|
||||
const int numTri = outR.NumTri();
|
||||
outR.meshRelation_.triProperties.resize(numTri);
|
||||
|
||||
VecDH<glm::vec3> bary(outR.halfedge_.size());
|
||||
for_each_n(policy, zip(countAt(0), refPQ.cbegin()), numTri,
|
||||
Barycentric({bary.ptrD(), inP.vertPos_.cptrD(),
|
||||
inQ.vertPos_.cptrD(), outR.vertPos_.cptrD(),
|
||||
inP.halfedge_.cptrD(), inQ.halfedge_.cptrD(),
|
||||
outR.halfedge_.cptrD(), outR.precision_}));
|
||||
Vec<glm::vec3> bary(outR.halfedge_.size());
|
||||
for_each_n(autoPolicy(numTri),
|
||||
zip(countAt(0), outR.meshRelation_.triRef.cbegin()), numTri,
|
||||
Barycentric({bary, inP.vertPos_, inQ.vertPos_, outR.vertPos_,
|
||||
inP.halfedge_, inQ.halfedge_, outR.halfedge_,
|
||||
outR.precision_}));
|
||||
|
||||
using Entry = std::pair<glm::ivec3, int>;
|
||||
int idMissProp = outR.NumVert();
|
||||
std::vector<std::vector<Entry>> propIdx(outR.NumVert() + 1);
|
||||
std::vector<int> propMissIdx[2];
|
||||
propMissIdx[0].resize(inQ.NumPropVert(), -1);
|
||||
propMissIdx[1].resize(inP.NumPropVert(), -1);
|
||||
outR.meshRelation_.properties.reserve(outR.NumVert() * numProp);
|
||||
int idx = 0;
|
||||
|
||||
@@ -491,14 +546,14 @@ void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
|
||||
// Skip collapsed triangles
|
||||
if (outR.halfedge_[3 * tri].startVert < 0) continue;
|
||||
|
||||
const int triPQ = refPQ[tri].tri;
|
||||
const bool PQ = refPQ[tri].meshID == 0;
|
||||
const TriRef ref = outR.meshRelation_.triRef[tri];
|
||||
const bool PQ = ref.meshID == 0;
|
||||
const int oldNumProp = PQ ? numPropP : numPropQ;
|
||||
const auto &properties =
|
||||
PQ ? inP.meshRelation_.properties : inQ.meshRelation_.properties;
|
||||
const glm::ivec3 &triProp = oldNumProp == 0 ? glm::ivec3(-1)
|
||||
: PQ ? inP.meshRelation_.triProperties[triPQ]
|
||||
: inQ.meshRelation_.triProperties[triPQ];
|
||||
: PQ ? inP.meshRelation_.triProperties[ref.tri]
|
||||
: inQ.meshRelation_.triProperties[ref.tri];
|
||||
|
||||
for (const int i : {0, 1, 2}) {
|
||||
const int vert = outR.halfedge_[3 * tri + i].startVert;
|
||||
@@ -506,8 +561,7 @@ void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
|
||||
|
||||
glm::ivec4 key(PQ, idMissProp, -1, -1);
|
||||
if (oldNumProp > 0) {
|
||||
key[1] = vert;
|
||||
int edge = -1;
|
||||
int edge = -2;
|
||||
for (const int j : {0, 1, 2}) {
|
||||
if (uvw[j] == 1) {
|
||||
// On a retained vert, the propVert must also match
|
||||
@@ -521,24 +575,37 @@ void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
|
||||
// On an edge, both propVerts must match
|
||||
const int p0 = triProp[Next3(edge)];
|
||||
const int p1 = triProp[Prev3(edge)];
|
||||
key[1] = vert;
|
||||
key[2] = glm::min(p0, p1);
|
||||
key[3] = glm::max(p0, p1);
|
||||
} else if (edge == -2) {
|
||||
key[1] = vert;
|
||||
}
|
||||
}
|
||||
|
||||
auto &bin = propIdx[key.y];
|
||||
bool bFound = false;
|
||||
for (int k = 0; k < bin.size(); ++k) {
|
||||
if (bin[k].first == glm::ivec3(key.x, key.z, key.w)) {
|
||||
bFound = true;
|
||||
outR.meshRelation_.triProperties[tri][i] = bin[k].second;
|
||||
break;
|
||||
if (key.y == idMissProp && key.z >= 0) {
|
||||
// only key.x/key.z matters
|
||||
auto &entry = propMissIdx[key.x][key.z];
|
||||
if (entry >= 0) {
|
||||
outR.meshRelation_.triProperties[tri][i] = entry;
|
||||
continue;
|
||||
}
|
||||
entry = idx;
|
||||
} else {
|
||||
auto &bin = propIdx[key.y];
|
||||
bool bFound = false;
|
||||
for (int k = 0; k < bin.size(); ++k) {
|
||||
if (bin[k].first == glm::ivec3(key.x, key.z, key.w)) {
|
||||
bFound = true;
|
||||
outR.meshRelation_.triProperties[tri][i] = bin[k].second;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (bFound) continue;
|
||||
bin.push_back(std::make_pair(glm::ivec3(key.x, key.z, key.w), idx));
|
||||
}
|
||||
if (bFound) continue;
|
||||
bin.push_back(std::make_pair(glm::ivec3(key.x, key.z, key.w), idx));
|
||||
|
||||
outR.meshRelation_.triProperties[tri][i] = idx++;
|
||||
|
||||
for (int p = 0; p < numProp; ++p) {
|
||||
if (p < oldNumProp) {
|
||||
glm::vec3 oldProps;
|
||||
@@ -583,39 +650,44 @@ Manifold::Impl Boolean3::Result(OpType op) const {
|
||||
const bool invertQ = op == OpType::Subtract;
|
||||
|
||||
// Convert winding numbers to inclusion values based on operation type.
|
||||
VecDH<int> i12(x12_.size());
|
||||
VecDH<int> i21(x21_.size());
|
||||
VecDH<int> i03(w03_.size());
|
||||
VecDH<int> i30(w30_.size());
|
||||
Vec<int> i12(x12_.size());
|
||||
Vec<int> i21(x21_.size());
|
||||
Vec<int> i03(w03_.size());
|
||||
Vec<int> i30(w30_.size());
|
||||
|
||||
transform(policy_, x12_.begin(), x12_.end(), i12.begin(), c3 * _1);
|
||||
transform(policy_, x21_.begin(), x21_.end(), i21.begin(), c3 * _1);
|
||||
transform(policy_, w03_.begin(), w03_.end(), i03.begin(), c1 + c3 * _1);
|
||||
transform(policy_, w30_.begin(), w30_.end(), i30.begin(), c2 + c3 * _1);
|
||||
transform(autoPolicy(x12_.size()), x12_.begin(), x12_.end(), i12.begin(),
|
||||
c3 * _1);
|
||||
transform(autoPolicy(x21_.size()), x21_.begin(), x21_.end(), i21.begin(),
|
||||
c3 * _1);
|
||||
transform(autoPolicy(w03_.size()), w03_.begin(), w03_.end(), i03.begin(),
|
||||
c1 + c3 * _1);
|
||||
transform(autoPolicy(w30_.size()), w30_.begin(), w30_.end(), i30.begin(),
|
||||
c2 + c3 * _1);
|
||||
|
||||
VecDH<int> vP2R(inP_.NumVert());
|
||||
exclusive_scan(policy_, i03.begin(), i03.end(), vP2R.begin(), 0, AbsSum());
|
||||
Vec<int> vP2R(inP_.NumVert());
|
||||
exclusive_scan(autoPolicy(i03.size()), i03.begin(), i03.end(), vP2R.begin(),
|
||||
0, AbsSum());
|
||||
int numVertR = AbsSum()(vP2R.back(), i03.back());
|
||||
const int nPv = numVertR;
|
||||
|
||||
VecDH<int> vQ2R(inQ_.NumVert());
|
||||
exclusive_scan(policy_, i30.begin(), i30.end(), vQ2R.begin(), numVertR,
|
||||
AbsSum());
|
||||
Vec<int> vQ2R(inQ_.NumVert());
|
||||
exclusive_scan(autoPolicy(i30.size()), i30.begin(), i30.end(), vQ2R.begin(),
|
||||
numVertR, AbsSum());
|
||||
numVertR = AbsSum()(vQ2R.back(), i30.back());
|
||||
const int nQv = numVertR - nPv;
|
||||
|
||||
VecDH<int> v12R(v12_.size());
|
||||
Vec<int> v12R(v12_.size());
|
||||
if (v12_.size() > 0) {
|
||||
exclusive_scan(policy_, i12.begin(), i12.end(), v12R.begin(), numVertR,
|
||||
AbsSum());
|
||||
exclusive_scan(autoPolicy(i12.size()), i12.begin(), i12.end(), v12R.begin(),
|
||||
numVertR, AbsSum());
|
||||
numVertR = AbsSum()(v12R.back(), i12.back());
|
||||
}
|
||||
const int n12 = numVertR - nPv - nQv;
|
||||
|
||||
VecDH<int> v21R(v21_.size());
|
||||
Vec<int> v21R(v21_.size());
|
||||
if (v21_.size() > 0) {
|
||||
exclusive_scan(policy_, i21.begin(), i21.end(), v21R.begin(), numVertR,
|
||||
AbsSum());
|
||||
exclusive_scan(autoPolicy(i21.size()), i21.begin(), i21.end(), v21R.begin(),
|
||||
numVertR, AbsSum());
|
||||
numVertR = AbsSum()(v21R.back(), i21.back());
|
||||
}
|
||||
const int n21 = numVertR - nPv - nQv - n12;
|
||||
@@ -630,15 +702,19 @@ Manifold::Impl Boolean3::Result(OpType op) const {
|
||||
outR.vertPos_.resize(numVertR);
|
||||
// Add vertices, duplicating for inclusion numbers not in [-1, 1].
|
||||
// Retained vertices from P and Q:
|
||||
for_each_n(policy_, zip(i03.begin(), vP2R.begin(), inP_.vertPos_.begin()),
|
||||
inP_.NumVert(), DuplicateVerts({outR.vertPos_.ptrD()}));
|
||||
for_each_n(policy_, zip(i30.begin(), vQ2R.begin(), inQ_.vertPos_.begin()),
|
||||
inQ_.NumVert(), DuplicateVerts({outR.vertPos_.ptrD()}));
|
||||
for_each_n(autoPolicy(inP_.NumVert()),
|
||||
zip(i03.begin(), vP2R.begin(), inP_.vertPos_.begin()),
|
||||
inP_.NumVert(), DuplicateVerts({outR.vertPos_}));
|
||||
for_each_n(autoPolicy(inQ_.NumVert()),
|
||||
zip(i30.begin(), vQ2R.begin(), inQ_.vertPos_.begin()),
|
||||
inQ_.NumVert(), DuplicateVerts({outR.vertPos_}));
|
||||
// New vertices created from intersections:
|
||||
for_each_n(policy_, zip(i12.begin(), v12R.begin(), v12_.begin()), i12.size(),
|
||||
DuplicateVerts({outR.vertPos_.ptrD()}));
|
||||
for_each_n(policy_, zip(i21.begin(), v21R.begin(), v21_.begin()), i21.size(),
|
||||
DuplicateVerts({outR.vertPos_.ptrD()}));
|
||||
for_each_n(autoPolicy(i12.size()),
|
||||
zip(i12.begin(), v12R.begin(), v12_.begin()), i12.size(),
|
||||
DuplicateVerts({outR.vertPos_}));
|
||||
for_each_n(autoPolicy(i21.size()),
|
||||
zip(i21.begin(), v21R.begin(), v21_.begin()), i21.size(),
|
||||
DuplicateVerts({outR.vertPos_}));
|
||||
|
||||
PRINT(nPv << " verts from inP");
|
||||
PRINT(nQv << " verts from inQ");
|
||||
@@ -652,29 +728,28 @@ Manifold::Impl Boolean3::Result(OpType op) const {
|
||||
|
||||
// This key is the forward halfedge index of P or Q. Only includes intersected
|
||||
// edges.
|
||||
std::map<int, std::vector<EdgePos>> edgesP, edgesQ;
|
||||
concurrent_map<int, std::vector<EdgePos>> edgesP, edgesQ;
|
||||
// This key is the face index of <P, Q>
|
||||
std::map<std::pair<int, int>, std::vector<EdgePos>> edgesNew;
|
||||
concurrent_map<std::pair<int, int>, std::vector<EdgePos>> edgesNew;
|
||||
|
||||
AddNewEdgeVerts(edgesP, edgesNew, p1q2_, i12, v12R, inP_.halfedge_, true);
|
||||
AddNewEdgeVerts(edgesQ, edgesNew, p2q1_, i21, v21R, inQ_.halfedge_, false);
|
||||
|
||||
// Level 4
|
||||
VecDH<int> faceEdge;
|
||||
VecDH<int> facePQ2R;
|
||||
std::tie(faceEdge, facePQ2R) = SizeOutput(
|
||||
outR, inP_, inQ_, i03, i30, i12, i21, p1q2_, p2q1_, invertQ, policy_);
|
||||
Vec<int> faceEdge;
|
||||
Vec<int> facePQ2R;
|
||||
std::tie(faceEdge, facePQ2R) =
|
||||
SizeOutput(outR, inP_, inQ_, i03, i30, i12, i21, p1q2_, p2q1_, invertQ);
|
||||
|
||||
const int numFaceR = faceEdge.size() - 1;
|
||||
// This gets incremented for each halfedge that's added to a face so that the
|
||||
// next one knows where to slot in.
|
||||
VecDH<int> facePtrR = faceEdge;
|
||||
Vec<int> facePtrR = faceEdge;
|
||||
// Intersected halfedges are marked false.
|
||||
VecDH<char> wholeHalfedgeP(inP_.halfedge_.size(), true);
|
||||
VecDH<char> wholeHalfedgeQ(inQ_.halfedge_.size(), true);
|
||||
Vec<char> wholeHalfedgeP(inP_.halfedge_.size(), true);
|
||||
Vec<char> wholeHalfedgeQ(inQ_.halfedge_.size(), true);
|
||||
// The halfedgeRef contains the data that will become triRef once the faces
|
||||
// are triangulated.
|
||||
VecDH<TriRef> halfedgeRef(2 * outR.NumEdge());
|
||||
Vec<TriRef> halfedgeRef(2 * outR.NumEdge());
|
||||
|
||||
AppendPartialEdges(outR, wholeHalfedgeP, facePtrR, edgesP, halfedgeRef, inP_,
|
||||
i03, vP2R, facePQ2R.begin(), true);
|
||||
@@ -685,9 +760,9 @@ Manifold::Impl Boolean3::Result(OpType op) const {
|
||||
inP_.NumTri());
|
||||
|
||||
AppendWholeEdges(outR, facePtrR, halfedgeRef, inP_, wholeHalfedgeP, i03, vP2R,
|
||||
facePQ2R.cptrD(), true, policy_);
|
||||
facePQ2R.cview(0, inP_.NumTri()), true);
|
||||
AppendWholeEdges(outR, facePtrR, halfedgeRef, inQ_, wholeHalfedgeQ, i30, vQ2R,
|
||||
facePQ2R.cptrD() + inP_.NumTri(), false, policy_);
|
||||
facePQ2R.cview(inP_.NumTri(), inQ_.NumTri()), false);
|
||||
|
||||
#ifdef MANIFOLD_DEBUG
|
||||
assemble.Stop();
|
||||
@@ -711,12 +786,12 @@ Manifold::Impl Boolean3::Result(OpType op) const {
|
||||
if (ManifoldParams().intermediateChecks)
|
||||
ASSERT(outR.IsManifold(), logicErr, "triangulated mesh is not manifold!");
|
||||
|
||||
VecDH<TriRef> refPQ = UpdateReference(outR, inP_, inQ_, invertQ, policy_);
|
||||
CreateProperties(outR, inP_, inQ_);
|
||||
|
||||
UpdateReference(outR, inP_, inQ_, invertQ);
|
||||
|
||||
outR.SimplifyTopology();
|
||||
|
||||
CreateProperties(outR, refPQ, inP_, inQ_, policy_);
|
||||
|
||||
if (ManifoldParams().intermediateChecks)
|
||||
ASSERT(outR.Is2Manifold(), logicErr, "simplified mesh is not 2-manifold!");
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
|
||||
#include "cross_section.h"
|
||||
#include "csg_tree.h"
|
||||
#include "graph.h"
|
||||
#include "impl.h"
|
||||
#include "par.h"
|
||||
#include "polygon.h"
|
||||
@@ -27,7 +26,7 @@ using namespace thrust::placeholders;
|
||||
|
||||
struct ToSphere {
|
||||
float length;
|
||||
__host__ __device__ void operator()(glm::vec3& v) {
|
||||
void operator()(glm::vec3& v) {
|
||||
v = glm::cos(glm::half_pi<float>() * (1.0f - v));
|
||||
v = length * glm::normalize(v);
|
||||
if (isnan(v.x)) v = glm::vec3(0.0);
|
||||
@@ -36,15 +35,15 @@ struct ToSphere {
|
||||
|
||||
struct Equals {
|
||||
int val;
|
||||
__host__ __device__ bool operator()(int x) { return x == val; }
|
||||
bool operator()(int x) { return x == val; }
|
||||
};
|
||||
|
||||
struct RemoveFace {
|
||||
const Halfedge* halfedge;
|
||||
const int* vertLabel;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const int> vertLabel;
|
||||
const int keepLabel;
|
||||
|
||||
__host__ __device__ bool operator()(int face) {
|
||||
bool operator()(int face) {
|
||||
return vertLabel[halfedge[3 * face].startVert] != keepLabel;
|
||||
}
|
||||
};
|
||||
@@ -221,6 +220,9 @@ Manifold Manifold::Sphere(float radius, int circularSegments) {
|
||||
/**
|
||||
* Constructs a manifold from a set of polygons by extruding them along the
|
||||
* Z-axis.
|
||||
* Note that high twistDegrees with small nDivisions may cause
|
||||
* self-intersection. This is not checked here and it is up to the user to
|
||||
* choose the correct parameters.
|
||||
*
|
||||
* @param crossSection A set of non-overlapping polygons to extrude.
|
||||
* @param height Z-extent of extrusion.
|
||||
@@ -231,11 +233,13 @@ Manifold Manifold::Sphere(float radius, int circularSegments) {
|
||||
* bottom, interpolated linearly for the divisions in between.
|
||||
* @param scaleTop Amount to scale the top (independently in X and Y). If the
|
||||
* scale is {0, 0}, a pure cone is formed with only a single vertex at the top.
|
||||
* Note that scale is applied after twist.
|
||||
* Default {1, 1}.
|
||||
*/
|
||||
Manifold Manifold::Extrude(const CrossSection& crossSection, float height,
|
||||
int nDivisions, float twistDegrees,
|
||||
glm::vec2 scaleTop) {
|
||||
ZoneScoped;
|
||||
auto polygons = crossSection.ToPolygons();
|
||||
if (polygons.size() == 0 || height <= 0.0f) {
|
||||
return Invalid();
|
||||
@@ -247,7 +251,7 @@ Manifold Manifold::Extrude(const CrossSection& crossSection, float height,
|
||||
auto pImpl_ = std::make_shared<Impl>();
|
||||
++nDivisions;
|
||||
auto& vertPos = pImpl_->vertPos_;
|
||||
VecDH<glm::ivec3> triVertsDH;
|
||||
Vec<glm::ivec3> triVertsDH;
|
||||
auto& triVerts = triVertsDH;
|
||||
int nCrossSection = 0;
|
||||
bool isCone = scaleTop.x == 0.0 && scaleTop.y == 0.0;
|
||||
@@ -265,9 +269,9 @@ Manifold Manifold::Extrude(const CrossSection& crossSection, float height,
|
||||
for (int i = 1; i < nDivisions + 1; ++i) {
|
||||
float alpha = i / float(nDivisions);
|
||||
float phi = alpha * twistDegrees;
|
||||
glm::mat2 transform(cosd(phi), sind(phi), -sind(phi), cosd(phi));
|
||||
glm::vec2 scale = glm::mix(glm::vec2(1.0f), scaleTop, alpha);
|
||||
transform = transform * glm::mat2(scale.x, 0.0f, 0.0f, scale.y);
|
||||
glm::mat2 rotation(cosd(phi), sind(phi), -sind(phi), cosd(phi));
|
||||
glm::mat2 transform = glm::mat2(scale.x, 0.0f, 0.0f, scale.y) * rotation;
|
||||
int j = 0;
|
||||
int idx = 0;
|
||||
for (const auto& poly : polygons) {
|
||||
@@ -321,6 +325,7 @@ Manifold Manifold::Extrude(const CrossSection& crossSection, float height,
|
||||
*/
|
||||
Manifold Manifold::Revolve(const CrossSection& crossSection,
|
||||
int circularSegments, float revolveDegrees) {
|
||||
ZoneScoped;
|
||||
Polygons polygons = crossSection.ToPolygons();
|
||||
|
||||
if (polygons.size() == 0) {
|
||||
@@ -328,8 +333,9 @@ Manifold Manifold::Revolve(const CrossSection& crossSection,
|
||||
}
|
||||
|
||||
const Rect bounds = crossSection.Bounds();
|
||||
const float radius = bounds.max.x;
|
||||
|
||||
if (bounds.max.x <= 0) {
|
||||
if (radius <= 0) {
|
||||
return Invalid();
|
||||
} else if (bounds.min.x < 0) {
|
||||
// Take the x>=0 slice.
|
||||
@@ -341,25 +347,19 @@ Manifold Manifold::Revolve(const CrossSection& crossSection,
|
||||
polygons = (crossSection ^ posBoundingBox).ToPolygons();
|
||||
}
|
||||
|
||||
float radius = 0.0f;
|
||||
for (const auto& poly : polygons) {
|
||||
for (const auto& vert : poly) {
|
||||
radius = fmax(radius, vert.x);
|
||||
}
|
||||
}
|
||||
|
||||
if (revolveDegrees > 360.0f) {
|
||||
revolveDegrees = 360.0f;
|
||||
}
|
||||
const bool isFullRevolution = revolveDegrees == 360.0f;
|
||||
|
||||
const int nDivisions = circularSegments > 2
|
||||
? circularSegments
|
||||
: Quality::GetCircularSegments(radius);
|
||||
const int nDivisions =
|
||||
circularSegments > 2
|
||||
? circularSegments
|
||||
: Quality::GetCircularSegments(radius) * revolveDegrees / 360;
|
||||
|
||||
auto pImpl_ = std::make_shared<Impl>();
|
||||
auto& vertPos = pImpl_->vertPos_;
|
||||
VecDH<glm::ivec3> triVertsDH;
|
||||
Vec<glm::ivec3> triVertsDH;
|
||||
auto& triVerts = triVertsDH;
|
||||
|
||||
std::vector<int> startPoses;
|
||||
@@ -385,14 +385,14 @@ Manifold Manifold::Revolve(const CrossSection& crossSection,
|
||||
|
||||
if (!isFullRevolution) startPoses.push_back(startPosIndex);
|
||||
|
||||
const glm::vec2 currPolyVertex = poly[polyVert];
|
||||
const glm::vec2 prevPolyVertex =
|
||||
poly[polyVert == 0 ? poly.size() - 1 : polyVert - 1];
|
||||
|
||||
const int prevStartPosIndex =
|
||||
startPosIndex +
|
||||
(polyVert == 0 ? nRevolveAxisVerts + (nSlices * nPosVerts) - nSlices
|
||||
: poly[polyVert - 1].x == 0.0 ? -1
|
||||
: -nSlices);
|
||||
glm::vec2 currPolyVertex = poly[polyVert];
|
||||
glm::vec2 prevPolyVertex =
|
||||
poly[polyVert == 0 ? poly.size() - 1 : polyVert - 1];
|
||||
(polyVert == 0 ? nRevolveAxisVerts + (nSlices * nPosVerts) : 0) +
|
||||
(prevPolyVertex.x == 0.0 ? -1 : -nSlices);
|
||||
|
||||
for (int slice = 0; slice < nSlices; ++slice) {
|
||||
const float phi = slice * dPhi;
|
||||
@@ -465,24 +465,22 @@ Manifold Manifold::Compose(const std::vector<Manifold>& manifolds) {
|
||||
* containing a copy of the original. It is the inverse operation of Compose().
|
||||
*/
|
||||
std::vector<Manifold> Manifold::Decompose() const {
|
||||
Graph graph;
|
||||
ZoneScoped;
|
||||
UnionFind<> uf(NumVert());
|
||||
// Graph graph;
|
||||
auto pImpl_ = GetCsgLeafNode().GetImpl();
|
||||
for (int i = 0; i < NumVert(); ++i) {
|
||||
graph.add_nodes(i);
|
||||
}
|
||||
for (const Halfedge& halfedge : pImpl_->halfedge_) {
|
||||
if (halfedge.IsForward())
|
||||
graph.add_edge(halfedge.startVert, halfedge.endVert);
|
||||
if (halfedge.IsForward()) uf.unionXY(halfedge.startVert, halfedge.endVert);
|
||||
}
|
||||
std::vector<int> componentIndices;
|
||||
const int numComponents = ConnectedComponents(componentIndices, graph);
|
||||
const int numComponents = uf.connectedComponents(componentIndices);
|
||||
|
||||
if (numComponents == 1) {
|
||||
std::vector<Manifold> meshes(1);
|
||||
meshes[0] = *this;
|
||||
return meshes;
|
||||
}
|
||||
VecDH<int> vertLabel(componentIndices);
|
||||
Vec<int> vertLabel(componentIndices);
|
||||
|
||||
std::vector<Manifold> meshes;
|
||||
for (int i = 0; i < numComponents; ++i) {
|
||||
@@ -490,7 +488,7 @@ std::vector<Manifold> Manifold::Decompose() const {
|
||||
// inherit original object's precision
|
||||
impl->precision_ = pImpl_->precision_;
|
||||
impl->vertPos_.resize(NumVert());
|
||||
VecDH<int> vertNew2Old(NumVert());
|
||||
Vec<int> vertNew2Old(NumVert());
|
||||
auto policy = autoPolicy(NumVert());
|
||||
auto start = zip(impl->vertPos_.begin(), vertNew2Old.begin());
|
||||
int nVert =
|
||||
@@ -501,14 +499,13 @@ std::vector<Manifold> Manifold::Decompose() const {
|
||||
start;
|
||||
impl->vertPos_.resize(nVert);
|
||||
|
||||
VecDH<int> faceNew2Old(NumTri());
|
||||
Vec<int> faceNew2Old(NumTri());
|
||||
sequence(policy, faceNew2Old.begin(), faceNew2Old.end());
|
||||
|
||||
int nFace =
|
||||
remove_if<decltype(faceNew2Old.begin())>(
|
||||
policy, faceNew2Old.begin(), faceNew2Old.end(),
|
||||
RemoveFace({pImpl_->halfedge_.cptrD(), vertLabel.cptrD(), i})) -
|
||||
faceNew2Old.begin();
|
||||
int nFace = remove_if<decltype(faceNew2Old.begin())>(
|
||||
policy, faceNew2Old.begin(), faceNew2Old.end(),
|
||||
RemoveFace({pImpl_->halfedge_, vertLabel, i})) -
|
||||
faceNew2Old.begin();
|
||||
faceNew2Old.resize(nFace);
|
||||
|
||||
impl->GatherFaces(*pImpl_, faceNew2Old);
|
||||
|
||||
+117
-65
@@ -12,21 +12,29 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "csg_tree.h"
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_priority_queue.h>)
|
||||
#include <tbb/tbb.h>
|
||||
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
|
||||
#include <tbb/concurrent_priority_queue.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <variant>
|
||||
|
||||
#include "boolean3.h"
|
||||
#include "csg_tree.h"
|
||||
#include "impl.h"
|
||||
#include "mesh_fixes.h"
|
||||
#include "par.h"
|
||||
|
||||
constexpr int kParallelThreshold = 4096;
|
||||
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
struct Transform4x3 {
|
||||
const glm::mat4x3 transform;
|
||||
|
||||
__host__ __device__ glm::vec3 operator()(glm::vec3 position) {
|
||||
glm::vec3 operator()(glm::vec3 position) {
|
||||
return transform * glm::vec4(position, 1.0f);
|
||||
}
|
||||
};
|
||||
@@ -36,7 +44,7 @@ struct UpdateHalfedge {
|
||||
const int nextEdge;
|
||||
const int nextFace;
|
||||
|
||||
__host__ __device__ Halfedge operator()(Halfedge edge) {
|
||||
Halfedge operator()(Halfedge edge) {
|
||||
edge.startVert += nextVert;
|
||||
edge.endVert += nextVert;
|
||||
edge.pairedHalfedge += nextEdge;
|
||||
@@ -48,7 +56,7 @@ struct UpdateHalfedge {
|
||||
struct UpdateTriProp {
|
||||
const int nextProp;
|
||||
|
||||
__host__ __device__ glm::ivec3 operator()(glm::ivec3 tri) {
|
||||
glm::ivec3 operator()(glm::ivec3 tri) {
|
||||
tri += nextProp;
|
||||
return tri;
|
||||
}
|
||||
@@ -57,19 +65,36 @@ struct UpdateTriProp {
|
||||
struct UpdateMeshIDs {
|
||||
const int offset;
|
||||
|
||||
__host__ __device__ TriRef operator()(TriRef ref) {
|
||||
TriRef operator()(TriRef ref) {
|
||||
ref.meshID += offset;
|
||||
return ref;
|
||||
}
|
||||
};
|
||||
|
||||
struct CheckOverlap {
|
||||
const Box *boxes;
|
||||
VecView<const Box> boxes;
|
||||
const size_t i;
|
||||
__host__ __device__ bool operator()(int j) {
|
||||
return boxes[i].DoesOverlap(boxes[j]);
|
||||
bool operator()(int j) { return boxes[i].DoesOverlap(boxes[j]); }
|
||||
};
|
||||
|
||||
using SharedImpl = std::variant<std::shared_ptr<const Manifold::Impl>,
|
||||
std::shared_ptr<Manifold::Impl>>;
|
||||
struct GetImplPtr {
|
||||
const Manifold::Impl *operator()(const SharedImpl &p) {
|
||||
if (std::holds_alternative<std::shared_ptr<const Manifold::Impl>>(p)) {
|
||||
return std::get_if<std::shared_ptr<const Manifold::Impl>>(&p)->get();
|
||||
} else {
|
||||
return std::get_if<std::shared_ptr<Manifold::Impl>>(&p)->get();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
struct MeshCompare {
|
||||
bool operator()(const SharedImpl &a, const SharedImpl &b) {
|
||||
return GetImplPtr()(a)->NumVert() < GetImplPtr()(b)->NumVert();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
namespace manifold {
|
||||
|
||||
@@ -147,6 +172,7 @@ CsgNodeType CsgLeafNode::GetNodeType() const { return CsgNodeType::Leaf; }
|
||||
*/
|
||||
Manifold::Impl CsgLeafNode::Compose(
|
||||
const std::vector<std::shared_ptr<CsgLeafNode>> &nodes) {
|
||||
ZoneScoped;
|
||||
float precision = -1;
|
||||
int numVert = 0;
|
||||
int numEdge = 0;
|
||||
@@ -197,12 +223,10 @@ Manifold::Impl CsgLeafNode::Compose(
|
||||
|
||||
// if we are already parallelizing for each node, do not perform multithreaded
|
||||
// copying as it will slightly hurt performance
|
||||
if (nodes.size() > 1 &&
|
||||
(policy == ExecutionPolicy::Par ||
|
||||
(policy == ExecutionPolicy::ParUnseq && !CudaEnabled())))
|
||||
if (nodes.size() > 1 && policy == ExecutionPolicy::Par)
|
||||
policy = ExecutionPolicy::Seq;
|
||||
|
||||
for_each_n_host(
|
||||
for_each_n(
|
||||
nodes.size() > 1 ? ExecutionPolicy::Par : ExecutionPolicy::Seq,
|
||||
countAt(0), nodes.size(),
|
||||
[&nodes, &vertIndices, &edgeIndices, &triIndices, &propVertIndices,
|
||||
@@ -229,9 +253,9 @@ Manifold::Impl CsgLeafNode::Compose(
|
||||
auto &oldProp = node->pImpl_->meshRelation_.properties;
|
||||
auto &newProp = combined.meshRelation_.properties;
|
||||
for (int p = 0; p < numProp; ++p) {
|
||||
strided_range<VecDH<float>::IterC> oldRange(
|
||||
oldProp.begin() + p, oldProp.end(), numProp);
|
||||
strided_range<VecDH<float>::Iter> newRange(
|
||||
strided_range<Vec<float>::IterC> oldRange(oldProp.begin() + p,
|
||||
oldProp.end(), numProp);
|
||||
strided_range<Vec<float>::Iter> newRange(
|
||||
newProp.begin() + numPropOut * propVertIndices[i] + p,
|
||||
newProp.end(), numPropOut);
|
||||
copy(policy, oldRange.begin(), oldRange.end(), newRange.begin());
|
||||
@@ -271,14 +295,13 @@ Manifold::Impl CsgLeafNode::Compose(
|
||||
countAt(0)),
|
||||
node->pImpl_->halfedgeTangent_.size(),
|
||||
TransformTangents{glm::mat3(node->transform_), invert,
|
||||
node->pImpl_->halfedgeTangent_.cptrD(),
|
||||
node->pImpl_->halfedge_.cptrD()});
|
||||
node->pImpl_->halfedgeTangent_,
|
||||
node->pImpl_->halfedge_});
|
||||
if (invert)
|
||||
for_each_n(policy,
|
||||
zip(combined.meshRelation_.triRef.begin(),
|
||||
countAt(triIndices[i])),
|
||||
node->pImpl_->NumTri(),
|
||||
FlipTris({combined.halfedge_.ptrD()}));
|
||||
node->pImpl_->NumTri(), FlipTris({combined.halfedge_}));
|
||||
}
|
||||
// Since the nodes may be copies containing the same meshIDs, it is
|
||||
// important to add an offset so that each node instance gets
|
||||
@@ -432,17 +455,55 @@ std::shared_ptr<CsgLeafNode> CsgOpNode::ToLeafNode() const {
|
||||
std::shared_ptr<Manifold::Impl> CsgOpNode::BatchBoolean(
|
||||
OpType operation,
|
||||
std::vector<std::shared_ptr<const Manifold::Impl>> &results) {
|
||||
ZoneScoped;
|
||||
auto getImplPtr = GetImplPtr();
|
||||
ASSERT(operation != OpType::Subtract, logicErr,
|
||||
"BatchBoolean doesn't support Difference.");
|
||||
auto cmpFn = [](std::shared_ptr<const Manifold::Impl> a,
|
||||
std::shared_ptr<const Manifold::Impl> b) {
|
||||
// invert the order because we want a min heap
|
||||
return a->NumVert() > b->NumVert();
|
||||
};
|
||||
|
||||
// common cases
|
||||
if (results.size() == 0) return std::make_shared<Manifold::Impl>();
|
||||
if (results.size() == 1)
|
||||
return std::make_shared<Manifold::Impl>(*results.front());
|
||||
if (results.size() == 2) {
|
||||
Boolean3 boolean(*results[0], *results[1], operation);
|
||||
return std::make_shared<Manifold::Impl>(boolean.Result(operation));
|
||||
}
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
|
||||
if (!ManifoldParams().deterministic) {
|
||||
tbb::task_group group;
|
||||
tbb::concurrent_priority_queue<SharedImpl, MeshCompare> queue(
|
||||
results.size());
|
||||
for (auto result : results) {
|
||||
queue.emplace(result);
|
||||
}
|
||||
results.clear();
|
||||
std::function<void()> process = [&]() {
|
||||
while (queue.size() > 1) {
|
||||
SharedImpl a, b;
|
||||
if (!queue.try_pop(a)) continue;
|
||||
if (!queue.try_pop(b)) {
|
||||
queue.push(a);
|
||||
continue;
|
||||
}
|
||||
group.run([&, a, b]() {
|
||||
const Manifold::Impl *aImpl;
|
||||
const Manifold::Impl *bImpl;
|
||||
Boolean3 boolean(*getImplPtr(a), *getImplPtr(b), operation);
|
||||
queue.emplace(
|
||||
std::make_shared<Manifold::Impl>(boolean.Result(operation)));
|
||||
return group.run(process);
|
||||
});
|
||||
}
|
||||
};
|
||||
group.run_and_wait(process);
|
||||
SharedImpl r;
|
||||
queue.try_pop(r);
|
||||
return *std::get_if<std::shared_ptr<Manifold::Impl>>(&r);
|
||||
}
|
||||
#endif
|
||||
// apply boolean operations starting from smaller meshes
|
||||
// the assumption is that boolean operations on smaller meshes is faster,
|
||||
// due to less data being copied and processed
|
||||
auto cmpFn = MeshCompare();
|
||||
std::make_heap(results.begin(), results.end(), cmpFn);
|
||||
while (results.size() > 1) {
|
||||
std::pop_heap(results.begin(), results.end(), cmpFn);
|
||||
@@ -460,10 +521,7 @@ std::shared_ptr<Manifold::Impl> CsgOpNode::BatchBoolean(
|
||||
std::make_shared<const Manifold::Impl>(boolean.Result(operation)));
|
||||
std::push_heap(results.begin(), results.end(), cmpFn);
|
||||
}
|
||||
if (results.size() == 1) {
|
||||
return std::make_shared<Manifold::Impl>(*results.front());
|
||||
}
|
||||
return std::make_shared<Manifold::Impl>();
|
||||
return std::make_shared<Manifold::Impl>(*results.front());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -473,6 +531,7 @@ std::shared_ptr<Manifold::Impl> CsgOpNode::BatchBoolean(
|
||||
* `BatchBoolean` instead of using `Compose` for non-intersecting manifolds.
|
||||
*/
|
||||
void CsgOpNode::BatchUnion() const {
|
||||
ZoneScoped;
|
||||
// INVARIANT: children_ is a vector of leaf nodes
|
||||
// this kMaxUnionSize is a heuristic to avoid the pairwise disjoint check
|
||||
// with O(n^2) complexity to take too long.
|
||||
@@ -485,22 +544,20 @@ void CsgOpNode::BatchUnion() const {
|
||||
const int start = (children_.size() > kMaxUnionSize)
|
||||
? (children_.size() - kMaxUnionSize)
|
||||
: 0;
|
||||
VecDH<Box> boxes;
|
||||
Vec<Box> boxes;
|
||||
boxes.reserve(children_.size() - start);
|
||||
for (int i = start; i < children_.size(); i++) {
|
||||
boxes.push_back(std::dynamic_pointer_cast<CsgLeafNode>(children_[i])
|
||||
->GetImpl()
|
||||
->bBox_);
|
||||
}
|
||||
const Box *boxesD = boxes.cptrD();
|
||||
// partition the children into a set of disjoint sets
|
||||
// each set contains a set of children that are pairwise disjoint
|
||||
std::vector<VecDH<size_t>> disjointSets;
|
||||
std::vector<Vec<size_t>> disjointSets;
|
||||
for (size_t i = 0; i < boxes.size(); i++) {
|
||||
auto lambda = [boxesD, i](const VecDH<size_t> &set) {
|
||||
return find_if<decltype(set.end())>(
|
||||
autoPolicy(set.size()), set.begin(), set.end(),
|
||||
CheckOverlap({boxesD, i})) == set.end();
|
||||
auto lambda = [&boxes, i](const Vec<size_t> &set) {
|
||||
return std::find_if(set.begin(), set.end(), CheckOverlap({boxes, i})) ==
|
||||
set.end();
|
||||
};
|
||||
auto it = std::find_if(disjointSets.begin(), disjointSets.end(), lambda);
|
||||
if (it == disjointSets.end()) {
|
||||
@@ -510,27 +567,22 @@ void CsgOpNode::BatchUnion() const {
|
||||
}
|
||||
}
|
||||
// compose each set of disjoint children
|
||||
std::vector<std::shared_ptr<const Manifold::Impl>> impls(
|
||||
disjointSets.size());
|
||||
for_each_n_host(
|
||||
disjointSets.size() > 1 ? ExecutionPolicy::Par : ExecutionPolicy::Seq,
|
||||
countAt(0), disjointSets.size(),
|
||||
[children_, &impls, &disjointSets, start](int i) {
|
||||
auto set = disjointSets[i];
|
||||
if (set.size() == 1) {
|
||||
impls[i] = std::dynamic_pointer_cast<CsgLeafNode>(
|
||||
children_[start + set[0]])
|
||||
->GetImpl();
|
||||
} else {
|
||||
std::vector<std::shared_ptr<CsgLeafNode>> tmp;
|
||||
for (size_t j : set) {
|
||||
tmp.push_back(
|
||||
std::dynamic_pointer_cast<CsgLeafNode>(children_[start + j]));
|
||||
}
|
||||
impls[i] = std::make_shared<const Manifold::Impl>(
|
||||
CsgLeafNode::Compose(tmp));
|
||||
}
|
||||
});
|
||||
std::vector<std::shared_ptr<const Manifold::Impl>> impls;
|
||||
for (auto &set : disjointSets) {
|
||||
if (set.size() == 1) {
|
||||
impls.push_back(
|
||||
std::dynamic_pointer_cast<CsgLeafNode>(children_[start + set[0]])
|
||||
->GetImpl());
|
||||
} else {
|
||||
std::vector<std::shared_ptr<CsgLeafNode>> tmp;
|
||||
for (size_t j : set) {
|
||||
tmp.push_back(
|
||||
std::dynamic_pointer_cast<CsgLeafNode>(children_[start + j]));
|
||||
}
|
||||
impls.push_back(
|
||||
std::make_shared<const Manifold::Impl>(CsgLeafNode::Compose(tmp)));
|
||||
}
|
||||
}
|
||||
|
||||
children_.erase(children_.begin() + start, children_.end());
|
||||
children_.push_back(
|
||||
@@ -554,14 +606,14 @@ std::vector<std::shared_ptr<CsgNode>> &CsgOpNode::GetChildren(
|
||||
|
||||
if (forceToLeafNodes && !impl->forcedToLeafNodes_) {
|
||||
impl->forcedToLeafNodes_ = true;
|
||||
for_each_host(impl->children_.size() > 1 ? ExecutionPolicy::Par
|
||||
: ExecutionPolicy::Seq,
|
||||
impl->children_.begin(), impl->children_.end(),
|
||||
[](auto &child) {
|
||||
if (child->GetNodeType() != CsgNodeType::Leaf) {
|
||||
child = child->ToLeafNode();
|
||||
}
|
||||
});
|
||||
for_each(impl->children_.size() > 1 && !ManifoldParams().deterministic
|
||||
? ExecutionPolicy::Par
|
||||
: ExecutionPolicy::Seq,
|
||||
impl->children_.begin(), impl->children_.end(), [](auto &child) {
|
||||
if (child->GetNodeType() != CsgNodeType::Leaf) {
|
||||
child = child->ToLeafNode();
|
||||
}
|
||||
});
|
||||
}
|
||||
return impl->children_;
|
||||
}
|
||||
|
||||
+148
-73
@@ -18,7 +18,7 @@
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
|
||||
__host__ __device__ glm::ivec3 TriOf(int edge) {
|
||||
glm::ivec3 TriOf(int edge) {
|
||||
glm::ivec3 triEdge;
|
||||
triEdge[0] = edge;
|
||||
triEdge[1] = NextHalfedge(triEdge[0]);
|
||||
@@ -26,7 +26,7 @@ __host__ __device__ glm::ivec3 TriOf(int edge) {
|
||||
return triEdge;
|
||||
}
|
||||
|
||||
__host__ __device__ bool Is01Longest(glm::vec2 v0, glm::vec2 v1, glm::vec2 v2) {
|
||||
bool Is01Longest(glm::vec2 v0, glm::vec2 v1, glm::vec2 v2) {
|
||||
const glm::vec2 e[3] = {v1 - v0, v2 - v1, v0 - v2};
|
||||
float l[3];
|
||||
for (int i : {0, 1, 2}) l[i] = glm::dot(e[i], e[i]);
|
||||
@@ -36,7 +36,7 @@ __host__ __device__ bool Is01Longest(glm::vec2 v0, glm::vec2 v1, glm::vec2 v2) {
|
||||
struct DuplicateEdge {
|
||||
const Halfedge* sortedHalfedge;
|
||||
|
||||
__host__ __device__ bool operator()(int edge) {
|
||||
bool operator()(int edge) {
|
||||
const Halfedge& halfedge = sortedHalfedge[edge];
|
||||
const Halfedge& nextHalfedge = sortedHalfedge[edge + 1];
|
||||
return halfedge.startVert == nextHalfedge.startVert &&
|
||||
@@ -45,11 +45,11 @@ struct DuplicateEdge {
|
||||
};
|
||||
|
||||
struct ShortEdge {
|
||||
const Halfedge* halfedge;
|
||||
const glm::vec3* vertPos;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
const float precision;
|
||||
|
||||
__host__ __device__ bool operator()(int edge) const {
|
||||
bool operator()(int edge) const {
|
||||
if (halfedge[edge].pairedHalfedge < 0) return false;
|
||||
// Flag short edges
|
||||
const glm::vec3 delta =
|
||||
@@ -59,10 +59,10 @@ struct ShortEdge {
|
||||
};
|
||||
|
||||
struct FlagEdge {
|
||||
const Halfedge* halfedge;
|
||||
const TriRef* triRef;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const TriRef> triRef;
|
||||
|
||||
__host__ __device__ bool operator()(int edge) const {
|
||||
bool operator()(int edge) const {
|
||||
if (halfedge[edge].pairedHalfedge < 0) return false;
|
||||
// Flag redundant edges - those where the startVert is surrounded by only
|
||||
// two original triangles.
|
||||
@@ -82,12 +82,12 @@ struct FlagEdge {
|
||||
};
|
||||
|
||||
struct SwappableEdge {
|
||||
const Halfedge* halfedge;
|
||||
const glm::vec3* vertPos;
|
||||
const glm::vec3* triNormal;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
VecView<const glm::vec3> triNormal;
|
||||
const float precision;
|
||||
|
||||
__host__ __device__ bool operator()(int edge) const {
|
||||
bool operator()(int edge) const {
|
||||
if (halfedge[edge].pairedHalfedge < 0) return false;
|
||||
|
||||
int tri = halfedge[edge].face;
|
||||
@@ -145,27 +145,32 @@ namespace manifold {
|
||||
void Manifold::Impl::SimplifyTopology() {
|
||||
if (!halfedge_.size()) return;
|
||||
|
||||
int nbEdges = halfedge_.size();
|
||||
const int nbEdges = halfedge_.size();
|
||||
auto policy = autoPolicy(nbEdges);
|
||||
int numFlagged = 0;
|
||||
VecDH<uint8_t> bflags(nbEdges);
|
||||
uint8_t* bflagsPtr = bflags.ptrD();
|
||||
Vec<uint8_t> bflags(nbEdges);
|
||||
|
||||
VecDH<SortEntry> entries(nbEdges);
|
||||
SortEntry* entriesPtr = entries.ptrD();
|
||||
// In the case of a very bad triangulation, it is possible to create pinched
|
||||
// verts. They must be removed before edge collapse.
|
||||
SplitPinchedVerts();
|
||||
|
||||
auto policy = autoPolicy(halfedge_.size());
|
||||
for_each_n(policy, countAt(0), nbEdges, [=] __host__ __device__(int i) {
|
||||
entriesPtr[i].start = halfedge_[i].startVert;
|
||||
entriesPtr[i].end = halfedge_[i].endVert;
|
||||
entriesPtr[i].index = i;
|
||||
});
|
||||
{
|
||||
ZoneScopedN("DedupeEdge");
|
||||
Vec<SortEntry> entries;
|
||||
entries.reserve(nbEdges / 2);
|
||||
for (int i = 0; i < nbEdges; ++i) {
|
||||
if (halfedge_[i].IsForward()) {
|
||||
entries.push_back({halfedge_[i].startVert, halfedge_[i].endVert, i});
|
||||
}
|
||||
}
|
||||
|
||||
sort(policy, entries.begin(), entries.end());
|
||||
for (int i = 0; i < nbEdges - 1; ++i) {
|
||||
if (entries[i].start == entries[i + 1].start &&
|
||||
entries[i].end == entries[i + 1].end) {
|
||||
DedupeEdge(entries[i].index);
|
||||
numFlagged++;
|
||||
stable_sort(policy, entries.begin(), entries.end());
|
||||
for (int i = 0; i < entries.size() - 1; ++i) {
|
||||
if (entries[i].start == entries[i + 1].start &&
|
||||
entries[i].end == entries[i + 1].end) {
|
||||
DedupeEdge(entries[i].index);
|
||||
numFlagged++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,14 +181,21 @@ void Manifold::Impl::SimplifyTopology() {
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!ManifoldParams().cleanupTriangles) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<int> scratchBuffer;
|
||||
scratchBuffer.reserve(10);
|
||||
{
|
||||
ZoneScopedN("CollapseShortEdge");
|
||||
numFlagged = 0;
|
||||
ShortEdge se{halfedge_.cptrD(), vertPos_.cptrD(), precision_};
|
||||
for_each_n(policy, countAt(0), nbEdges,
|
||||
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
|
||||
ShortEdge se{halfedge_, vertPos_, precision_};
|
||||
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
|
||||
for (int i = 0; i < nbEdges; ++i) {
|
||||
if (bflags[i]) {
|
||||
CollapseEdge(i);
|
||||
CollapseEdge(i, scratchBuffer);
|
||||
scratchBuffer.resize(0);
|
||||
numFlagged++;
|
||||
}
|
||||
}
|
||||
@@ -197,13 +209,14 @@ void Manifold::Impl::SimplifyTopology() {
|
||||
#endif
|
||||
|
||||
{
|
||||
ZoneScopedN("CollapseFlaggedEdge");
|
||||
numFlagged = 0;
|
||||
FlagEdge se{halfedge_.cptrD(), meshRelation_.triRef.cptrD()};
|
||||
for_each_n(policy, countAt(0), nbEdges,
|
||||
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
|
||||
FlagEdge se{halfedge_, meshRelation_.triRef};
|
||||
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
|
||||
for (int i = 0; i < nbEdges; ++i) {
|
||||
if (bflags[i]) {
|
||||
CollapseEdge(i);
|
||||
CollapseEdge(i, scratchBuffer);
|
||||
scratchBuffer.resize(0);
|
||||
numFlagged++;
|
||||
}
|
||||
}
|
||||
@@ -217,15 +230,23 @@ void Manifold::Impl::SimplifyTopology() {
|
||||
#endif
|
||||
|
||||
{
|
||||
ZoneScopedN("RecursiveEdgeSwap");
|
||||
numFlagged = 0;
|
||||
SwappableEdge se{halfedge_.cptrD(), vertPos_.cptrD(), faceNormal_.cptrD(),
|
||||
precision_};
|
||||
for_each_n(policy, countAt(0), nbEdges,
|
||||
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
|
||||
SwappableEdge se{halfedge_, vertPos_, faceNormal_, precision_};
|
||||
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
|
||||
std::vector<int> edgeSwapStack;
|
||||
std::vector<int> visited(halfedge_.size(), -1);
|
||||
int tag = 0;
|
||||
for (int i = 0; i < nbEdges; ++i) {
|
||||
if (bflags[i]) {
|
||||
RecursiveEdgeSwap(i);
|
||||
numFlagged++;
|
||||
tag++;
|
||||
RecursiveEdgeSwap(i, tag, visited, edgeSwapStack, scratchBuffer);
|
||||
while (!edgeSwapStack.empty()) {
|
||||
int last = edgeSwapStack.back();
|
||||
edgeSwapStack.pop_back();
|
||||
RecursiveEdgeSwap(last, tag, visited, edgeSwapStack, scratchBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,6 +258,8 @@ void Manifold::Impl::SimplifyTopology() {
|
||||
#endif
|
||||
}
|
||||
|
||||
// Deduplicate the given 4-manifold edge by duplicating endVert, thus making the
|
||||
// edges distinct. Also duplicates startVert if it becomes pinched.
|
||||
void Manifold::Impl::DedupeEdge(const int edge) {
|
||||
// Orbit endVert
|
||||
const int startVert = halfedge_[edge].startVert;
|
||||
@@ -245,6 +268,7 @@ void Manifold::Impl::DedupeEdge(const int edge) {
|
||||
while (current != edge) {
|
||||
const int vert = halfedge_[current].startVert;
|
||||
if (vert == startVert) {
|
||||
// Single topological unit needs 2 faces added to be split
|
||||
const int newVert = vertPos_.size();
|
||||
vertPos_.push_back(vertPos_[endVert]);
|
||||
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
|
||||
@@ -291,6 +315,45 @@ void Manifold::Impl::DedupeEdge(const int edge) {
|
||||
|
||||
current = halfedge_[NextHalfedge(current)].pairedHalfedge;
|
||||
}
|
||||
|
||||
if (current == edge) {
|
||||
// Separate topological unit needs no new faces to be split
|
||||
const int newVert = vertPos_.size();
|
||||
vertPos_.push_back(vertPos_[endVert]);
|
||||
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
|
||||
|
||||
do {
|
||||
halfedge_[current].endVert = newVert;
|
||||
current = NextHalfedge(current);
|
||||
halfedge_[current].startVert = newVert;
|
||||
current = halfedge_[current].pairedHalfedge;
|
||||
} while (current != edge);
|
||||
}
|
||||
|
||||
// Orbit startVert
|
||||
const int pair = halfedge_[edge].pairedHalfedge;
|
||||
current = halfedge_[NextHalfedge(pair)].pairedHalfedge;
|
||||
while (current != pair) {
|
||||
const int vert = halfedge_[current].startVert;
|
||||
if (vert == endVert) {
|
||||
break; // Connected: not a pinched vert
|
||||
}
|
||||
current = halfedge_[NextHalfedge(current)].pairedHalfedge;
|
||||
}
|
||||
|
||||
if (current == pair) {
|
||||
// Split the pinched vert the previous split created.
|
||||
const int newVert = vertPos_.size();
|
||||
vertPos_.push_back(vertPos_[endVert]);
|
||||
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
|
||||
|
||||
do {
|
||||
halfedge_[current].endVert = newVert;
|
||||
current = NextHalfedge(current);
|
||||
halfedge_[current].startVert = newVert;
|
||||
current = halfedge_[current].pairedHalfedge;
|
||||
} while (current != pair);
|
||||
}
|
||||
}
|
||||
|
||||
void Manifold::Impl::PairUp(int edge0, int edge1) {
|
||||
@@ -336,6 +399,7 @@ void Manifold::Impl::FormLoop(int current, int end) {
|
||||
}
|
||||
|
||||
void Manifold::Impl::CollapseTri(const glm::ivec3& triEdge) {
|
||||
if (halfedge_[triEdge[1]].pairedHalfedge == -1) return;
|
||||
int pair1 = halfedge_[triEdge[1]].pairedHalfedge;
|
||||
int pair2 = halfedge_[triEdge[2]].pairedHalfedge;
|
||||
halfedge_[pair1].pairedHalfedge = pair2;
|
||||
@@ -348,6 +412,7 @@ void Manifold::Impl::CollapseTri(const glm::ivec3& triEdge) {
|
||||
void Manifold::Impl::RemoveIfFolded(int edge) {
|
||||
const glm::ivec3 tri0edge = TriOf(edge);
|
||||
const glm::ivec3 tri1edge = TriOf(halfedge_[edge].pairedHalfedge);
|
||||
if (halfedge_[tri0edge[1]].pairedHalfedge == -1) return;
|
||||
if (halfedge_[tri0edge[1]].endVert == halfedge_[tri1edge[1]].endVert) {
|
||||
if (halfedge_[tri0edge[1]].pairedHalfedge == tri1edge[2]) {
|
||||
if (halfedge_[tri0edge[2]].pairedHalfedge == tri1edge[1]) {
|
||||
@@ -372,9 +437,13 @@ void Manifold::Impl::RemoveIfFolded(int edge) {
|
||||
}
|
||||
}
|
||||
|
||||
void Manifold::Impl::CollapseEdge(const int edge) {
|
||||
VecDH<TriRef>& triRef = meshRelation_.triRef;
|
||||
VecDH<glm::ivec3>& triProp = meshRelation_.triProperties;
|
||||
// Collapses the given edge by removing startVert. May split the mesh
|
||||
// topologically if the collapse would have resulted in a 4-manifold edge. Do
|
||||
// not collapse an edge if startVert is pinched - the vert will be marked NaN,
|
||||
// but other edges may still be pointing to it.
|
||||
void Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
|
||||
Vec<TriRef>& triRef = meshRelation_.triRef;
|
||||
Vec<glm::ivec3>& triProp = meshRelation_.triProperties;
|
||||
|
||||
const Halfedge toRemove = halfedge_[edge];
|
||||
if (toRemove.pairedHalfedge < 0) return;
|
||||
@@ -388,7 +457,6 @@ void Manifold::Impl::CollapseEdge(const int edge) {
|
||||
const glm::vec3 delta = pNew - pOld;
|
||||
const bool shortEdge = glm::dot(delta, delta) < precision_ * precision_;
|
||||
|
||||
std::vector<int> edges;
|
||||
// Orbit endVert
|
||||
int current = halfedge_[tri0edge[1]].pairedHalfedge;
|
||||
while (current != tri1edge[2]) {
|
||||
@@ -443,25 +511,20 @@ void Manifold::Impl::CollapseEdge(const int edge) {
|
||||
const int tri1 = toRemove.pairedHalfedge / 3;
|
||||
const int triVert0 = (edge + 1) % 3;
|
||||
const int triVert1 = toRemove.pairedHalfedge % 3;
|
||||
const int prop0 = triProp.size() > 0 ? triProp[tri0][edge % 3] : -1;
|
||||
const int prop1 = triProp.size() > 0
|
||||
? triProp[tri1][(toRemove.pairedHalfedge + 1) % 3]
|
||||
: -1;
|
||||
current = start;
|
||||
while (current != tri0edge[2]) {
|
||||
current = NextHalfedge(current);
|
||||
|
||||
// Update the shifted triangles to the vertBary of endVert
|
||||
const int tri = current / 3;
|
||||
const int vIdx = current - 3 * tri;
|
||||
|
||||
if (!shortEdge) {
|
||||
if (triProp.size() > 0) {
|
||||
if (triProp[tri][vIdx] == prop0) {
|
||||
triProp[tri][vIdx] = triProp[tri0][triVert0];
|
||||
} else if (triProp[tri][vIdx] == prop1) {
|
||||
triProp[tri][vIdx] = triProp[tri1][triVert1];
|
||||
}
|
||||
if (triProp.size() > 0) {
|
||||
// Update the shifted triangles to the vertBary of endVert
|
||||
const int tri = current / 3;
|
||||
const int vIdx = current - 3 * tri;
|
||||
if (triRef[tri].meshID == triRef[tri0].meshID &&
|
||||
triRef[tri].tri == triRef[tri0].tri) {
|
||||
triProp[tri][vIdx] = triProp[tri0][triVert0];
|
||||
} else if (triRef[tri].meshID == triRef[tri1].meshID &&
|
||||
triRef[tri].tri == triRef[tri1].tri) {
|
||||
triProp[tri][vIdx] = triProp[tri1][triVert1];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,13 +546,19 @@ void Manifold::Impl::CollapseEdge(const int edge) {
|
||||
RemoveIfFolded(start);
|
||||
}
|
||||
|
||||
void Manifold::Impl::RecursiveEdgeSwap(const int edge) {
|
||||
VecDH<TriRef>& triRef = meshRelation_.triRef;
|
||||
void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
|
||||
std::vector<int>& visited,
|
||||
std::vector<int>& edgeSwapStack,
|
||||
std::vector<int>& edges) {
|
||||
Vec<TriRef>& triRef = meshRelation_.triRef;
|
||||
|
||||
if (edge < 0) return;
|
||||
const int pair = halfedge_[edge].pairedHalfedge;
|
||||
if (pair < 0) return;
|
||||
|
||||
// avoid infinite recursion
|
||||
if (visited[edge] == tag && visited[pair] == tag) return;
|
||||
|
||||
const glm::ivec3 tri0edge = TriOf(edge);
|
||||
const glm::ivec3 tri1edge = TriOf(pair);
|
||||
const glm::ivec3 perm0 = TriOf(edge % 3);
|
||||
@@ -530,8 +599,8 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge) {
|
||||
const float a = glm::max(0.0f, glm::min(1.0f, l02 / l01));
|
||||
// Update properties if applicable
|
||||
if (meshRelation_.properties.size() > 0) {
|
||||
VecDH<glm::ivec3>& triProp = meshRelation_.triProperties;
|
||||
VecDH<float>& prop = meshRelation_.properties;
|
||||
Vec<glm::ivec3>& triProp = meshRelation_.triProperties;
|
||||
Vec<float>& prop = meshRelation_.properties;
|
||||
triProp[tri0] = triProp[tri1];
|
||||
triProp[tri0][perm0[1]] = triProp[tri1][perm1[0]];
|
||||
triProp[tri0][perm0[0]] = triProp[tri1][perm1[2]];
|
||||
@@ -568,12 +637,14 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge) {
|
||||
SwapEdge();
|
||||
const glm::vec2 e23 = v[3] - v[2];
|
||||
if (glm::dot(e23, e23) < precision_ * precision_) {
|
||||
CollapseEdge(tri0edge[2]);
|
||||
tag++;
|
||||
CollapseEdge(tri0edge[2], edges);
|
||||
edges.resize(0);
|
||||
} else {
|
||||
RecursiveEdgeSwap(tri0edge[0]);
|
||||
RecursiveEdgeSwap(tri0edge[1]);
|
||||
RecursiveEdgeSwap(tri1edge[0]);
|
||||
RecursiveEdgeSwap(tri1edge[1]);
|
||||
visited[edge] = tag;
|
||||
visited[pair] = tag;
|
||||
edgeSwapStack.insert(edgeSwapStack.end(), {tri1edge[1], tri1edge[0],
|
||||
tri0edge[1], tri0edge[0]});
|
||||
}
|
||||
return;
|
||||
} else if (CCW(v[0], v[3], v[2], precision_) <= 0 ||
|
||||
@@ -582,11 +653,15 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge) {
|
||||
}
|
||||
// Normal path
|
||||
SwapEdge();
|
||||
RecursiveEdgeSwap(halfedge_[tri0edge[1]].pairedHalfedge);
|
||||
RecursiveEdgeSwap(halfedge_[tri1edge[0]].pairedHalfedge);
|
||||
visited[edge] = tag;
|
||||
visited[pair] = tag;
|
||||
edgeSwapStack.insert(edgeSwapStack.end(),
|
||||
{halfedge_[tri1edge[0]].pairedHalfedge,
|
||||
halfedge_[tri0edge[1]].pairedHalfedge});
|
||||
}
|
||||
|
||||
void Manifold::Impl::SplitPinchedVerts() {
|
||||
ZoneScoped;
|
||||
std::vector<bool> vertProcessed(NumVert(), false);
|
||||
std::vector<bool> halfedgeProcessed(halfedge_.size(), false);
|
||||
for (int i = 0; i < halfedge_.size(); ++i) {
|
||||
|
||||
+189
-43
@@ -12,13 +12,21 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <map>
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_map.h>)
|
||||
#include <tbb/tbb.h>
|
||||
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
|
||||
#include <tbb/concurrent_map.h>
|
||||
#endif
|
||||
#include <unordered_set>
|
||||
|
||||
#include "impl.h"
|
||||
#include "polygon.h"
|
||||
|
||||
namespace manifold {
|
||||
|
||||
using GeneralTriangulation = std::function<std::vector<glm::ivec3>(int)>;
|
||||
using AddTriangle = std::function<void(int, glm::ivec3, glm::vec3, TriRef)>;
|
||||
|
||||
/**
|
||||
* Triangulates the faces. In this case, the halfedge_ vector is not yet a set
|
||||
* of triangles as required by this data structure, but is instead a set of
|
||||
@@ -29,17 +37,15 @@ namespace manifold {
|
||||
* represents the mesh as a set of triangles as usual. In this process the
|
||||
* faceNormal_ values are retained, repeated as necessary.
|
||||
*/
|
||||
void Manifold::Impl::Face2Tri(const VecDH<int>& faceEdge,
|
||||
const VecDH<TriRef>& halfedgeRef) {
|
||||
VecDH<glm::ivec3> triVerts;
|
||||
VecDH<glm::vec3> triNormal;
|
||||
VecDH<TriRef>& triRef = meshRelation_.triRef;
|
||||
void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
|
||||
const Vec<TriRef>& halfedgeRef) {
|
||||
ZoneScoped;
|
||||
Vec<glm::ivec3> triVerts;
|
||||
Vec<glm::vec3> triNormal;
|
||||
Vec<TriRef>& triRef = meshRelation_.triRef;
|
||||
triRef.resize(0);
|
||||
triVerts.reserve(halfedge_.size());
|
||||
triNormal.reserve(halfedge_.size());
|
||||
triRef.reserve(halfedge_.size());
|
||||
|
||||
for (int face = 0; face < faceEdge.size() - 1; ++face) {
|
||||
auto processFace = [&](GeneralTriangulation general, AddTriangle addTri,
|
||||
int face) {
|
||||
const int firstEdge = faceEdge[face];
|
||||
const int lastEdge = faceEdge[face + 1];
|
||||
const int numEdge = lastEdge - firstEdge;
|
||||
@@ -63,9 +69,7 @@ void Manifold::Impl::Face2Tri(const VecDH<int>& faceEdge,
|
||||
ASSERT(ends[0] == tri[1] && ends[1] == tri[2] && ends[2] == tri[0],
|
||||
topologyErr, "These 3 edges do not form a triangle!");
|
||||
|
||||
triVerts.push_back(tri);
|
||||
triNormal.push_back(normal);
|
||||
triRef.push_back(halfedgeRef[firstEdge]);
|
||||
addTri(face, tri, normal, halfedgeRef[firstEdge]);
|
||||
} else if (numEdge == 4) { // Pair of triangles
|
||||
int mapping[4] = {halfedge_[firstEdge].startVert,
|
||||
halfedge_[firstEdge + 1].startVert,
|
||||
@@ -111,44 +115,95 @@ void Manifold::Impl::Face2Tri(const VecDH<int>& faceEdge,
|
||||
}
|
||||
}
|
||||
|
||||
for (auto tri : {tri0, tri1}) {
|
||||
triVerts.push_back(tri);
|
||||
triNormal.push_back(normal);
|
||||
triRef.push_back(halfedgeRef[firstEdge]);
|
||||
for (const auto& tri : {tri0, tri1}) {
|
||||
addTri(face, tri, normal, halfedgeRef[firstEdge]);
|
||||
}
|
||||
} else { // General triangulation
|
||||
const glm::mat3x2 projection = GetAxisAlignedProjection(normal);
|
||||
|
||||
const PolygonsIdx polys = Face2Polygons(face, projection, faceEdge);
|
||||
|
||||
std::vector<glm::ivec3> newTris = TriangulateIdx(polys, precision_);
|
||||
|
||||
for (auto tri : newTris) {
|
||||
triVerts.push_back(tri);
|
||||
triNormal.push_back(normal);
|
||||
triRef.push_back(halfedgeRef[firstEdge]);
|
||||
for (const auto& tri : general(face)) {
|
||||
addTri(face, tri, normal, halfedgeRef[firstEdge]);
|
||||
}
|
||||
}
|
||||
};
|
||||
auto generalTriangulation = [&](int face) {
|
||||
const glm::vec3 normal = faceNormal_[face];
|
||||
const glm::mat3x2 projection = GetAxisAlignedProjection(normal);
|
||||
const PolygonsIdx polys =
|
||||
Face2Polygons(halfedge_.cbegin() + faceEdge[face],
|
||||
halfedge_.cbegin() + faceEdge[face + 1], projection);
|
||||
return TriangulateIdx(polys, precision_);
|
||||
};
|
||||
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
|
||||
tbb::task_group group;
|
||||
// map from face to triangle
|
||||
tbb::concurrent_unordered_map<int, std::vector<glm::ivec3>> results;
|
||||
Vec<int> triCount(faceEdge.size());
|
||||
triCount.back() = 0;
|
||||
// precompute number of triangles per face, and launch async tasks to
|
||||
// triangulate complex faces
|
||||
for_each(autoPolicy(faceEdge.size()), countAt(0),
|
||||
countAt(faceEdge.size() - 1), [&](int face) {
|
||||
triCount[face] = faceEdge[face + 1] - faceEdge[face] - 2;
|
||||
ASSERT(triCount[face] >= 1, topologyErr,
|
||||
"face has less than three edges.");
|
||||
if (triCount[face] > 2)
|
||||
group.run([&, face] {
|
||||
std::vector<glm::ivec3> newTris = generalTriangulation(face);
|
||||
triCount[face] = newTris.size();
|
||||
results[face] = std::move(newTris);
|
||||
});
|
||||
});
|
||||
group.wait();
|
||||
// prefix sum computation (assign unique index to each face) and preallocation
|
||||
exclusive_scan(autoPolicy(triCount.size()), triCount.begin(), triCount.end(),
|
||||
triCount.begin(), 0);
|
||||
triVerts.resize(triCount.back());
|
||||
triNormal.resize(triCount.back());
|
||||
triRef.resize(triCount.back());
|
||||
|
||||
auto processFace2 = std::bind(
|
||||
processFace, [&](int face) { return std::move(results[face]); },
|
||||
[&](int face, glm::ivec3 tri, glm::vec3 normal, TriRef r) {
|
||||
triVerts[triCount[face]] = tri;
|
||||
triNormal[triCount[face]] = normal;
|
||||
triRef[triCount[face]] = r;
|
||||
triCount[face]++;
|
||||
},
|
||||
std::placeholders::_1);
|
||||
// set triangles in parallel
|
||||
for_each(autoPolicy(faceEdge.size()), countAt(0),
|
||||
countAt(faceEdge.size() - 1), processFace2);
|
||||
#else
|
||||
triVerts.reserve(faceEdge.size());
|
||||
triNormal.reserve(faceEdge.size());
|
||||
triRef.reserve(faceEdge.size());
|
||||
auto processFace2 = std::bind(
|
||||
processFace, generalTriangulation,
|
||||
[&](int _face, glm::ivec3 tri, glm::vec3 normal, TriRef r) {
|
||||
triVerts.push_back(tri);
|
||||
triNormal.push_back(normal);
|
||||
triRef.push_back(r);
|
||||
},
|
||||
std::placeholders::_1);
|
||||
for (int face = 0; face < faceEdge.size() - 1; ++face) {
|
||||
processFace2(face);
|
||||
}
|
||||
#endif
|
||||
|
||||
faceNormal_ = std::move(triNormal);
|
||||
CreateHalfedges(triVerts);
|
||||
}
|
||||
|
||||
/**
|
||||
* For the input face index, return a set of 2D polygons formed by the input
|
||||
* projection of the vertices.
|
||||
* Returns a set of 2D polygons formed by the input projection of the vertices
|
||||
* of the list of Halfedges, which must be an even-manifold, meaning each vert
|
||||
* must be referenced the same number of times as a startVert and endVert.
|
||||
*/
|
||||
PolygonsIdx Manifold::Impl::Face2Polygons(int face, glm::mat3x2 projection,
|
||||
const VecDH<int>& faceEdge) const {
|
||||
const int firstEdge = faceEdge[face];
|
||||
const int lastEdge = faceEdge[face + 1];
|
||||
|
||||
std::map<int, int> vert_edge;
|
||||
for (int edge = firstEdge; edge < lastEdge; ++edge) {
|
||||
const bool inserted =
|
||||
vert_edge.emplace(std::make_pair(halfedge_[edge].startVert, edge))
|
||||
.second;
|
||||
ASSERT(inserted, topologyErr, "face has duplicate vertices.");
|
||||
PolygonsIdx Manifold::Impl::Face2Polygons(VecView<Halfedge>::IterC start,
|
||||
VecView<Halfedge>::IterC end,
|
||||
glm::mat3x2 projection) const {
|
||||
std::multimap<int, int> vert_edge;
|
||||
for (auto edge = start; edge != end; ++edge) {
|
||||
vert_edge.emplace(std::make_pair(edge->startVert, edge - start));
|
||||
}
|
||||
|
||||
PolygonsIdx polys;
|
||||
@@ -161,13 +216,104 @@ PolygonsIdx Manifold::Impl::Face2Polygons(int face, glm::mat3x2 projection,
|
||||
thisEdge = startEdge;
|
||||
polys.push_back({});
|
||||
}
|
||||
int vert = halfedge_[thisEdge].startVert;
|
||||
int vert = (start + thisEdge)->startVert;
|
||||
polys.back().push_back({projection * vertPos_[vert], vert});
|
||||
const auto result = vert_edge.find(halfedge_[thisEdge].endVert);
|
||||
const auto result = vert_edge.find((start + thisEdge)->endVert);
|
||||
ASSERT(result != vert_edge.end(), topologyErr, "non-manifold edge");
|
||||
thisEdge = result->second;
|
||||
vert_edge.erase(result);
|
||||
}
|
||||
return polys;
|
||||
}
|
||||
|
||||
CrossSection Manifold::Impl::Slice(float height) const {
|
||||
Box plane = bBox_;
|
||||
plane.min.z = plane.max.z = height;
|
||||
Vec<Box> query;
|
||||
query.push_back(plane);
|
||||
const SparseIndices collisions =
|
||||
collider_.Collisions<false, false>(query.cview());
|
||||
|
||||
std::unordered_set<int> tris;
|
||||
for (int i = 0; i < collisions.size(); ++i) {
|
||||
const int tri = collisions.Get(i, 1);
|
||||
float min = std::numeric_limits<float>::infinity();
|
||||
float max = -std::numeric_limits<float>::infinity();
|
||||
for (const int j : {0, 1, 2}) {
|
||||
const float z = vertPos_[halfedge_[3 * tri + j].startVert].z;
|
||||
min = glm::min(min, z);
|
||||
max = glm::max(max, z);
|
||||
}
|
||||
|
||||
if (min <= height && max > height) {
|
||||
tris.insert(tri);
|
||||
}
|
||||
}
|
||||
|
||||
Polygons polys;
|
||||
while (!tris.empty()) {
|
||||
const int startTri = *tris.begin();
|
||||
SimplePolygon poly;
|
||||
|
||||
int k = 0;
|
||||
for (const int j : {0, 1, 2}) {
|
||||
if (vertPos_[halfedge_[3 * startTri + j].startVert].z > height &&
|
||||
vertPos_[halfedge_[3 * startTri + Next3(j)].startVert].z <= height) {
|
||||
k = Next3(j);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int tri = startTri;
|
||||
do {
|
||||
tris.erase(tris.find(tri));
|
||||
if (vertPos_[halfedge_[3 * tri + k].endVert].z <= height) {
|
||||
k = Next3(k);
|
||||
}
|
||||
|
||||
Halfedge up = halfedge_[3 * tri + k];
|
||||
const glm::vec3 below = vertPos_[up.startVert];
|
||||
const glm::vec3 above = vertPos_[up.endVert];
|
||||
const float a = (height - below.z) / (above.z - below.z);
|
||||
poly.push_back(glm::vec2(glm::mix(below, above, a)));
|
||||
|
||||
const int pair = up.pairedHalfedge;
|
||||
tri = pair / 3;
|
||||
k = Next3(pair % 3);
|
||||
} while (tri != startTri);
|
||||
|
||||
polys.push_back(poly);
|
||||
}
|
||||
|
||||
return CrossSection(polys);
|
||||
}
|
||||
|
||||
CrossSection Manifold::Impl::Project() const {
|
||||
const glm::mat3x2 projection = GetAxisAlignedProjection({0, 0, 1});
|
||||
auto policy = autoPolicy(halfedge_.size());
|
||||
|
||||
Vec<Halfedge> cusps(NumEdge());
|
||||
cusps.resize(copy_if<decltype(cusps.begin())>(
|
||||
policy, halfedge_.cbegin(), halfedge_.cend(), cusps.begin(),
|
||||
[&](Halfedge edge) {
|
||||
return faceNormal_[edge.face].z >= 0 &&
|
||||
faceNormal_[halfedge_[edge.pairedHalfedge].face].z <
|
||||
0;
|
||||
}) -
|
||||
cusps.begin());
|
||||
|
||||
PolygonsIdx polysIndexed =
|
||||
Face2Polygons(cusps.cbegin(), cusps.cend(), projection);
|
||||
|
||||
Polygons polys;
|
||||
for (const auto& poly : polysIndexed) {
|
||||
SimplePolygon simple;
|
||||
for (const PolyVert& polyVert : poly) {
|
||||
simple.push_back(polyVert.pos);
|
||||
}
|
||||
polys.push_back(simple);
|
||||
}
|
||||
|
||||
return CrossSection(polys).Simplify(precision_);
|
||||
}
|
||||
} // namespace manifold
|
||||
|
||||
+132
-123
@@ -14,58 +14,51 @@
|
||||
|
||||
#include "impl.h"
|
||||
|
||||
#include <thrust/logical.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
|
||||
#include "graph.h"
|
||||
#include "hashtable.h"
|
||||
#include "mesh_fixes.h"
|
||||
#include "par.h"
|
||||
#include "svd.h"
|
||||
|
||||
namespace {
|
||||
using namespace manifold;
|
||||
|
||||
constexpr uint64_t kRemove = std::numeric_limits<uint64_t>::max();
|
||||
|
||||
__host__ __device__ void AtomicAddVec3(glm::vec3& target,
|
||||
const glm::vec3& add) {
|
||||
void AtomicAddVec3(glm::vec3& target, const glm::vec3& add) {
|
||||
for (int i : {0, 1, 2}) {
|
||||
#ifdef __CUDA_ARCH__
|
||||
atomicAdd(&target[i], add[i]);
|
||||
#else
|
||||
std::atomic<float>& tar = reinterpret_cast<std::atomic<float>&>(target[i]);
|
||||
float old_val = tar.load(std::memory_order_relaxed);
|
||||
while (!tar.compare_exchange_weak(old_val, old_val + add[i],
|
||||
std::memory_order_relaxed))
|
||||
;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
struct Normalize {
|
||||
__host__ __device__ void operator()(glm::vec3& v) { v = SafeNormalize(v); }
|
||||
void operator()(glm::vec3& v) { v = SafeNormalize(v); }
|
||||
};
|
||||
|
||||
struct Transform4x3 {
|
||||
const glm::mat4x3 transform;
|
||||
|
||||
__host__ __device__ glm::vec3 operator()(glm::vec3 position) {
|
||||
glm::vec3 operator()(glm::vec3 position) {
|
||||
return transform * glm::vec4(position, 1.0f);
|
||||
}
|
||||
};
|
||||
|
||||
struct AssignNormals {
|
||||
glm::vec3* vertNormal;
|
||||
const glm::vec3* vertPos;
|
||||
const Halfedge* halfedges;
|
||||
VecView<glm::vec3> vertNormal;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
VecView<const Halfedge> halfedges;
|
||||
const float precision;
|
||||
const bool calculateTriNormal;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<glm::vec3&, int> in) {
|
||||
void operator()(thrust::tuple<glm::vec3&, int> in) {
|
||||
glm::vec3& triNormal = thrust::get<0>(in);
|
||||
const int face = thrust::get<1>(in);
|
||||
|
||||
@@ -99,11 +92,10 @@ struct AssignNormals {
|
||||
};
|
||||
|
||||
struct Tri2Halfedges {
|
||||
Halfedge* halfedges;
|
||||
glm::uint64_t* edges;
|
||||
VecView<Halfedge> halfedges;
|
||||
VecView<glm::uint64_t> edges;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
thrust::tuple<int, const glm::ivec3&> in) {
|
||||
void operator()(thrust::tuple<int, const glm::ivec3&> in) {
|
||||
const int tri = thrust::get<0>(in);
|
||||
const glm::ivec3& triVerts = thrust::get<1>(in);
|
||||
for (const int i : {0, 1, 2}) {
|
||||
@@ -120,11 +112,11 @@ struct Tri2Halfedges {
|
||||
};
|
||||
|
||||
struct LinkHalfedges {
|
||||
Halfedge* halfedges;
|
||||
const int* ids;
|
||||
VecView<Halfedge> halfedges;
|
||||
VecView<const int> ids;
|
||||
const int numEdge;
|
||||
|
||||
__host__ __device__ void operator()(int i) {
|
||||
void operator()(int i) {
|
||||
const int pair0 = ids[i];
|
||||
const int pair1 = ids[i + numEdge];
|
||||
halfedges[pair0].pairedHalfedge = pair1;
|
||||
@@ -133,19 +125,20 @@ struct LinkHalfedges {
|
||||
};
|
||||
|
||||
struct MarkVerts {
|
||||
int* vert;
|
||||
VecView<int> vert;
|
||||
|
||||
__host__ __device__ void operator()(glm::ivec3 triVerts) {
|
||||
void operator()(glm::ivec3 triVerts) {
|
||||
for (int i : {0, 1, 2}) {
|
||||
vert[triVerts[i]] = 1;
|
||||
reinterpret_cast<std::atomic<int>*>(&vert[triVerts[i]])
|
||||
->store(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct ReindexTriVerts {
|
||||
const int* old2new;
|
||||
VecView<const int> old2new;
|
||||
|
||||
__host__ __device__ void operator()(glm::ivec3& triVerts) {
|
||||
void operator()(glm::ivec3& triVerts) {
|
||||
for (int i : {0, 1, 2}) {
|
||||
triVerts[i] = old2new[triVerts[i]];
|
||||
}
|
||||
@@ -154,9 +147,9 @@ struct ReindexTriVerts {
|
||||
|
||||
struct InitializeTriRef {
|
||||
const int meshID;
|
||||
const Halfedge* halfedge;
|
||||
VecView<const Halfedge> halfedge;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<TriRef&, int> inOut) {
|
||||
void operator()(thrust::tuple<TriRef&, int> inOut) {
|
||||
TriRef& baryRef = thrust::get<0>(inOut);
|
||||
int tri = thrust::get<1>(inOut);
|
||||
|
||||
@@ -169,23 +162,22 @@ struct InitializeTriRef {
|
||||
struct UpdateMeshID {
|
||||
const HashTableD<uint32_t> meshIDold2new;
|
||||
|
||||
__host__ __device__ void operator()(TriRef& ref) {
|
||||
ref.meshID = meshIDold2new[ref.meshID];
|
||||
}
|
||||
void operator()(TriRef& ref) { ref.meshID = meshIDold2new[ref.meshID]; }
|
||||
};
|
||||
|
||||
struct CoplanarEdge {
|
||||
float* triArea;
|
||||
const Halfedge* halfedge;
|
||||
const glm::vec3* vertPos;
|
||||
const TriRef* triRef;
|
||||
const glm::ivec3* triProp;
|
||||
const float* prop;
|
||||
const float* propTol;
|
||||
VecView<float> triArea;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
VecView<const TriRef> triRef;
|
||||
VecView<const glm::ivec3> triProp;
|
||||
VecView<const float> prop;
|
||||
VecView<const float> propTol;
|
||||
const int numProp;
|
||||
const float precision;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
// FIXME: race condition
|
||||
void operator()(
|
||||
thrust::tuple<thrust::pair<int, int>&, thrust::pair<int, int>&, int>
|
||||
inOut) {
|
||||
thrust::pair<int, int>& face2face = thrust::get<0>(inOut);
|
||||
@@ -277,14 +269,14 @@ struct CoplanarEdge {
|
||||
};
|
||||
|
||||
struct CheckCoplanarity {
|
||||
int* comp2tri;
|
||||
const Halfedge* halfedge;
|
||||
const glm::vec3* vertPos;
|
||||
const int* components;
|
||||
VecView<int> comp2tri;
|
||||
VecView<const Halfedge> halfedge;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
std::vector<int>* components;
|
||||
const float precision;
|
||||
|
||||
__host__ __device__ void operator()(int tri) {
|
||||
const int component = components[tri];
|
||||
void operator()(int tri) {
|
||||
const int component = (*components)[tri];
|
||||
const int referenceTri = comp2tri[component];
|
||||
if (referenceTri < 0 || referenceTri == tri) return;
|
||||
|
||||
@@ -299,7 +291,8 @@ struct CheckCoplanarity {
|
||||
// triangle, unmark the entire component so that none of its triangles are
|
||||
// marked coplanar.
|
||||
if (glm::abs(glm::dot(normal, vert - origin)) > precision) {
|
||||
comp2tri[component] = -1;
|
||||
reinterpret_cast<std::atomic<int>*>(&comp2tri[component])
|
||||
->store(-1, std::memory_order_relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -307,32 +300,28 @@ struct CheckCoplanarity {
|
||||
};
|
||||
|
||||
struct EdgeBox {
|
||||
const glm::vec3* vertPos;
|
||||
VecView<const glm::vec3> vertPos;
|
||||
|
||||
__host__ __device__ void operator()(
|
||||
thrust::tuple<Box&, const TmpEdge&> inout) {
|
||||
void operator()(thrust::tuple<Box&, const TmpEdge&> inout) {
|
||||
const TmpEdge& edge = thrust::get<1>(inout);
|
||||
thrust::get<0>(inout) = Box(vertPos[edge.first], vertPos[edge.second]);
|
||||
}
|
||||
};
|
||||
|
||||
int GetLabels(std::vector<int>& components,
|
||||
const VecDH<thrust::pair<int, int>>& edges, int numNodes) {
|
||||
Graph graph;
|
||||
for (int i = 0; i < numNodes; ++i) {
|
||||
graph.add_nodes(i);
|
||||
}
|
||||
for (int i = 0; i < edges.size(); ++i) {
|
||||
const thrust::pair<int, int> edge = edges[i];
|
||||
if (edge.first < 0) continue;
|
||||
graph.add_edge(edge.first, edge.second);
|
||||
const Vec<thrust::pair<int, int>>& edges, int numNodes) {
|
||||
UnionFind<> uf(numNodes);
|
||||
for (auto edge : edges) {
|
||||
if (edge.first == -1 || edge.second == -1) continue;
|
||||
uf.unionXY(edge.first, edge.second);
|
||||
}
|
||||
|
||||
return ConnectedComponents(components, graph);
|
||||
return uf.connectedComponents(components);
|
||||
}
|
||||
|
||||
void DedupePropVerts(manifold::VecDH<glm::ivec3>& triProp,
|
||||
const VecDH<thrust::pair<int, int>>& vert2vert) {
|
||||
void DedupePropVerts(manifold::Vec<glm::ivec3>& triProp,
|
||||
const Vec<thrust::pair<int, int>>& vert2vert) {
|
||||
ZoneScoped;
|
||||
std::vector<int> vertLabels;
|
||||
const int numLabels = GetLabels(vertLabels, vert2vert, vert2vert.size());
|
||||
|
||||
@@ -494,7 +483,7 @@ Manifold::Impl::Impl(const Mesh& mesh, const MeshRelationD& relation,
|
||||
meshRelation_ = {relation.originalID, relation.numProp, relation.properties,
|
||||
relation.meshIDtransform};
|
||||
|
||||
VecDH<glm::ivec3> triVerts;
|
||||
Vec<glm::ivec3> triVerts;
|
||||
for (int i = 0; i < mesh.triVerts.size(); ++i) {
|
||||
const glm::ivec3 tri = mesh.triVerts[i];
|
||||
// Remove topological degenerates
|
||||
@@ -593,13 +582,14 @@ Manifold::Impl::Impl(Shape shape) {
|
||||
CreateFaces();
|
||||
}
|
||||
|
||||
void Manifold::Impl::RemoveUnreferencedVerts(VecDH<glm::ivec3>& triVerts) {
|
||||
VecDH<int> vertOld2New(NumVert() + 1, 0);
|
||||
void Manifold::Impl::RemoveUnreferencedVerts(Vec<glm::ivec3>& triVerts) {
|
||||
ZoneScoped;
|
||||
Vec<int> vertOld2New(NumVert() + 1, 0);
|
||||
auto policy = autoPolicy(NumVert());
|
||||
for_each(policy, triVerts.cbegin(), triVerts.cend(),
|
||||
MarkVerts({vertOld2New.ptrD() + 1}));
|
||||
MarkVerts({vertOld2New.view(1)}));
|
||||
|
||||
const VecDH<glm::vec3> oldVertPos = vertPos_;
|
||||
const Vec<glm::vec3> oldVertPos = vertPos_;
|
||||
vertPos_.resize(copy_if<decltype(vertPos_.begin())>(
|
||||
policy, oldVertPos.cbegin(), oldVertPos.cend(),
|
||||
vertOld2New.cbegin() + 1, vertPos_.begin(),
|
||||
@@ -610,7 +600,7 @@ void Manifold::Impl::RemoveUnreferencedVerts(VecDH<glm::ivec3>& triVerts) {
|
||||
vertOld2New.begin() + 1);
|
||||
|
||||
for_each(policy, triVerts.begin(), triVerts.end(),
|
||||
ReindexTriVerts({vertOld2New.cptrD()}));
|
||||
ReindexTriVerts({vertOld2New}));
|
||||
}
|
||||
|
||||
void Manifold::Impl::InitializeOriginal() {
|
||||
@@ -620,28 +610,26 @@ void Manifold::Impl::InitializeOriginal() {
|
||||
meshRelation_.triRef.resize(NumTri());
|
||||
for_each_n(autoPolicy(NumTri()),
|
||||
zip(meshRelation_.triRef.begin(), countAt(0)), NumTri(),
|
||||
InitializeTriRef({meshID, halfedge_.cptrD()}));
|
||||
InitializeTriRef({meshID, halfedge_}));
|
||||
meshRelation_.meshIDtransform.clear();
|
||||
meshRelation_.meshIDtransform[meshID] = {meshID};
|
||||
}
|
||||
|
||||
void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
|
||||
VecDH<float> propertyToleranceD =
|
||||
propertyTolerance.empty()
|
||||
? VecDH<float>(meshRelation_.numProp, kTolerance)
|
||||
: propertyTolerance;
|
||||
ZoneScoped;
|
||||
Vec<float> propertyToleranceD =
|
||||
propertyTolerance.empty() ? Vec<float>(meshRelation_.numProp, kTolerance)
|
||||
: propertyTolerance;
|
||||
|
||||
VecDH<thrust::pair<int, int>> face2face(halfedge_.size(), {-1, -1});
|
||||
VecDH<thrust::pair<int, int>> vert2vert(halfedge_.size(), {-1, -1});
|
||||
VecDH<float> triArea(NumTri());
|
||||
Vec<thrust::pair<int, int>> face2face(halfedge_.size(), {-1, -1});
|
||||
Vec<thrust::pair<int, int>> vert2vert(halfedge_.size(), {-1, -1});
|
||||
Vec<float> triArea(NumTri());
|
||||
for_each_n(
|
||||
autoPolicy(halfedge_.size()),
|
||||
zip(face2face.begin(), vert2vert.begin(), countAt(0)), halfedge_.size(),
|
||||
CoplanarEdge(
|
||||
{triArea.ptrD(), halfedge_.cptrD(), vertPos_.cptrD(),
|
||||
meshRelation_.triRef.cptrD(), meshRelation_.triProperties.cptrD(),
|
||||
meshRelation_.properties.cptrD(), propertyToleranceD.cptrD(),
|
||||
meshRelation_.numProp, precision_}));
|
||||
CoplanarEdge({triArea, halfedge_, vertPos_, meshRelation_.triRef,
|
||||
meshRelation_.triProperties, meshRelation_.properties,
|
||||
propertyToleranceD, meshRelation_.numProp, precision_}));
|
||||
|
||||
if (meshRelation_.triProperties.size() > 0) {
|
||||
DedupePropVerts(meshRelation_.triProperties, vert2vert);
|
||||
@@ -650,7 +638,7 @@ void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
|
||||
std::vector<int> components;
|
||||
const int numComponent = GetLabels(components, face2face, NumTri());
|
||||
|
||||
std::vector<int> comp2tri(numComponent, -1);
|
||||
Vec<int> comp2tri(numComponent, -1);
|
||||
for (int tri = 0; tri < NumTri(); ++tri) {
|
||||
const int comp = components[tri];
|
||||
const int current = comp2tri[comp];
|
||||
@@ -660,16 +648,13 @@ void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
|
||||
}
|
||||
}
|
||||
|
||||
VecDH<int> componentsD(components);
|
||||
VecDH<int> comp2triD(comp2tri);
|
||||
for_each_n(
|
||||
autoPolicy(halfedge_.size()), countAt(0), NumTri(),
|
||||
CheckCoplanarity({comp2triD.ptrD(), halfedge_.cptrD(), vertPos_.cptrD(),
|
||||
componentsD.cptrD(), precision_}));
|
||||
for_each_n(autoPolicy(halfedge_.size()), countAt(0), NumTri(),
|
||||
CheckCoplanarity(
|
||||
{comp2tri, halfedge_, vertPos_, &components, precision_}));
|
||||
|
||||
VecDH<TriRef>& triRef = meshRelation_.triRef;
|
||||
Vec<TriRef>& triRef = meshRelation_.triRef;
|
||||
for (int tri = 0; tri < NumTri(); ++tri) {
|
||||
const int referenceTri = comp2triD[components[tri]];
|
||||
const int referenceTri = comp2tri[components[tri]];
|
||||
if (referenceTri >= 0) {
|
||||
triRef[tri].tri = referenceTri;
|
||||
}
|
||||
@@ -679,29 +664,35 @@ void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
|
||||
/**
|
||||
* Create the halfedge_ data structure from an input triVerts array like Mesh.
|
||||
*/
|
||||
void Manifold::Impl::CreateHalfedges(const VecDH<glm::ivec3>& triVerts) {
|
||||
void Manifold::Impl::CreateHalfedges(const Vec<glm::ivec3>& triVerts) {
|
||||
ZoneScoped;
|
||||
const int numTri = triVerts.size();
|
||||
const int numHalfedge = 3 * numTri;
|
||||
// drop the old value first to avoid copy
|
||||
halfedge_.resize(0);
|
||||
halfedge_.resize(numHalfedge);
|
||||
VecDH<uint64_t> edge(numHalfedge);
|
||||
VecDH<int> ids(numHalfedge);
|
||||
Vec<uint64_t> edge(numHalfedge);
|
||||
Vec<int> ids(numHalfedge);
|
||||
auto policy = autoPolicy(numTri);
|
||||
sequence(policy, ids.begin(), ids.end());
|
||||
for_each_n(policy, zip(countAt(0), triVerts.begin()), numTri,
|
||||
Tri2Halfedges({halfedge_.ptrD(), edge.ptrD()}));
|
||||
Tri2Halfedges({halfedge_, edge}));
|
||||
// Stable sort is required here so that halfedges from the same face are
|
||||
// paired together (the triangles were created in face order). In some
|
||||
// degenerate situations the triangulator can add the same internal edge in
|
||||
// two different faces, causing this edge to not be 2-manifold. These are
|
||||
// fixed by duplicating verts in SimplifyTopology.
|
||||
stable_sort_by_key(policy, edge.begin(), edge.end(), ids.begin());
|
||||
stable_sort(policy, zip(edge.begin(), ids.begin()),
|
||||
zip(edge.end(), ids.end()),
|
||||
[](const thrust::tuple<uint64_t, int>& a,
|
||||
const thrust::tuple<uint64_t, int>& b) {
|
||||
return thrust::get<0>(a) < thrust::get<0>(b);
|
||||
});
|
||||
// Once sorted, the first half of the range is the forward halfedges, which
|
||||
// correspond to their backward pair at the same offset in the second half
|
||||
// of the range.
|
||||
for_each_n(policy, countAt(0), numHalfedge / 2,
|
||||
LinkHalfedges({halfedge_.ptrD(), ids.ptrD(), numHalfedge / 2}));
|
||||
LinkHalfedges({halfedge_, ids, numHalfedge / 2}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -710,8 +701,8 @@ void Manifold::Impl::CreateHalfedges(const VecDH<glm::ivec3>& triVerts) {
|
||||
*/
|
||||
void Manifold::Impl::Update() {
|
||||
CalculateBBox();
|
||||
VecDH<Box> faceBox;
|
||||
VecDH<uint32_t> faceMorton;
|
||||
Vec<Box> faceBox;
|
||||
Vec<uint32_t> faceMorton;
|
||||
GetFaceBoxMorton(faceBox, faceMorton);
|
||||
collider_.UpdateBoxes(faceBox);
|
||||
}
|
||||
@@ -728,7 +719,14 @@ void Manifold::Impl::MarkFailure(Error status) {
|
||||
}
|
||||
|
||||
void Manifold::Impl::Warp(std::function<void(glm::vec3&)> warpFunc) {
|
||||
thrust::for_each_n(thrust::host, vertPos_.begin(), NumVert(), warpFunc);
|
||||
WarpBatch([&warpFunc](VecView<glm::vec3> vecs) {
|
||||
thrust::for_each(thrust::host, vecs.begin(), vecs.end(), warpFunc);
|
||||
});
|
||||
}
|
||||
|
||||
void Manifold::Impl::WarpBatch(
|
||||
std::function<void(VecView<glm::vec3>)> warpFunc) {
|
||||
warpFunc(vertPos_.view());
|
||||
CalculateBBox();
|
||||
if (!IsFinite()) {
|
||||
MarkFailure(Error::NonFiniteVertex);
|
||||
@@ -739,11 +737,11 @@ void Manifold::Impl::Warp(std::function<void(glm::vec3&)> warpFunc) {
|
||||
CalculateNormals();
|
||||
SetPrecision();
|
||||
CreateFaces();
|
||||
SimplifyTopology();
|
||||
Finish();
|
||||
}
|
||||
|
||||
Manifold::Impl Manifold::Impl::Transform(const glm::mat4x3& transform_) const {
|
||||
ZoneScoped;
|
||||
if (transform_ == glm::mat4x3(1.0f)) return *this;
|
||||
auto policy = autoPolicy(NumVert());
|
||||
Impl result;
|
||||
@@ -774,16 +772,15 @@ Manifold::Impl Manifold::Impl::Transform(const glm::mat4x3& transform_) const {
|
||||
const bool invert = glm::determinant(glm::mat3(transform_)) < 0;
|
||||
|
||||
if (halfedgeTangent_.size() > 0) {
|
||||
for_each_n(
|
||||
policy, zip(result.halfedgeTangent_.begin(), countAt(0)),
|
||||
halfedgeTangent_.size(),
|
||||
TransformTangents({glm::mat3(transform_), invert,
|
||||
halfedgeTangent_.cptrD(), halfedge_.cptrD()}));
|
||||
for_each_n(policy, zip(result.halfedgeTangent_.begin(), countAt(0)),
|
||||
halfedgeTangent_.size(),
|
||||
TransformTangents({glm::mat3(transform_), invert,
|
||||
halfedgeTangent_, halfedge_}));
|
||||
}
|
||||
|
||||
if (invert) {
|
||||
for_each_n(policy, zip(result.meshRelation_.triRef.begin(), countAt(0)),
|
||||
result.NumTri(), FlipTris({result.halfedge_.ptrD()}));
|
||||
result.NumTri(), FlipTris({result.halfedge_}));
|
||||
}
|
||||
|
||||
// This optimization does a cheap collider update if the transform is
|
||||
@@ -791,11 +788,8 @@ Manifold::Impl Manifold::Impl::Transform(const glm::mat4x3& transform_) const {
|
||||
if (!result.collider_.Transform(transform_)) result.Update();
|
||||
|
||||
result.CalculateBBox();
|
||||
float scale = 0;
|
||||
for (int i : {0, 1, 2})
|
||||
scale =
|
||||
glm::max(scale, transform_[0][i] + transform_[1][i] + transform_[2][i]);
|
||||
result.precision_ *= scale;
|
||||
// Scale the precision by the norm of the 3x3 portion of the transform.
|
||||
result.precision_ *= SpectralNorm(glm::mat3(transform_));
|
||||
// Maximum of inherited precision loss and translational precision loss.
|
||||
result.SetPrecision(result.precision_);
|
||||
return result;
|
||||
@@ -822,6 +816,7 @@ void Manifold::Impl::SetPrecision(float minPrecision) {
|
||||
* recalculation.
|
||||
*/
|
||||
void Manifold::Impl::CalculateNormals() {
|
||||
ZoneScoped;
|
||||
vertNormal_.resize(NumVert());
|
||||
auto policy = autoPolicy(NumTri());
|
||||
fill(policy, vertNormal_.begin(), vertNormal_.end(), glm::vec3(0));
|
||||
@@ -830,10 +825,9 @@ void Manifold::Impl::CalculateNormals() {
|
||||
faceNormal_.resize(NumTri());
|
||||
calculateTriNormal = true;
|
||||
}
|
||||
for_each_n(
|
||||
policy, zip(faceNormal_.begin(), countAt(0)), NumTri(),
|
||||
AssignNormals({vertNormal_.ptrD(), vertPos_.cptrD(), halfedge_.cptrD(),
|
||||
precision_, calculateTriNormal}));
|
||||
for_each_n(policy, zip(faceNormal_.begin(), countAt(0)), NumTri(),
|
||||
AssignNormals({vertNormal_, vertPos_, halfedge_, precision_,
|
||||
calculateTriNormal}));
|
||||
for_each(policy, vertNormal_.begin(), vertNormal_.end(), Normalize());
|
||||
}
|
||||
|
||||
@@ -863,17 +857,28 @@ void Manifold::Impl::IncrementMeshIDs() {
|
||||
* the input manifold, Q and the faces of this manifold. Returned indices only
|
||||
* point to forward halfedges.
|
||||
*/
|
||||
SparseIndices Manifold::Impl::EdgeCollisions(const Impl& Q) const {
|
||||
VecDH<TmpEdge> edges = CreateTmpEdges(Q.halfedge_);
|
||||
SparseIndices Manifold::Impl::EdgeCollisions(const Impl& Q,
|
||||
bool inverted) const {
|
||||
ZoneScoped;
|
||||
Vec<TmpEdge> edges = CreateTmpEdges(Q.halfedge_);
|
||||
const int numEdge = edges.size();
|
||||
VecDH<Box> QedgeBB(numEdge);
|
||||
Vec<Box> QedgeBB(numEdge);
|
||||
auto policy = autoPolicy(numEdge);
|
||||
for_each_n(policy, zip(QedgeBB.begin(), edges.cbegin()), numEdge,
|
||||
EdgeBox({Q.vertPos_.cptrD()}));
|
||||
EdgeBox({Q.vertPos_}));
|
||||
|
||||
SparseIndices q1p2 = collider_.Collisions(QedgeBB);
|
||||
SparseIndices q1p2(0);
|
||||
if (inverted)
|
||||
q1p2 = collider_.Collisions<false, true>(QedgeBB.cview());
|
||||
else
|
||||
q1p2 = collider_.Collisions<false, false>(QedgeBB.cview());
|
||||
|
||||
for_each(policy, q1p2.begin(0), q1p2.end(0), ReindexEdge({edges.cptrD()}));
|
||||
if (inverted)
|
||||
for_each(policy, countAt(0), countAt(q1p2.size()),
|
||||
ReindexEdge<true>({edges, q1p2}));
|
||||
else
|
||||
for_each(policy, countAt(0), countAt(q1p2.size()),
|
||||
ReindexEdge<false>({edges, q1p2}));
|
||||
return q1p2;
|
||||
}
|
||||
|
||||
@@ -882,7 +887,11 @@ SparseIndices Manifold::Impl::EdgeCollisions(const Impl& Q) const {
|
||||
* bounding boxes of the faces of this manifold.
|
||||
*/
|
||||
SparseIndices Manifold::Impl::VertexCollisionsZ(
|
||||
const VecDH<glm::vec3>& vertsIn) const {
|
||||
return collider_.Collisions(vertsIn);
|
||||
VecView<const glm::vec3> vertsIn, bool inverted) const {
|
||||
ZoneScoped;
|
||||
if (inverted)
|
||||
return collider_.Collisions<false, true>(vertsIn);
|
||||
else
|
||||
return collider_.Collisions<false, false>(vertsIn);
|
||||
}
|
||||
} // namespace manifold
|
||||
|
||||
+32
-25
@@ -22,7 +22,7 @@
|
||||
#include "shared.h"
|
||||
#include "sparse.h"
|
||||
#include "utils.h"
|
||||
#include "vec_dh.h"
|
||||
#include "vec.h"
|
||||
|
||||
namespace manifold {
|
||||
|
||||
@@ -37,20 +37,20 @@ struct Manifold::Impl {
|
||||
/// The originalID of this Manifold if it is an original; -1 otherwise.
|
||||
int originalID = -1;
|
||||
int numProp = 0;
|
||||
VecDH<float> properties;
|
||||
Vec<float> properties;
|
||||
std::map<int, Relation> meshIDtransform;
|
||||
VecDH<TriRef> triRef;
|
||||
VecDH<glm::ivec3> triProperties;
|
||||
Vec<TriRef> triRef;
|
||||
Vec<glm::ivec3> triProperties;
|
||||
};
|
||||
|
||||
Box bBox_;
|
||||
float precision_ = -1;
|
||||
Error status_ = Error::NoError;
|
||||
VecDH<glm::vec3> vertPos_;
|
||||
VecDH<Halfedge> halfedge_;
|
||||
VecDH<glm::vec3> vertNormal_;
|
||||
VecDH<glm::vec3> faceNormal_;
|
||||
VecDH<glm::vec4> halfedgeTangent_;
|
||||
Vec<glm::vec3> vertPos_;
|
||||
Vec<Halfedge> halfedge_;
|
||||
Vec<glm::vec3> vertNormal_;
|
||||
Vec<glm::vec3> faceNormal_;
|
||||
Vec<glm::vec4> halfedgeTangent_;
|
||||
MeshRelationD meshRelation_;
|
||||
Collider collider_;
|
||||
|
||||
@@ -67,18 +67,20 @@ struct Manifold::Impl {
|
||||
bool hasFaceIDs = false);
|
||||
|
||||
void CreateFaces(const std::vector<float>& propertyTolerance = {});
|
||||
void RemoveUnreferencedVerts(VecDH<glm::ivec3>& triVerts);
|
||||
void RemoveUnreferencedVerts(Vec<glm::ivec3>& triVerts);
|
||||
void InitializeOriginal();
|
||||
void CreateHalfedges(const VecDH<glm::ivec3>& triVerts);
|
||||
void CreateHalfedges(const Vec<glm::ivec3>& triVerts);
|
||||
void CalculateNormals();
|
||||
void IncrementMeshIDs();
|
||||
|
||||
void Update();
|
||||
void MarkFailure(Error status);
|
||||
void Warp(std::function<void(glm::vec3&)> warpFunc);
|
||||
void WarpBatch(std::function<void(VecView<glm::vec3>)> warpFunc);
|
||||
Impl Transform(const glm::mat4x3& transform) const;
|
||||
SparseIndices EdgeCollisions(const Impl& B) const;
|
||||
SparseIndices VertexCollisionsZ(const VecDH<glm::vec3>& vertsIn) const;
|
||||
SparseIndices EdgeCollisions(const Impl& B, bool inverted = false) const;
|
||||
SparseIndices VertexCollisionsZ(VecView<const glm::vec3> vertsIn,
|
||||
bool inverted = false) const;
|
||||
|
||||
bool IsEmpty() const { return NumVert() == 0; }
|
||||
int NumVert() const { return vertPos_.size(); }
|
||||
@@ -95,7 +97,7 @@ struct Manifold::Impl {
|
||||
void CalculateCurvature(int gaussianIdx, int meanIdx);
|
||||
void CalculateBBox();
|
||||
bool IsFinite() const;
|
||||
bool IsIndexInBounds(const VecDH<glm::ivec3>& triVerts) const;
|
||||
bool IsIndexInBounds(VecView<const glm::ivec3> triVerts) const;
|
||||
void SetPrecision(float minPrecision = -1);
|
||||
bool IsManifold() const;
|
||||
bool Is2Manifold() const;
|
||||
@@ -105,23 +107,28 @@ struct Manifold::Impl {
|
||||
// sort.cu
|
||||
void Finish();
|
||||
void SortVerts();
|
||||
void ReindexVerts(const VecDH<int>& vertNew2Old, int numOldVert);
|
||||
void ReindexVerts(const Vec<int>& vertNew2Old, int numOldVert);
|
||||
void CompactProps();
|
||||
void GetFaceBoxMorton(VecDH<Box>& faceBox, VecDH<uint32_t>& faceMorton) const;
|
||||
void SortFaces(VecDH<Box>& faceBox, VecDH<uint32_t>& faceMorton);
|
||||
void GatherFaces(const VecDH<int>& faceNew2Old);
|
||||
void GatherFaces(const Impl& old, const VecDH<int>& faceNew2Old);
|
||||
void GetFaceBoxMorton(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) const;
|
||||
void SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton);
|
||||
void GatherFaces(const Vec<int>& faceNew2Old);
|
||||
void GatherFaces(const Impl& old, const Vec<int>& faceNew2Old);
|
||||
|
||||
// face_op.cu
|
||||
void Face2Tri(const VecDH<int>& faceEdge, const VecDH<TriRef>& halfedgeRef);
|
||||
PolygonsIdx Face2Polygons(int face, glm::mat3x2 projection,
|
||||
const VecDH<int>& faceEdge) const;
|
||||
void Face2Tri(const Vec<int>& faceEdge, const Vec<TriRef>& halfedgeRef);
|
||||
PolygonsIdx Face2Polygons(VecView<Halfedge>::IterC start,
|
||||
VecView<Halfedge>::IterC end,
|
||||
glm::mat3x2 projection) const;
|
||||
CrossSection Slice(float height) const;
|
||||
CrossSection Project() const;
|
||||
|
||||
// edge_op.cu
|
||||
void SimplifyTopology();
|
||||
void DedupeEdge(int edge);
|
||||
void CollapseEdge(int edge);
|
||||
void RecursiveEdgeSwap(int edge);
|
||||
void CollapseEdge(int edge, std::vector<int>& edges);
|
||||
void RecursiveEdgeSwap(int edge, int& tag, std::vector<int>& visited,
|
||||
std::vector<int>& edgeSwapStack,
|
||||
std::vector<int>& edges);
|
||||
void RemoveIfFolded(int edge);
|
||||
void PairUp(int edge0, int edge1);
|
||||
void UpdateVert(int vert, int startEdge, int endEdge);
|
||||
@@ -131,7 +138,7 @@ struct Manifold::Impl {
|
||||
|
||||
// smoothing.cu
|
||||
void CreateTangents(const std::vector<Smoothness>&);
|
||||
VecDH<Barycentric> Subdivide(int n);
|
||||
Vec<Barycentric> Subdivide(int n);
|
||||
void Refine(int n);
|
||||
};
|
||||
} // namespace manifold
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <QuickHull.hpp>
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
|
||||
#include "QuickHull.hpp"
|
||||
#include "boolean3.h"
|
||||
#include "csg_tree.h"
|
||||
#include "impl.h"
|
||||
@@ -26,12 +26,12 @@ namespace {
|
||||
using namespace manifold;
|
||||
using namespace thrust::placeholders;
|
||||
|
||||
ExecutionParams params;
|
||||
ExecutionParams manifoldParams;
|
||||
|
||||
struct MakeTri {
|
||||
const Halfedge* halfedges;
|
||||
VecView<const Halfedge> halfedges;
|
||||
|
||||
__host__ __device__ void operator()(thrust::tuple<glm::ivec3&, int> inOut) {
|
||||
void operator()(thrust::tuple<glm::ivec3&, int> inOut) {
|
||||
glm::ivec3& tri = thrust::get<0>(inOut);
|
||||
const int face = 3 * thrust::get<1>(inOut);
|
||||
|
||||
@@ -51,7 +51,7 @@ struct UpdateProperties {
|
||||
const Halfedge* halfedges;
|
||||
std::function<void(float*, glm::vec3, const float*)> propFunc;
|
||||
|
||||
__host__ __device__ void operator()(int tri) {
|
||||
void operator()(int tri) {
|
||||
for (int i : {0, 1, 2}) {
|
||||
const int vert = halfedges[3 * tri + i].startVert;
|
||||
const int propVert = triProperties[tri][i];
|
||||
@@ -155,6 +155,7 @@ Manifold::Manifold(const Mesh& mesh) {
|
||||
* saving or other operations outside of the context of this library.
|
||||
*/
|
||||
Mesh Manifold::GetMesh() const {
|
||||
ZoneScoped;
|
||||
const Impl& impl = *GetCsgLeafNode().GetImpl();
|
||||
|
||||
Mesh result;
|
||||
@@ -170,7 +171,7 @@ Mesh Manifold::GetMesh() const {
|
||||
result.triVerts.resize(NumTri());
|
||||
// note that `triVerts` is `std::vector`, so we cannot use thrust::device
|
||||
thrust::for_each_n(thrust::host, zip(result.triVerts.begin(), countAt(0)),
|
||||
NumTri(), MakeTri({impl.halfedge_.cptrH()}));
|
||||
NumTri(), MakeTri({impl.halfedge_}));
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -189,6 +190,7 @@ Mesh Manifold::GetMesh() const {
|
||||
* MeshGLs must use the same channels for their normals.
|
||||
*/
|
||||
MeshGL Manifold::GetMeshGL(glm::ivec3 normalIdx) const {
|
||||
ZoneScoped;
|
||||
const Impl& impl = *GetCsgLeafNode().GetImpl();
|
||||
|
||||
const int numProp = NumProp();
|
||||
@@ -218,7 +220,7 @@ MeshGL Manifold::GetMeshGL(glm::ivec3 normalIdx) const {
|
||||
out.faceID.resize(numTri);
|
||||
std::vector<int> triNew2Old(numTri);
|
||||
std::iota(triNew2Old.begin(), triNew2Old.end(), 0);
|
||||
const TriRef* triRef = impl.meshRelation_.triRef.cptrD();
|
||||
VecView<const TriRef> triRef = impl.meshRelation_.triRef;
|
||||
// Don't sort originals - keep them in order
|
||||
if (!isOriginal) {
|
||||
std::sort(triNew2Old.begin(), triNew2Old.end(), [triRef](int a, int b) {
|
||||
@@ -260,7 +262,10 @@ MeshGL Manifold::GetMeshGL(glm::ivec3 normalIdx) const {
|
||||
out.triVerts[3 * tri + i] = impl.halfedge_[3 * oldTri + i].startVert;
|
||||
|
||||
if (meshID != lastID) {
|
||||
addRun(out, runNormalTransform, tri, meshIDtransform.at(meshID));
|
||||
Impl::Relation rel;
|
||||
auto it = meshIDtransform.find(meshID);
|
||||
if (it != meshIDtransform.end()) rel = it->second;
|
||||
addRun(out, runNormalTransform, tri, rel);
|
||||
meshIDtransform.erase(meshID);
|
||||
lastID = meshID;
|
||||
}
|
||||
@@ -286,7 +291,7 @@ MeshGL Manifold::GetMeshGL(glm::ivec3 normalIdx) const {
|
||||
// Duplicate verts with different props
|
||||
std::vector<int> vert2idx(impl.NumVert(), -1);
|
||||
std::vector<std::vector<glm::ivec2>> vertPropPair(impl.NumVert());
|
||||
out.vertProperties.reserve(numVert * out.numProp);
|
||||
out.vertProperties.reserve(numVert * static_cast<size_t>(out.numProp));
|
||||
|
||||
for (int run = 0; run < out.runOriginalID.size(); ++run) {
|
||||
for (int tri = out.runIndex[run] / 3; tri < out.runIndex[run + 1] / 3;
|
||||
@@ -481,7 +486,7 @@ int Manifold::NumOverlaps(const Manifold& other) const {
|
||||
|
||||
overlaps = other.GetCsgLeafNode().GetImpl()->EdgeCollisions(
|
||||
*GetCsgLeafNode().GetImpl());
|
||||
return num_overlaps += overlaps.size();
|
||||
return num_overlaps + overlaps.size();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -564,6 +569,20 @@ Manifold Manifold::Warp(std::function<void(glm::vec3&)> warpFunc) const {
|
||||
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as Manifold::Warp but calls warpFunc with with
|
||||
* a VecView which is roughly equivalent to std::span
|
||||
* pointing to all vec3 elements to be modified in-place
|
||||
*
|
||||
* @param warpFunc A function that modifies multiple vertex positions.
|
||||
*/
|
||||
Manifold Manifold::WarpBatch(
|
||||
std::function<void(VecView<glm::vec3>)> warpFunc) const {
|
||||
auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
|
||||
pImpl->WarpBatch(warpFunc);
|
||||
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new copy of this manifold with updated vertex properties by
|
||||
* supplying a function that takes the existing position and properties as
|
||||
@@ -580,7 +599,7 @@ Manifold Manifold::SetProperties(
|
||||
propFunc) const {
|
||||
auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
|
||||
const int oldNumProp = NumProp();
|
||||
const VecDH<float> oldProperties = pImpl->meshRelation_.properties;
|
||||
const Vec<float> oldProperties = pImpl->meshRelation_.properties;
|
||||
|
||||
auto& triProperties = pImpl->meshRelation_.triProperties;
|
||||
if (numProp == 0) {
|
||||
@@ -596,22 +615,20 @@ Manifold Manifold::SetProperties(
|
||||
triProperties[i][j] = idx++;
|
||||
}
|
||||
}
|
||||
pImpl->meshRelation_.properties = VecDH<float>(numProp * idx, 0);
|
||||
pImpl->meshRelation_.properties = Vec<float>(numProp * idx, 0);
|
||||
} else {
|
||||
pImpl->meshRelation_.properties =
|
||||
VecDH<float>(numProp * NumPropVert(), 0);
|
||||
pImpl->meshRelation_.properties = Vec<float>(numProp * NumPropVert(), 0);
|
||||
}
|
||||
thrust::for_each_n(
|
||||
thrust::host, countAt(0), NumTri(),
|
||||
UpdateProperties({pImpl->meshRelation_.properties.ptrH(), numProp,
|
||||
oldProperties.ptrH(), oldNumProp,
|
||||
pImpl->vertPos_.ptrH(), triProperties.ptrH(),
|
||||
pImpl->halfedge_.ptrH(), propFunc}));
|
||||
UpdateProperties({pImpl->meshRelation_.properties.data(), numProp,
|
||||
oldProperties.data(), oldNumProp,
|
||||
pImpl->vertPos_.data(), triProperties.data(),
|
||||
pImpl->halfedge_.data(), propFunc}));
|
||||
}
|
||||
|
||||
pImpl->meshRelation_.numProp = numProp;
|
||||
pImpl->CreateFaces();
|
||||
pImpl->SimplifyTopology();
|
||||
pImpl->Finish();
|
||||
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
|
||||
}
|
||||
@@ -775,7 +792,25 @@ Manifold Manifold::TrimByPlane(glm::vec3 normal, float originOffset) const {
|
||||
return *this ^ Halfspace(BoundingBox(), normal, originOffset);
|
||||
}
|
||||
|
||||
ExecutionParams& ManifoldParams() { return params; }
|
||||
/**
|
||||
* Returns the cross section of this object parallel to the X-Y plane at the
|
||||
* specified Z height, defaulting to zero. Using a height equal to the bottom of
|
||||
* the bounding box will return the bottom faces, while using a height equal to
|
||||
* the top of the bounding box will return empty.
|
||||
*/
|
||||
CrossSection Manifold::Slice(float height) const {
|
||||
return GetCsgLeafNode().GetImpl()->Slice(height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a cross section representing the projected outline of this object
|
||||
* onto the X-Y plane.
|
||||
*/
|
||||
CrossSection Manifold::Project() const {
|
||||
return GetCsgLeafNode().GetImpl()->Project();
|
||||
}
|
||||
|
||||
ExecutionParams& ManifoldParams() { return manifoldParams; }
|
||||
|
||||
/**
|
||||
* Compute the convex hull of a set of points. If the given points are fewer
|
||||
@@ -785,6 +820,7 @@ ExecutionParams& ManifoldParams() { return params; }
|
||||
* hull.
|
||||
*/
|
||||
Manifold Manifold::Hull(const std::vector<glm::vec3>& pts) {
|
||||
ZoneScoped;
|
||||
const int numVert = pts.size();
|
||||
if (numVert < 4) return Manifold();
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user