Compare commits

..
Author SHA1 Message Date
Emmett Lalish 25cc2e496f 11 polygon tests failing 2023-09-13 08:36:17 -07:00
Emmett Lalish c1053cf309 more fixes 2023-09-04 15:43:35 -07:00
Emmett Lalish 945fee8308 small fixes 2023-09-03 23:09:19 -07:00
Emmett Lalish 4bdd53e417 readded shifting 2023-09-03 22:20:20 -07:00
Emmett Lalish 1b1cb5fda0 starting shift 2023-08-31 23:37:26 -07:00
Emmett Lalish 4f390c290b 47 tests passing 2023-08-31 22:31:19 -07:00
Emmett Lalish aa8611477f fixed more tests 2023-08-30 23:31:46 -07:00
Emmett Lalish 93d9b64f7c fixed MultiMerge 2023-08-30 22:14:23 -07:00
Emmett Lalish ebb96769ba another refactor, more tests passing 2023-08-30 21:39:05 -07:00
Emmett Lalish 9905a7585b rename 2023-08-30 10:09:22 -07:00
Emmett Lalish c09087bbd8 SimpleHole passes 2023-08-29 16:58:40 -07:00
Emmett Lalish 90b49380d5 fwd-bwd 2023-08-29 15:08:28 -07:00
Emmett Lalish 476c51a337 compiles 2023-08-29 14:13:06 -07:00
Emmett Lalish ee61127d72 started refactor 2023-08-15 17:09:33 -07:00
87 changed files with 4833 additions and 5289 deletions
-56
View File
@@ -1,56 +0,0 @@
name: build_wheels
on: [release, 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-beta:
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
+5 -38
View File
@@ -22,7 +22,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get -y update
DEBIAN_FRONTEND=noninteractive sudo apt install -y libglm-dev libgtest-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip lcov
DEBIAN_FRONTEND=noninteractive sudo apt install -y libgtest-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip lcov
pip install trimesh
- uses: actions/checkout@v3
with:
@@ -41,7 +41,7 @@ jobs:
cd build/test
./manifold_test
cd ../../
python3 bindings/python/examples/run_all.py -e
python3 bindings/python/examples/run_all.py
- name: Coverage Report
# only do code coverage for default sequential backend, it seems that TBB
# backend will cause failure
@@ -73,7 +73,7 @@ jobs:
- name: Install dependencies
run: |
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
DEBIAN_FRONTEND=noninteractive sudo apt install -y libgtest-dev libassimp-dev git libtbb-dev pkg-config libpython3-dev python3 python3-distutils python3-pip
- uses: actions/checkout@v3
with:
submodules: recursive
@@ -96,7 +96,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get -y update
DEBIAN_FRONTEND=noninteractive sudo apt install -y nodejs libglm-dev
DEBIAN_FRONTEND=noninteractive sudo apt install -y nodejs
- uses: actions/checkout@v3
with:
submodules: recursive
@@ -157,28 +157,6 @@ jobs:
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:
@@ -219,16 +197,5 @@ jobs:
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v15
- 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'
+13 -3
View File
@@ -1,9 +1,19 @@
[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
+1 -2
View File
@@ -120,7 +120,7 @@
"-DMANIFOLD_USE_CUDA=OFF",
"-DMANIFOLD_PAR=TBB",
"-DCODE_COVERAGE=OFF",
"-DCMAKE_CXX_FLAGS=''" //'-fsanitize=address,undefined'"
"-DCMAKE_CXX_FLAGS='-fsanitize=address,undefined'" //''" //
],
"search.exclude": {
"**/third_party/*": true,
@@ -144,5 +144,4 @@
"editor.defaultFormatter": "ms-python.black-formatter"
},
"python.formatting.provider": "none",
"clang-format.executable": "clang-format",
}
+20 -20
View File
@@ -16,20 +16,16 @@ 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)
option(MANIFOLD_DEBUG "Enable debug tracing/timing" OFF)
option(MANIFOLD_PYBIND "Build python bindings" ON)
option(MANIFOLD_CBIND "Build C (FFI) bindings" OFF)
option(MANIFOLD_JSBIND "Build js binding" ${EMSCRIPTEN})
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)
@@ -42,6 +38,9 @@ else()
option(CMAKE_BUILD_TYPE "Build type" Release)
endif()
set(MANIFOLD_PAR "NONE" CACHE STRING "Parallel backend, either \"TBB\" or \"NONE\"")
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} -O3)
if(EMSCRIPTEN)
message("Building for Emscripten")
set(MANIFOLD_FLAGS -fexceptions -D_LIBCUDACXX_HAS_THREAD_API_EXTERNAL -D_LIBCUDACXX_HAS_THREAD_API_CUDA)
@@ -50,39 +49,40 @@ if(EMSCRIPTEN)
endif()
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()
find_package(Python COMPONENTS Interpreter Development.Module REQUIRED)
endif()
if(CMAKE_EXPORT_COMPILE_COMMANDS AND NOT EMSCRIPTEN)
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(CMAKE_EXPORT_COMPILE_COMMANDS AND !EMSCRIPTEN)
# for nixos
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES})
endif()
if (MSVC)
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} /DNOMINMAX)
else()
if(NOT MSVC)
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)
set(MANIFOLD_FLAGS
"${MANIFOLD_FLAGS}"
"$<$<COMPILE_LANGUAGE:CXX>:${WARNING_FLAGS}>")
endif()
if(CODE_COVERAGE AND NOT MSVC)
set(COVERAGE_FLAGS -coverage -fno-inline-small-functions -fkeep-inline-functions -fkeep-static-functions)
set(MANIFOLD_FLAGS ${MANIFOLD_FLAGS} ${COVERAGE_FLAGS})
set(MANIFOLD_FLAGS
"${MANIFOLD_FLAGS}"
"$<$<COMPILE_LANGUAGE:CXX>:${COVERAGE_FLAGS}>")
add_link_options("-coverage")
endif()
include(GNUInstallDirs)
add_subdirectory(src)
add_subdirectory(bindings)
+6 -21
View File
@@ -11,7 +11,7 @@ For example, here is a log-log plot of Manifold's performance vs. earlier OpenSC
## [ManifoldCAD.org](https://manifoldcad.org)
If you like OpenSCAD / JSCAD, you might also like ManifoldCAD - our own solid modelling web app. Our WASM is not multithreaded yet, but it's still quite fast and a good way to test out our Manifold library.
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.
![A metallic Menger sponge](https://elalish.github.io/manifold/samples/models/mengerSponge3.webp "A metallic Menger sponge")
@@ -31,15 +31,11 @@ of this repository may solve the problem.
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.
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.
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)
## What's here
@@ -68,22 +64,11 @@ test/manifold_test
```
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
+1 -1
View File
@@ -20,6 +20,6 @@ if(NOT EMSCRIPTEN AND MANIFOLD_PYBIND)
add_subdirectory(python)
endif()
if(EMSCRIPTEN AND MANIFOLD_JSBIND)
if(EMSCRIPTEN)
add_subdirectory(wasm)
endif()
+1 -12
View File
@@ -14,20 +14,9 @@ endif()
target_link_libraries(
${PROJECT_NAME}
PRIVATE manifold sdf cross_section
PRIVATE manifold sdf graphlite 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
)
+3 -16
View File
@@ -1,20 +1,7 @@
// 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 "conv.h"
#include "manifold.h"
#include "public.h"
#include "types.h"
ManifoldBox *manifold_box(void *mem, float x1, float y1, float z1, float x2,
+4 -17
View File
@@ -1,25 +1,12 @@
// 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 <conv.h>
#include <manifold.h>
#include <sdf.h>
#include <vector>
#include "cross_section.h"
#include "manifold.h"
#include "include/types.h"
#include "public.h"
#include "sdf.h"
#include "types.h"
ManifoldManifold *to_c(manifold::Manifold *m) {
+3 -16
View File
@@ -1,23 +1,10 @@
// 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 <vector>
#include "conv.h"
#include "cross_section.h"
#include "manifold.h"
#include "public.h"
#include "types.h"
ManifoldCrossSection *manifold_cross_section_empty(void *mem) {
+5 -20
View File
@@ -1,28 +1,13 @@
// 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 <manifold.h>
#include <public.h>
#include <sdf.h>
#include <types.h>
#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>;
+3 -16
View File
@@ -1,21 +1,6 @@
// 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>
@@ -301,6 +286,8 @@ 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
-14
View File
@@ -1,17 +1,3 @@
// 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>
+4 -16
View File
@@ -1,17 +1,3 @@
// 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>
@@ -43,7 +29,8 @@ 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 mesh = LevelSet(fun, *from_c(bounds), edge_length, level, !seq);
auto pol = seq ? std::make_optional(ExecutionPolicy::Seq) : std::nullopt;
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, pol);
return to_c(new (mem) MeshGL(mesh));
}
ManifoldMeshGL *level_set_context(
@@ -56,7 +43,8 @@ ManifoldMeshGL *level_set_context(
std::function<float(glm::vec3)> fun = [sdf](glm::vec3 v) {
return (sdf(v.x, v.y, v.z));
};
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, !seq);
auto pol = seq ? std::make_optional(ExecutionPolicy::Seq) : std::nullopt;
auto mesh = LevelSet(fun, *from_c(bounds), edge_length, level, pol);
return to_c(new (mem) MeshGL(mesh));
}
} // namespace
+3 -16
View File
@@ -1,21 +1,8 @@
// 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 "types.h"
#include <conv.h>
#include "include/types.h"
// C <-> C++ conversions
+9 -16
View File
@@ -1,21 +1,8 @@
// 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 "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) {
@@ -98,3 +85,9 @@ 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));
}
+4 -19
View File
@@ -15,25 +15,10 @@
project(python)
add_subdirectory(third_party)
nanobind_add_module(
manifold3d
NB_STATIC STABLE_ABI LTO
manifold3d.cpp)
pybind11_add_module(manifold3d manifold3d.cpp)
target_link_libraries(manifold3d PRIVATE manifold)
target_compile_options(manifold3d PRIVATE ${MANIFOLD_FLAGS} -DMODULE_NAME=manifold3d)
target_compile_options(manifold3d PRIVATE ${MANIFOLD_FLAGS})
target_compile_features(manifold3d PUBLIC cxx_std_17)
set_target_properties(manifold3d PROPERTIES OUTPUT_NAME "manifold3d")
if(SKBUILD)
install(
TARGETS manifold3d
LIBRARY DESTINATION ${SKBUILD_PLATLIB_DIR}
COMPONENT bindings
target_include_directories(manifold3d
PRIVATE ${PYBIND11_DIR}/include
)
else()
install(
TARGETS manifold3d
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
COMPONENT bindings
)
endif()
+6 -6
View File
@@ -1,4 +1,4 @@
from manifold3d import CrossSection
from manifold3d import CrossSection, FillRule
def run():
@@ -11,7 +11,7 @@ def run():
polygons = cross_section.to_polygons()
polygon = polygons[0]
if set(polygon) != set(polygon_points):
raise Exception(f"polygon={polygon} differs from polygon_points={polygon_points}")
raise Exception(f"{polygon=} differs from {polygon_points=}")
# extrude a polygon to create a manifold
extruded_polygon = cross_section.extrude(10.0)
@@ -19,20 +19,20 @@ def run():
observed_volume = extruded_polygon.get_volume()
expected_volume = 10.0
if abs(observed_volume - expected_volume) > eps:
raise Exception(f"observed_volume={observed_volume} differs from expected_volume={expected_volume}")
raise Exception(f"{observed_volume=} differs from {expected_volume=}")
observed_surface_area = extruded_polygon.get_surface_area()
expected_surface_area = 42.0
if abs(observed_surface_area - expected_surface_area) > eps:
raise Exception(f"observed_surface_area={observed_surface_area} differs from expected_surface_area={expected_surface_area}")
raise Exception(f"{observed_surface_area=} differs from {expected_surface_area=}")
# get bounding box from manifold
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={observed_bbox} differs from expected_bbox={expected_bbox}")
raise Exception(f"{observed_bbox=} differs from {expected_bbox=}")
return extruded_polygon
if __name__ == "__main__":
run()
run()
+275 -316
View File
@@ -12,70 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <optional>
#include <string>
#include "cross_section.h"
#include "manifold.h"
#include "nanobind/nanobind.h"
#include "nanobind/ndarray.h"
#include "nanobind/operators.h"
#include "nanobind/stl/function.h"
#include "nanobind/stl/optional.h"
#include "nanobind/stl/tuple.h"
#include "nanobind/stl/vector.h"
#include "pybind11/functional.h"
#include "pybind11/numpy.h"
#include "pybind11/operators.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
template <>
struct nanobind::detail::type_caster<glm::vec3> {
NB_TYPE_CASTER(glm::vec3, const_name("Vec3"));
using Caster = make_caster<float>;
bool from_python(handle src, uint8_t flags, cleanup_list *cleanup) noexcept {
size_t size;
PyObject *temp;
/* Will initialize 'size' and 'temp'. All return values and
return parameters are zero/NULL in the case of a failure. */
PyObject **o = seq_get(src.ptr(), &size, &temp);
if (size != 3) return false;
Caster caster;
if (o == nullptr) {
Py_XDECREF(temp);
return false;
}
bool success = true;
for (size_t i = 0; i < size; ++i) {
if (!caster.from_python(o[i], flags, cleanup)) {
success = false;
break;
}
value[i] = caster.value;
}
Py_XDECREF(temp);
return success;
}
static handle from_cpp(glm::vec3 vec, rv_policy policy,
cleanup_list *ls) noexcept {
std::vector<float> v{vec.x, vec.y, vec.z};
return make_caster<std::vector<float>>().from_cpp(&v, policy, ls);
}
};
namespace nb = nanobind;
namespace py = pybind11;
using namespace manifold;
typedef std::tuple<float, float> Float2;
typedef std::tuple<float, float, float> Float3;
constexpr auto pyArrayFlags = py::array::c_style | py::array::forcecast;
PYBIND11_MAKE_OPAQUE(std::vector<int>);
PYBIND11_MAKE_OPAQUE(std::vector<uint32_t>);
PYBIND11_MAKE_OPAQUE(std::vector<float>);
template <typename T>
std::vector<T> toVector(const T *arr, size_t size) {
return std::vector<T>(arr, arr + size);
std::vector<T> toVector(const py::array_t<T> &arr) {
return std::vector<T>(arr.data(), arr.data() + arr.size());
}
NB_MODULE(manifold3d, m) {
PYBIND11_MODULE(manifold3d, m) {
m.doc() = "Python binding for the Manifold library.";
m.def("set_min_circular_angle", Quality::SetMinCircularAngle,
@@ -114,26 +77,25 @@ NB_MODULE(manifold3d, m) {
":param radius: For a given radius of circle, determine how many "
"default");
nb::class_<Manifold>(m, "Manifold")
.def(nb::init<>())
.def(
"__init__",
[](Manifold *self, std::vector<Manifold> &manifolds) {
if (manifolds.size() >= 1) {
// for some reason using Manifold() as the initial object
// will cause failure for python specifically
// unable to reproduce with c++ directly
Manifold first = manifolds[0];
for (int i = 1; i < manifolds.size(); i++) first += manifolds[i];
new (self) Manifold(first);
} else {
new (self) Manifold();
}
},
"Construct manifold as the union of a set of manifolds.")
.def(nb::self + nb::self, "Boolean union.")
.def(nb::self - nb::self, "Boolean difference.")
.def(nb::self ^ nb::self, "Boolean intersection.")
py::class_<Manifold>(m, "Manifold")
.def(py::init<>())
.def(py::init([](std::vector<Manifold> &manifolds) {
Manifold result;
if (manifolds.size() >= 1) {
// for some reason using Manifold() as the initial object
// will cause failure for python specifically
// unable to reproduce with c++ directly
Manifold first = manifolds[0];
for (int i = 1; i < manifolds.size(); i++) first += manifolds[i];
return first;
} else {
return Manifold();
}
}),
"Construct manifold as the union of a set of manifolds.")
.def(py::self + py::self, "Boolean union.")
.def(py::self - py::self, "Boolean difference.")
.def(py::self ^ py::self, "Boolean intersection.")
.def(
"hull", [](Manifold &self) { return self.Hull(); },
"Compute the convex hull of all points in this manifold.")
@@ -154,18 +116,19 @@ NB_MODULE(manifold3d, m) {
"Compute the convex hull enveloping a set of 3d points.")
.def(
"transform",
[](Manifold &self, nb::ndarray<float, nb::shape<3, 4>> &mat) {
[](Manifold &self, py::array_t<float> &mat) {
auto mat_view = mat.unchecked<2>();
if (mat.ndim() != 2 || mat.shape(0) != 3 || mat.shape(1) != 4)
throw std::runtime_error("Invalid matrix shape, expected (3, 4)");
glm::mat4x3 mat_glm;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
mat_glm[j][i] = mat(i, j);
mat_glm[j][i] = mat_view(i, j);
}
}
return self.Transform(mat_glm);
},
nb::arg("m"),
py::arg("m"),
"Transform this Manifold in space. The first three columns form a "
"3x3 matrix transform and the last is a translation vector. This "
"operation can be chained. Transforms are combined and applied "
@@ -177,45 +140,74 @@ NB_MODULE(manifold3d, m) {
[](Manifold &self, float x = 0.0f, float y = 0.0f, float z = 0.0f) {
return self.Translate(glm::vec3(x, y, z));
},
nb::arg("x") = 0.0f, nb::arg("y") = 0.0f, nb::arg("z") = 0.0f,
py::arg("x") = 0.0f, py::arg("y") = 0.0f, py::arg("z") = 0.0f,
"Move this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param x: X axis translation. (default 0.0).\n"
":param y: Y axis translation. (default 0.0).\n"
":param z: Z axis translation. (default 0.0).")
.def("translate", &Manifold::Translate, nb::arg("t"),
"Move this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param v: The vector to add to every vertex.")
.def(
"translate",
[](Manifold &self, py::array_t<float> &t) {
auto t_view = t.unchecked<1>();
if (t.ndim() != 1 || t.shape(0) != 3)
throw std::runtime_error("Invalid vector shape");
return self.Translate(glm::vec3(t_view(0), t_view(1), t_view(2)));
},
py::arg("t"),
"Move this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param v: The vector to add to every vertex.")
.def(
"scale",
[](Manifold &self, float scale) {
return self.Scale(glm::vec3(scale));
},
nb::arg("scale"),
py::arg("scale"),
"Scale this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param scale: The scalar multiplier for each component of every "
"vertices.")
.def("scale", &Manifold::Scale, nb::arg("v"),
"Scale this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param v: The vector to multiply every vertex by component.")
.def("mirror", &Manifold::Mirror, nb::arg("v"),
"Mirror this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param mirror: The vector defining the axis of mirroring.")
.def(
"scale",
[](Manifold &self, py::array_t<float> &scale) {
auto scale_view = scale.unchecked<1>();
if (scale.ndim() != 1 || scale.shape(0) != 3)
throw std::runtime_error("Invalid vector shape, expected (3)");
glm::vec3 v(scale_view(0), scale_view(1), scale_view(2));
return self.Scale(v);
},
py::arg("v"),
"Scale this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param v: The vector to multiply every vertex by component.")
.def(
"mirror",
[](Manifold &self, py::array_t<float> &mirror) {
auto v_view = mirror.unchecked<1>();
if (mirror.ndim() != 1 || mirror.shape(0) != 3)
throw std::runtime_error("Invalid vector shape, expected (3)");
glm::vec3 v(v_view(0), v_view(1), v_view(2));
return self.Mirror(v);
},
py::arg("v"),
"Mirror this Manifold in space. This operation can be chained. "
"Transforms are combined and applied lazily."
"\n\n"
":param mirror: The vector defining the axis of mirroring.")
.def(
"rotate",
[](Manifold &self, glm::vec3 v) {
return self.Rotate(v[0], v[1], v[2]);
[](Manifold &self, py::array_t<float> &v) {
auto v_view = v.unchecked<1>();
if (v.ndim() != 1 || v.shape(0) != 3)
throw std::runtime_error("Invalid vector shape, expected (3)");
return self.Rotate(v_view(0), v_view(1), v_view(2));
},
nb::arg("v"),
py::arg("v"),
"Applies an Euler angle rotation to the manifold, first about the X "
"axis, then Y, then Z, in degrees. We use degrees so that we can "
"minimize rounding error, and eliminate it completely for any "
@@ -231,8 +223,8 @@ NB_MODULE(manifold3d, m) {
float zDegrees = 0.0f) {
return self.Rotate(xDegrees, yDegrees, zDegrees);
},
nb::arg("x_degrees") = 0.0f, nb::arg("y_degrees") = 0.0f,
nb::arg("z_degrees") = 0.0f,
py::arg("x_degrees") = 0.0f, py::arg("y_degrees") = 0.0f,
py::arg("z_degrees") = 0.0f,
"Applies an Euler angle rotation to the manifold, first about the X "
"axis, then Y, then Z, in degrees. We use degrees so that we can "
"minimize rounding error, and eliminate it completely for any "
@@ -254,7 +246,7 @@ NB_MODULE(manifold3d, m) {
v.z = std::get<2>(fv);
});
},
nb::arg("f"),
py::arg("f"),
"This function does not change the topology, but allows the vertices "
"to be moved according to any arbitrary input function. It is easy "
"to create a function that warps a geometrically valid object into "
@@ -265,34 +257,23 @@ NB_MODULE(manifold3d, m) {
.def(
"set_properties",
[](Manifold &self, int newNumProp,
const std::function<nb::object(
Float3, const nb::ndarray<nb::numpy, const float, nb::c_contig>
&)> &f) {
const std::function<py::array_t<float>(
Float3, const py::array_t<float> &)> &f) {
const int oldNumProp = self.NumProp();
return self.SetProperties(newNumProp, [newNumProp, oldNumProp, &f](
float *newProps,
glm::vec3 v,
const float *oldProps) {
auto result =
f(std::make_tuple(v.x, v.y, v.z),
nb::ndarray<nb::numpy, const float, nb::c_contig>(
&oldProps, {static_cast<unsigned long>(oldNumProp)}));
nb::ndarray<float, nb::shape<nb::any>> array;
std::vector<float> vec;
if (nb::try_cast(result, array)) {
if (array.ndim() != 1 || array.shape(0) != newNumProp)
throw std::runtime_error("Invalid vector shape, expected (" +
std::to_string(newNumProp) + ")");
for (int i = 0; i < newNumProp; i++) newProps[i] = array(i);
} else if (nb::try_cast(result, vec)) {
for (int i = 0; i < newNumProp; i++) newProps[i] = vec[i];
} else {
throw std::runtime_error(
"Callback in set_properties should return an array");
}
auto array = f(std::make_tuple(v.x, v.y, v.z),
py::array(oldNumProp, oldProps));
if (array.ndim() != 1 || array.shape(0) != newNumProp)
throw std::runtime_error("Invalid vector shape, expected (" +
std::to_string(newNumProp) + ")");
auto array_view = array.unchecked<1>();
for (int i = 0; i < newNumProp; i++) newProps[i] = array_view(i);
});
},
nb::arg("new_num_prop"), nb::arg("f"),
py::arg("new_num_prop"), py::arg("f"),
"Create a new copy of this manifold with updated vertex properties "
"by supplying a function that takes the existing position and "
"properties as input. You may specify any number of output "
@@ -305,7 +286,7 @@ NB_MODULE(manifold3d, m) {
"vertex.")
.def(
"refine", [](Manifold &self, int n) { return self.Refine(n); },
nb::arg("n"),
py::arg("n"),
"Increase the density of the mesh by splitting every edge into n "
"pieces. For instance, with n = 2, each triangle will be split into "
"4 triangles. These will all be coplanar (and will not be "
@@ -318,14 +299,15 @@ NB_MODULE(manifold3d, m) {
"1.")
.def(
"to_mesh",
[](Manifold &self,
std::optional<nb::ndarray<uint32_t, nb::shape<3>>> &normalIdx) {
[](Manifold &self, std::optional<py::array_t<uint32_t>> &normalIdx) {
glm::ivec3 v(0);
if (normalIdx.has_value()) {
if (normalIdx->ndim() != 1 || normalIdx->shape(0) != 3)
if (normalIdx.value().ndim() != 1 ||
normalIdx.value().shape(0) != 3)
throw std::runtime_error("Invalid vector shape, expected (3)");
auto value = *normalIdx;
v = glm::ivec3(value(0), value(1), value(2));
auto normalIdx_view = normalIdx.value().unchecked<1>();
v = glm::ivec3(normalIdx_view(0), normalIdx_view(1),
normalIdx_view(2));
}
return self.GetMeshGL(v);
},
@@ -342,7 +324,7 @@ NB_MODULE(manifold3d, m) {
"according to the applied transforms and front/back side. Each "
"channel must be >= 3 and < numProp, and all original MeshGLs must "
"use the same channels for their normals.",
nb::arg("normalIdx") = nb::none())
py::arg("normalIdx") = py::none())
.def("num_vert", &Manifold::NumVert,
"The number of vertices in the Manifold.")
.def("num_edge", &Manifold::NumEdge,
@@ -408,7 +390,7 @@ NB_MODULE(manifold3d, m) {
{std::get<0>(normal), std::get<1>(normal), std::get<2>(normal)},
originOffset);
},
nb::arg("normal"), nb::arg("origin_offset"),
py::arg("normal"), py::arg("origin_offset"),
"Convenient version of Split() for a half-space."
"\n\n"
":param normal: This vector is normal to the cutting plane and its "
@@ -423,7 +405,7 @@ NB_MODULE(manifold3d, m) {
{std::get<0>(normal), std::get<1>(normal), std::get<2>(normal)},
originOffset);
},
nb::arg("normal"), nb::arg("origin_offset"),
py::arg("normal"), py::arg("origin_offset"),
"Identical to SplitByPlane(), but calculating and returning only the "
"first result."
"\n\n"
@@ -432,19 +414,11 @@ NB_MODULE(manifold3d, m) {
"vector from the plane.\n"
":param originOffset: The distance of the plane from the origin in "
"the direction of the normal vector.")
.def("status", &Manifold::Status,
"Returns the reason for an input Mesh producing an empty Manifold. "
"This Status only applies to Manifolds newly-created from an input "
"Mesh - once they are combined into a new Manifold via operations, "
"the status reverts to NoError, simply processing the problem mesh "
"as empty. Likewise, empty meshes may still show NoError, for "
"instance if they are small enough relative to their precision to "
"be collapsed to nothing.")
.def_prop_ro(
.def_property_readonly(
"bounding_box",
[](Manifold &self) {
auto b = self.BoundingBox();
nb::tuple box = nb::make_tuple(b.min[0], b.min[1], b.min[2],
py::tuple box = py::make_tuple(b.min[0], b.min[1], b.min[2],
b.max[0], b.max[1], b.max[2]);
return box;
},
@@ -483,7 +457,7 @@ NB_MODULE(manifold3d, m) {
"formed.")
.def_static(
"from_mesh", [](const MeshGL &mesh) { return Manifold(mesh); },
nb::arg("mesh"))
py::arg("mesh"))
.def_static(
"compose",
[](const std::vector<Manifold> &list) {
@@ -503,15 +477,23 @@ NB_MODULE(manifold3d, m) {
std::get<2>(size)),
center);
},
nb::arg("size") = std::make_tuple(1.0f, 1.0f, 1.0f),
nb::arg("center") = false,
py::arg("size") = std::make_tuple(1.0f, 1.0f, 1.0f),
py::arg("center") = false,
"Constructs a unit cube (edge lengths all one), by default in the "
"first octant, touching the origin."
"\n\n"
":param size: The X, Y, and Z dimensions of the box.\n"
":param center: Set to true to shift the center to the origin.")
.def_static(
"cube", &Manifold::Cube, nb::arg("size"), nb::arg("center") = false,
"cube",
[](py::array_t<float> &size, bool center = false) {
auto size_view = size.unchecked<1>();
if (size.ndim() != 1 || size.shape(0) != 3)
throw std::runtime_error("Invalid vector shape, expected (3)");
return Manifold::Cube(
glm::vec3(size_view(0), size_view(1), size_view(2)), center);
},
py::arg("size"), py::arg("center") = false,
"Constructs a unit cube (edge lengths all one), by default in the "
"first octant, touching the origin."
"\n\n"
@@ -522,7 +504,7 @@ NB_MODULE(manifold3d, m) {
[](float x, float y, float z, bool center = false) {
return Manifold::Cube(glm::vec3(x, y, z), center);
},
nb::arg("x"), nb::arg("y"), nb::arg("z"), nb::arg("center") = false,
py::arg("x"), py::arg("y"), py::arg("z"), py::arg("center") = false,
"Constructs a unit cube (edge lengths all one), by default in the "
"first octant, touching the origin."
"\n\n"
@@ -537,9 +519,9 @@ NB_MODULE(manifold3d, m) {
return Manifold::Cylinder(height, radiusLow, radiusHigh,
circularSegments, center);
},
nb::arg("height"), nb::arg("radius_low"),
nb::arg("radius_high") = -1.0f, nb::arg("circular_segments") = 0,
nb::arg("center") = false,
py::arg("height"), py::arg("radius_low"),
py::arg("radius_high") = -1.0f, py::arg("circular_segments") = 0,
py::arg("center") = false,
"A convenience constructor for the common case of extruding a "
"circle. Can also form cones if both radii are specified."
"\n\n"
@@ -556,7 +538,7 @@ NB_MODULE(manifold3d, m) {
[](float radius, int circularSegments = 0) {
return Manifold::Sphere(radius, circularSegments);
},
nb::arg("radius"), nb::arg("circular_segments") = 0,
py::arg("radius"), py::arg("circular_segments") = 0,
"Constructs a geodesic sphere of a given radius.\n"
"\n"
":param radius: Radius of the sphere. Must be positive.\n"
@@ -565,145 +547,123 @@ NB_MODULE(manifold3d, m) {
"four, as this sphere is constructed by refining an octahedron. This "
"means there are a circle of vertices on all three of the axis "
"planes. Default is calculated by the static Defaults.")
.def_static("reserve_ids", Manifold::ReserveIDs, nb::arg("n"),
.def_static("reserve_ids", Manifold::ReserveIDs, py::arg("n"),
"Returns the first of n sequential new unique mesh IDs for "
"marking sets of triangles that can be looked up after "
"further operations. Assign to MeshGL.runOriginalID vector");
nb::class_<MeshGL>(m, "Mesh")
py::class_<MeshGL>(m, "Mesh")
.def(
// note that reshape requires mutable ndarray, but this will not
// note that reshape requires mutable array_t, but this will not
// affect the original array passed into the function
"__init__",
[](MeshGL *self,
nb::ndarray<float, nb::shape<nb::any, nb::any>, nb::c_contig>
&vertProp,
nb::ndarray<uint32_t, nb::shape<nb::any, 3>, nb::c_contig>
&triVerts,
const std::optional<nb::ndarray<uint32_t, nb::shape<nb::any>,
nb::c_contig>> &mergeFromVert,
const std::optional<nb::ndarray<uint32_t, nb::shape<nb::any>,
nb::c_contig>> &mergeToVert,
const std::optional<nb::ndarray<uint32_t, nb::shape<nb::any>,
nb::c_contig>> &runIndex,
const std::optional<nb::ndarray<uint32_t, nb::shape<nb::any>,
nb::c_contig>> &runOriginalID,
std::optional<nb::ndarray<float, nb::shape<nb::any, 4, 3>,
nb::c_contig>> &runTransform,
const std::optional<nb::ndarray<uint32_t, nb::shape<nb::any>,
nb::c_contig>> &faceID,
const std::optional<nb::ndarray<float, nb::shape<nb::any, 3, 4>,
nb::c_contig>> &halfedgeTangent,
float precision) {
new (self) MeshGL();
MeshGL &out = *self;
out.numProp = vertProp.shape(1);
out.vertProperties =
toVector<float>(vertProp.data(), vertProp.size());
py::init(
[](py::array_t<float, pyArrayFlags> &vertProp,
py::array_t<int, pyArrayFlags> &triVerts,
const std::optional<py::array_t<uint32_t, pyArrayFlags>>
&mergeFromVert,
const std::optional<py::array_t<uint32_t, pyArrayFlags>>
&mergeToVert,
const std::optional<py::array_t<uint32_t, pyArrayFlags>>
&runIndex,
const std::optional<py::array_t<uint32_t, pyArrayFlags>>
&runOriginalID,
std::optional<py::array_t<float, pyArrayFlags>> &runTransform,
const std::optional<py::array_t<uint32_t, pyArrayFlags>>
&faceID,
const std::optional<py::array_t<float, pyArrayFlags>>
&halfedgeTangent,
float precision) {
MeshGL out;
if (triVerts.ndim() != 2 || triVerts.shape(1) != 3)
throw std::runtime_error(
"Invalid tri_verts shape, expected (-1, 3)");
out.triVerts = toVector<uint32_t>(triVerts.data(), triVerts.size());
out.numProp = vertProp.shape(1);
vertProp = vertProp.reshape({-1});
out.vertProperties = toVector<float>(vertProp);
if (mergeFromVert.has_value())
out.mergeFromVert = toVector<uint32_t>(mergeFromVert->data(),
mergeFromVert->size());
if (triVerts.ndim() != 2 || triVerts.shape(1) != 3)
throw std::runtime_error(
"Invalid tri_verts shape, expected (-1, 3)");
triVerts = triVerts.reshape({-1});
out.triVerts = toVector<uint32_t>(triVerts);
if (mergeToVert.has_value())
out.mergeToVert =
toVector<uint32_t>(mergeToVert->data(), mergeToVert->size());
if (mergeFromVert.has_value())
out.mergeFromVert = toVector<uint32_t>(mergeFromVert.value());
if (runIndex.has_value())
out.runIndex =
toVector<uint32_t>(runIndex->data(), runIndex->size());
if (mergeToVert.has_value())
out.mergeToVert = toVector<uint32_t>(mergeToVert.value());
if (runOriginalID.has_value())
out.runOriginalID = toVector<uint32_t>(runOriginalID->data(),
runOriginalID->size());
if (runIndex.has_value())
out.runIndex = toVector<uint32_t>(runIndex.value());
if (runTransform.has_value()) {
auto runTransform1 = *runTransform;
if (runTransform1.ndim() != 3 || runTransform1.shape(1) != 4 ||
runTransform1.shape(2) != 3)
throw std::runtime_error(
"Invalid run_transform shape, expected (-1, 4, 3)");
out.runTransform =
toVector<float>(runTransform1.data(), runTransform1.size());
}
if (runOriginalID.has_value())
out.runOriginalID = toVector<uint32_t>(runOriginalID.value());
if (faceID.has_value())
out.faceID = toVector<uint32_t>(faceID->data(), faceID->size());
if (runTransform.has_value()) {
auto runTransform1 = runTransform.value();
if (runTransform1.ndim() != 3 ||
runTransform1.shape(1) != 4 ||
runTransform1.shape(2) != 3)
throw std::runtime_error(
"Invalid run_transform shape, expected (-1, 4, 3)");
runTransform1 = runTransform1.reshape({-1});
out.runTransform = toVector<float>(runTransform1);
}
if (halfedgeTangent.has_value()) {
auto halfedgeTangent1 = *halfedgeTangent;
if (halfedgeTangent1.ndim() != 3 ||
halfedgeTangent1.shape(1) != 3 ||
halfedgeTangent1.shape(2) != 4)
throw std::runtime_error(
"Invalid halfedge_tangent shape, expected (-1, 3, 4)");
out.halfedgeTangent = toVector<float>(halfedgeTangent1.data(),
halfedgeTangent1.size());
}
},
nb::arg("vert_properties"), nb::arg("tri_verts"),
nb::arg("merge_from_vert") = nb::none(),
nb::arg("merge_to_vert") = nb::none(),
nb::arg("run_index") = nb::none(),
nb::arg("run_original_id") = nb::none(),
nb::arg("run_transform") = nb::none(),
nb::arg("face_id") = nb::none(),
nb::arg("halfedge_tangent") = nb::none(), nb::arg("precision") = 0)
.def_prop_ro("vert_properties",
[](const MeshGL &self) {
return nb::ndarray<nb::numpy, const float, nb::c_contig>(
self.vertProperties.data(),
{self.vertProperties.size() / self.numProp,
self.numProp});
}, nb::rv_policy::reference_internal)
.def_prop_ro("tri_verts",
[](const MeshGL &self) {
return nb::ndarray<nb::numpy, const int, nb::c_contig>(
self.triVerts.data(), {self.triVerts.size() / 3, 3});
}, nb::rv_policy::reference_internal)
.def_prop_ro("run_transform",
[](const MeshGL &self) {
return nb::ndarray<nb::numpy, const float, nb::c_contig>(
self.runTransform.data(), {self.runTransform.size() / 12, 4, 3});
}, nb::rv_policy::reference_internal)
.def_prop_ro("halfedge_tangent",
[](const MeshGL &self) {
float *data = new float[self.halfedgeTangent.size()];
std::copy(self.halfedgeTangent.data(),
self.halfedgeTangent.data() +
self.halfedgeTangent.size(),
data);
return nb::ndarray<nb::numpy, const float, nb::c_contig>(
self.halfedgeTangent.data(), {self.halfedgeTangent.size() / 12, 3, 4});
}, nb::rv_policy::reference_internal)
.def_ro("merge_from_vert", &MeshGL::mergeFromVert)
.def_ro("merge_to_vert", &MeshGL::mergeToVert)
.def_ro("run_index", &MeshGL::runIndex)
.def_ro("run_original_id", &MeshGL::runOriginalID)
.def_ro("face_id", &MeshGL::faceID);
if (faceID.has_value())
out.faceID = toVector<uint32_t>(faceID.value());
nb::enum_<Manifold::Error>(m, "Error")
.value("NoError", Manifold::Error::NoError)
.value("NonFiniteVertex", Manifold::Error::NonFiniteVertex)
.value("NotManifold", Manifold::Error::NotManifold)
.value("VertexOutOfBounds", Manifold::Error::VertexOutOfBounds)
.value("PropertiesWrongLength", Manifold::Error::PropertiesWrongLength)
.value("MissingPositionProperties",
Manifold::Error::MissingPositionProperties)
.value("MergeVectorsDifferentLengths",
Manifold::Error::MergeVectorsDifferentLengths)
.value("MergeIndexOutOfBounds", Manifold::Error::MergeIndexOutOfBounds)
.value("TransformWrongLength", Manifold::Error::TransformWrongLength)
.value("RunIndexWrongLength", Manifold::Error::RunIndexWrongLength)
.value("FaceIDWrongLength", Manifold::Error::FaceIDWrongLength)
.value("InvalidConstruction", Manifold::Error::InvalidConstruction);
if (halfedgeTangent.has_value()) {
auto halfedgeTangent1 = halfedgeTangent.value();
if (halfedgeTangent1.ndim() != 3 ||
halfedgeTangent1.shape(1) != 3 ||
halfedgeTangent1.shape(2) != 4)
throw std::runtime_error(
"Invalid halfedge_tangent shape, expected (-1, 3, 4)");
halfedgeTangent1 = halfedgeTangent1.reshape({-1});
out.halfedgeTangent = toVector<float>(halfedgeTangent1);
}
nb::enum_<CrossSection::FillRule>(m, "FillRule")
return out;
}),
py::arg("vert_properties"), py::arg("tri_verts"),
py::arg("merge_from_vert") = py::none(),
py::arg("merge_to_vert") = py::none(),
py::arg("run_index") = py::none(),
py::arg("run_original_id") = py::none(),
py::arg("run_transform") = py::none(),
py::arg("face_id") = py::none(),
py::arg("halfedge_tangent") = py::none(), py::arg("precision") = 0)
.def_property_readonly(
"vert_properties",
[](const MeshGL &self) {
return py::array(self.vertProperties.size(),
self.vertProperties.data())
.reshape(std::array<int, 2>{-1, (int)self.numProp});
})
.def_property_readonly("tri_verts",
[](const MeshGL &self) {
return py::array(self.triVerts.size(),
self.triVerts.data())
.reshape(std::array<int, 2>{-1, 3});
})
.def_property_readonly("run_transform",
[](const MeshGL &self) {
return py::array(self.runTransform.size(),
self.runTransform.data())
.reshape(std::array<int, 3>{-1, 4, 3});
})
.def_property_readonly("halfedge_tangent",
[](const MeshGL &self) {
return py::array(self.halfedgeTangent.size(),
self.halfedgeTangent.data())
.reshape(std::array<int, 3>{-1, 3, 4});
})
.def_readonly("merge_from_vert", &MeshGL::mergeFromVert)
.def_readonly("merge_to_vert", &MeshGL::mergeToVert)
.def_readonly("run_index", &MeshGL::runIndex)
.def_readonly("run_original_id", &MeshGL::runOriginalID)
.def_readonly("face_id", &MeshGL::faceID);
py::enum_<CrossSection::FillRule>(m, "FillRule")
.value("EvenOdd", CrossSection::FillRule::EvenOdd,
"Only odd numbered sub-regions are filled.")
.value("NonZero", CrossSection::FillRule::NonZero,
@@ -713,7 +673,7 @@ NB_MODULE(manifold3d, m) {
.value("Negative", CrossSection::FillRule::Negative,
"Only sub-regions with winding counts < 0 are filled.");
nb::enum_<CrossSection::JoinType>(m, "JoinType")
py::enum_<CrossSection::JoinType>(m, "JoinType")
.value("Square", CrossSection::JoinType::Square,
"Squaring is applied uniformly at all joins where the internal "
"join angle is less that 90 degrees. The squared edge will be at "
@@ -731,39 +691,37 @@ NB_MODULE(manifold3d, m) {
"joins would exceed a given maximum miter distance (relative to the "
"offset distance), these are 'squared' instead.");
nb::class_<CrossSection>(
py::class_<CrossSection>(
m, "CrossSection",
"Two-dimensional cross sections guaranteed to be without "
"self-intersections, or overlaps between polygons (from construction "
"onwards). This class makes use of the "
"[Clipper2](http://www.angusj.com/clipper2/Docs/Overview.htm) library "
"for polygon clipping (boolean) and offsetting operations.")
.def(nb::init<>())
.def(
"__init__",
[](CrossSection *self, std::vector<std::vector<Float2>> &polygons,
CrossSection::FillRule fillrule) {
std::vector<SimplePolygon> simplePolygons(polygons.size());
for (int i = 0; i < polygons.size(); i++) {
simplePolygons[i] = std::vector<glm::vec2>(polygons[i].size());
for (int j = 0; j < polygons[i].size(); j++) {
simplePolygons[i][j] = {std::get<0>(polygons[i][j]),
std::get<1>(polygons[i][j])};
}
}
new (self) CrossSection(simplePolygons, fillrule);
},
nb::arg("polygons"),
nb::arg("fillrule") = CrossSection::FillRule::Positive,
"Create a 2d cross-section from a set of contours (complex "
"polygons). A boolean union operation (with Positive filling rule "
"by default) performed to combine overlapping polygons and ensure "
"the resulting CrossSection is free of intersections."
"\n\n"
":param contours: A set of closed paths describing zero or more "
"complex polygons.\n"
":param fillrule: The filling rule used to interpret polygon "
"sub-regions in contours.")
.def(py::init<>())
.def(py::init([](std::vector<std::vector<Float2>> &polygons,
CrossSection::FillRule fillrule) {
std::vector<SimplePolygon> simplePolygons(polygons.size());
for (int i = 0; i < polygons.size(); i++) {
simplePolygons[i] = std::vector<glm::vec2>(polygons[i].size());
for (int j = 0; j < polygons[i].size(); j++) {
simplePolygons[i][j] = {std::get<0>(polygons[i][j]),
std::get<1>(polygons[i][j])};
}
}
return CrossSection(simplePolygons, fillrule);
}),
py::arg("polygons"),
py::arg("fillrule") = CrossSection::FillRule::Positive,
"Create a 2d cross-section from a set of contours (complex "
"polygons). A boolean union operation (with Positive filling rule "
"by default) performed to combine overlapping polygons and ensure "
"the resulting CrossSection is free of intersections."
"\n\n"
":param contours: A set of closed paths describing zero or more "
"complex polygons.\n"
":param fillrule: The filling rule used to interpret polygon "
"sub-regions in contours.")
.def("area", &CrossSection::Area,
"Return the total area covered by complex polygons making up the "
"CrossSection.")
@@ -811,13 +769,14 @@ NB_MODULE(manifold3d, m) {
":param ax: the axis to be mirrored over")
.def(
"transform",
[](CrossSection self, nb::ndarray<float, nb::shape<2, 3>> &mat) {
[](CrossSection self, py::array_t<float> &mat) {
auto mat_view = mat.unchecked<2>();
if (mat.ndim() != 2 || mat.shape(0) != 2 || mat.shape(1) != 3)
throw std::runtime_error("Invalid matrix shape, expected (2, 3)");
glm::mat3x2 mat_glm;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
mat_glm[j][i] = mat(i, j);
mat_glm[j][i] = mat_view(i, j);
}
}
return self.Transform(mat_glm);
@@ -837,7 +796,7 @@ NB_MODULE(manifold3d, m) {
v.y = std::get<1>(fv);
});
},
nb::arg("f"),
py::arg("f"),
"Move the vertices of this CrossSection (creating a new one) "
"according to any arbitrary input function, followed by a union "
"operation (with a Positive fill rule) that ensures any introduced "
@@ -857,9 +816,9 @@ NB_MODULE(manifold3d, m) {
"do not improve quality in any meaningful way. This is particularly "
"important if further offseting operations are to be performed, "
"which would compound the issue.")
.def("offset", &CrossSection::Offset, nb::arg("delta"),
nb::arg("join_type"), nb::arg("miter_limit") = 2.0,
nb::arg("arc_tolerance") = 0.0,
.def("offset", &CrossSection::Offset, py::arg("delta"),
py::arg("join_type"), py::arg("miter_limit") = 2.0,
py::arg("arc_tolerance") = 0.0,
"Inflate the contours in CrossSection by the specified delta, "
"handling corners according to the given JoinType."
"\n\n"
@@ -879,9 +838,9 @@ NB_MODULE(manifold3d, m) {
"<B>JoinType::Round</B> corners (roughly, the number of vertices "
"that will be added to each contour). Default is calculated by the "
"static Quality defaults according to the radius.")
.def(nb::self + nb::self, "Boolean union.")
.def(nb::self - nb::self, "Boolean difference.")
.def(nb::self ^ nb::self, "Boolean intersection.")
.def(py::self + py::self, "Boolean union.")
.def(py::self - py::self, "Boolean difference.")
.def(py::self ^ py::self, "Boolean intersection.")
.def(
"hull", [](CrossSection &self) { return self.Hull(); },
"Compute the convex hull of this cross-section.")
@@ -907,12 +866,12 @@ NB_MODULE(manifold3d, m) {
"to_polygons",
[](CrossSection self) {
const Polygons &data = self.ToPolygons();
nb::list polygon_list;
py::list polygon_list;
for (int i = 0; i < data.size(); ++i) {
nb::list polygon;
py::list polygon;
for (int j = 0; j < data[i].size(); ++j) {
auto f = data[i][j];
nb::tuple vertex = nb::make_tuple(f[0], f[1]);
py::tuple vertex = py::make_tuple(f[0], f[1]);
polygon.append(vertex);
}
polygon_list.append(polygon);
@@ -930,9 +889,9 @@ NB_MODULE(manifold3d, m) {
return Manifold::Extrude(self, height, nDivisions, twistDegrees,
scaleTopVec);
},
nb::arg("height"), nb::arg("n_divisions") = 0,
nb::arg("twist_degrees") = 0.0f,
nb::arg("scale_top") = std::make_tuple(1.0f, 1.0f),
py::arg("height"), py::arg("n_divisions") = 0,
py::arg("twist_degrees") = 0.0f,
py::arg("scale_top") = std::make_tuple(1.0f, 1.0f),
"Constructs a manifold from the set of polygons by extruding them "
"along the Z-axis.\n"
"\n"
@@ -951,7 +910,7 @@ NB_MODULE(manifold3d, m) {
[](CrossSection self, int circularSegments = 0) {
return Manifold::Revolve(self, circularSegments);
},
nb::arg("circular_segments") = 0,
py::arg("circular_segments") = 0,
"Constructs a manifold from the set of polygons by revolving this "
"cross-section around its Y-axis and then setting this as the Z-axis "
"of the resulting manifold. If the polygons cross the Y-axis, only "
@@ -966,7 +925,7 @@ NB_MODULE(manifold3d, m) {
return CrossSection::Square({std::get<0>(dims), std::get<1>(dims)},
center);
},
nb::arg("dims"), nb::arg("center") = false,
py::arg("dims"), py::arg("center") = false,
"Constructs a square with the given XY dimensions. By default it is "
"positioned in the first quadrant, touching the origin. If any "
"dimensions in size are negative, or if all are zero, an empty "
@@ -979,7 +938,7 @@ NB_MODULE(manifold3d, m) {
[](float radius, int circularSegments) {
return CrossSection::Circle(radius, circularSegments);
},
nb::arg("radius"), nb::arg("circularSegments") = 0,
py::arg("radius"), py::arg("circularSegments") = 0,
"Constructs a circle of a given radius."
"\n\n"
":param radius: Radius of the circle. Must be positive.\n"
+1 -1
View File
@@ -1 +1 @@
add_subdirectory(nanobind)
add_subdirectory(pybind11)
+3 -3
View File
@@ -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;
+3 -3
View File
@@ -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;
+1
View File
@@ -42,6 +42,7 @@ if(BUILD_TEST_CGAL)
add_executable(perfTestCGAL perf_test_cgal.cpp)
find_package(CGAL REQUIRED COMPONENTS Core)
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_compile_options(perfTestCGAL PRIVATE ${MANIFOLD_FLAGS})
target_compile_features(perfTestCGAL PUBLIC cxx_std_17)
+3 -2
View File
@@ -57,9 +57,10 @@ 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.Translate(glm::vec3(0.5));
Manifold sphere2 = sphere;
sphere2.Translate(glm::vec3(0.5));
TriangleMesh cgalSphere, cgalSphere2;
TriangleMesh cgalSphere, cgalSphere2, cgalOut;
manifoldToCGALSurfaceMesh(sphere, cgalSphere);
manifoldToCGALSurfaceMesh(sphere2, cgalSphere2);
Generated
+6 -6
View File
@@ -5,11 +5,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1692799911,
"narHash": "sha256-3eihraek4qL744EvQXsK1Ha6C3CR7nnT8X2qWap4RNk=",
"lastModified": 1689068808,
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "f9e7cf818399d17d347f847525c5a5a8032e4e44",
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
"type": "github"
},
"original": {
@@ -37,11 +37,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1692734709,
"narHash": "sha256-SCFnyHCyYjwEmgUsHDDuU0TsbVMKeU1vwkR+r7uS2Rg=",
"lastModified": 1691006197,
"narHash": "sha256-DbtxVWPt+ZP5W0Usg7jAyTomIM//c3Jtfa59Ht7AV8s=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b85ed9dcbf187b909ef7964774f8847d554fab3b",
"rev": "66aedfd010204949cb225cf749be08cb13ce1813",
"type": "github"
},
"original": {
+17 -76
View File
@@ -5,6 +5,7 @@
url = "github:google/googletest/v1.14.0";
flake = false;
};
outputs = { self, nixpkgs, flake-utils, gtest-src }:
flake-utils.lib.eachDefaultSystem
(system:
@@ -13,37 +14,6 @@
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"
, doCheck ? true
@@ -52,21 +22,16 @@
}: pkgs.stdenv.mkDerivation {
inherit doCheck;
pname = "manifold-${parallel-backend}";
version = "2.2.0";
version = "beta";
src = self;
nativeBuildInputs = (with pkgs; [
cmake
thrust-210
glm
ninja
(python39.withPackages
(ps: with ps; [ trimesh ]))
gtest
]) ++ build-tools;
cmakeFlags = [
"-DMANIFOLD_PYBIND=ON"
"-DMANIFOLD_CBIND=ON"
"-DBUILD_SHARED_LIBS=ON"
"-DMANIFOLD_PAR=${pkgs.lib.strings.toUpper parallel-backend}"
];
checkPhase = ''
@@ -76,20 +41,31 @@
PYTHONPATH=$PYTHONPATH:$(pwd)/build/bindings/python python3 bindings/python/examples/run_all.py
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 = "tbb";
build-tools = with pkgs; [ tbb_2021_8 pkg-config ];
build-tools = with pkgs; [ tbb pkg-config ];
}
];
devShell = { additional ? [ ] }: pkgs.mkShell {
buildInputs = with pkgs; [
cmake
tbb_2021_8
thrust-210
llvmPackages_13.openmp
clang-tools
clang_13
emscripten
tbb
lcov
gtest
tracy
] ++ additional;
};
in
@@ -112,10 +88,7 @@
export EM_CACHE=$(pwd)/.emscriptencache
mkdir build
cd build
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} ..
emcmake cmake -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_GOOGLETEST=${gtest-src} ..
'';
buildPhase = ''
emmake make -j''${NIX_BUILD_CORES}
@@ -131,38 +104,6 @@
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.2.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
];
format = "pyproject";
dontUseCmakeConfigure = true;
doCheck = true;
checkPhase = ''
python3 bindings/python/examples/run_all.py
'';
};
};
devShell = devShell { };
}
-11
View File
@@ -29,14 +29,3 @@ 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
)
-78
View File
@@ -1,78 +0,0 @@
[project]
name = "manifold3d"
version = "2.2.0"
authors = [
{ name="Emmett Lalish", email="elalish@gmail.com" },
]
description = "Library for geometric robustness"
readme = "README.md"
classifiers = [
"Development Status :: 4 - Beta",
"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"]
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}"
+19 -4
View File
@@ -14,17 +14,32 @@
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
src/gyroid_module.cpp src/condensed_matter.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)
target_include_directories(samples
PUBLIC ${PROJECT_SOURCE_DIR}/include
)
target_link_libraries(samples
PUBLIC manifold sdf
PUBLIC manifold
)
target_compile_options(samples PRIVATE ${MANIFOLD_FLAGS})
target_compile_features(samples PUBLIC cxx_std_17)
project(samplesGPU)
add_library(samplesGPU src/gyroid_module.cpp)
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
)
-2
View File
@@ -51,7 +51,5 @@ 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
-149
View File
@@ -1,149 +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.
// 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
+2 -4
View File
@@ -12,15 +12,13 @@
// 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 {
float operator()(glm::vec3 p) const {
__host__ __device__ 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);
}
@@ -56,4 +54,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
+1 -2
View File
@@ -12,8 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# do not add third_party installations
add_subdirectory(third_party EXCLUDE_FROM_ALL)
add_subdirectory(third_party)
add_subdirectory(utilities)
add_subdirectory(collider)
add_subdirectory(cross_section)
-7
View File
@@ -19,14 +19,7 @@ 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
)
+7 -8
View File
@@ -15,7 +15,7 @@
#pragma once
#include "public.h"
#include "sparse.h"
#include "vec.h"
#include "vec_dh.h"
namespace manifold {
@@ -23,19 +23,18 @@ namespace manifold {
class Collider {
public:
Collider() {}
Collider(const VecView<const Box>& leafBB,
const VecView<const uint32_t>& leafMorton);
Collider(const VecDH<Box>& leafBB, const VecDH<uint32_t>& leafMorton);
bool Transform(glm::mat4x3);
void UpdateBoxes(const VecView<const Box>& leafBB);
void UpdateBoxes(const VecDH<Box>& leafBB);
template <const bool selfCollision = false, const bool inverted = false,
typename T>
SparseIndices Collisions(const VecView<const T>& queriesIn) const;
SparseIndices Collisions(const VecDH<T>& queriesIn) const;
private:
Vec<Box> nodeBBox_;
Vec<int> nodeParent_;
VecDH<Box> nodeBBox_;
VecDH<int> nodeParent_;
// even nodes are leaves, odd nodes are internal, root is 1
Vec<thrust::pair<int, int>> internalChildren_;
VecDH<thrust::pair<int, int>> internalChildren_;
int NumInternal() const { return internalChildren_.size(); };
int NumLeaves() const { return NumInternal() + 1; };
+43 -37
View File
@@ -68,9 +68,9 @@ int Node2Leaf(int node) { return node / 2; }
int Leaf2Node(int leaf) { return leaf * 2; }
struct CreateRadixTree {
VecView<int> nodeParent_;
VecView<thrust::pair<int, int>> internalChildren_;
const VecView<const uint32_t> leafMorton_;
int* nodeParent_;
thrust::pair<int, int>* internalChildren_;
const VecDc<uint32_t> leafMorton_;
int PrefixLength(uint32_t a, uint32_t b) const {
// count-leading-zeros is used to find the number of identical highest-order
@@ -154,9 +154,9 @@ struct CreateRadixTree {
template <typename T, const bool selfCollision, typename Recorder>
struct FindCollisions {
VecView<const Box> nodeBBox_;
VecView<const thrust::pair<int, int>> internalChildren_;
Recorder recorder;
const Box* nodeBBox_;
const thrust::pair<int, int>* internalChildren_;
const Recorder& recorder;
int RecordCollision(int node, thrust::tuple<T, int>& query) {
const T& queryObj = thrust::get<0>(query);
@@ -205,11 +205,11 @@ struct FindCollisions {
};
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) {
int* counts;
char* empty;
void record(int queryIdx, int _leafIdx) const { counts[queryIdx]++; }
bool earlyexit(int _queryIdx) const { return false; }
void end(int queryIdx) const {
if (counts[queryIdx] == 0) empty[queryIdx] = 1;
}
};
@@ -230,9 +230,9 @@ struct SeqCollisionRecorder {
template <const bool inverted>
struct ParCollisionRecorder {
SparseIndices& queryTri;
VecView<int> counts;
VecView<char> empty;
void record(int queryIdx, int leafIdx) {
int* counts;
char* empty;
void record(int queryIdx, int leafIdx) const {
int pos = counts[queryIdx]++;
if (inverted)
queryTri.Set(pos, leafIdx, queryIdx);
@@ -244,10 +244,10 @@ struct ParCollisionRecorder {
};
struct BuildInternalBoxes {
VecView<Box> nodeBBox_;
VecView<int> counter_;
const VecView<int> nodeParent_;
const VecView<thrust::pair<int, int>> internalChildren_;
Box* nodeBBox_;
int* counter_;
const int* nodeParent_;
const thrust::pair<int, int>* internalChildren_;
void operator()(int leaf) {
int node = Leaf2Node(leaf);
@@ -274,8 +274,8 @@ namespace manifold {
* bounding boxes and corresponding Morton codes. It is assumed these vectors
* are already sorted by increasing Morton code.
*/
Collider::Collider(const VecView<const Box>& leafBB,
const VecView<const uint32_t>& leafMorton) {
Collider::Collider(const VecDH<Box>& leafBB,
const VecDH<uint32_t>& leafMorton) {
ASSERT(leafBB.size() == leafMorton.size(), userErr,
"vectors must be the same length");
int num_nodes = 2 * leafBB.size() - 1;
@@ -285,7 +285,8 @@ Collider::Collider(const VecView<const Box>& leafBB,
internalChildren_.resize(leafBB.size() - 1, thrust::make_pair(-1, -1));
// organize tree
for_each_n(autoPolicy(NumInternal()), countAt(0), NumInternal(),
CreateRadixTree({nodeParent_, internalChildren_, leafMorton}));
CreateRadixTree(
{nodeParent_.ptrD(), internalChildren_.ptrD(), leafMorton}));
UpdateBoxes(leafBB);
}
@@ -298,7 +299,7 @@ Collider::Collider(const VecView<const Box>& leafBB,
* then not report any collisions between an index and itself.
*/
template <const bool selfCollision, const bool inverted, typename T>
SparseIndices Collider::Collisions(const VecView<const T>& queriesIn) const {
SparseIndices Collider::Collisions(const VecDH<T>& queriesIn) const {
// note that the length is 1 larger than the number of queries so the last
// element can store the sum when using exclusive scan
if (queriesIn.size() < kSequentialThreshold) {
@@ -306,17 +307,19 @@ SparseIndices Collider::Collisions(const VecView<const T>& queriesIn) const {
for_each_n(ExecutionPolicy::Seq, zip(queriesIn.cbegin(), countAt(0)),
queriesIn.size(),
FindCollisions<T, selfCollision, SeqCollisionRecorder<inverted>>{
nodeBBox_, internalChildren_, {queryTri}});
nodeBBox_.ptrD(), internalChildren_.ptrD(), {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);
VecDH<int> counts(queriesIn.size() + 1, 0);
VecDH<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}});
nodeBBox_.ptrD(),
internalChildren_.ptrD(),
{counts.ptrD(), empty.ptrD()}});
// compute start index for each query and total count
exclusive_scan(ExecutionPolicy::Par, counts.begin(), counts.end(),
counts.begin(), 0, std::plus<int>());
@@ -326,7 +329,9 @@ SparseIndices Collider::Collisions(const VecView<const T>& queriesIn) const {
for_each_n(ExecutionPolicy::Par, zip(queriesIn.cbegin(), countAt(0)),
queriesIn.size(),
FindCollisions<T, selfCollision, ParCollisionRecorder<inverted>>{
nodeBBox_, internalChildren_, {queryTri, counts, empty}});
nodeBBox_.ptrD(),
internalChildren_.ptrD(),
{queryTri, counts.ptrD(), empty.ptrD()}});
return queryTri;
}
}
@@ -335,19 +340,20 @@ SparseIndices Collider::Collisions(const VecView<const T>& queriesIn) const {
* Recalculate the collider's internal bounding boxes without changing the
* hierarchy.
*/
void Collider::UpdateBoxes(const VecView<const Box>& leafBB) {
void Collider::UpdateBoxes(const VecDH<Box>& leafBB) {
ASSERT(leafBB.size() == NumLeaves(), userErr,
"must have the same number of updated boxes as original");
// copy in leaf node Boxes
strided_range<Vec<Box>::Iter> leaves(nodeBBox_.begin(), nodeBBox_.end(), 2);
strided_range<VecDH<Box>::Iter> leaves(nodeBBox_.begin(), nodeBBox_.end(), 2);
auto policy = autoPolicy(NumInternal());
copy(policy, leafBB.cbegin(), leafBB.cend(), leaves.begin());
// create global counters
Vec<int> counter(NumInternal(), 0);
VecDH<int> counter(NumInternal(), 0);
// kernel over leaves to save internal Boxes
for_each_n(
policy, countAt(0), NumLeaves(),
BuildInternalBoxes({nodeBBox_, counter, nodeParent_, internalChildren_}));
BuildInternalBoxes({nodeBBox_.ptrD(), counter.ptrD(), nodeParent_.cptrD(),
internalChildren_.cptrD()}));
}
/**
@@ -371,21 +377,21 @@ bool Collider::Transform(glm::mat4x3 transform) {
}
template SparseIndices Collider::Collisions<true, false, Box>(
const VecView<const Box>&) const;
const VecDH<Box>&) const;
template SparseIndices Collider::Collisions<false, false, Box>(
const VecView<const Box>&) const;
const VecDH<Box>&) const;
template SparseIndices Collider::Collisions<false, false, glm::vec3>(
const VecView<const glm::vec3>&) const;
const VecDH<glm::vec3>&) const;
template SparseIndices Collider::Collisions<true, true, Box>(
const VecView<const Box>&) const;
const VecDH<Box>&) const;
template SparseIndices Collider::Collisions<false, true, Box>(
const VecView<const Box>&) const;
const VecDH<Box>&) const;
template SparseIndices Collider::Collisions<false, true, glm::vec3>(
const VecView<const glm::vec3>&) const;
const VecDH<glm::vec3>&) const;
} // namespace manifold
-12
View File
@@ -26,15 +26,3 @@ 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
)
+71 -6
View File
@@ -14,22 +14,27 @@
#pragma once
#include <functional>
#include <clipper2/clipper.h>
#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;
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
@@ -164,10 +169,70 @@ class CrossSection {
///@}
private:
mutable std::shared_ptr<const PathImpl> paths_;
mutable std::shared_ptr<const C2::PathsD> paths_;
mutable glm::mat3x2 transform_ = glm::mat3x2(1.0f);
CrossSection(std::shared_ptr<const PathImpl> paths);
std::shared_ptr<const PathImpl> GetPaths() const;
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;
///@}
};
/** @} */
} // namespace manifold
+200 -54
View File
@@ -14,22 +14,8 @@
#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;
@@ -110,8 +96,8 @@ C2::PathsD transform(const C2::PathsD ps, const glm::mat3x2 m) {
return transformed;
}
std::shared_ptr<const PathImpl> shared_paths(const C2::PathsD& ps) {
return std::make_shared<const PathImpl>(ps);
std::shared_ptr<const C2::PathsD> shared_paths(const C2::PathsD& ps) {
return std::make_shared<const C2::PathsD>(ps);
}
// forward declaration for mutual recursion
@@ -205,9 +191,7 @@ namespace manifold {
/**
* The default constructor is an empty cross-section (containing no contours).
*/
CrossSection::CrossSection() {
paths_ = std::make_shared<const PathImpl>(C2::PathsD());
}
CrossSection::CrossSection() { paths_ = shared_paths(C2::PathsD()); }
CrossSection::~CrossSection() = default;
CrossSection::CrossSection(CrossSection&&) noexcept = default;
@@ -234,7 +218,7 @@ CrossSection& CrossSection::operator=(const CrossSection& other) {
};
// Private, skips unioning.
CrossSection::CrossSection(std::shared_ptr<const PathImpl> ps) { paths_ = ps; }
CrossSection::CrossSection(C2::PathsD ps) { paths_ = shared_paths(ps); }
/**
* Create a 2d cross-section from a single contour. A boolean union operation
@@ -287,13 +271,13 @@ CrossSection::CrossSection(const Rect& rect) {
// Private
// All access to paths_ should be done through the GetPaths() method, which
// applies the accumulated transform_
std::shared_ptr<const PathImpl> CrossSection::GetPaths() const {
C2::PathsD CrossSection::GetPaths() const {
if (transform_ == glm::mat3x2(1.0f)) {
return paths_;
return *paths_;
}
paths_ = shared_paths(::transform(paths_->paths_, transform_));
paths_ = shared_paths(transform(*paths_, transform_));
transform_ = glm::mat3x2(1.0f);
return paths_;
return *paths_;
}
/**
@@ -325,7 +309,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(shared_paths(C2::PathsD{p}));
return CrossSection(C2::PathsD{p});
}
/**
@@ -346,7 +330,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(shared_paths(C2::PathsD{circle}));
return CrossSection(C2::PathsD{circle});
}
/**
@@ -355,9 +339,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()->paths_,
second.GetPaths()->paths_, precision_);
return CrossSection(shared_paths(res));
auto res = C2::BooleanOp(ct, C2::FillRule::Positive, GetPaths(),
second.GetPaths(), precision_);
return CrossSection(res);
}
/**
@@ -374,19 +358,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()->paths_.size();
n_clips += crossSections[i].GetPaths().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->paths_.begin(), ps->paths_.end());
clips.insert(clips.end(), ps.begin(), ps.end());
}
auto ct = cliptype_of_op(op);
auto res = C2::BooleanOp(ct, C2::FillRule::Positive, subjs->paths_, clips,
precision_);
return CrossSection(shared_paths(res));
auto res =
C2::BooleanOp(ct, C2::FillRule::Positive, subjs, clips, precision_);
return CrossSection(res);
}
/**
@@ -457,7 +441,7 @@ std::vector<CrossSection> CrossSection::Decompose() const {
}
C2::PolyTreeD tree;
C2::BooleanOp(C2::ClipType::Union, C2::FillRule::Positive, GetPaths()->paths_,
C2::BooleanOp(C2::ClipType::Union, C2::FillRule::Positive, GetPaths(),
C2::PathsD(), tree, precision_);
auto polys = std::vector<C2::PathsD>();
@@ -467,7 +451,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(shared_paths(polys[i]));
comps[n_polys - i - 1] = CrossSection(polys[i]);
}
return comps;
@@ -557,8 +541,8 @@ CrossSection CrossSection::Warp(
std::function<void(glm::vec2&)> warpFunc) const {
auto paths = GetPaths();
auto warped = C2::PathsD();
warped.reserve(paths->paths_.size());
for (auto path : paths->paths_) {
warped.reserve(paths.size());
for (auto path : paths) {
auto sz = path.size();
auto s = C2::PathD(sz);
for (int i = 0; i < sz; ++i) {
@@ -568,8 +552,7 @@ CrossSection CrossSection::Warp(
}
warped.push_back(s);
}
return CrossSection(
shared_paths(C2::Union(warped, C2::FillRule::Positive, precision_)));
return CrossSection(C2::Union(warped, C2::FillRule::Positive, precision_));
}
/**
@@ -585,8 +568,8 @@ CrossSection CrossSection::Warp(
* offseting operations are to be performed, which would compound the issue.
*/
CrossSection CrossSection::Simplify(double epsilon) const {
auto ps = SimplifyPaths(GetPaths()->paths_, epsilon, false);
return CrossSection(shared_paths(ps));
auto ps = SimplifyPaths(GetPaths(), epsilon, false);
return CrossSection(ps);
}
/**
@@ -624,9 +607,9 @@ CrossSection CrossSection::Offset(double delta, JoinType jointype,
arc_tol = (std::cos(Clipper2Lib::PI / n) - 1) * -scaled_delta;
}
auto ps =
C2::InflatePaths(GetPaths()->paths_, delta, jt(jointype),
C2::EndType::Polygon, miter_limit, precision_, arc_tol);
return CrossSection(shared_paths(ps));
C2::InflatePaths(GetPaths(), delta, jt(jointype), C2::EndType::Polygon,
miter_limit, precision_, arc_tol);
return CrossSection(ps);
}
/**
@@ -642,14 +625,14 @@ CrossSection CrossSection::Hull(
SimplePolygon pts;
pts.reserve(n);
for (auto cs : crossSections) {
auto paths = cs.GetPaths()->paths_;
auto paths = cs.GetPaths();
for (auto path : paths) {
for (auto p : path) {
pts.push_back(v2_of_pd(p));
}
}
}
return CrossSection(shared_paths(C2::PathsD{HullImpl(pts)}));
return CrossSection(C2::PathsD{HullImpl(pts)});
}
/**
@@ -667,7 +650,7 @@ CrossSection CrossSection::Hull() const {
* hull.
*/
CrossSection CrossSection::Hull(SimplePolygon pts) {
return CrossSection(shared_paths(C2::PathsD{HullImpl(pts)}));
return CrossSection(C2::PathsD{HullImpl(pts)});
}
/**
@@ -691,14 +674,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()->paths_); }
double CrossSection::Area() const { return C2::Area(GetPaths()); }
/**
* Return the number of vertices in the CrossSection.
*/
int CrossSection::NumVert() const {
int n = 0;
auto paths = GetPaths()->paths_;
auto paths = GetPaths();
for (auto p : paths) {
n += p.size();
}
@@ -709,19 +692,19 @@ int CrossSection::NumVert() const {
* Return the number of contours (both outer and inner paths) in the
* CrossSection.
*/
int CrossSection::NumContour() const { return GetPaths()->paths_.size(); }
int CrossSection::NumContour() const { return GetPaths().size(); }
/**
* Does the CrossSection contain any contours?
*/
bool CrossSection::IsEmpty() const { return GetPaths()->paths_.empty(); }
bool CrossSection::IsEmpty() const { return GetPaths().empty(); }
/**
* Returns the axis-aligned bounding rectangle of all the CrossSections'
* vertices.
*/
Rect CrossSection::Bounds() const {
auto r = C2::GetBounds(GetPaths()->paths_);
auto r = C2::GetBounds(GetPaths());
return Rect({r.left, r.bottom}, {r.right, r.top});
}
@@ -730,7 +713,7 @@ Rect CrossSection::Bounds() const {
*/
Polygons CrossSection::ToPolygons() const {
auto polys = Polygons();
auto paths = GetPaths()->paths_;
auto paths = GetPaths();
polys.reserve(paths.size());
for (auto p : paths) {
auto sp = SimplePolygon();
@@ -742,4 +725,167 @@ 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
+1 -15
View File
@@ -20,23 +20,9 @@ add_library(${PROJECT_NAME} ${SOURCE_FILES})
target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)
target_link_libraries(${PROJECT_NAME}
PUBLIC utilities cross_section
PRIVATE collider polygon ${MANIFOLD_INCLUDE} Clipper2 quickhull
PRIVATE collider polygon ${MANIFOLD_INCLUDE} graphlite 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
)
+110 -107
View File
@@ -71,7 +71,7 @@ struct CopyFaceEdges {
// const int *p1q1;
// x can be either vert or edge (0 or 1).
SparseIndices &pXq1;
VecView<const Halfedge> halfedgesQ;
const Halfedge *halfedgesQ;
void operator()(thrust::tuple<int, int> in) {
int idx = 3 * thrust::get<0>(in);
@@ -91,19 +91,18 @@ struct CopyFaceEdges {
};
SparseIndices Filter11(const Manifold::Impl &inP, const Manifold::Impl &inQ,
const SparseIndices &p1q2, const SparseIndices &p2q1) {
const SparseIndices &p1q2, const SparseIndices &p2q1,
ExecutionPolicy policy) {
SparseIndices p1q1(3 * p1q2.size() + 3 * p2q1.size());
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();
for_each_n(policy, zip(countAt(0), countAt(0)), p1q2.size(),
CopyFaceEdges<false>({p1q2, p1q1, inQ.halfedge_.cptrD()}));
for_each_n(policy, zip(countAt(p1q2.size()), countAt(0)), p2q1.size(),
CopyFaceEdges<true>({p2q1, p1q1, inP.halfedge_.cptrD()}));
p1q1.Unique(policy);
return p1q1;
}
inline bool Shadows(float p, float q, float dir) {
return p == q ? dir < 0 : p < q;
}
bool Shadows(float p, float q, float dir) { return p == q ? dir < 0 : p < q; }
/**
* Since this function is called from two different places, it is necessary that
@@ -116,10 +115,10 @@ inline 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.
*/
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) {
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) {
const int q1s = halfedgeQ[q1].startVert;
const int q1e = halfedgeQ[q1].endVert;
const float p0x = vertPosP[p0].x;
@@ -149,12 +148,13 @@ inline thrust::pair<int, glm::vec2> Shadow01(
// 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) {
int monobound_quaternary_search(const int64_t *array, unsigned int array_size,
int64_t key) {
if (array_size == 0) {
return -1;
}
unsigned int bot = 0;
unsigned int top = array.size();
unsigned int top = array_size;
while (top >= 65536) {
unsigned int mid = top / 4;
top -= mid * 3;
@@ -187,12 +187,12 @@ int monobound_quaternary_search(VecView<const int64_t> array, int64_t key) {
}
struct Kernel11 {
VecView<const glm::vec3> vertPosP;
VecView<const glm::vec3> vertPosQ;
VecView<const Halfedge> halfedgeP;
VecView<const Halfedge> halfedgeQ;
const glm::vec3 *vertPosP;
const glm::vec3 *vertPosQ;
const Halfedge *halfedgeP;
const Halfedge *halfedgeQ;
float expandP;
VecView<const glm::vec3> normalP;
const glm::vec3 *normalP;
const SparseIndices &p1q1;
void operator()(thrust::tuple<int, glm::vec4 &, int &> inout) {
@@ -269,17 +269,18 @@ struct Kernel11 {
}
};
std::tuple<Vec<int>, Vec<glm::vec4>> Shadow11(SparseIndices &p1q1,
const Manifold::Impl &inP,
const Manifold::Impl &inQ,
float expandP) {
Vec<int> s11(p1q1.size());
Vec<glm::vec4> xyzz11(p1q1.size());
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());
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}));
for_each_n(policy, zip(countAt(0), xyzz11.begin(), s11.begin()), p1q1.size(),
Kernel11({inP.vertPos_.cptrD(), inQ.vertPos_.cptrD(),
inP.halfedge_.cptrD(), inQ.halfedge_.cptrD(), expandP,
inP.vertNormal_.cptrD(), p1q1}));
p1q1.KeepFinite(xyzz11, s11);
@@ -287,13 +288,13 @@ std::tuple<Vec<int>, Vec<glm::vec4>> Shadow11(SparseIndices &p1q1,
};
struct Kernel02 {
VecView<const glm::vec3> vertPosP;
VecView<const Halfedge> halfedgeQ;
VecView<const glm::vec3> vertPosQ;
const float expandP;
VecView<const glm::vec3> vertNormalP;
const SparseIndices &p0q2;
const glm::vec3 *vertPosP;
const Halfedge *halfedgeQ;
const glm::vec3 *vertPosQ;
const bool forward;
const float expandP;
const glm::vec3 *vertNormalP;
const SparseIndices &p0q2;
void operator()(thrust::tuple<int, int &, float &> inout) {
const int p0 = p0q2.Get(thrust::get<0>(inout), !forward);
@@ -363,18 +364,20 @@ struct Kernel02 {
}
};
std::tuple<Vec<int>, Vec<float>> Shadow02(const Manifold::Impl &inP,
const Manifold::Impl &inQ,
SparseIndices &p0q2, bool forward,
float expandP) {
Vec<int> s02(p0q2.size());
Vec<float> z02(p0q2.size());
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());
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}));
auto vertNormalP =
forward ? inP.vertNormal_.cptrD() : inQ.vertNormal_.cptrD();
for_each_n(
policy, zip(countAt(0), s02.begin(), z02.begin()), p0q2.size(),
Kernel02({inP.vertPos_.cptrD(), inQ.halfedge_.cptrD(),
inQ.vertPos_.cptrD(), forward, expandP, vertNormalP, p0q2}));
p0q2.KeepFinite(z02, s02);
@@ -382,15 +385,17 @@ std::tuple<Vec<int>, Vec<float>> Shadow02(const Manifold::Impl &inP,
};
struct Kernel12 {
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 VecDH<int64_t> &p0q2;
const int *s02;
const float *z02;
const int size02;
const VecDH<int64_t> &p1q1;
const int *s11;
const glm::vec4 *xyzz11;
const int size11;
const Halfedge *halfedgesP;
const Halfedge *halfedgesQ;
const glm::vec3 *vertPosP;
const bool forward;
const SparseIndices &p1q2;
@@ -414,7 +419,7 @@ struct Kernel12 {
for (int vert : {edge.startVert, edge.endVert}) {
const int64_t key = forward ? SparseIndices::EncodePQ(vert, q2)
: SparseIndices::EncodePQ(q2, vert);
const int idx = monobound_quaternary_search(p0q2, key);
const int idx = monobound_quaternary_search(p0q2.ptrD(), size02, key);
if (idx != -1) {
const int s = s02[idx];
x12 += s * ((vert == edge.startVert) == forward ? 1 : -1);
@@ -435,7 +440,7 @@ struct Kernel12 {
const int q1F = edge.IsForward() ? q1 : edge.pairedHalfedge;
const int64_t key = forward ? SparseIndices::EncodePQ(p1, q1F)
: SparseIndices::EncodePQ(q1F, p1);
const int idx = monobound_quaternary_search(p1q1, key);
const int idx = monobound_quaternary_search(p1q1.ptrD(), size11, key);
if (idx != -1) { // s is implicitly zero for anything not found
const int s = s11[idx];
x12 -= s * (edge.IsForward() ? 1 : -1);
@@ -471,39 +476,33 @@ struct Kernel12 {
}
};
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) {
Vec<int> x12(p1q2.size());
Vec<glm::vec3> v12(p1q2.size());
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());
for_each_n(
autoPolicy(p1q2.size()), zip(countAt(0), x12.begin(), v12.begin()),
p1q2.size(),
Kernel12({p0q2.AsVec64(), s02, z02, p1q1.AsVec64(), s11, xyzz11,
inP.halfedge_, inQ.halfedge_, inP.vertPos_, forward, p1q2}));
for_each_n(policy, zip(countAt(0), x12.begin(), v12.begin()), p1q2.size(),
Kernel12({p0q2.AsVec64(), s02.ptrD(), z02.cptrD(), p0q2.size(),
p1q1.AsVec64(), s11.ptrD(), xyzz11.cptrD(), p1q1.size(),
inP.halfedge_.cptrD(), inQ.halfedge_.cptrD(),
inP.vertPos_.cptrD(), forward, p1q2}));
p1q2.KeepFinite(v12, x12);
return std::make_tuple(x12, v12);
};
Vec<int> Winding03(const Manifold::Impl &inP, Vec<int> &vertices, Vec<int> &s02,
bool reverse) {
VecDH<int> Winding03(const Manifold::Impl &inP, VecDH<int> &vertices,
VecDH<int> &s02, bool reverse, ExecutionPolicy policy) {
// verts that are not shadowed (not in p0q2) have winding number zero.
Vec<int> w03(inP.NumVert(), 0);
VecDH<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());
stable_sort_by_key(policy, vertices.begin(), vertices.end(), s02.begin());
VecDH<int> w03val(w03.size());
VecDH<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())>>(
@@ -521,7 +520,10 @@ Vec<int> Winding03(const Manifold::Impl &inP, Vec<int> &vertices, Vec<int> &s02,
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) {
: inP_(inP),
inQ_(inQ),
expandP_(op == OpType::Add ? 1.0 : -1.0),
policy_(autoPolicy(glm::max(inP.NumEdge(), inQ.NumEdge()))) {
// Symbolic perturbation:
// Union -> expand inP
// Difference, Intersection -> contract inP
@@ -543,24 +545,25 @@ Boolean3::Boolean3(const Manifold::Impl &inP, const Manifold::Impl &inQ,
p1q2_ = inQ_.EdgeCollisions(inP_);
p2q1_ = inP_.EdgeCollisions(inQ_, true); // inverted
p1q2_.Sort();
policy_ = autoPolicy(glm::max(p1q2_.size(), p2q1_.size()));
p1q2_.Sort(policy_);
PRINT("p1q2 size = " << p1q2_.size());
p2q1_.Sort();
p2q1_.Sort(policy_);
PRINT("p2q1 size = " << p2q1_.size());
// Level 2
// Find vertices that overlap faces in XY-projection
SparseIndices p0q2 = inQ.VertexCollisionsZ(inP.vertPos_);
p0q2.Sort();
p0q2.Sort(policy_);
PRINT("p0q2 size = " << p0q2.size());
SparseIndices p2q0 = inP.VertexCollisionsZ(inQ.vertPos_, true); // inverted
p2q0.Sort();
p2q0.Sort(policy_);
PRINT("p2q0 size = " << p2q0.size());
// Find involved edge pairs from Level 3
SparseIndices p1q1 = Filter11(inP_, inQ_, p1q2_, p2q1_);
SparseIndices p1q1 = Filter11(inP_, inQ_, p1q2_, p2q1_, policy_);
PRINT("p1q1 size = " << p1q1.size());
#ifdef MANIFOLD_DEBUG
@@ -572,43 +575,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.
Vec<int> s11;
Vec<glm::vec4> xyzz11;
std::tie(s11, xyzz11) = Shadow11(p1q1, inP, inQ, expandP_);
VecDH<int> s11;
VecDH<glm::vec4> xyzz11;
std::tie(s11, xyzz11) = Shadow11(p1q1, inP, inQ, expandP_, policy_);
PRINT("s11 size = " << s11.size());
// Build up Z-projection of vertices onto triangles, keeping only those that
// fall inside the triangle.
Vec<int> s02;
Vec<float> z02;
std::tie(s02, z02) = Shadow02(inP, inQ, p0q2, true, expandP_);
VecDH<int> s02;
VecDH<float> z02;
std::tie(s02, z02) = Shadow02(inP, inQ, p0q2, true, expandP_, policy_);
PRINT("s02 size = " << s02.size());
Vec<int> s20;
Vec<float> z20;
std::tie(s20, z20) = Shadow02(inQ, inP, p2q0, false, expandP_);
VecDH<int> s20;
VecDH<float> z20;
std::tie(s20, z20) = Shadow02(inQ, inP, p2q0, false, expandP_, policy_);
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);
std::tie(x12_, v12_) = Intersect12(inP, inQ, s02, p0q2, s11, p1q1, z02,
xyzz11, p1q2_, true, policy_);
PRINT("x12 size = " << x12_.size());
std::tie(x21_, v21_) =
Intersect12(inQ, inP, s20, p2q0, s11, p1q1, z20, xyzz11, p2q1_, false);
std::tie(x21_, v21_) = Intersect12(inQ, inP, s20, p2q0, s11, p1q1, z20,
xyzz11, p2q1_, false, policy_);
PRINT("x21 size = " << x21_.size());
Vec<int> p0 = p0q2.Copy(false);
VecDH<int> p0 = p0q2.Copy(false);
p0q2.Resize(0);
Vec<int> q0 = p2q0.Copy(true);
VecDH<int> q0 = p2q0.Copy(true);
p2q0.Resize(0);
// Sum up the winding numbers of all vertices.
w03_ = Winding03(inP, p0, s02, false);
w03_ = Winding03(inP, p0, s02, false, policy_);
w30_ = Winding03(inQ, q0, s20, true);
w30_ = Winding03(inQ, q0, s20, true, policy_);
#ifdef MANIFOLD_DEBUG
intersections.Stop();
+3 -2
View File
@@ -54,7 +54,8 @@ class Boolean3 {
const Manifold::Impl &inP_, &inQ_;
const float expandP_;
SparseIndices p1q2_, p2q1_;
Vec<int> x12_, x21_, w03_, w30_;
Vec<glm::vec3> v12_, v21_;
VecDH<int> x12_, x21_, w03_, w30_;
VecDH<glm::vec3> v12_, v21_;
ExecutionPolicy policy_;
};
} // namespace manifold
+141 -151
View File
@@ -16,7 +16,7 @@
#include <array>
#include <map>
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_map.h>)
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
#include <tbb/concurrent_map.h>
#include <tbb/parallel_for.h>
@@ -44,14 +44,12 @@ struct std::hash<std::pair<int, int>> {
namespace {
constexpr int kParallelThreshold = 128;
struct AbsSum : public thrust::binary_function<int, int, int> {
int operator()(int a, int b) { return abs(a) + abs(b); }
};
struct DuplicateVerts {
VecView<glm::vec3> vertPosR;
glm::vec3 *vertPosR;
void operator()(thrust::tuple<int, int, glm::vec3> in) {
int inclusion = abs(thrust::get<0>(in));
@@ -65,8 +63,8 @@ struct DuplicateVerts {
};
struct CountVerts {
VecView<int> count;
VecView<const int> inclusion;
int *count;
const int *inclusion;
void operator()(const Halfedge &edge) {
AtomicAdd(count[edge.face], glm::abs(inclusion[edge.startVert]));
@@ -75,10 +73,10 @@ struct CountVerts {
template <const bool inverted>
struct CountNewVerts {
VecView<int> countP;
VecView<int> countQ;
int *countP;
int *countQ;
const SparseIndices &pq;
VecView<const Halfedge> halfedges;
const Halfedge *halfedges;
void operator()(thrust::tuple<int, int> in) {
int edgeP = pq.Get(thrust::get<0>(in), inverted);
@@ -96,60 +94,56 @@ struct NotZero : public thrust::unary_function<int, int> {
int operator()(int x) const { return x > 0 ? 1 : 0; }
};
std::tuple<Vec<int>, Vec<int>> SizeOutput(
std::tuple<VecDH<int>, VecDH<int>> SizeOutput(
Manifold::Impl &outR, const Manifold::Impl &inP, const Manifold::Impl &inQ,
const Vec<int> &i03, const Vec<int> &i30, const Vec<int> &i12,
const Vec<int> &i21, const SparseIndices &p1q2, const SparseIndices &p2q1,
bool invertQ) {
Vec<int> sidesPerFacePQ(inP.NumTri() + inQ.NumTri(), 0);
auto sidesPerFaceP = sidesPerFacePQ.view(0, inP.NumTri());
auto sidesPerFaceQ = sidesPerFacePQ.view(inP.NumTri(), inQ.NumTri());
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();
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(),
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_n(policy, zip(countAt(0), i12.begin()), i12.size(),
CountNewVerts<false>(
{sidesPerFaceP, sidesPerFaceQ, p1q2, inP.halfedge_}));
for_each_n(
autoPolicy(i21.size()), zip(countAt(0), i21.begin()), i21.size(),
CountNewVerts<true>({sidesPerFaceQ, sidesPerFaceP, p2q1, inQ.halfedge_}));
{sidesPerFaceP, sidesPerFaceQ, p1q2, inP.halfedge_.cptrD()}));
for_each_n(policy, zip(countAt(0), i21.begin()), i21.size(),
CountNewVerts<true>(
{sidesPerFaceQ, sidesPerFaceP, p2q1, inQ.halfedge_.cptrD()}));
Vec<int> facePQ2R(inP.NumTri() + inQ.NumTri() + 1, 0);
VecDH<int> facePQ2R(inP.NumTri() + inQ.NumTri() + 1, 0);
auto keepFace =
thrust::make_transform_iterator(sidesPerFacePQ.begin(), NotZero());
inclusive_scan(autoPolicy(sidesPerFacePQ.size()), keepFace,
keepFace + sidesPerFacePQ.size(), facePQ2R.begin() + 1);
inclusive_scan(policy, 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())>(
autoPolicy(inP.faceNormal_.size()), inP.faceNormal_.begin(),
inP.faceNormal_.end(), keepFace, outR.faceNormal_.begin(),
thrust::identity<bool>());
policy, 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())>(
autoPolicy(inQ.faceNormal_.size()), start, end, keepFace + inP.NumTri(),
next, thrust::identity<bool>());
copy_if<decltype(inQ.faceNormal_.begin())>(policy, start, end,
keepFace + inP.NumTri(), next,
thrust::identity<bool>());
} else {
copy_if<decltype(inQ.faceNormal_.begin())>(
autoPolicy(inQ.faceNormal_.size()), inQ.faceNormal_.begin(),
inQ.faceNormal_.end(), keepFace + inP.NumTri(), next,
thrust::identity<bool>());
policy, inQ.faceNormal_.begin(), inQ.faceNormal_.end(),
keepFace + inP.NumTri(), next, thrust::identity<bool>());
}
auto newEnd = remove<decltype(sidesPerFacePQ.begin())>(
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);
policy, sidesPerFacePQ.begin(), sidesPerFacePQ.end(), 0);
VecDH<int> faceEdge(newEnd - sidesPerFacePQ.begin() + 1, 0);
inclusive_scan(policy, sidesPerFacePQ.begin(), newEnd, faceEdge.begin() + 1);
outR.halfedge_.resize(faceEdge.back());
return std::make_tuple(faceEdge, facePQ2R);
@@ -165,17 +159,19 @@ void AddNewEdgeVerts(
// 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) {
const SparseIndices &p1q2, const VecDH<int> &i12, const VecDH<int> &v12R,
const VecDH<Halfedge> &halfedgeP, bool forward) {
// 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.Copy(!forward);
const VecDH<int> &q2 = p1q2.Copy(forward);
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 edgeP = p1[i];
const int faceQ = q2[i];
const int vert = v12R[i];
const int inclusion = i12[i];
@@ -206,10 +202,10 @@ void AddNewEdgeVerts(
#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;
if (p1q2.size() > 128) {
// ideally we should have 1 mutex per key, but 128 is enough to avoid
// contention for most of the cases
std::array<std::mutex, 128> mutexes;
static tbb::affinity_partitioner ap;
auto processFun = std::bind(
process, [&](size_t hash) { mutexes[hash % mutexes.size()].lock(); },
@@ -242,28 +238,28 @@ 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::stable_sort(edgePos.begin(), middle, cmp);
std::stable_sort(middle, edgePos.end(), cmp);
std::sort(edgePos.begin(), middle, cmp);
std::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, Vec<char> &wholeHalfedgeP,
Vec<int> &facePtrR,
void AppendPartialEdges(Manifold::Impl &outR, VecDH<char> &wholeHalfedgeP,
VecDH<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) {
VecDH<TriRef> &halfedgeRef, const Manifold::Impl &inP,
const VecDH<int> &i03, const VecDH<int> &vP2R,
const VecDH<int>::IterC faceP2R, bool forward) {
// 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.
Vec<Halfedge> &halfedgeR = outR.halfedge_;
const Vec<glm::vec3> &vertPosP = inP.vertPos_;
const Vec<Halfedge> &halfedgeP = inP.halfedge_;
VecDH<Halfedge> &halfedgeR = outR.halfedge_;
const VecDH<glm::vec3> &vertPosP = inP.vertPos_;
const VecDH<Halfedge> &halfedgeP = inP.halfedge_;
for (auto &value : edgesP) {
const int edgeP = value.first;
@@ -334,12 +330,13 @@ void AppendPartialEdges(Manifold::Impl &outR, Vec<char> &wholeHalfedgeP,
}
void AppendNewEdges(
Manifold::Impl &outR, Vec<int> &facePtrR,
Manifold::Impl &outR, VecDH<int> &facePtrR,
concurrent_map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
Vec<TriRef> &halfedgeRef, const Vec<int> &facePQ2R, const int numFaceP) {
VecDH<TriRef> &halfedgeRef, const VecDH<int> &facePQ2R,
const int numFaceP) {
// Pair up each edge's verts and distribute to faces based on indices in key.
Vec<Halfedge> &halfedgeR = outR.halfedge_;
Vec<glm::vec3> &vertPosR = outR.vertPos_;
VecDH<Halfedge> &halfedgeR = outR.halfedge_;
VecDH<glm::vec3> &vertPosR = outR.vertPos_;
for (auto &value : edgesNew) {
const int faceP = value.first.first;
@@ -386,13 +383,13 @@ void AppendNewEdges(
}
struct DuplicateHalfedges {
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;
Halfedge *halfedgesR;
TriRef *halfedgeRef;
int *facePtr;
const Halfedge *halfedgesP;
const int *i03;
const int *vP2R;
const int *faceP2R;
const bool forward;
void operator()(thrust::tuple<bool, Halfedge, int> in) {
@@ -437,22 +434,22 @@ struct DuplicateHalfedges {
}
};
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) {
for_each_n(ManifoldParams().deterministic ? ExecutionPolicy::Seq
: autoPolicy(inP.halfedge_.size()),
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,
zip(wholeHalfedgeP.begin(), inP.halfedge_.begin(), countAt(0)),
inP.halfedge_.size(),
DuplicateHalfedges({outR.halfedge_, halfedgeRef, facePtrR,
inP.halfedge_, i03, vP2R, faceP2R, forward}));
DuplicateHalfedges({outR.halfedge_.ptrD(), halfedgeRef.ptrD(),
facePtrR.ptrD(), inP.halfedge_.cptrD(),
i03.cptrD(), vP2R.cptrD(), faceP2R, forward}));
}
struct MapTriRef {
VecView<const TriRef> triRefP;
VecView<const TriRef> triRefQ;
const TriRef *triRefP;
const TriRef *triRefQ;
const int offsetQ;
void operator()(TriRef &triRef) {
@@ -463,14 +460,14 @@ struct MapTriRef {
}
};
Vec<TriRef> UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
const Manifold::Impl &inQ, bool invertQ) {
Vec<TriRef> refPQ = outR.meshRelation_.triRef;
VecDH<TriRef> UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
const Manifold::Impl &inQ, bool invertQ,
ExecutionPolicy policy) {
VecDH<TriRef> refPQ = outR.meshRelation_.triRef;
const int offsetQ = Manifold::Impl::meshIDCounter_;
for_each_n(
autoPolicy(outR.NumTri()), outR.meshRelation_.triRef.begin(),
outR.NumTri(),
MapTriRef({inP.meshRelation_.triRef, inQ.meshRelation_.triRef, offsetQ}));
for_each_n(policy, outR.meshRelation_.triRef.begin(), outR.NumTri(),
MapTriRef({inP.meshRelation_.triRef.cptrD(),
inQ.meshRelation_.triRef.cptrD(), offsetQ}));
for (const auto &pair : inP.meshRelation_.meshIDtransform) {
outR.meshRelation_.meshIDtransform[pair.first] = pair.second;
@@ -484,13 +481,13 @@ Vec<TriRef> UpdateReference(Manifold::Impl &outR, const Manifold::Impl &inP,
}
struct Barycentric {
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;
glm::vec3 *uvw;
const glm::vec3 *vertPosP;
const glm::vec3 *vertPosQ;
const glm::vec3 *vertPosR;
const Halfedge *halfedgeP;
const Halfedge *halfedgeQ;
const Halfedge *halfedgeR;
const float precision;
void operator()(thrust::tuple<int, TriRef> in) {
@@ -514,8 +511,9 @@ struct Barycentric {
}
};
void CreateProperties(Manifold::Impl &outR, const Vec<TriRef> &refPQ,
const Manifold::Impl &inP, const Manifold::Impl &inQ) {
void CreateProperties(Manifold::Impl &outR, const VecDH<TriRef> &refPQ,
const Manifold::Impl &inP, const Manifold::Impl &inQ,
ExecutionPolicy policy) {
const int numPropP = inP.NumProp();
const int numPropQ = inQ.NumProp();
const int numProp = glm::max(numPropP, numPropQ);
@@ -525,11 +523,12 @@ void CreateProperties(Manifold::Impl &outR, const Vec<TriRef> &refPQ,
const int numTri = outR.NumTri();
outR.meshRelation_.triProperties.resize(numTri);
Vec<glm::vec3> bary(outR.halfedge_.size());
for_each_n(autoPolicy(numTri), zip(countAt(0), refPQ.cbegin()), numTri,
Barycentric({bary, inP.vertPos_, inQ.vertPos_, outR.vertPos_,
inP.halfedge_, inQ.halfedge_, outR.halfedge_,
outR.precision_}));
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_}));
using Entry = std::pair<glm::ivec3, int>;
int idMissProp = outR.NumVert();
@@ -633,44 +632,39 @@ Manifold::Impl Boolean3::Result(OpType op) const {
const bool invertQ = op == OpType::Subtract;
// Convert winding numbers to inclusion values based on operation type.
Vec<int> i12(x12_.size());
Vec<int> i21(x21_.size());
Vec<int> i03(w03_.size());
Vec<int> i30(w30_.size());
VecDH<int> i12(x12_.size());
VecDH<int> i21(x21_.size());
VecDH<int> i03(w03_.size());
VecDH<int> i30(w30_.size());
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);
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);
Vec<int> vP2R(inP_.NumVert());
exclusive_scan(autoPolicy(i03.size()), i03.begin(), i03.end(), vP2R.begin(),
0, AbsSum());
VecDH<int> vP2R(inP_.NumVert());
exclusive_scan(policy_, i03.begin(), i03.end(), vP2R.begin(), 0, AbsSum());
int numVertR = AbsSum()(vP2R.back(), i03.back());
const int nPv = numVertR;
Vec<int> vQ2R(inQ_.NumVert());
exclusive_scan(autoPolicy(i30.size()), i30.begin(), i30.end(), vQ2R.begin(),
numVertR, AbsSum());
VecDH<int> vQ2R(inQ_.NumVert());
exclusive_scan(policy_, i30.begin(), i30.end(), vQ2R.begin(), numVertR,
AbsSum());
numVertR = AbsSum()(vQ2R.back(), i30.back());
const int nQv = numVertR - nPv;
Vec<int> v12R(v12_.size());
VecDH<int> v12R(v12_.size());
if (v12_.size() > 0) {
exclusive_scan(autoPolicy(i12.size()), i12.begin(), i12.end(), v12R.begin(),
numVertR, AbsSum());
exclusive_scan(policy_, i12.begin(), i12.end(), v12R.begin(), numVertR,
AbsSum());
numVertR = AbsSum()(v12R.back(), i12.back());
}
const int n12 = numVertR - nPv - nQv;
Vec<int> v21R(v21_.size());
VecDH<int> v21R(v21_.size());
if (v21_.size() > 0) {
exclusive_scan(autoPolicy(i21.size()), i21.begin(), i21.end(), v21R.begin(),
numVertR, AbsSum());
exclusive_scan(policy_, i21.begin(), i21.end(), v21R.begin(), numVertR,
AbsSum());
numVertR = AbsSum()(v21R.back(), i21.back());
}
const int n21 = numVertR - nPv - nQv - n12;
@@ -685,19 +679,15 @@ 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(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_}));
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()}));
// New vertices created from intersections:
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_}));
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()}));
PRINT(nPv << " verts from inP");
PRINT(nQv << " verts from inQ");
@@ -719,21 +709,21 @@ Manifold::Impl Boolean3::Result(OpType op) const {
AddNewEdgeVerts(edgesQ, edgesNew, p2q1_, i21, v21R, inQ_.halfedge_, false);
// Level 4
Vec<int> faceEdge;
Vec<int> facePQ2R;
std::tie(faceEdge, facePQ2R) =
SizeOutput(outR, inP_, inQ_, i03, i30, i12, i21, p1q2_, p2q1_, invertQ);
VecDH<int> faceEdge;
VecDH<int> facePQ2R;
std::tie(faceEdge, facePQ2R) = SizeOutput(
outR, inP_, inQ_, i03, i30, i12, i21, p1q2_, p2q1_, invertQ, policy_);
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.
Vec<int> facePtrR = faceEdge;
VecDH<int> facePtrR = faceEdge;
// Intersected halfedges are marked false.
Vec<char> wholeHalfedgeP(inP_.halfedge_.size(), true);
Vec<char> wholeHalfedgeQ(inQ_.halfedge_.size(), true);
VecDH<char> wholeHalfedgeP(inP_.halfedge_.size(), true);
VecDH<char> wholeHalfedgeQ(inQ_.halfedge_.size(), true);
// The halfedgeRef contains the data that will become triRef once the faces
// are triangulated.
Vec<TriRef> halfedgeRef(2 * outR.NumEdge());
VecDH<TriRef> halfedgeRef(2 * outR.NumEdge());
AppendPartialEdges(outR, wholeHalfedgeP, facePtrR, edgesP, halfedgeRef, inP_,
i03, vP2R, facePQ2R.begin(), true);
@@ -744,9 +734,9 @@ Manifold::Impl Boolean3::Result(OpType op) const {
inP_.NumTri());
AppendWholeEdges(outR, facePtrR, halfedgeRef, inP_, wholeHalfedgeP, i03, vP2R,
facePQ2R.cview(0, inP_.NumTri()), true);
facePQ2R.cptrD(), true, policy_);
AppendWholeEdges(outR, facePtrR, halfedgeRef, inQ_, wholeHalfedgeQ, i30, vQ2R,
facePQ2R.cview(inP_.NumTri(), inQ_.NumTri()), false);
facePQ2R.cptrD() + inP_.NumTri(), false, policy_);
#ifdef MANIFOLD_DEBUG
assemble.Stop();
@@ -770,11 +760,11 @@ Manifold::Impl Boolean3::Result(OpType op) const {
if (ManifoldParams().intermediateChecks)
ASSERT(outR.IsManifold(), logicErr, "triangulated mesh is not manifold!");
Vec<TriRef> refPQ = UpdateReference(outR, inP_, inQ_, invertQ);
VecDH<TriRef> refPQ = UpdateReference(outR, inP_, inQ_, invertQ, policy_);
outR.SimplifyTopology();
CreateProperties(outR, refPQ, inP_, inQ_);
CreateProperties(outR, refPQ, inP_, inQ_, policy_);
if (ManifoldParams().intermediateChecks)
ASSERT(outR.Is2Manifold(), logicErr, "simplified mesh is not 2-manifold!");
+20 -15
View File
@@ -16,6 +16,7 @@
#include "cross_section.h"
#include "csg_tree.h"
#include "graph.h"
#include "impl.h"
#include "par.h"
#include "polygon.h"
@@ -39,8 +40,8 @@ struct Equals {
};
struct RemoveFace {
VecView<const Halfedge> halfedge;
VecView<const int> vertLabel;
const Halfedge* halfedge;
const int* vertLabel;
const int keepLabel;
bool operator()(int face) {
@@ -246,7 +247,7 @@ Manifold Manifold::Extrude(const CrossSection& crossSection, float height,
auto pImpl_ = std::make_shared<Impl>();
++nDivisions;
auto& vertPos = pImpl_->vertPos_;
Vec<glm::ivec3> triVertsDH;
VecDH<glm::ivec3> triVertsDH;
auto& triVerts = triVertsDH;
int nCrossSection = 0;
bool isCone = scaleTop.x == 0.0 && scaleTop.y == 0.0;
@@ -358,7 +359,7 @@ Manifold Manifold::Revolve(const CrossSection& crossSection,
auto pImpl_ = std::make_shared<Impl>();
auto& vertPos = pImpl_->vertPos_;
Vec<glm::ivec3> triVertsDH;
VecDH<glm::ivec3> triVertsDH;
auto& triVerts = triVertsDH;
std::vector<int> startPoses;
@@ -464,21 +465,24 @@ 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 {
UnionFind<> uf(NumVert());
// Graph graph;
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()) uf.unionXY(halfedge.startVert, halfedge.endVert);
if (halfedge.IsForward())
graph.add_edge(halfedge.startVert, halfedge.endVert);
}
std::vector<int> componentIndices;
const int numComponents = uf.connectedComponents(componentIndices);
const int numComponents = ConnectedComponents(componentIndices, graph);
if (numComponents == 1) {
std::vector<Manifold> meshes(1);
meshes[0] = *this;
return meshes;
}
Vec<int> vertLabel(componentIndices);
VecDH<int> vertLabel(componentIndices);
std::vector<Manifold> meshes;
for (int i = 0; i < numComponents; ++i) {
@@ -486,7 +490,7 @@ std::vector<Manifold> Manifold::Decompose() const {
// inherit original object's precision
impl->precision_ = pImpl_->precision_;
impl->vertPos_.resize(NumVert());
Vec<int> vertNew2Old(NumVert());
VecDH<int> vertNew2Old(NumVert());
auto policy = autoPolicy(NumVert());
auto start = zip(impl->vertPos_.begin(), vertNew2Old.begin());
int nVert =
@@ -497,13 +501,14 @@ std::vector<Manifold> Manifold::Decompose() const {
start;
impl->vertPos_.resize(nVert);
Vec<int> faceNew2Old(NumTri());
VecDH<int> faceNew2Old(NumTri());
sequence(policy, faceNew2Old.begin(), faceNew2Old.end());
int nFace = remove_if<decltype(faceNew2Old.begin())>(
policy, faceNew2Old.begin(), faceNew2Old.end(),
RemoveFace({pImpl_->halfedge_, vertLabel, i})) -
faceNew2Old.begin();
int nFace =
remove_if<decltype(faceNew2Old.begin())>(
policy, faceNew2Old.begin(), faceNew2Old.end(),
RemoveFace({pImpl_->halfedge_.cptrD(), vertLabel.cptrD(), i})) -
faceNew2Old.begin();
faceNew2Old.resize(nFace);
impl->GatherFaces(*pImpl_, faceNew2Old);
+88 -90
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_priority_queue.h>)
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
#include <tbb/tbb.h>
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
#include <tbb/concurrent_priority_queue.h>
@@ -72,29 +72,10 @@ struct UpdateMeshIDs {
};
struct CheckOverlap {
VecView<const Box> boxes;
const Box *boxes;
const size_t i;
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 {
@@ -225,7 +206,7 @@ Manifold::Impl CsgLeafNode::Compose(
if (nodes.size() > 1 && policy == ExecutionPolicy::Par)
policy = ExecutionPolicy::Seq;
for_each_n(
for_each_n_host(
nodes.size() > 1 ? ExecutionPolicy::Par : ExecutionPolicy::Seq,
countAt(0), nodes.size(),
[&nodes, &vertIndices, &edgeIndices, &triIndices, &propVertIndices,
@@ -252,9 +233,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<Vec<float>::IterC> oldRange(oldProp.begin() + p,
oldProp.end(), numProp);
strided_range<Vec<float>::Iter> newRange(
strided_range<VecDH<float>::IterC> oldRange(
oldProp.begin() + p, oldProp.end(), numProp);
strided_range<VecDH<float>::Iter> newRange(
newProp.begin() + numPropOut * propVertIndices[i] + p,
newProp.end(), numPropOut);
copy(policy, oldRange.begin(), oldRange.end(), newRange.begin());
@@ -294,13 +275,14 @@ Manifold::Impl CsgLeafNode::Compose(
countAt(0)),
node->pImpl_->halfedgeTangent_.size(),
TransformTangents{glm::mat3(node->transform_), invert,
node->pImpl_->halfedgeTangent_,
node->pImpl_->halfedge_});
node->pImpl_->halfedgeTangent_.cptrD(),
node->pImpl_->halfedge_.cptrD()});
if (invert)
for_each_n(policy,
zip(combined.meshRelation_.triRef.begin(),
countAt(triIndices[i])),
node->pImpl_->NumTri(), FlipTris({combined.halfedge_}));
node->pImpl_->NumTri(),
FlipTris({combined.halfedge_.ptrD()}));
}
// Since the nodes may be copies containing the same meshIDs, it is
// important to add an offset so that each node instance gets
@@ -454,9 +436,21 @@ 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) {
auto getImplPtr = GetImplPtr();
using SharedImpl = std::variant<std::shared_ptr<const Manifold::Impl>,
std::shared_ptr<Manifold::Impl>>;
auto getImplPtr = [](const SharedImpl &p) -> const Manifold::Impl * {
if (std::holds_alternative<std::shared_ptr<const Manifold::Impl>>(p)) {
return std::get<std::shared_ptr<const Manifold::Impl>>(p).get();
} else {
return std::get<std::shared_ptr<Manifold::Impl>>(p).get();
}
};
ASSERT(operation != OpType::Subtract, logicErr,
"BatchBoolean doesn't support Difference.");
auto cmpFn = [&getImplPtr](const SharedImpl &a, const SharedImpl &b) {
return getImplPtr(a)->NumVert() < getImplPtr(b)->NumVert();
};
// common cases
if (results.size() == 0) return std::make_shared<Manifold::Impl>();
if (results.size() == 1)
@@ -466,42 +460,38 @@ std::shared_ptr<Manifold::Impl> CsgOpNode::BatchBoolean(
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);
tbb::task_group group;
tbb::concurrent_priority_queue<SharedImpl, decltype(cmpFn)> queue(cmpFn);
for (auto result : results) {
queue.emplace(result);
}
#endif
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<std::shared_ptr<Manifold::Impl>>(r);
#else
// 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);
@@ -520,6 +510,7 @@ std::shared_ptr<Manifold::Impl> CsgOpNode::BatchBoolean(
std::push_heap(results.begin(), results.end(), cmpFn);
}
return std::make_shared<Manifold::Impl>(*results.front());
#endif
}
/**
@@ -541,20 +532,22 @@ void CsgOpNode::BatchUnion() const {
const int start = (children_.size() > kMaxUnionSize)
? (children_.size() - kMaxUnionSize)
: 0;
Vec<Box> boxes;
VecDH<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<Vec<size_t>> disjointSets;
std::vector<VecDH<size_t>> disjointSets;
for (size_t i = 0; i < boxes.size(); i++) {
auto lambda = [&boxes, i](const Vec<size_t> &set) {
return std::find_if(set.begin(), set.end(), CheckOverlap({boxes, i})) ==
set.end();
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 it = std::find_if(disjointSets.begin(), disjointSets.end(), lambda);
if (it == disjointSets.end()) {
@@ -564,22 +557,27 @@ void CsgOpNode::BatchUnion() const {
}
}
// compose each set of disjoint children
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)));
}
}
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));
}
});
children_.erase(children_.begin() + start, children_.end());
children_.push_back(
@@ -603,14 +601,14 @@ std::vector<std::shared_ptr<CsgNode>> &CsgOpNode::GetChildren(
if (forceToLeafNodes && !impl->forcedToLeafNodes_) {
impl->forcedToLeafNodes_ = true;
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();
}
});
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();
}
});
}
return impl->children_;
}
+35 -81
View File
@@ -45,8 +45,8 @@ struct DuplicateEdge {
};
struct ShortEdge {
VecView<const Halfedge> halfedge;
VecView<const glm::vec3> vertPos;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const float precision;
bool operator()(int edge) const {
@@ -59,8 +59,8 @@ struct ShortEdge {
};
struct FlagEdge {
VecView<const Halfedge> halfedge;
VecView<const TriRef> triRef;
const Halfedge* halfedge;
const TriRef* triRef;
bool operator()(int edge) const {
if (halfedge[edge].pairedHalfedge < 0) return false;
@@ -82,9 +82,9 @@ struct FlagEdge {
};
struct SwappableEdge {
VecView<const Halfedge> halfedge;
VecView<const glm::vec3> vertPos;
VecView<const glm::vec3> triNormal;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const glm::vec3* triNormal;
const float precision;
bool operator()(int edge) const {
@@ -145,25 +145,23 @@ namespace manifold {
void Manifold::Impl::SimplifyTopology() {
if (!halfedge_.size()) return;
const int nbEdges = halfedge_.size();
auto policy = autoPolicy(nbEdges);
int nbEdges = halfedge_.size();
int numFlagged = 0;
Vec<uint8_t> bflags(nbEdges);
VecDH<uint8_t> bflags(nbEdges);
uint8_t* bflagsPtr = bflags.ptrD();
// In the case of a very bad triangulation, it is possible to create pinched
// verts. They must be removed before edge collapse.
SplitPinchedVerts();
VecDH<SortEntry> entries(nbEdges);
SortEntry* entriesPtr = entries.ptrD();
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});
}
}
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;
});
stable_sort(policy, entries.begin(), entries.end());
for (int i = 0; i < entries.size() - 1; ++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);
@@ -182,8 +180,9 @@ void Manifold::Impl::SimplifyTopology() {
scratchBuffer.reserve(10);
{
numFlagged = 0;
ShortEdge se{halfedge_, vertPos_, precision_};
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
ShortEdge se{halfedge_.cptrD(), vertPos_.cptrD(), precision_};
for_each_n(policy, countAt(0), nbEdges,
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
for (int i = 0; i < nbEdges; ++i) {
if (bflags[i]) {
CollapseEdge(i, scratchBuffer);
@@ -202,8 +201,9 @@ void Manifold::Impl::SimplifyTopology() {
{
numFlagged = 0;
FlagEdge se{halfedge_, meshRelation_.triRef};
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
FlagEdge se{halfedge_.cptrD(), meshRelation_.triRef.cptrD()};
for_each_n(policy, countAt(0), nbEdges,
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
for (int i = 0; i < nbEdges; ++i) {
if (bflags[i]) {
CollapseEdge(i, scratchBuffer);
@@ -222,8 +222,10 @@ void Manifold::Impl::SimplifyTopology() {
{
numFlagged = 0;
SwappableEdge se{halfedge_, vertPos_, faceNormal_, precision_};
for_each_n(policy, countAt(0), nbEdges, [&](int i) { bflags[i] = se(i); });
SwappableEdge se{halfedge_.cptrD(), vertPos_.cptrD(), faceNormal_.cptrD(),
precision_};
for_each_n(policy, countAt(0), nbEdges,
[=] __host__ __device__(int i) { bflagsPtr[i] = se(i); });
std::vector<int> edgeSwapStack;
std::vector<int> visited(halfedge_.size(), -1);
int tag = 0;
@@ -248,8 +250,6 @@ 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;
@@ -258,7 +258,6 @@ 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]);
@@ -305,45 +304,6 @@ 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) {
@@ -389,7 +349,6 @@ 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;
@@ -402,7 +361,6 @@ 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]) {
@@ -427,13 +385,9 @@ void Manifold::Impl::RemoveIfFolded(int edge) {
}
}
// 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;
VecDH<TriRef>& triRef = meshRelation_.triRef;
VecDH<glm::ivec3>& triProp = meshRelation_.triProperties;
const Halfedge toRemove = halfedge_[edge];
if (toRemove.pairedHalfedge < 0) return;
@@ -545,7 +499,7 @@ 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;
VecDH<TriRef>& triRef = meshRelation_.triRef;
if (edge < 0) return;
const int pair = halfedge_[edge].pairedHalfedge;
@@ -594,8 +548,8 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
const float a = glm::max(0.0f, glm::min(1.0f, l02 / l01));
// Update properties if applicable
if (meshRelation_.properties.size() > 0) {
Vec<glm::ivec3>& triProp = meshRelation_.triProperties;
Vec<float>& prop = meshRelation_.properties;
VecDH<glm::ivec3>& triProp = meshRelation_.triProperties;
VecDH<float>& prop = meshRelation_.properties;
triProp[tri0] = triProp[tri1];
triProp[tri0][perm0[1]] = triProp[tri1][perm1[0]];
triProp[tri0][perm0[0]] = triProp[tri1][perm1[2]];
+23 -22
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/concurrent_map.h>)
#if MANIFOLD_PAR == 'T' && __has_include(<tbb/tbb.h>)
#include <tbb/tbb.h>
#define TBB_PREVIEW_CONCURRENT_ORDERED_CONTAINERS 1
#include <tbb/concurrent_map.h>
@@ -37,11 +37,11 @@ using AddTriangle = std::function<void(int, glm::ivec3, glm::vec3, TriRef)>;
* 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 Vec<int>& faceEdge,
const Vec<TriRef>& halfedgeRef) {
Vec<glm::ivec3> triVerts;
Vec<glm::vec3> triNormal;
Vec<TriRef>& triRef = meshRelation_.triRef;
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;
triRef.resize(0);
auto processFace = [&](GeneralTriangulation general, AddTriangle addTri,
int face) {
@@ -133,22 +133,23 @@ void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
tbb::task_group group;
// map from face to triangle
tbb::concurrent_unordered_map<int, std::vector<glm::ivec3>> results;
Vec<int> triCount(faceEdge.size());
VecDH<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);
});
});
for_each_host(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(),
@@ -167,8 +168,8 @@ void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
},
std::placeholders::_1);
// set triangles in parallel
for_each(autoPolicy(faceEdge.size()), countAt(0),
countAt(faceEdge.size() - 1), processFace2);
for_each_host(autoPolicy(faceEdge.size()), countAt(0),
countAt(faceEdge.size() - 1), processFace2);
#else
triVerts.reserve(faceEdge.size());
triNormal.reserve(faceEdge.size());
@@ -195,7 +196,7 @@ void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
* projection of the vertices.
*/
PolygonsIdx Manifold::Impl::Face2Polygons(int face, glm::mat3x2 projection,
const Vec<int>& faceEdge) const {
const VecDH<int>& faceEdge) const {
const int firstEdge = faceEdge[face];
const int lastEdge = faceEdge[face + 1];
+97 -87
View File
@@ -14,11 +14,14 @@
#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"
@@ -51,9 +54,9 @@ struct Transform4x3 {
};
struct AssignNormals {
VecView<glm::vec3> vertNormal;
VecView<const glm::vec3> vertPos;
VecView<const Halfedge> halfedges;
glm::vec3* vertNormal;
const glm::vec3* vertPos;
const Halfedge* halfedges;
const float precision;
const bool calculateTriNormal;
@@ -91,8 +94,8 @@ struct AssignNormals {
};
struct Tri2Halfedges {
VecView<Halfedge> halfedges;
VecView<glm::uint64_t> edges;
Halfedge* halfedges;
glm::uint64_t* edges;
void operator()(thrust::tuple<int, const glm::ivec3&> in) {
const int tri = thrust::get<0>(in);
@@ -111,8 +114,8 @@ struct Tri2Halfedges {
};
struct LinkHalfedges {
VecView<Halfedge> halfedges;
VecView<const int> ids;
Halfedge* halfedges;
const int* ids;
const int numEdge;
void operator()(int i) {
@@ -124,18 +127,18 @@ struct LinkHalfedges {
};
struct MarkVerts {
VecView<int> vert;
int* vert;
void operator()(glm::ivec3 triVerts) {
for (int i : {0, 1, 2}) {
reinterpret_cast<std::atomic<int>*>(&vert[triVerts[i]])
->store(1, std::memory_order_relaxed);
reinterpret_cast<std::atomic<int>*>(vert)[triVerts[i]].store(
1, std::memory_order_relaxed);
}
}
};
struct ReindexTriVerts {
VecView<const int> old2new;
const int* old2new;
void operator()(glm::ivec3& triVerts) {
for (int i : {0, 1, 2}) {
@@ -146,7 +149,7 @@ struct ReindexTriVerts {
struct InitializeTriRef {
const int meshID;
VecView<const Halfedge> halfedge;
const Halfedge* halfedge;
void operator()(thrust::tuple<TriRef&, int> inOut) {
TriRef& baryRef = thrust::get<0>(inOut);
@@ -165,13 +168,13 @@ struct UpdateMeshID {
};
struct CoplanarEdge {
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;
float* triArea;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const TriRef* triRef;
const glm::ivec3* triProp;
const float* prop;
const float* propTol;
const int numProp;
const float precision;
@@ -268,14 +271,14 @@ struct CoplanarEdge {
};
struct CheckCoplanarity {
VecView<int> comp2tri;
VecView<const Halfedge> halfedge;
VecView<const glm::vec3> vertPos;
std::vector<int>* components;
int* comp2tri;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const int* components;
const float precision;
void operator()(int tri) {
const int component = (*components)[tri];
const int component = components[tri];
const int referenceTri = comp2tri[component];
if (referenceTri < 0 || referenceTri == tri) return;
@@ -290,8 +293,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) {
reinterpret_cast<std::atomic<int>*>(&comp2tri[component])
->store(-1, std::memory_order_relaxed);
reinterpret_cast<std::atomic<int>*>(comp2tri)[component].store(
-1, std::memory_order_relaxed);
break;
}
}
@@ -299,7 +302,7 @@ struct CheckCoplanarity {
};
struct EdgeBox {
VecView<const glm::vec3> vertPos;
const glm::vec3* vertPos;
void operator()(thrust::tuple<Box&, const TmpEdge&> inout) {
const TmpEdge& edge = thrust::get<1>(inout);
@@ -308,18 +311,22 @@ struct EdgeBox {
};
int GetLabels(std::vector<int>& components,
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);
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);
}
return uf.connectedComponents(components);
return ConnectedComponents(components, graph);
}
void DedupePropVerts(manifold::Vec<glm::ivec3>& triProp,
const Vec<thrust::pair<int, int>>& vert2vert) {
void DedupePropVerts(manifold::VecDH<glm::ivec3>& triProp,
const VecDH<thrust::pair<int, int>>& vert2vert) {
std::vector<int> vertLabels;
const int numLabels = GetLabels(vertLabels, vert2vert, vert2vert.size());
@@ -481,7 +488,7 @@ Manifold::Impl::Impl(const Mesh& mesh, const MeshRelationD& relation,
meshRelation_ = {relation.originalID, relation.numProp, relation.properties,
relation.meshIDtransform};
Vec<glm::ivec3> triVerts;
VecDH<glm::ivec3> triVerts;
for (int i = 0; i < mesh.triVerts.size(); ++i) {
const glm::ivec3 tri = mesh.triVerts[i];
// Remove topological degenerates
@@ -580,13 +587,13 @@ Manifold::Impl::Impl(Shape shape) {
CreateFaces();
}
void Manifold::Impl::RemoveUnreferencedVerts(Vec<glm::ivec3>& triVerts) {
Vec<int> vertOld2New(NumVert() + 1, 0);
void Manifold::Impl::RemoveUnreferencedVerts(VecDH<glm::ivec3>& triVerts) {
VecDH<int> vertOld2New(NumVert() + 1, 0);
auto policy = autoPolicy(NumVert());
for_each(policy, triVerts.cbegin(), triVerts.cend(),
MarkVerts({vertOld2New.view(1)}));
MarkVerts({vertOld2New.ptrD() + 1}));
const Vec<glm::vec3> oldVertPos = vertPos_;
const VecDH<glm::vec3> oldVertPos = vertPos_;
vertPos_.resize(copy_if<decltype(vertPos_.begin())>(
policy, oldVertPos.cbegin(), oldVertPos.cend(),
vertOld2New.cbegin() + 1, vertPos_.begin(),
@@ -597,7 +604,7 @@ void Manifold::Impl::RemoveUnreferencedVerts(Vec<glm::ivec3>& triVerts) {
vertOld2New.begin() + 1);
for_each(policy, triVerts.begin(), triVerts.end(),
ReindexTriVerts({vertOld2New}));
ReindexTriVerts({vertOld2New.cptrD()}));
}
void Manifold::Impl::InitializeOriginal() {
@@ -607,25 +614,28 @@ void Manifold::Impl::InitializeOriginal() {
meshRelation_.triRef.resize(NumTri());
for_each_n(autoPolicy(NumTri()),
zip(meshRelation_.triRef.begin(), countAt(0)), NumTri(),
InitializeTriRef({meshID, halfedge_}));
InitializeTriRef({meshID, halfedge_.cptrD()}));
meshRelation_.meshIDtransform.clear();
meshRelation_.meshIDtransform[meshID] = {meshID};
}
void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
Vec<float> propertyToleranceD =
propertyTolerance.empty() ? Vec<float>(meshRelation_.numProp, kTolerance)
: propertyTolerance;
VecDH<float> propertyToleranceD =
propertyTolerance.empty()
? VecDH<float>(meshRelation_.numProp, kTolerance)
: propertyTolerance;
Vec<thrust::pair<int, int>> face2face(halfedge_.size(), {-1, -1});
Vec<thrust::pair<int, int>> vert2vert(halfedge_.size(), {-1, -1});
Vec<float> triArea(NumTri());
VecDH<thrust::pair<int, int>> face2face(halfedge_.size(), {-1, -1});
VecDH<thrust::pair<int, int>> vert2vert(halfedge_.size(), {-1, -1});
VecDH<float> triArea(NumTri());
for_each_n(
autoPolicy(halfedge_.size()),
zip(face2face.begin(), vert2vert.begin(), countAt(0)), halfedge_.size(),
CoplanarEdge({triArea, halfedge_, vertPos_, meshRelation_.triRef,
meshRelation_.triProperties, meshRelation_.properties,
propertyToleranceD, meshRelation_.numProp, precision_}));
CoplanarEdge(
{triArea.ptrD(), halfedge_.cptrD(), vertPos_.cptrD(),
meshRelation_.triRef.cptrD(), meshRelation_.triProperties.cptrD(),
meshRelation_.properties.cptrD(), propertyToleranceD.cptrD(),
meshRelation_.numProp, precision_}));
if (meshRelation_.triProperties.size() > 0) {
DedupePropVerts(meshRelation_.triProperties, vert2vert);
@@ -634,7 +644,7 @@ void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
std::vector<int> components;
const int numComponent = GetLabels(components, face2face, NumTri());
Vec<int> comp2tri(numComponent, -1);
std::vector<int> comp2tri(numComponent, -1);
for (int tri = 0; tri < NumTri(); ++tri) {
const int comp = components[tri];
const int current = comp2tri[comp];
@@ -644,13 +654,16 @@ void Manifold::Impl::CreateFaces(const std::vector<float>& propertyTolerance) {
}
}
for_each_n(autoPolicy(halfedge_.size()), countAt(0), NumTri(),
CheckCoplanarity(
{comp2tri, halfedge_, vertPos_, &components, precision_}));
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_}));
Vec<TriRef>& triRef = meshRelation_.triRef;
VecDH<TriRef>& triRef = meshRelation_.triRef;
for (int tri = 0; tri < NumTri(); ++tri) {
const int referenceTri = comp2tri[components[tri]];
const int referenceTri = comp2triD[components[tri]];
if (referenceTri >= 0) {
triRef[tri].tri = referenceTri;
}
@@ -660,34 +673,29 @@ 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 Vec<glm::ivec3>& triVerts) {
void Manifold::Impl::CreateHalfedges(const VecDH<glm::ivec3>& triVerts) {
const int numTri = triVerts.size();
const int numHalfedge = 3 * numTri;
// drop the old value first to avoid copy
halfedge_.resize(0);
halfedge_.resize(numHalfedge);
Vec<uint64_t> edge(numHalfedge);
Vec<int> ids(numHalfedge);
VecDH<uint64_t> edge(numHalfedge);
VecDH<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_, edge}));
Tri2Halfedges({halfedge_.ptrD(), edge.ptrD()}));
// 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(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);
});
stable_sort_by_key(policy, edge.begin(), edge.end(), ids.begin());
// 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_, ids, numHalfedge / 2}));
LinkHalfedges({halfedge_.ptrD(), ids.ptrD(), numHalfedge / 2}));
}
/**
@@ -696,8 +704,8 @@ void Manifold::Impl::CreateHalfedges(const Vec<glm::ivec3>& triVerts) {
*/
void Manifold::Impl::Update() {
CalculateBBox();
Vec<Box> faceBox;
Vec<uint32_t> faceMorton;
VecDH<Box> faceBox;
VecDH<uint32_t> faceMorton;
GetFaceBoxMorton(faceBox, faceMorton);
collider_.UpdateBoxes(faceBox);
}
@@ -760,15 +768,16 @@ 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_, halfedge_}));
for_each_n(
policy, zip(result.halfedgeTangent_.begin(), countAt(0)),
halfedgeTangent_.size(),
TransformTangents({glm::mat3(transform_), invert,
halfedgeTangent_.cptrD(), halfedge_.cptrD()}));
}
if (invert) {
for_each_n(policy, zip(result.meshRelation_.triRef.begin(), countAt(0)),
result.NumTri(), FlipTris({result.halfedge_}));
result.NumTri(), FlipTris({result.halfedge_.ptrD()}));
}
// This optimization does a cheap collider update if the transform is
@@ -815,9 +824,10 @@ void Manifold::Impl::CalculateNormals() {
faceNormal_.resize(NumTri());
calculateTriNormal = true;
}
for_each_n(policy, zip(faceNormal_.begin(), countAt(0)), NumTri(),
AssignNormals({vertNormal_, vertPos_, halfedge_, precision_,
calculateTriNormal}));
for_each_n(
policy, zip(faceNormal_.begin(), countAt(0)), NumTri(),
AssignNormals({vertNormal_.ptrD(), vertPos_.cptrD(), halfedge_.cptrD(),
precision_, calculateTriNormal}));
for_each(policy, vertNormal_.begin(), vertNormal_.end(), Normalize());
}
@@ -849,25 +859,25 @@ void Manifold::Impl::IncrementMeshIDs() {
*/
SparseIndices Manifold::Impl::EdgeCollisions(const Impl& Q,
bool inverted) const {
Vec<TmpEdge> edges = CreateTmpEdges(Q.halfedge_);
VecDH<TmpEdge> edges = CreateTmpEdges(Q.halfedge_);
const int numEdge = edges.size();
Vec<Box> QedgeBB(numEdge);
VecDH<Box> QedgeBB(numEdge);
auto policy = autoPolicy(numEdge);
for_each_n(policy, zip(QedgeBB.begin(), edges.cbegin()), numEdge,
EdgeBox({Q.vertPos_}));
EdgeBox({Q.vertPos_.cptrD()}));
SparseIndices q1p2(0);
if (inverted)
q1p2 = collider_.Collisions<false, true>(QedgeBB.cview());
q1p2 = collider_.Collisions<false, true>(QedgeBB);
else
q1p2 = collider_.Collisions<false, false>(QedgeBB.cview());
q1p2 = collider_.Collisions<false, false>(QedgeBB);
if (inverted)
for_each(policy, countAt(0), countAt(q1p2.size()),
ReindexEdge<true>({edges, q1p2}));
ReindexEdge<true>({edges.cptrD(), q1p2}));
else
for_each(policy, countAt(0), countAt(q1p2.size()),
ReindexEdge<false>({edges, q1p2}));
ReindexEdge<false>({edges.cptrD(), q1p2}));
return q1p2;
}
@@ -875,8 +885,8 @@ SparseIndices Manifold::Impl::EdgeCollisions(const Impl& Q,
* Returns a sparse array of the input vertices that project inside the XY
* bounding boxes of the faces of this manifold.
*/
SparseIndices Manifold::Impl::VertexCollisionsZ(
VecView<const glm::vec3> vertsIn, bool inverted) const {
SparseIndices Manifold::Impl::VertexCollisionsZ(const VecDH<glm::vec3>& vertsIn,
bool inverted) const {
if (inverted)
return collider_.Collisions<false, true>(vertsIn);
else
+21 -21
View File
@@ -22,7 +22,7 @@
#include "shared.h"
#include "sparse.h"
#include "utils.h"
#include "vec.h"
#include "vec_dh.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;
Vec<float> properties;
VecDH<float> properties;
std::map<int, Relation> meshIDtransform;
Vec<TriRef> triRef;
Vec<glm::ivec3> triProperties;
VecDH<TriRef> triRef;
VecDH<glm::ivec3> triProperties;
};
Box bBox_;
float precision_ = -1;
Error status_ = Error::NoError;
Vec<glm::vec3> vertPos_;
Vec<Halfedge> halfedge_;
Vec<glm::vec3> vertNormal_;
Vec<glm::vec3> faceNormal_;
Vec<glm::vec4> halfedgeTangent_;
VecDH<glm::vec3> vertPos_;
VecDH<Halfedge> halfedge_;
VecDH<glm::vec3> vertNormal_;
VecDH<glm::vec3> faceNormal_;
VecDH<glm::vec4> halfedgeTangent_;
MeshRelationD meshRelation_;
Collider collider_;
@@ -67,9 +67,9 @@ struct Manifold::Impl {
bool hasFaceIDs = false);
void CreateFaces(const std::vector<float>& propertyTolerance = {});
void RemoveUnreferencedVerts(Vec<glm::ivec3>& triVerts);
void RemoveUnreferencedVerts(VecDH<glm::ivec3>& triVerts);
void InitializeOriginal();
void CreateHalfedges(const Vec<glm::ivec3>& triVerts);
void CreateHalfedges(const VecDH<glm::ivec3>& triVerts);
void CalculateNormals();
void IncrementMeshIDs();
@@ -78,7 +78,7 @@ struct Manifold::Impl {
void Warp(std::function<void(glm::vec3&)> warpFunc);
Impl Transform(const glm::mat4x3& transform) const;
SparseIndices EdgeCollisions(const Impl& B, bool inverted = false) const;
SparseIndices VertexCollisionsZ(VecView<const glm::vec3> vertsIn,
SparseIndices VertexCollisionsZ(const VecDH<glm::vec3>& vertsIn,
bool inverted = false) const;
bool IsEmpty() const { return NumVert() == 0; }
@@ -96,7 +96,7 @@ struct Manifold::Impl {
void CalculateCurvature(int gaussianIdx, int meanIdx);
void CalculateBBox();
bool IsFinite() const;
bool IsIndexInBounds(VecView<const glm::ivec3> triVerts) const;
bool IsIndexInBounds(const VecDH<glm::ivec3>& triVerts) const;
void SetPrecision(float minPrecision = -1);
bool IsManifold() const;
bool Is2Manifold() const;
@@ -106,17 +106,17 @@ struct Manifold::Impl {
// sort.cu
void Finish();
void SortVerts();
void ReindexVerts(const Vec<int>& vertNew2Old, int numOldVert);
void ReindexVerts(const VecDH<int>& vertNew2Old, int numOldVert);
void CompactProps();
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);
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);
// face_op.cu
void Face2Tri(const Vec<int>& faceEdge, const Vec<TriRef>& halfedgeRef);
void Face2Tri(const VecDH<int>& faceEdge, const VecDH<TriRef>& halfedgeRef);
PolygonsIdx Face2Polygons(int face, glm::mat3x2 projection,
const Vec<int>& faceEdge) const;
const VecDH<int>& faceEdge) const;
// edge_op.cu
void SimplifyTopology();
@@ -134,7 +134,7 @@ struct Manifold::Impl {
// smoothing.cu
void CreateTangents(const std::vector<Smoothness>&);
Vec<Barycentric> Subdivide(int n);
VecDH<Barycentric> Subdivide(int n);
void Refine(int n);
};
} // namespace manifold
+12 -11
View File
@@ -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"
@@ -29,7 +29,7 @@ using namespace thrust::placeholders;
ExecutionParams manifoldParams;
struct MakeTri {
VecView<const Halfedge> halfedges;
const Halfedge* halfedges;
void operator()(thrust::tuple<glm::ivec3&, int> inOut) {
glm::ivec3& tri = thrust::get<0>(inOut);
@@ -170,7 +170,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_}));
NumTri(), MakeTri({impl.halfedge_.cptrH()}));
return result;
}
@@ -218,7 +218,7 @@ MeshGL Manifold::GetMeshGL(glm::ivec3 normalIdx) const {
out.faceID.resize(numTri);
std::vector<int> triNew2Old(numTri);
std::iota(triNew2Old.begin(), triNew2Old.end(), 0);
VecView<const TriRef> triRef = impl.meshRelation_.triRef;
const TriRef* triRef = impl.meshRelation_.triRef.cptrD();
// Don't sort originals - keep them in order
if (!isOriginal) {
std::sort(triNew2Old.begin(), triNew2Old.end(), [triRef](int a, int b) {
@@ -583,7 +583,7 @@ Manifold Manifold::SetProperties(
propFunc) const {
auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
const int oldNumProp = NumProp();
const Vec<float> oldProperties = pImpl->meshRelation_.properties;
const VecDH<float> oldProperties = pImpl->meshRelation_.properties;
auto& triProperties = pImpl->meshRelation_.triProperties;
if (numProp == 0) {
@@ -599,16 +599,17 @@ Manifold Manifold::SetProperties(
triProperties[i][j] = idx++;
}
}
pImpl->meshRelation_.properties = Vec<float>(numProp * idx, 0);
pImpl->meshRelation_.properties = VecDH<float>(numProp * idx, 0);
} else {
pImpl->meshRelation_.properties = Vec<float>(numProp * NumPropVert(), 0);
pImpl->meshRelation_.properties =
VecDH<float>(numProp * NumPropVert(), 0);
}
thrust::for_each_n(
thrust::host, countAt(0), NumTri(),
UpdateProperties({pImpl->meshRelation_.properties.data(), numProp,
oldProperties.data(), oldNumProp,
pImpl->vertPos_.data(), triProperties.data(),
pImpl->halfedge_.data(), propFunc}));
UpdateProperties({pImpl->meshRelation_.properties.ptrH(), numProp,
oldProperties.ptrH(), oldNumProp,
pImpl->vertPos_.ptrH(), triProperties.ptrH(),
pImpl->halfedge_.ptrH(), propFunc}));
}
pImpl->meshRelation_.numProp = numProp;
+3 -3
View File
@@ -22,8 +22,8 @@ struct TransformNormals {
struct TransformTangents {
const glm::mat3 transform;
const bool invert;
VecView<const glm::vec4> oldTangents;
VecView<const Halfedge> halfedge;
const glm::vec4* oldTangents;
const Halfedge* halfedge;
void operator()(thrust::tuple<glm::vec4&, int> inOut) {
glm::vec4& tangent = thrust::get<0>(inOut);
@@ -38,7 +38,7 @@ struct TransformTangents {
};
struct FlipTris {
VecView<Halfedge> halfedge;
Halfedge* halfedge;
void operator()(thrust::tuple<TriRef&, int> inOut) {
TriRef& bary = thrust::get<0>(inOut);
+54 -64
View File
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <thrust/count.h>
#include <thrust/logical.h>
#include <thrust/transform_reduce.h>
#include <limits>
#include "impl.h"
@@ -21,8 +25,8 @@ namespace {
using namespace manifold;
struct FaceAreaVolume {
VecView<const Halfedge> halfedges;
VecView<const glm::vec3> vertPos;
const Halfedge* halfedges;
const glm::vec3* vertPos;
const float precision;
thrust::pair<float, float> operator()(int face) {
@@ -93,13 +97,13 @@ struct SumPair : public thrust::binary_function<thrust::pair<float, float>,
};
struct CurvatureAngles {
VecView<float> meanCurvature;
VecView<float> gaussianCurvature;
VecView<float> area;
VecView<float> degree;
VecView<const Halfedge> halfedge;
VecView<const glm::vec3> vertPos;
VecView<const glm::vec3> triNormal;
float* meanCurvature;
float* gaussianCurvature;
float* area;
float* degree;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const glm::vec3* triNormal;
void operator()(int tri) {
glm::vec3 edge[3];
@@ -148,12 +152,12 @@ struct NormalizeCurvature {
};
struct UpdateProperties {
VecView<float> properties;
float* properties;
VecView<const float> oldProperties;
VecView<const Halfedge> halfedge;
VecView<const float> meanCurvature;
VecView<const float> gaussianCurvature;
const float* oldProperties;
const Halfedge* halfedge;
const float* meanCurvature;
const float* gaussianCurvature;
const int oldNumProp;
const int numProp;
const int gaussianIdx;
@@ -187,17 +191,13 @@ struct UpdateProperties {
};
struct CheckHalfedges {
VecView<const Halfedge> halfedges;
VecView<const glm::vec3> vertPos;
const Halfedge* halfedges;
bool operator()(int edge) {
const Halfedge halfedge = halfedges[edge];
if (halfedge.startVert == -1 || halfedge.endVert == -1) return true;
if (halfedge.startVert == -1 && halfedge.endVert == -1) return true;
if (halfedge.pairedHalfedge == -1) return false;
if (!isfinite(vertPos[halfedge.startVert][0])) return false;
if (!isfinite(vertPos[halfedge.endVert][0])) return false;
const Halfedge paired = halfedges[halfedge.pairedHalfedge];
bool good = true;
good &= paired.pairedHalfedge == edge;
@@ -209,7 +209,7 @@ struct CheckHalfedges {
};
struct NoDuplicates {
VecView<const Halfedge> halfedges;
const Halfedge* halfedges;
bool operator()(int edge) {
const Halfedge halfedge = halfedges[edge];
@@ -222,9 +222,9 @@ struct NoDuplicates {
};
struct CheckCCW {
VecView<const Halfedge> halfedges;
VecView<const glm::vec3> vertPos;
VecView<const glm::vec3> triNormal;
const Halfedge* halfedges;
const glm::vec3* vertPos;
const glm::vec3* triNormal;
const float tol;
bool operator()(int face) {
@@ -276,7 +276,7 @@ bool Manifold::Impl::IsManifold() const {
auto policy = autoPolicy(halfedge_.size());
return all_of(policy, countAt(0), countAt(halfedge_.size()),
CheckHalfedges({halfedge_, vertPos_}));
CheckHalfedges({halfedge_.cptrD()}));
}
/**
@@ -289,11 +289,11 @@ bool Manifold::Impl::Is2Manifold() const {
if (!IsManifold()) return false;
Vec<Halfedge> halfedge(halfedge_);
stable_sort(policy, halfedge.begin(), halfedge.end());
VecDH<Halfedge> halfedge(halfedge_);
sort(policy, halfedge.begin(), halfedge.end());
return all_of(policy, countAt(0), countAt(2 * NumEdge() - 1),
NoDuplicates({halfedge}));
NoDuplicates({halfedge.cptrD()}));
}
/**
@@ -302,7 +302,8 @@ bool Manifold::Impl::Is2Manifold() const {
bool Manifold::Impl::MatchesTriNormals() const {
if (halfedge_.size() == 0 || faceNormal_.size() != NumTri()) return true;
return all_of(autoPolicy(NumTri()), countAt(0), countAt(NumTri()),
CheckCCW({halfedge_, vertPos_, faceNormal_, 2 * precision_}));
CheckCCW({halfedge_.cptrD(), vertPos_.cptrD(),
faceNormal_.cptrD(), 2 * precision_}));
}
/**
@@ -310,45 +311,33 @@ bool Manifold::Impl::MatchesTriNormals() const {
*/
int Manifold::Impl::NumDegenerateTris() const {
if (halfedge_.size() == 0 || faceNormal_.size() != NumTri()) return true;
return count_if(
autoPolicy(NumTri()), countAt(0), countAt(NumTri()),
CheckCCW({halfedge_, vertPos_, faceNormal_, -1 * precision_ / 2}));
return count_if(autoPolicy(NumTri()), countAt(0), countAt(NumTri()),
CheckCCW({halfedge_.cptrD(), vertPos_.cptrD(),
faceNormal_.cptrD(), -1 * precision_ / 2}));
}
Properties Manifold::Impl::GetProperties() const {
if (IsEmpty()) return {0, 0};
// Kahan summation
float area = 0;
float volume = 0;
float areaCompensation = 0;
float volumeCompensation = 0;
for (int i = 0; i < NumTri(); ++i) {
auto [area1, volume1] =
FaceAreaVolume({halfedge_, vertPos_, precision_})(i);
const float t1 = area + area1;
const float t2 = volume + volume1;
areaCompensation += (area - t1) + area1;
volumeCompensation += (volume - t2) + volume1;
area = t1;
volume = t2;
}
area += areaCompensation;
volume += volumeCompensation;
return {area, volume};
auto areaVolume = transform_reduce<thrust::pair<float, float>>(
autoPolicy(NumTri()), countAt(0), countAt(NumTri()),
FaceAreaVolume({halfedge_.cptrD(), vertPos_.cptrD(), precision_}),
thrust::make_pair(0.0f, 0.0f), SumPair());
return {areaVolume.first, areaVolume.second};
}
void Manifold::Impl::CalculateCurvature(int gaussianIdx, int meanIdx) {
if (IsEmpty()) return;
if (gaussianIdx < 0 && meanIdx < 0) return;
Vec<float> vertMeanCurvature(NumVert(), 0);
Vec<float> vertGaussianCurvature(NumVert(), glm::two_pi<float>());
Vec<float> vertArea(NumVert(), 0);
Vec<float> degree(NumVert(), 0);
VecDH<float> vertMeanCurvature(NumVert(), 0);
VecDH<float> vertGaussianCurvature(NumVert(), glm::two_pi<float>());
VecDH<float> vertArea(NumVert(), 0);
VecDH<float> degree(NumVert(), 0);
auto policy = autoPolicy(NumTri());
for_each(policy, countAt(0), countAt(NumTri()),
CurvatureAngles({vertMeanCurvature, vertGaussianCurvature, vertArea,
degree, halfedge_, vertPos_, faceNormal_}));
for_each(
policy, countAt(0), countAt(NumTri()),
CurvatureAngles({vertMeanCurvature.ptrD(), vertGaussianCurvature.ptrD(),
vertArea.ptrD(), degree.ptrD(), halfedge_.cptrD(),
vertPos_.cptrD(), faceNormal_.cptrD()}));
for_each_n(policy,
zip(vertMeanCurvature.begin(), vertGaussianCurvature.begin(),
vertArea.begin(), degree.begin()),
@@ -356,8 +345,8 @@ void Manifold::Impl::CalculateCurvature(int gaussianIdx, int meanIdx) {
const int oldNumProp = NumProp();
const int numProp = glm::max(oldNumProp, glm::max(gaussianIdx, meanIdx) + 1);
const Vec<float> oldProperties = meshRelation_.properties;
meshRelation_.properties = Vec<float>(numProp * NumPropVert(), 0);
const VecDH<float> oldProperties = meshRelation_.properties;
meshRelation_.properties = VecDH<float>(numProp * NumPropVert(), 0);
meshRelation_.numProp = numProp;
if (meshRelation_.triProperties.size() == 0) {
meshRelation_.triProperties.resize(NumTri());
@@ -365,9 +354,10 @@ void Manifold::Impl::CalculateCurvature(int gaussianIdx, int meanIdx) {
for_each_n(
policy, zip(meshRelation_.triProperties.begin(), countAt(0)), NumTri(),
UpdateProperties({meshRelation_.properties, oldProperties, halfedge_,
vertMeanCurvature, vertGaussianCurvature, oldNumProp,
numProp, gaussianIdx, meanIdx}));
UpdateProperties({meshRelation_.properties.ptrD(), oldProperties.cptrD(),
halfedge_.cptrD(), vertMeanCurvature.cptrD(),
vertGaussianCurvature.cptrD(), oldNumProp, numProp,
gaussianIdx, meanIdx}));
CreateFaces();
SimplifyTopology();
@@ -404,7 +394,7 @@ bool Manifold::Impl::IsFinite() const {
* Checks that the input triVerts array has all indices inside bounds of the
* vertPos_ array.
*/
bool Manifold::Impl::IsIndexInBounds(VecView<const glm::ivec3> triVerts) const {
bool Manifold::Impl::IsIndexInBounds(const VecDH<glm::ivec3>& triVerts) const {
auto policy = autoPolicy(triVerts.size());
glm::ivec2 minmax = transform_reduce<glm::ivec2>(
policy, triVerts.begin(), triVerts.end(), MakeMinMax(),
+4 -4
View File
@@ -17,7 +17,7 @@
#include "par.h"
#include "sparse.h"
#include "utils.h"
#include "vec.h"
#include "vec_dh.h"
namespace manifold {
@@ -193,8 +193,8 @@ struct TmpInvalid {
bool operator()(const TmpEdge& edge) { return edge.halfedgeIdx < 0; }
};
Vec<TmpEdge> inline CreateTmpEdges(const Vec<Halfedge>& halfedge) {
Vec<TmpEdge> edges(halfedge.size());
VecDH<TmpEdge> inline CreateTmpEdges(const VecDH<Halfedge>& halfedge) {
VecDH<TmpEdge> edges(halfedge.size());
for_each_n(autoPolicy(edges.size()),
zip(edges.begin(), halfedge.begin(), countAt(0)), edges.size(),
Halfedge2Tmp());
@@ -209,7 +209,7 @@ Vec<TmpEdge> inline CreateTmpEdges(const Vec<Halfedge>& halfedge) {
template <const bool inverted>
struct ReindexEdge {
VecView<const TmpEdge> edges;
const TmpEdge* edges;
SparseIndices& indices;
void operator()(int i) {
+38 -35
View File
@@ -39,8 +39,8 @@ int VertsPerTri(int edgeVerts) {
* CPU for simplicity for now. Using AtomicCAS on .tri should work for a GPU
* version if desired.
*/
void FillRetainedVerts(Vec<Barycentric>& vertBary,
const Vec<Halfedge>& halfedge_) {
void FillRetainedVerts(VecDH<Barycentric>& vertBary,
const VecDH<Halfedge>& halfedge_) {
const int numTri = halfedge_.size() / 3;
for (int tri = 0; tri < numTri; ++tri) {
for (const int i : {0, 1, 2}) {
@@ -52,7 +52,7 @@ void FillRetainedVerts(Vec<Barycentric>& vertBary,
}
struct ReindexHalfedge {
VecView<int> half2Edge;
int* half2Edge;
void operator()(thrust::tuple<int, TmpEdge> in) {
const int edge = thrust::get<0>(in);
@@ -63,8 +63,8 @@ struct ReindexHalfedge {
};
struct EdgeVerts {
VecView<glm::vec3> vertPos;
VecView<Barycentric> vertBary;
glm::vec3* vertPos;
Barycentric* vertBary;
const int startIdx;
const int n;
@@ -91,11 +91,11 @@ struct EdgeVerts {
};
struct InteriorVerts {
VecView<glm::vec3> vertPos;
VecView<Barycentric> vertBary;
glm::vec3* vertPos;
Barycentric* vertBary;
const int startIdx;
const int n;
VecView<const Halfedge> halfedge;
const Halfedge* halfedge;
void operator()(int tri) {
const float invTotal = 1.0f / n;
@@ -119,9 +119,9 @@ struct InteriorVerts {
};
struct SplitTris {
VecView<glm::ivec3> triVerts;
VecView<Halfedge> halfedge;
VecView<const int> half2Edge;
glm::ivec3* triVerts;
const Halfedge* halfedge;
const int* half2Edge;
const int edgeIdx;
const int triIdx;
const int n;
@@ -182,10 +182,10 @@ struct SplitTris {
};
struct SmoothBezier {
VecView<const glm::vec3> vertPos;
VecView<const glm::vec3> triNormal;
VecView<const glm::vec3> vertNormal;
VecView<const Halfedge> halfedge;
const glm::vec3* vertPos;
const glm::vec3* triNormal;
const glm::vec3* vertNormal;
const Halfedge* halfedge;
void operator()(thrust::tuple<glm::vec4&, Halfedge> inOut) {
glm::vec4& tangent = thrust::get<0>(inOut);
@@ -212,9 +212,9 @@ struct SmoothBezier {
};
struct InterpTri {
VecView<const Halfedge> halfedge;
VecView<const glm::vec4> halfedgeTangent;
VecView<const glm::vec3> vertPos;
const Halfedge* halfedge;
const glm::vec4* halfedgeTangent;
const glm::vec3* vertPos;
glm::vec4 Homogeneous(glm::vec4 v) const {
v.x *= v.w;
@@ -325,10 +325,11 @@ void Manifold::Impl::CreateTangents(
for_each_n(autoPolicy(numHalfedge),
zip(halfedgeTangent_.begin(), halfedge_.cbegin()), numHalfedge,
SmoothBezier({vertPos_, faceNormal_, vertNormal_, halfedge_}));
SmoothBezier({vertPos_.cptrD(), faceNormal_.cptrD(),
vertNormal_.cptrD(), halfedge_.cptrD()}));
if (!sharpenedEdges.empty()) {
const Vec<TriRef>& triRef = meshRelation_.triRef;
const VecDH<TriRef>& triRef = meshRelation_.triRef;
// sharpenedEdges are referenced to the input Mesh, but the triangles have
// been sorted in creating the Manifold, so the indices are converted using
@@ -361,7 +362,7 @@ void Manifold::Impl::CreateTangents(
{edge.second, edge.first});
}
Vec<glm::vec4>& tangent = halfedgeTangent_;
VecDH<glm::vec4>& tangent = halfedgeTangent_;
for (const auto& value : vertTangents) {
const std::vector<Pair>& vert = value.second;
// Sharp edges that end are smooth at their terminal vert.
@@ -422,8 +423,8 @@ void Manifold::Impl::CreateTangents(
* run after the new vertices have moved, which is a likely scenario after
* refinement (smoothing).
*/
Vec<Barycentric> Manifold::Impl::Subdivide(int n) {
if (n < 2) return Vec<Barycentric>();
VecDH<Barycentric> Manifold::Impl::Subdivide(int n) {
if (n < 2) return VecDH<Barycentric>();
faceNormal_.resize(0);
vertNormal_.resize(0);
const int numVert = NumVert();
@@ -433,27 +434,28 @@ Vec<Barycentric> Manifold::Impl::Subdivide(int n) {
const int vertsPerEdge = n - 1;
const int triVertStart = numVert + numEdge * vertsPerEdge;
vertPos_.resize(triVertStart + numTri * VertsPerTri(n - 2));
Vec<Barycentric> vertBary(vertPos_.size());
VecDH<Barycentric> vertBary(vertPos_.size());
FillRetainedVerts(vertBary, halfedge_);
MeshRelationD oldMeshRelation = std::move(meshRelation_);
meshRelation_.triRef.resize(n * n * numTri);
meshRelation_.originalID = oldMeshRelation.originalID;
Vec<TmpEdge> edges = CreateTmpEdges(halfedge_);
Vec<int> half2Edge(2 * numEdge);
VecDH<TmpEdge> edges = CreateTmpEdges(halfedge_);
VecDH<int> half2Edge(2 * numEdge);
auto policy = autoPolicy(numEdge);
for_each_n(policy, zip(countAt(0), edges.begin()), numEdge,
ReindexHalfedge({half2Edge}));
ReindexHalfedge({half2Edge.ptrD()}));
for_each_n(policy, zip(countAt(0), edges.begin()), numEdge,
EdgeVerts({vertPos_, vertBary, numVert, n}));
EdgeVerts({vertPos_.ptrD(), vertBary.ptrD(), numVert, n}));
for_each_n(policy, countAt(0), numTri,
InteriorVerts({vertPos_, vertBary, triVertStart, n, halfedge_}));
InteriorVerts({vertPos_.ptrD(), vertBary.ptrD(), triVertStart, n,
halfedge_.cptrD()}));
// Create sub-triangles
Vec<glm::ivec3> triVerts(n * n * numTri);
for_each_n(
policy, countAt(0), numTri,
SplitTris({triVerts, halfedge_, half2Edge, numVert, triVertStart, n}));
VecDH<glm::ivec3> triVerts(n * n * numTri);
for_each_n(policy, countAt(0), numTri,
SplitTris({triVerts.ptrD(), halfedge_.cptrD(), half2Edge.cptrD(),
numVert, triVertStart, n}));
CreateHalfedges(triVerts);
// Make original since the subdivided faces are intended to be warped into
// being non-coplanar, and hence not being related to the original faces.
@@ -473,13 +475,14 @@ Vec<Barycentric> Manifold::Impl::Subdivide(int n) {
void Manifold::Impl::Refine(int n) {
Manifold::Impl old = *this;
Vec<Barycentric> vertBary = Subdivide(n);
VecDH<Barycentric> vertBary = Subdivide(n);
if (vertBary.size() == 0) return;
if (old.halfedgeTangent_.size() == old.halfedge_.size()) {
for_each_n(autoPolicy(NumTri()), zip(vertPos_.begin(), vertBary.begin()),
NumVert(),
InterpTri({old.halfedge_, old.halfedgeTangent_, old.vertPos_}));
InterpTri({old.halfedge_.cptrD(), old.halfedgeTangent_.cptrD(),
old.vertPos_.cptrD()}));
}
halfedgeTangent_.resize(0);
+93 -85
View File
@@ -12,10 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <thrust/sequence.h>
#include <atomic>
#include <numeric>
#include <set>
#include "graph.h"
#include "impl.h"
#include "par.h"
@@ -79,8 +82,8 @@ struct Morton {
};
struct FaceMortonBox {
VecView<const Halfedge> halfedge;
VecView<const glm::vec3> vertPos;
const Halfedge* halfedge;
const glm::vec3* vertPos;
const Box bBox;
void operator()(thrust::tuple<uint32_t&, Box&, int> inout) {
@@ -110,7 +113,7 @@ struct FaceMortonBox {
};
struct Reindex {
VecView<const int> indexInv;
const int* indexInv;
void operator()(Halfedge& edge) {
if (edge.startVert < 0) return;
@@ -120,19 +123,19 @@ struct Reindex {
};
struct MarkProp {
VecView<int> keep;
int* keep;
void operator()(glm::ivec3 triProp) {
for (const int i : {0, 1, 2}) {
reinterpret_cast<std::atomic<int>*>(&keep[triProp[i]])
->store(1, std::memory_order_relaxed);
reinterpret_cast<std::atomic<int>*>(keep)[triProp[i]].store(
1, std::memory_order_relaxed);
}
}
};
struct GatherProps {
VecView<float> properties;
VecView<const float> oldProperties;
float* properties;
const float* oldProperties;
const int numProp;
void operator()(thrust::tuple<int, int, int> in) {
@@ -147,7 +150,7 @@ struct GatherProps {
};
struct ReindexProps {
VecView<const int> old2new;
const int* old2new;
void operator()(glm::ivec3& triProp) {
for (const int i : {0, 1, 2}) {
@@ -157,23 +160,23 @@ struct ReindexProps {
};
template <typename T>
void Permute(Vec<T>& inOut, const Vec<int>& new2Old) {
Vec<T> tmp(std::move(inOut));
void Permute(VecDH<T>& inOut, const VecDH<int>& new2Old) {
VecDH<T> tmp(std::move(inOut));
inOut.resize(new2Old.size());
gather(autoPolicy(new2Old.size()), new2Old.begin(), new2Old.end(),
tmp.begin(), inOut.begin());
}
template void Permute<TriRef>(Vec<TriRef>&, const Vec<int>&);
template void Permute<glm::vec3>(Vec<glm::vec3>&, const Vec<int>&);
template void Permute<TriRef>(VecDH<TriRef>&, const VecDH<int>&);
template void Permute<glm::vec3>(VecDH<glm::vec3>&, const VecDH<int>&);
struct ReindexFace {
VecView<Halfedge> halfedge;
VecView<glm::vec4> halfedgeTangent;
VecView<const Halfedge> oldHalfedge;
VecView<const glm::vec4> oldHalfedgeTangent;
VecView<const int> faceNew2Old;
VecView<const int> faceOld2New;
Halfedge* halfedge;
glm::vec4* halfedgeTangent;
const Halfedge* oldHalfedge;
const glm::vec4* oldHalfedgeTangent;
const int* faceNew2Old;
const int* faceOld2New;
void operator()(int newFace) {
const int oldFace = faceNew2Old[newFace];
@@ -186,7 +189,7 @@ struct ReindexFace {
edge.pairedHalfedge = 3 * faceOld2New[pairedFace] + offset;
const int newEdge = 3 * newFace + i;
halfedge[newEdge] = edge;
if (!oldHalfedgeTangent.empty()) {
if (oldHalfedgeTangent != nullptr) {
halfedgeTangent[newEdge] = oldHalfedgeTangent[oldEdge];
}
}
@@ -194,7 +197,7 @@ struct ReindexFace {
};
struct VertMortonBox {
VecView<const float> vertProperties;
const float* vertProperties;
const uint32_t numProp;
const float tol;
const Box bBox;
@@ -251,8 +254,8 @@ void Manifold::Impl::Finish() {
}
SortVerts();
Vec<Box> faceBox;
Vec<uint32_t> faceMorton;
VecDH<Box> faceBox;
VecDH<uint32_t> faceMorton;
GetFaceBoxMorton(faceBox, faceMorton);
SortFaces(faceBox, faceMorton);
if (halfedge_.size() == 0) return;
@@ -301,27 +304,24 @@ void Manifold::Impl::Finish() {
*/
void Manifold::Impl::SortVerts() {
const int numVert = NumVert();
Vec<uint32_t> vertMorton(numVert);
VecDH<uint32_t> vertMorton(numVert);
auto policy = autoPolicy(numVert);
for_each_n(policy, zip(vertMorton.begin(), vertPos_.cbegin()), numVert,
Morton({bBox_}));
Vec<int> vertNew2Old(numVert);
VecDH<int> vertNew2Old(numVert);
sequence(policy, vertNew2Old.begin(), vertNew2Old.end());
stable_sort(policy, zip(vertMorton.begin(), vertNew2Old.begin()),
zip(vertMorton.end(), vertNew2Old.end()),
[](const thrust::tuple<uint32_t, int>& a,
const thrust::tuple<uint32_t, int>& b) {
return thrust::get<0>(a) < thrust::get<0>(b);
});
sort_by_key(policy, vertMorton.begin(), vertMorton.end(),
vertNew2Old.begin());
ReindexVerts(vertNew2Old, numVert);
// Verts were flagged for removal with NaNs and assigned kNoCode to sort
// them to the end, which allows them to be removed.
const int newNumVert =
std::lower_bound(vertMorton.begin(), vertMorton.end(), kNoCode) -
lower_bound<decltype(vertMorton.begin())>(policy, vertMorton.begin(),
vertMorton.end(), kNoCode) -
vertMorton.begin();
vertNew2Old.resize(newNumVert);
@@ -337,12 +337,13 @@ void Manifold::Impl::SortVerts() {
* vertNew2Old. This may be a subset, so the total number of original verts is
* also given.
*/
void Manifold::Impl::ReindexVerts(const Vec<int>& vertNew2Old, int oldNumVert) {
Vec<int> vertOld2New(oldNumVert);
void Manifold::Impl::ReindexVerts(const VecDH<int>& vertNew2Old,
int oldNumVert) {
VecDH<int> vertOld2New(oldNumVert);
scatter(autoPolicy(oldNumVert), countAt(0), countAt(NumVert()),
vertNew2Old.begin(), vertOld2New.begin());
for_each(autoPolicy(oldNumVert), halfedge_.begin(), halfedge_.end(),
Reindex({vertOld2New}));
Reindex({vertOld2New.cptrD()}));
}
/**
@@ -352,22 +353,23 @@ void Manifold::Impl::CompactProps() {
if (meshRelation_.numProp == 0) return;
const int numVerts = meshRelation_.properties.size() / meshRelation_.numProp;
Vec<int> keep(numVerts, 0);
VecDH<int> keep(numVerts, 0);
auto policy = autoPolicy(numVerts);
for_each(policy, meshRelation_.triProperties.cbegin(),
meshRelation_.triProperties.cend(), MarkProp({keep}));
Vec<int> propOld2New(numVerts + 1, 0);
meshRelation_.triProperties.cend(), MarkProp({keep.ptrD()}));
VecDH<int> propOld2New(numVerts + 1, 0);
inclusive_scan(policy, keep.begin(), keep.end(), propOld2New.begin() + 1);
Vec<float> oldProp = meshRelation_.properties;
VecDH<float> oldProp = meshRelation_.properties;
const int numVertsNew = propOld2New[numVerts];
meshRelation_.properties.resize(meshRelation_.numProp * numVertsNew);
for_each_n(
policy, zip(countAt(0), propOld2New.cbegin(), keep.cbegin()), numVerts,
GatherProps({meshRelation_.properties, oldProp, meshRelation_.numProp}));
for_each_n(policy, zip(countAt(0), propOld2New.cbegin(), keep.cbegin()),
numVerts,
GatherProps({meshRelation_.properties.ptrD(), oldProp.cptrD(),
meshRelation_.numProp}));
for_each_n(policy, meshRelation_.triProperties.begin(), NumTri(),
ReindexProps({propOld2New}));
ReindexProps({propOld2New.cptrD()}));
}
/**
@@ -375,30 +377,27 @@ void Manifold::Impl::CompactProps() {
* codes of the faces, respectively. The Morton code is based on the center of
* the bounding box.
*/
void Manifold::Impl::GetFaceBoxMorton(Vec<Box>& faceBox,
Vec<uint32_t>& faceMorton) const {
void Manifold::Impl::GetFaceBoxMorton(VecDH<Box>& faceBox,
VecDH<uint32_t>& faceMorton) const {
faceBox.resize(NumTri());
faceMorton.resize(NumTri());
for_each_n(autoPolicy(NumTri()),
zip(faceMorton.begin(), faceBox.begin(), countAt(0)), NumTri(),
FaceMortonBox({halfedge_, vertPos_, bBox_}));
FaceMortonBox({halfedge_.cptrD(), vertPos_.cptrD(), bBox_}));
}
/**
* Sorts the faces of this manifold according to their input Morton code. The
* bounding box and Morton code arrays are also sorted accordingly.
*/
void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) {
Vec<int> faceNew2Old(NumTri());
void Manifold::Impl::SortFaces(VecDH<Box>& faceBox,
VecDH<uint32_t>& faceMorton) {
VecDH<int> faceNew2Old(NumTri());
auto policy = autoPolicy(faceNew2Old.size());
sequence(policy, faceNew2Old.begin(), faceNew2Old.end());
stable_sort(policy, zip(faceMorton.begin(), faceNew2Old.begin()),
zip(faceMorton.end(), faceNew2Old.end()),
[](const thrust::tuple<uint32_t, int>& a,
const thrust::tuple<uint32_t, int>& b) {
return thrust::get<0>(a) < thrust::get<0>(b);
});
sort_by_key(policy, faceMorton.begin(), faceMorton.end(),
faceNew2Old.begin());
// Tris were flagged for removal with pairedHalfedge = -1 and assigned kNoCode
// to sort them to the end, which allows them to be removed.
@@ -418,7 +417,7 @@ void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) {
* another manifold, given by oldHalfedge. Input faceNew2Old defines the old
* faces to gather into this.
*/
void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old) {
void Manifold::Impl::GatherFaces(const VecDH<int>& faceNew2Old) {
const int numTri = faceNew2Old.size();
if (meshRelation_.triRef.size() == NumTri())
Permute(meshRelation_.triRef, faceNew2Old);
@@ -426,9 +425,9 @@ void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old) {
Permute(meshRelation_.triProperties, faceNew2Old);
if (faceNormal_.size() == NumTri()) Permute(faceNormal_, faceNew2Old);
Vec<Halfedge> oldHalfedge(std::move(halfedge_));
Vec<glm::vec4> oldHalfedgeTangent(std::move(halfedgeTangent_));
Vec<int> faceOld2New(oldHalfedge.size() / 3);
VecDH<Halfedge> oldHalfedge(std::move(halfedge_));
VecDH<glm::vec4> oldHalfedgeTangent(std::move(halfedgeTangent_));
VecDH<int> faceOld2New(oldHalfedge.size() / 3);
auto policy = autoPolicy(numTri);
scatter(policy, countAt(0), countAt(numTri), faceNew2Old.begin(),
faceOld2New.begin());
@@ -436,11 +435,13 @@ void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old) {
halfedge_.resize(3 * numTri);
if (oldHalfedgeTangent.size() != 0) halfedgeTangent_.resize(3 * numTri);
for_each_n(policy, countAt(0), numTri,
ReindexFace({halfedge_, halfedgeTangent_, oldHalfedge,
oldHalfedgeTangent, faceNew2Old, faceOld2New}));
ReindexFace({halfedge_.ptrD(), halfedgeTangent_.ptrD(),
oldHalfedge.cptrD(), oldHalfedgeTangent.cptrD(),
faceNew2Old.cptrD(), faceOld2New.cptrD()}));
}
void Manifold::Impl::GatherFaces(const Impl& old, const Vec<int>& faceNew2Old) {
void Manifold::Impl::GatherFaces(const Impl& old,
const VecDH<int>& faceNew2Old) {
const int numTri = faceNew2Old.size();
auto policy = autoPolicy(numTri);
@@ -466,15 +467,16 @@ void Manifold::Impl::GatherFaces(const Impl& old, const Vec<int>& faceNew2Old) {
old.faceNormal_.begin(), faceNormal_.begin());
}
Vec<int> faceOld2New(old.NumTri());
VecDH<int> faceOld2New(old.NumTri());
scatter(policy, countAt(0), countAt(numTri), faceNew2Old.begin(),
faceOld2New.begin());
halfedge_.resize(3 * numTri);
if (old.halfedgeTangent_.size() != 0) halfedgeTangent_.resize(3 * numTri);
for_each_n(policy, countAt(0), numTri,
ReindexFace({halfedge_, halfedgeTangent_, old.halfedge_,
old.halfedgeTangent_, faceNew2Old, faceOld2New}));
ReindexFace({halfedge_.ptrD(), halfedgeTangent_.ptrD(),
old.halfedge_.cptrD(), old.halfedgeTangent_.cptrD(),
faceNew2Old.cptrD(), faceOld2New.cptrD()}));
}
/// Constructs a position-only MeshGL from the input Mesh.
@@ -540,18 +542,18 @@ bool MeshGL::Merge() {
}
const int numOpenVert = openEdges.size();
Vec<int> openVerts(numOpenVert);
VecDH<int> openVerts(numOpenVert);
int i = 0;
for (const auto& edge : openEdges) {
const int vert = edge.first;
openVerts[i++] = vert;
}
Vec<float> vertPropD(vertProperties);
VecDH<float> vertPropD(vertProperties);
Box bBox;
for (const int i : {0, 1, 2}) {
strided_range<Vec<float>::Iter> iPos(vertPropD.begin() + i, vertPropD.end(),
numProp);
strided_range<VecDH<float>::Iter> iPos(vertPropD.begin() + i,
vertPropD.end(), numProp);
auto minMax = transform_reduce<thrust::pair<float, float>>(
autoPolicy(numVert), iPos.begin(), iPos.end(), Duplicate(),
thrust::make_pair(std::numeric_limits<float>::infinity(),
@@ -564,38 +566,44 @@ bool MeshGL::Merge() {
if (precision < 0) return false;
auto policy = autoPolicy(numOpenVert);
Vec<Box> vertBox(numOpenVert);
Vec<uint32_t> vertMorton(numOpenVert);
VecDH<Box> vertBox(numOpenVert);
VecDH<uint32_t> vertMorton(numOpenVert);
for_each_n(policy,
zip(vertMorton.begin(), vertBox.begin(), openVerts.cbegin()),
numOpenVert, VertMortonBox({vertPropD, numProp, precision, bBox}));
numOpenVert,
VertMortonBox({vertPropD.cptrD(), numProp, precision, bBox}));
stable_sort(policy,
zip(vertMorton.begin(), vertBox.begin(), openVerts.begin()),
zip(vertMorton.end(), vertBox.end(), openVerts.end()),
[](const thrust::tuple<uint32_t, Box, int>& a,
const thrust::tuple<uint32_t, Box, int>& b) {
return thrust::get<0>(a) < thrust::get<0>(b);
});
sort_by_key(policy, vertMorton.begin(), vertMorton.end(),
zip(vertBox.begin(), openVerts.begin()));
Collider collider(vertBox, vertMorton);
SparseIndices toMerge = collider.Collisions<true>(vertBox.cview());
SparseIndices toMerge = collider.Collisions<true>(vertBox);
UnionFind<> uf(numVert);
Graph graph;
for (int i = 0; i < numVert; ++i) {
graph.add_nodes(i);
}
for (int i = 0; i < mergeFromVert.size(); ++i) {
uf.unionXY(static_cast<int>(mergeFromVert[i]),
static_cast<int>(mergeToVert[i]));
graph.add_edge(static_cast<int>(mergeFromVert[i]),
static_cast<int>(mergeToVert[i]));
}
for (int i = 0; i < toMerge.size(); ++i) {
uf.unionXY(openVerts[toMerge.Get(i, false)],
openVerts[toMerge.Get(i, true)]);
graph.add_edge(openVerts[toMerge.Get(i, false)],
openVerts[toMerge.Get(i, true)]);
}
std::vector<int> vertLabels;
const int numLabels = ConnectedComponents(vertLabels, graph);
std::vector<int> label2vert(numLabels);
for (int v = 0; v < numVert; ++v) {
label2vert[vertLabels[v]] = v;
}
mergeToVert.clear();
mergeFromVert.clear();
for (int v = 0; v < numVert; ++v) {
const int mergeTo = uf.find(v);
const int mergeTo = label2vert[vertLabels[v]];
if (mergeTo != v) {
mergeFromVert.push_back(v);
mergeToVert.push_back(mergeTo);
File diff suppressed because it is too large Load Diff
+3 -17
View File
@@ -14,25 +14,11 @@
project(sdf)
add_library(${PROJECT_NAME} src/sdf.cpp)
add_library(${PROJECT_NAME} INTERFACE)
target_include_directories(${PROJECT_NAME}
PUBLIC
INTERFACE
${PROJECT_SOURCE_DIR}/include
)
target_link_libraries(${PROJECT_NAME} PUBLIC utilities)
target_compile_options(${PROJECT_NAME} PRIVATE ${MANIFOLD_FLAGS})
install(
TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}
COMPONENT runtime
)
install(
DIRECTORY include/
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
COMPONENT devel
)
target_link_libraries(${PROJECT_NAME} INTERFACE utilities)
+355 -5
View File
@@ -1,4 +1,4 @@
// Copyright 2023 The Manifold Authors.
// 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.
@@ -14,11 +14,361 @@
#pragma once
#include <functional>
#include "hashtable.h"
#include "optional"
#include "par.h"
#include "public.h"
#include "utils.h"
#include "vec_dh.h"
namespace {
using namespace manifold;
Uint64 identity(Uint64 x) { return x; }
glm::ivec3 TetTri0(int i) {
constexpr glm::ivec3 tetTri0[16] = {{-1, -1, -1}, //
{0, 3, 4}, //
{0, 1, 5}, //
{1, 5, 3}, //
{1, 4, 2}, //
{1, 0, 3}, //
{2, 5, 0}, //
{5, 3, 2}, //
{2, 3, 5}, //
{0, 5, 2}, //
{3, 0, 1}, //
{2, 4, 1}, //
{3, 5, 1}, //
{5, 1, 0}, //
{4, 3, 0}, //
{-1, -1, -1}};
return tetTri0[i];
}
glm::ivec3 TetTri1(int i) {
constexpr glm::ivec3 tetTri1[16] = {{-1, -1, -1}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{3, 4, 1}, //
{-1, -1, -1}, //
{3, 2, 1}, //
{0, 4, 2}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{2, 4, 0}, //
{1, 2, 3}, //
{-1, -1, -1}, //
{1, 4, 3}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{-1, -1, -1}};
return tetTri1[i];
}
glm::ivec4 Neighbors(int i) {
constexpr glm::ivec4 neighbors[7] = {{0, 0, 0, 1}, //
{1, 0, 0, 0}, //
{0, 1, 0, 0}, //
{0, 0, 1, 0}, //
{-1, 0, 0, 1}, //
{0, -1, 0, 1}, //
{0, 0, -1, 1}};
return neighbors[i];
}
Uint64 SpreadBits3(Uint64 v) {
v = v & 0x1fffff;
v = (v | v << 32) & 0x1f00000000ffff;
v = (v | v << 16) & 0x1f0000ff0000ff;
v = (v | v << 8) & 0x100f00f00f00f00f;
v = (v | v << 4) & 0x10c30c30c30c30c3;
v = (v | v << 2) & 0x1249249249249249;
return v;
}
Uint64 SqueezeBits3(Uint64 v) {
v = v & 0x1249249249249249;
v = (v ^ v >> 2) & 0x10c30c30c30c30c3;
v = (v ^ v >> 4) & 0x100f00f00f00f00f;
v = (v ^ v >> 8) & 0x1f0000ff0000ff;
v = (v ^ v >> 16) & 0x1f00000000ffff;
v = (v ^ v >> 32) & 0x1fffff;
return v;
}
// This is a modified 3D MortonCode, where the xyz code is shifted by one bit
// and the w bit is added as the least significant. This allows 21 bits per x,
// y, and z channel and 1 for w, filling the 64 bit total.
Uint64 MortonCode(const glm::ivec4& index) {
return static_cast<Uint64>(index.w) | (SpreadBits3(index.x) << 1) |
(SpreadBits3(index.y) << 2) | (SpreadBits3(index.z) << 3);
}
glm::ivec4 DecodeMorton(Uint64 code) {
glm::ivec4 index;
index.x = SqueezeBits3(code >> 1);
index.y = SqueezeBits3(code >> 2);
index.z = SqueezeBits3(code >> 3);
index.w = code & 0x1u;
return index;
}
struct GridVert {
float distance = NAN;
int edgeVerts[7] = {-1, -1, -1, -1, -1, -1, -1};
int Inside() const { return distance > 0 ? 1 : -1; }
int NeighborInside(int i) const {
return Inside() * (edgeVerts[i] < 0 ? 1 : -1);
}
};
template <typename Func>
struct ComputeVerts {
glm::vec3* vertPos;
int* vertIndex;
HashTableD<GridVert, identity> gridVerts;
const Func sdf;
const glm::vec3 origin;
const glm::ivec3 gridSize;
const glm::vec3 spacing;
const float level;
inline glm::vec3 Position(glm::ivec4 gridIndex) const {
return origin +
spacing * (glm::vec3(gridIndex) + (gridIndex.w == 1 ? 0.0f : -0.5f));
}
inline float BoundedSDF(glm::ivec4 gridIndex) const {
const float d = sdf(Position(gridIndex)) - level;
const glm::ivec3 xyz(gridIndex);
const bool onLowerBound = glm::any(glm::lessThanEqual(xyz, glm::ivec3(0)));
const bool onUpperBound = glm::any(glm::greaterThanEqual(xyz, gridSize));
const bool onHalfBound =
gridIndex.w == 1 && glm::any(glm::greaterThanEqual(xyz, gridSize - 1));
if (onLowerBound || onUpperBound || onHalfBound) return glm::min(d, 0.0f);
return d;
}
inline void operator()(Uint64 mortonCode) {
if (gridVerts.Full()) return;
const glm::ivec4 gridIndex = DecodeMorton(mortonCode);
if (glm::any(glm::greaterThan(glm::ivec3(gridIndex), gridSize))) return;
const glm::vec3 position = Position(gridIndex);
GridVert gridVert;
gridVert.distance = BoundedSDF(gridIndex);
bool keep = false;
// These seven edges are uniquely owned by this gridVert; any of them
// which intersect the surface create a vert.
for (int i = 0; i < 7; ++i) {
glm::ivec4 neighborIndex = gridIndex + Neighbors(i);
if (neighborIndex.w == 2) {
neighborIndex += 1;
neighborIndex.w = 0;
}
const float val = BoundedSDF(neighborIndex);
if ((val > 0) == (gridVert.distance > 0)) continue;
keep = true;
const int idx = AtomicAdd(*vertIndex, 1);
vertPos[idx] =
(val * position - gridVert.distance * Position(neighborIndex)) /
(val - gridVert.distance);
gridVert.edgeVerts[i] = idx;
}
if (keep) gridVerts.Insert(mortonCode, gridVert);
}
};
struct BuildTris {
glm::ivec3* triVerts;
int* triIndex;
const HashTableD<GridVert, identity> gridVerts;
void CreateTri(const glm::ivec3& tri, const int edges[6]) {
if (tri[0] < 0) return;
int idx = AtomicAdd(*triIndex, 1);
triVerts[idx] = {edges[tri[0]], edges[tri[1]], edges[tri[2]]};
}
void CreateTris(const glm::ivec4& tet, const int edges[6]) {
const int i = (tet[0] > 0 ? 1 : 0) + (tet[1] > 0 ? 2 : 0) +
(tet[2] > 0 ? 4 : 0) + (tet[3] > 0 ? 8 : 0);
CreateTri(TetTri0(i), edges);
CreateTri(TetTri1(i), edges);
}
void operator()(int idx) {
Uint64 basekey = gridVerts.KeyAt(idx);
if (basekey == kOpen) return;
const GridVert& base = gridVerts.At(idx);
const glm::ivec4 baseIndex = DecodeMorton(basekey);
glm::ivec4 leadIndex = baseIndex;
if (leadIndex.w == 0)
leadIndex.w = 1;
else {
leadIndex += 1;
leadIndex.w = 0;
}
// This GridVert is in charge of the 6 tetrahedra surrounding its edge in
// the (1,1,1) direction (edge 0).
glm::ivec4 tet(base.NeighborInside(0), base.Inside(), -2, -2);
glm::ivec4 thisIndex = baseIndex;
thisIndex.x += 1;
GridVert thisVert = gridVerts[MortonCode(thisIndex)];
tet[2] = base.NeighborInside(1);
for (const int i : {0, 1, 2}) {
thisIndex = leadIndex;
--thisIndex[Prev3(i)];
// MortonCodes take unsigned input, so check for negatives, given the
// decrement.
GridVert nextVert = thisIndex[Prev3(i)] < 0
? GridVert()
: gridVerts[MortonCode(thisIndex)];
tet[3] = base.NeighborInside(Prev3(i) + 4);
const int edges1[6] = {base.edgeVerts[0],
base.edgeVerts[i + 1],
nextVert.edgeVerts[Next3(i) + 4],
nextVert.edgeVerts[Prev3(i) + 1],
thisVert.edgeVerts[i + 4],
base.edgeVerts[Prev3(i) + 4]};
thisVert = nextVert;
CreateTris(tet, edges1);
thisIndex = baseIndex;
++thisIndex[Next3(i)];
nextVert = gridVerts[MortonCode(thisIndex)];
tet[2] = tet[3];
tet[3] = base.NeighborInside(Next3(i) + 1);
const int edges2[6] = {base.edgeVerts[0],
edges1[5],
thisVert.edgeVerts[i + 4],
nextVert.edgeVerts[Next3(i) + 4],
edges1[3],
base.edgeVerts[Next3(i) + 1]};
thisVert = nextVert;
CreateTris(tet, edges2);
tet[2] = tet[3];
}
}
};
template <typename Func>
void for_each_n_wrapper(ExecutionPolicy policy, int morton,
ComputeVerts<Func> cv) {
for_each_n(policy, countAt(0), morton, cv);
}
template <>
void for_each_n_wrapper<std::function<float(glm::vec3)>>(
ExecutionPolicy policy, int morton,
ComputeVerts<std::function<float(glm::vec3)>> cv) {
for_each_n(policy, countAt(0), morton, cv);
}
} // namespace
namespace manifold {
Mesh LevelSet(std::function<float(glm::vec3)> sdf, Box bounds, float edgeLength,
float level = 0, bool canParallel = true);
/** @addtogroup Core
* @{
*/
/**
* Constructs a level-set Mesh from the input Signed-Distance Function (SDF).
* This uses a form of Marching Tetrahedra (akin to Marching Cubes, but better
* for manifoldness). Instead of using a cubic grid, it uses a body-centered
* cubic grid (two shifted cubic grids). This means if your function's interior
* exceeds the given bounds, you will see a kind of egg-crate shape closing off
* the manifold, which is due to the underlying grid.
*
* @param sdf The signed-distance functor, containing this function signature:
* `float operator()(glm::vec3 point)`, which returns the
* signed distance of a given point in R^3. Positive values are inside,
* negative outside.
* @param bounds An axis-aligned box that defines the extent of the grid.
* @param edgeLength Approximate maximum edge length of the triangles in the
* final result. This affects grid spacing, and hence has a strong effect on
* performance.
* @param level You can inset your Mesh by using a positive value, or outset
* it with a negative value.
* @return Mesh This class does not depend on Manifold, so it just returns a
* Mesh, but it is guaranteed to be manifold and so can always be used as
* input to the Manifold constructor for further operations.
*/
template <typename Func>
inline Mesh LevelSet(Func sdf, Box bounds, float edgeLength, float level = 0,
std::optional<ExecutionPolicy> policy = std::nullopt) {
Mesh out;
const glm::vec3 dim = bounds.Size();
const float maxDim = std::max(dim[0], std::max(dim[1], dim[2]));
const glm::ivec3 gridSize(dim / edgeLength);
const glm::vec3 spacing = dim / (glm::vec3(gridSize));
const Uint64 maxMorton = MortonCode(glm::ivec4(gridSize + 1, 1));
// Parallel policies violate will crash language runtimes with runtime locks
// that expect to not be called back by unregistered threads. This allows
// bindings use LevelSet despite being compiled with MANIFOLD_PAR
// active.
const auto pol = !policy.has_value() ? autoPolicy(maxMorton) : policy.value();
int tableSize = glm::min(
2 * maxMorton, static_cast<Uint64>(10 * glm::pow(maxMorton, 0.667)));
HashTable<GridVert, identity> gridVerts(tableSize);
VecDH<glm::vec3> vertPos(gridVerts.Size() * 7);
while (1) {
VecDH<int> index(1, 0);
for_each_n_wrapper<Func>(
pol, maxMorton + 1,
ComputeVerts<Func>({vertPos.ptrD(), index.ptrD(), gridVerts.D(), sdf,
bounds.min, gridSize + 1, spacing, level}));
if (gridVerts.Full()) { // Resize HashTable
const glm::vec3 lastVert = vertPos[index[0] - 1];
const Uint64 lastMorton =
MortonCode(glm::ivec4((lastVert - bounds.min) / spacing, 1));
const float ratio = static_cast<float>(maxMorton) / lastMorton;
if (ratio > 1000) // do not trust the ratio if it is too large
tableSize *= 2;
else
tableSize *= ratio;
gridVerts = HashTable<GridVert, identity>(tableSize);
vertPos = VecDH<glm::vec3>(gridVerts.Size() * 7);
} else { // Success
vertPos.resize(index[0]);
break;
}
}
VecDH<glm::ivec3> triVerts(gridVerts.Entries() * 12); // worst case
VecDH<int> index(1, 0);
for_each_n(pol, countAt(0), gridVerts.Size(),
BuildTris({triVerts.ptrD(), index.ptrD(), gridVerts.D()}));
triVerts.resize(index[0]);
out.vertPos.insert(out.vertPos.end(), vertPos.begin(), vertPos.end());
out.triVerts.insert(out.triVerts.end(), triVerts.begin(), triVerts.end());
return out;
}
/** @} */
} // namespace manifold
-360
View File
@@ -1,360 +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.
#include "sdf.h"
#include "hashtable.h"
#include "par.h"
#include "utils.h"
#include "vec.h"
namespace {
using namespace manifold;
Uint64 identity(Uint64 x) { return x; }
glm::ivec3 TetTri0(int i) {
constexpr glm::ivec3 tetTri0[16] = {{-1, -1, -1}, //
{0, 3, 4}, //
{0, 1, 5}, //
{1, 5, 3}, //
{1, 4, 2}, //
{1, 0, 3}, //
{2, 5, 0}, //
{5, 3, 2}, //
{2, 3, 5}, //
{0, 5, 2}, //
{3, 0, 1}, //
{2, 4, 1}, //
{3, 5, 1}, //
{5, 1, 0}, //
{4, 3, 0}, //
{-1, -1, -1}};
return tetTri0[i];
}
glm::ivec3 TetTri1(int i) {
constexpr glm::ivec3 tetTri1[16] = {{-1, -1, -1}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{3, 4, 1}, //
{-1, -1, -1}, //
{3, 2, 1}, //
{0, 4, 2}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{2, 4, 0}, //
{1, 2, 3}, //
{-1, -1, -1}, //
{1, 4, 3}, //
{-1, -1, -1}, //
{-1, -1, -1}, //
{-1, -1, -1}};
return tetTri1[i];
}
glm::ivec4 Neighbors(int i) {
constexpr glm::ivec4 neighbors[7] = {{0, 0, 0, 1}, //
{1, 0, 0, 0}, //
{0, 1, 0, 0}, //
{0, 0, 1, 0}, //
{-1, 0, 0, 1}, //
{0, -1, 0, 1}, //
{0, 0, -1, 1}};
return neighbors[i];
}
Uint64 SpreadBits3(Uint64 v) {
v = v & 0x1fffff;
v = (v | v << 32) & 0x1f00000000ffff;
v = (v | v << 16) & 0x1f0000ff0000ff;
v = (v | v << 8) & 0x100f00f00f00f00f;
v = (v | v << 4) & 0x10c30c30c30c30c3;
v = (v | v << 2) & 0x1249249249249249;
return v;
}
Uint64 SqueezeBits3(Uint64 v) {
v = v & 0x1249249249249249;
v = (v ^ v >> 2) & 0x10c30c30c30c30c3;
v = (v ^ v >> 4) & 0x100f00f00f00f00f;
v = (v ^ v >> 8) & 0x1f0000ff0000ff;
v = (v ^ v >> 16) & 0x1f00000000ffff;
v = (v ^ v >> 32) & 0x1fffff;
return v;
}
// This is a modified 3D MortonCode, where the xyz code is shifted by one bit
// and the w bit is added as the least significant. This allows 21 bits per x,
// y, and z channel and 1 for w, filling the 64 bit total.
Uint64 MortonCode(const glm::ivec4& index) {
return static_cast<Uint64>(index.w) | (SpreadBits3(index.x) << 1) |
(SpreadBits3(index.y) << 2) | (SpreadBits3(index.z) << 3);
}
glm::ivec4 DecodeMorton(Uint64 code) {
glm::ivec4 index;
index.x = SqueezeBits3(code >> 1);
index.y = SqueezeBits3(code >> 2);
index.z = SqueezeBits3(code >> 3);
index.w = code & 0x1u;
return index;
}
struct GridVert {
float distance = NAN;
int edgeVerts[7] = {-1, -1, -1, -1, -1, -1, -1};
int Inside() const { return distance > 0 ? 1 : -1; }
int NeighborInside(int i) const {
return Inside() * (edgeVerts[i] < 0 ? 1 : -1);
}
};
struct ComputeVerts {
VecView<glm::vec3> vertPos;
VecView<int> vertIndex;
HashTableD<GridVert, identity> gridVerts;
const std::function<float(glm::vec3)> sdf;
const glm::vec3 origin;
const glm::ivec3 gridSize;
const glm::vec3 spacing;
const float level;
inline glm::vec3 Position(glm::ivec4 gridIndex) const {
return origin +
spacing * (glm::vec3(gridIndex) + (gridIndex.w == 1 ? 0.0f : -0.5f));
}
inline float BoundedSDF(glm::ivec4 gridIndex) const {
const float d = sdf(Position(gridIndex)) - level;
const glm::ivec3 xyz(gridIndex);
const bool onLowerBound = glm::any(glm::lessThanEqual(xyz, glm::ivec3(0)));
const bool onUpperBound = glm::any(glm::greaterThanEqual(xyz, gridSize));
const bool onHalfBound =
gridIndex.w == 1 && glm::any(glm::greaterThanEqual(xyz, gridSize - 1));
if (onLowerBound || onUpperBound || onHalfBound) return glm::min(d, 0.0f);
return d;
}
inline void operator()(Uint64 mortonCode) {
if (gridVerts.Full()) return;
const glm::ivec4 gridIndex = DecodeMorton(mortonCode);
if (glm::any(glm::greaterThan(glm::ivec3(gridIndex), gridSize))) return;
const glm::vec3 position = Position(gridIndex);
GridVert gridVert;
gridVert.distance = BoundedSDF(gridIndex);
bool keep = false;
// These seven edges are uniquely owned by this gridVert; any of them
// which intersect the surface create a vert.
for (int i = 0; i < 7; ++i) {
glm::ivec4 neighborIndex = gridIndex + Neighbors(i);
if (neighborIndex.w == 2) {
neighborIndex += 1;
neighborIndex.w = 0;
}
const float val = BoundedSDF(neighborIndex);
if ((val > 0) == (gridVert.distance > 0)) continue;
keep = true;
const int idx = AtomicAdd(vertIndex[0], 1);
vertPos[idx] =
(val * position - gridVert.distance * Position(neighborIndex)) /
(val - gridVert.distance);
gridVert.edgeVerts[i] = idx;
}
if (keep) gridVerts.Insert(mortonCode, gridVert);
}
};
struct BuildTris {
VecView<glm::ivec3> triVerts;
VecView<int> triIndex;
const HashTableD<GridVert, identity> gridVerts;
void CreateTri(const glm::ivec3& tri, const int edges[6]) {
if (tri[0] < 0) return;
int idx = AtomicAdd(triIndex[0], 1);
triVerts[idx] = {edges[tri[0]], edges[tri[1]], edges[tri[2]]};
}
void CreateTris(const glm::ivec4& tet, const int edges[6]) {
const int i = (tet[0] > 0 ? 1 : 0) + (tet[1] > 0 ? 2 : 0) +
(tet[2] > 0 ? 4 : 0) + (tet[3] > 0 ? 8 : 0);
CreateTri(TetTri0(i), edges);
CreateTri(TetTri1(i), edges);
}
void operator()(int idx) {
Uint64 basekey = gridVerts.KeyAt(idx);
if (basekey == kOpen) return;
const GridVert& base = gridVerts.At(idx);
const glm::ivec4 baseIndex = DecodeMorton(basekey);
glm::ivec4 leadIndex = baseIndex;
if (leadIndex.w == 0)
leadIndex.w = 1;
else {
leadIndex += 1;
leadIndex.w = 0;
}
// This GridVert is in charge of the 6 tetrahedra surrounding its edge in
// the (1,1,1) direction (edge 0).
glm::ivec4 tet(base.NeighborInside(0), base.Inside(), -2, -2);
glm::ivec4 thisIndex = baseIndex;
thisIndex.x += 1;
GridVert thisVert = gridVerts[MortonCode(thisIndex)];
tet[2] = base.NeighborInside(1);
for (const int i : {0, 1, 2}) {
thisIndex = leadIndex;
--thisIndex[Prev3(i)];
// MortonCodes take unsigned input, so check for negatives, given the
// decrement.
GridVert nextVert = thisIndex[Prev3(i)] < 0
? GridVert()
: gridVerts[MortonCode(thisIndex)];
tet[3] = base.NeighborInside(Prev3(i) + 4);
const int edges1[6] = {base.edgeVerts[0],
base.edgeVerts[i + 1],
nextVert.edgeVerts[Next3(i) + 4],
nextVert.edgeVerts[Prev3(i) + 1],
thisVert.edgeVerts[i + 4],
base.edgeVerts[Prev3(i) + 4]};
thisVert = nextVert;
CreateTris(tet, edges1);
thisIndex = baseIndex;
++thisIndex[Next3(i)];
nextVert = gridVerts[MortonCode(thisIndex)];
tet[2] = tet[3];
tet[3] = base.NeighborInside(Next3(i) + 1);
const int edges2[6] = {base.edgeVerts[0],
edges1[5],
thisVert.edgeVerts[i + 4],
nextVert.edgeVerts[Next3(i) + 4],
edges1[3],
base.edgeVerts[Next3(i) + 1]};
thisVert = nextVert;
CreateTris(tet, edges2);
tet[2] = tet[3];
}
}
};
} // namespace
namespace manifold {
/** @addtogroup Core
* @{
*/
/**
* Constructs a level-set Mesh from the input Signed-Distance Function (SDF).
* This uses a form of Marching Tetrahedra (akin to Marching Cubes, but better
* for manifoldness). Instead of using a cubic grid, it uses a body-centered
* cubic grid (two shifted cubic grids). This means if your function's interior
* exceeds the given bounds, you will see a kind of egg-crate shape closing off
* the manifold, which is due to the underlying grid.
*
* @param sdf The signed-distance functor, containing this function signature:
* `float operator()(glm::vec3 point)`, which returns the
* signed distance of a given point in R^3. Positive values are inside,
* negative outside.
* @param bounds An axis-aligned box that defines the extent of the grid.
* @param edgeLength Approximate maximum edge length of the triangles in the
* final result. This affects grid spacing, and hence has a strong effect on
* performance.
* @param level You can inset your Mesh by using a positive value, or outset
* it with a negative value.
* @param canParallel Parallel policies violate will crash language runtimes
* with runtime locks that expect to not be called back by unregistered threads.
* This allows bindings use LevelSet despite being compiled with MANIFOLD_PAR
* active.
* @return Mesh This class does not depend on Manifold, so it just returns a
* Mesh, but it is guaranteed to be manifold and so can always be used as
* input to the Manifold constructor for further operations.
*/
Mesh LevelSet(std::function<float(glm::vec3)> sdf, Box bounds, float edgeLength,
float level, bool canParallel) {
Mesh out;
const glm::vec3 dim = bounds.Size();
const float maxDim = std::max(dim[0], std::max(dim[1], dim[2]));
const glm::ivec3 gridSize(dim / edgeLength);
const glm::vec3 spacing = dim / (glm::vec3(gridSize));
const Uint64 maxMorton = MortonCode(glm::ivec4(gridSize + 1, 1));
// Parallel policies violate will crash language runtimes with runtime locks
// that expect to not be called back by unregistered threads. This allows
// bindings use LevelSet despite being compiled with MANIFOLD_PAR
// active.
const auto pol = canParallel ? autoPolicy(maxMorton) : ExecutionPolicy::Seq;
int tableSize = glm::min(
2 * maxMorton, static_cast<Uint64>(10 * glm::pow(maxMorton, 0.667)));
HashTable<GridVert, identity> gridVerts(tableSize);
Vec<glm::vec3> vertPos(gridVerts.Size() * 7);
while (1) {
Vec<int> index(1, 0);
for_each_n(pol, countAt(0), maxMorton + 1,
ComputeVerts({vertPos, index, gridVerts.D(), sdf, bounds.min,
gridSize + 1, spacing, level}));
if (gridVerts.Full()) { // Resize HashTable
const glm::vec3 lastVert = vertPos[index[0] - 1];
const Uint64 lastMorton =
MortonCode(glm::ivec4((lastVert - bounds.min) / spacing, 1));
const float ratio = static_cast<float>(maxMorton) / lastMorton;
if (ratio > 1000) // do not trust the ratio if it is too large
tableSize *= 2;
else
tableSize *= ratio;
gridVerts = HashTable<GridVert, identity>(tableSize);
vertPos = Vec<glm::vec3>(gridVerts.Size() * 7);
} else { // Success
vertPos.resize(index[0]);
break;
}
}
Vec<glm::ivec3> triVerts(gridVerts.Entries() * 12); // worst case
Vec<int> index(1, 0);
for_each_n(pol, countAt(0), gridVerts.Size(),
BuildTris({triVerts, index, gridVerts.D()}));
triVerts.resize(index[0]);
out.vertPos.insert(out.vertPos.end(), vertPos.begin(), vertPos.end());
out.triVerts.insert(out.triVerts.end(), triVerts.begin(), triVerts.end());
return out;
}
/** @} */
} // namespace manifold
+4
View File
@@ -1,7 +1,11 @@
add_subdirectory(glm)
add_subdirectory(graphlite)
set(CLIPPER2_UTILS OFF)
set(CLIPPER2_EXAMPLES OFF)
set(CLIPPER2_TESTS OFF)
set(CLIPPER2_USINGZ "OFF" CACHE STRING "Preempt cache default of USINGZ (we only use 2d)")
add_definitions(-D_HAS_EXCEPTIONS=0) # disable exceptions for STL
add_subdirectory(clipper2/CPP)
add_library(quickhull quickhull/QuickHull.cpp)
Vendored Submodule
+1
Submodule src/third_party/glm added at bf71a83494
+10
View File
@@ -0,0 +1,10 @@
project (graphlite)
add_library(${PROJECT_NAME} src/connected_components.cpp)
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)
+7
View File
@@ -0,0 +1,7 @@
Copyright 2021 Guohao Dou
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
// 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
//
// 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 "graph_lite.h"
namespace manifold {
typedef typename graph_lite::Graph<
int, void, void, graph_lite::EdgeDirection::UNDIRECTED,
graph_lite::MultiEdge::DISALLOWED, graph_lite::SelfLoop::DISALLOWED,
graph_lite::Map::UNORDERED_MAP, graph_lite::Container::VEC>
Graph;
int ConnectedComponents(std::vector<int>& components, const Graph& g);
} // namespace manifold
File diff suppressed because it is too large Load Diff
+53
View File
@@ -0,0 +1,53 @@
// 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
//
// 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 <deque>
#include "graph.h"
namespace manifold {
int ConnectedComponents(std::vector<int>& components, const Graph& graph) {
if (!graph.size()) {
return 0;
}
components.resize(graph.size());
std::fill(components.begin(), components.end(), -1);
std::deque<int> queue;
int numComponent = 0;
for (auto it = graph.begin(); it != graph.end(); ++it) {
const int& root = *it;
if (components[root] >= 0) continue; // skip visited nodes
// new component
components[root] = numComponent;
queue.emplace_back(root);
// traverse all connected nodes
while (!queue.empty()) {
const auto [n_begin, n_end] = graph.neighbors(queue.front());
queue.pop_front();
for (auto n_it = n_begin; n_it != n_end; ++n_it) {
const int& neighbor = *n_it;
if (components[neighbor] < 0) { // unvisited
components[neighbor] = numComponent;
queue.emplace_back(neighbor);
}
}
}
++numComponent;
}
return numComponent;
}
} // namespace manifold
Vendored Submodule
+1
Submodule src/third_party/thrust added at 3cd56842c9
+21 -54
View File
@@ -15,38 +15,23 @@
project(utilities)
add_library(${PROJECT_NAME} INTERFACE)
message("Parallel Backend: ${MANIFOLD_PAR}")
include(FetchContent)
FetchContent_Declare(glm
GIT_REPOSITORY https://github.com/g-truc/glm.git
GIT_TAG 0.9.9.8
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
FIND_PACKAGE_ARGS NAMES glm
)
FetchContent_MakeAvailable(glm)
FetchContent_Declare(Thrust
GIT_REPOSITORY https://github.com/NVIDIA/thrust.git
GIT_TAG 2.1.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
FIND_PACKAGE_ARGS NAMES Thrust
)
FetchContent_MakeAvailable(Thrust)
target_include_directories(${PROJECT_NAME} INTERFACE ${PROJECT_SOURCE_DIR}/include)
target_include_directories(${PROJECT_NAME} INTERFACE ${THRUST_INC_DIR}/dependencies/libcudacxx/include)
if (TRACY_ENABLE)
include(FetchContent)
FetchContent_Declare(tracy
GIT_REPOSITORY https://github.com/wolfpld/tracy.git
GIT_TAG v0.9.1
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(tracy)
target_link_libraries(${PROJECT_NAME} INTERFACE TracyClient)
target_compile_options(${PROJECT_NAME} INTERFACE -DTRACY_NO_CODE_TRANSFER=1)
include(FetchContent)
FetchContent_Declare(tracy
GIT_REPOSITORY https://github.com/wolfpld/tracy.git
GIT_TAG v0.9.1
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(tracy)
target_link_libraries(${PROJECT_NAME} INTERFACE TracyClient)
target_compile_options(${PROJECT_NAME} INTERFACE -DTRACY_NO_CODE_TRANSFER=1)
endif()
if(MANIFOLD_PAR STREQUAL "TBB")
@@ -60,13 +45,12 @@ if(MANIFOLD_PAR STREQUAL "TBB")
set(TBB_TEST OFF CACHE INTERNAL "" FORCE)
set(TBB_STRICT OFF CACHE INTERNAL "" FORCE)
FetchContent_Declare(TBB
GIT_REPOSITORY https://github.com/oneapi-src/oneTBB.git
GIT_TAG v2021.10.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
GIT_REPOSITORY https://github.com/oneapi-src/oneTBB.git
GIT_TAG v2021.10.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(TBB)
set_property(DIRECTORY ${TBB_SOURCE_DIR} PROPERTY EXCLUDE_FROM_ALL YES)
endif()
target_compile_options(${PROJECT_NAME} INTERFACE -DMANIFOLD_PAR='T')
if(TARGET TBB::tbb)
@@ -82,21 +66,11 @@ else()
"Should be \"TBB\" or \"NONE\"")
endif()
target_include_directories(${PROJECT_NAME} INTERFACE ${PROJECT_SOURCE_DIR}/include)
target_link_libraries(${PROJECT_NAME} INTERFACE glm::glm)
if(DEFINED Thrust_SOURCE_DIR)
target_include_directories(${PROJECT_NAME} INTERFACE
${Thrust_SOURCE_DIR}
${Thrust_SOURCE_DIR}/dependencies/libcudacxx/include
)
else()
target_include_directories(${PROJECT_NAME} INTERFACE
${THRUST_ROOT}
${THRUST_ROOT}/dependencies/libcudacxx/include
)
endif()
target_include_directories(${PROJECT_NAME} INTERFACE ${THRUST_INC_DIR})
target_link_libraries(${PROJECT_NAME} INTERFACE glm)
target_compile_options(${PROJECT_NAME} INTERFACE
target_compile_options(${PROJECT_NAME}
INTERFACE ${MANIFOLD_FLAGS}
-DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_SYSTEM_${MANIFOLD_PAR}
)
@@ -106,10 +80,3 @@ if(MANIFOLD_DEBUG)
endif()
target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_17)
install(
FILES include/public.h
DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/manifold
COMPONENT devel
)
+12 -24
View File
@@ -18,12 +18,12 @@
#include "public.h"
#include "utils.h"
#include "vec.h"
#include "vec_dh.h"
namespace {
typedef unsigned long long int Uint64;
typedef Uint64 (*hash_fun_t)(Uint64);
inline constexpr Uint64 kOpen = std::numeric_limits<Uint64>::max();
constexpr Uint64 kOpen = std::numeric_limits<Uint64>::max();
template <typename T>
T AtomicCAS(T& target, T compare, T val) {
@@ -63,7 +63,7 @@ namespace manifold {
template <typename V, hash_fun_t H = hash64bit>
class HashTableD {
public:
HashTableD(Vec<Uint64>& keys, Vec<V>& values, Vec<uint32_t>& used,
HashTableD(VecDH<Uint64>& keys, VecDH<V>& values, VecDH<uint32_t>& used,
uint32_t step = 1)
: step_{step}, keys_{keys}, values_{values}, used_{used} {}
@@ -87,18 +87,7 @@ class HashTableD {
}
}
V& operator[](Uint64 key) {
uint32_t idx = H(key) & (Size() - 1);
while (1) {
const Uint64 k = AtomicLoad(keys_[idx]);
if (k == key || k == kOpen) {
return values_[idx];
}
idx = (idx + step_) & (Size() - 1);
}
}
const V& operator[](Uint64 key) const {
V& operator[](Uint64 key) const {
uint32_t idx = H(key) & (Size() - 1);
while (1) {
const Uint64 k = AtomicLoad(keys_[idx]);
@@ -110,14 +99,13 @@ class HashTableD {
}
Uint64 KeyAt(int idx) const { return AtomicLoad(keys_[idx]); }
V& At(int idx) { return values_[idx]; }
const V& At(int idx) const { return values_[idx]; }
V& At(int idx) const { return values_[idx]; }
private:
uint32_t step_;
VecView<Uint64> keys_;
VecView<V> values_;
VecView<uint32_t> used_;
VecD<Uint64> keys_;
VecD<V> values_;
VecD<uint32_t> used_;
};
template <typename V, hash_fun_t H = hash64bit>
@@ -140,14 +128,14 @@ class HashTable {
return static_cast<float>(AtomicLoad(used_[0])) / Size();
}
Vec<V>& GetValueStore() { return values_; }
VecDH<V>& GetValueStore() { return values_; }
static Uint64 Open() { return kOpen; }
private:
Vec<Uint64> keys_;
Vec<V> values_;
Vec<uint32_t> used_ = Vec<uint32_t>(1, 0);
VecDH<Uint64> keys_;
VecDH<V> values_;
VecDH<uint32_t> used_ = VecDH<uint32_t>(1, 0);
HashTableD<V, H> table_;
};
+32 -29
View File
@@ -23,18 +23,16 @@
#include <thrust/sort.h>
#include <thrust/system/cpp/execution_policy.h>
#include <thrust/uninitialized_copy.h>
#include <algorithm>
#include <numeric>
#if MANIFOLD_PAR == 'T'
#include <thrust/unique.h>
#if MANIFOLD_PAR == 'O'
#include <thrust/system/omp/execution_policy.h>
#define MANIFOLD_PAR_NS omp
#elif MANIFOLD_PAR == 'T'
#include <thrust/system/tbb/execution_policy.h>
#if MANIFOLD_PAR == 'T' && TBB_INTERFACE_VERSION >= 10000 && \
__has_include(<pstl/glue_execution_defs.h>)
#include <algorithm>
#include <execution>
#endif
#include "tbb/tbb.h"
#include <numeric>
#define MANIFOLD_PAR_NS tbb
#else
#define MANIFOLD_PAR_NS cpp
@@ -84,9 +82,21 @@ inline constexpr ExecutionPolicy autoPolicy(int size) {
return thrust::NAME(thrust::cpp::par, args...); \
}
#if MANIFOLD_PAR != 'T' || \
(TBB_INTERFACE_VERSION >= 10000 && __has_include(<pstl/glue_execution_defs.h>))
#if MANIFOLD_PAR == 'T'
#define THRUST_DYNAMIC_BACKEND_HOST_VOID(NAME) \
template <typename... Args> \
void NAME##_host(ExecutionPolicy policy, Args... args) { \
switch (policy) { \
case ExecutionPolicy::Par: \
thrust::NAME(thrust::MANIFOLD_PAR_NS::par, args...); \
break; \
case ExecutionPolicy::Seq: \
thrust::NAME(thrust::cpp::par, args...); \
break; \
} \
}
#if MANIFOLD_PAR == 'T' && __has_include(<pstl/glue_execution_defs.h>)
// sometimes stl variant is faster
#define STL_DYNAMIC_BACKEND(NAME, RET) \
template <typename Ret = RET, typename... Args> \
Ret NAME(ExecutionPolicy policy, Args... args) { \
@@ -110,18 +120,6 @@ inline constexpr ExecutionPolicy autoPolicy(int size) {
break; \
} \
}
#else
#define STL_DYNAMIC_BACKEND(NAME, RET) \
template <typename Ret = RET, typename... Args> \
Ret NAME(ExecutionPolicy policy, Args... args) { \
return std::NAME(args...); \
}
#define STL_DYNAMIC_BACKEND_VOID(NAME) \
template <typename... Args> \
void NAME(ExecutionPolicy policy, Args... args) { \
std::NAME(args...); \
}
#endif
template <typename... Args>
void exclusive_scan(ExecutionPolicy policy, Args... args) {
@@ -146,14 +144,10 @@ template <typename DerivedPolicy, typename InputIterator1,
OutputIterator copy_if(ExecutionPolicy policy, InputIterator1 first,
InputIterator1 last, OutputIterator result,
Predicate pred) {
#if MANIFOLD_PAR == 'T'
if (policy == ExecutionPolicy::Seq)
return std::copy_if(first, last, result, pred);
else
return std::copy_if(std::execution::par_unseq, first, last, result, pred);
#else
return std::copy_if(first, last, result, pred);
#endif
}
#else
@@ -164,12 +158,17 @@ THRUST_DYNAMIC_BACKEND_VOID(exclusive_scan)
THRUST_DYNAMIC_BACKEND(copy_if, void)
#endif
THRUST_DYNAMIC_BACKEND_HOST_VOID(for_each)
THRUST_DYNAMIC_BACKEND_HOST_VOID(for_each_n)
THRUST_DYNAMIC_BACKEND_VOID(gather)
THRUST_DYNAMIC_BACKEND_VOID(scatter)
THRUST_DYNAMIC_BACKEND_VOID(for_each)
THRUST_DYNAMIC_BACKEND_VOID(for_each_n)
THRUST_DYNAMIC_BACKEND_VOID(sequence)
STL_DYNAMIC_BACKEND_VOID(transform)
THRUST_DYNAMIC_BACKEND_VOID(sort_by_key)
THRUST_DYNAMIC_BACKEND_VOID(stable_sort_by_key)
THRUST_DYNAMIC_BACKEND_VOID(transform)
STL_DYNAMIC_BACKEND_VOID(uninitialized_fill)
STL_DYNAMIC_BACKEND_VOID(uninitialized_copy)
STL_DYNAMIC_BACKEND_VOID(stable_sort)
@@ -177,12 +176,14 @@ STL_DYNAMIC_BACKEND_VOID(fill)
STL_DYNAMIC_BACKEND_VOID(copy)
STL_DYNAMIC_BACKEND_VOID(inclusive_scan)
STL_DYNAMIC_BACKEND_VOID(copy_n)
STL_DYNAMIC_BACKEND_VOID(sort)
// void implies that the user have to specify the return type in the template
// argument, as we are unable to deduce it
THRUST_DYNAMIC_BACKEND(transform_reduce, void)
THRUST_DYNAMIC_BACKEND(gather_if, void)
THRUST_DYNAMIC_BACKEND(reduce_by_key, void)
THRUST_DYNAMIC_BACKEND(lower_bound, void)
STL_DYNAMIC_BACKEND(remove, void)
STL_DYNAMIC_BACKEND(find, void)
STL_DYNAMIC_BACKEND(find_if, void)
@@ -190,6 +191,8 @@ STL_DYNAMIC_BACKEND(all_of, bool)
STL_DYNAMIC_BACKEND(is_sorted, bool)
STL_DYNAMIC_BACKEND(reduce, void)
STL_DYNAMIC_BACKEND(count_if, int)
STL_DYNAMIC_BACKEND(binary_search, bool)
STL_DYNAMIC_BACKEND(remove_if, void)
STL_DYNAMIC_BACKEND(unique, void)
} // namespace manifold
+36 -200
View File
@@ -34,6 +34,12 @@ namespace manifold {
constexpr float kTolerance = 1e-5;
#ifdef __CUDACC__
#define HOST_DEVICE __host__ __device__
#else
#define HOST_DEVICE
#endif
/** @defgroup Connections
* @brief Move data in and out of the Manifold class.
* @{
@@ -44,7 +50,7 @@ constexpr float kTolerance = 1e-5;
*
* @param x Angle in degrees.
*/
inline float sind(float x) {
inline HOST_DEVICE float sind(float x) {
if (!std::isfinite(x)) return sin(x);
if (x < 0.0f) return -sind(-x);
int quo;
@@ -67,7 +73,7 @@ inline float sind(float x) {
*
* @param x Angle in degrees.
*/
inline float cosd(float x) { return sind(x + 90.0f); }
inline HOST_DEVICE float cosd(float x) { return sind(x + 90.0f); }
/**
* This 4x3 matrix can be used as an input to Manifold.Transform() to turn an
@@ -75,7 +81,7 @@ inline float cosd(float x) { return sind(x + 90.0f); }
*
* @param up The vector to be turned to point upwards. Length does not matter.
*/
inline glm::mat4x3 RotateUp(glm::vec3 up) {
inline HOST_DEVICE glm::mat4x3 RotateUp(glm::vec3 up) {
up = glm::normalize(up);
glm::vec3 axis = glm::cross(up, {0, 0, 1});
float angle = glm::asin(glm::length(axis));
@@ -94,7 +100,8 @@ inline glm::mat4x3 RotateUp(glm::vec3 up) {
* @return int, like Signum, this returns 1 for CCW, -1 for CW, and 0 if within
* tol of colinear.
*/
inline int CCW(glm::vec2 p0, glm::vec2 p1, glm::vec2 p2, float tol) {
inline HOST_DEVICE int CCW(glm::vec2 p0, glm::vec2 p1, glm::vec2 p2,
float tol) {
glm::vec2 v1 = p1 - p0;
glm::vec2 v2 = p2 - p0;
float area = v1.x * v2.y - v1.y * v2.x;
@@ -172,12 +179,12 @@ struct Box {
/**
* Default constructor is an infinite box that contains all space.
*/
Box() {}
HOST_DEVICE Box() {}
/**
* Creates a box that contains the two given points.
*/
Box(const glm::vec3 p1, const glm::vec3 p2) {
HOST_DEVICE Box(const glm::vec3 p1, const glm::vec3 p2) {
min = glm::min(p1, p2);
max = glm::max(p1, p2);
}
@@ -185,18 +192,18 @@ struct Box {
/**
* Returns the dimensions of the Box.
*/
glm::vec3 Size() const { return max - min; }
HOST_DEVICE glm::vec3 Size() const { return max - min; }
/**
* Returns the center point of the Box.
*/
glm::vec3 Center() const { return 0.5f * (max + min); }
HOST_DEVICE glm::vec3 Center() const { return 0.5f * (max + min); }
/**
* Returns the absolute-largest coordinate value of any contained
* point.
*/
float Scale() const {
HOST_DEVICE float Scale() const {
glm::vec3 absMax = glm::max(glm::abs(min), glm::abs(max));
return glm::max(absMax.x, glm::max(absMax.y, absMax.z));
}
@@ -204,7 +211,7 @@ struct Box {
/**
* Does this box contain (includes equal) the given point?
*/
bool Contains(const glm::vec3& p) const {
HOST_DEVICE bool Contains(const glm::vec3& p) const {
return glm::all(glm::greaterThanEqual(p, min)) &&
glm::all(glm::greaterThanEqual(max, p));
}
@@ -212,7 +219,7 @@ struct Box {
/**
* Does this box contain (includes equal) the given box?
*/
bool Contains(const Box& box) const {
HOST_DEVICE bool Contains(const Box& box) const {
return glm::all(glm::greaterThanEqual(box.min, min)) &&
glm::all(glm::greaterThanEqual(max, box.max));
}
@@ -220,7 +227,7 @@ struct Box {
/**
* Expand this box to include the given point.
*/
void Union(const glm::vec3 p) {
HOST_DEVICE void Union(const glm::vec3 p) {
min = glm::min(min, p);
max = glm::max(max, p);
}
@@ -228,7 +235,7 @@ struct Box {
/**
* Expand this box to include the given box.
*/
Box Union(const Box& box) const {
HOST_DEVICE Box Union(const Box& box) const {
Box out;
out.min = glm::min(min, box.min);
out.max = glm::max(max, box.max);
@@ -242,7 +249,7 @@ struct Box {
* multiples of 90 degrees), or else the resulting bounding box will no longer
* bound properly.
*/
Box Transform(const glm::mat4x3& transform) const {
HOST_DEVICE Box Transform(const glm::mat4x3& transform) const {
Box out;
glm::vec3 minT = transform * glm::vec4(min, 1.0f);
glm::vec3 maxT = transform * glm::vec4(max, 1.0f);
@@ -254,7 +261,7 @@ struct Box {
/**
* Shift this box by the given vector.
*/
Box operator+(glm::vec3 shift) const {
HOST_DEVICE Box operator+(glm::vec3 shift) const {
Box out;
out.min = min + shift;
out.max = max + shift;
@@ -264,7 +271,7 @@ struct Box {
/**
* Shift this box in-place by the given vector.
*/
Box& operator+=(glm::vec3 shift) {
HOST_DEVICE Box& operator+=(glm::vec3 shift) {
min += shift;
max += shift;
return *this;
@@ -273,7 +280,7 @@ struct Box {
/**
* Scale this box by the given vector.
*/
Box operator*(glm::vec3 scale) const {
HOST_DEVICE Box operator*(glm::vec3 scale) const {
Box out;
out.min = min * scale;
out.max = max * scale;
@@ -283,7 +290,7 @@ struct Box {
/**
* Scale this box in-place by the given vector.
*/
Box& operator*=(glm::vec3 scale) {
HOST_DEVICE Box& operator*=(glm::vec3 scale) {
min *= scale;
max *= scale;
return *this;
@@ -292,7 +299,7 @@ struct Box {
/**
* Does this box overlap the one given (including equality)?
*/
inline bool DoesOverlap(const Box& box) const {
HOST_DEVICE bool DoesOverlap(const Box& box) const {
return min.x <= box.max.x && min.y <= box.max.y && min.z <= box.max.z &&
max.x >= box.min.x && max.y >= box.min.y && max.z >= box.min.z;
}
@@ -301,183 +308,17 @@ struct Box {
* Does the given point project within the XY extent of this box
* (including equality)?
*/
inline bool DoesOverlap(glm::vec3 p) const { // projected in z
HOST_DEVICE bool DoesOverlap(glm::vec3 p) const { // projected in z
return p.x <= max.x && p.x >= min.x && p.y <= max.y && p.y >= min.y;
}
/**
* Does this box have finite bounds?
*/
bool IsFinite() const {
HOST_DEVICE bool IsFinite() const {
return glm::all(glm::isfinite(min)) && glm::all(glm::isfinite(max));
}
};
/**
* Axis-aligned rectangular bounds.
*/
struct Rect {
glm::vec2 min = glm::vec2(std::numeric_limits<float>::infinity());
glm::vec2 max = glm::vec2(-std::numeric_limits<float>::infinity());
/**
* Default constructor is an empty rectangle..
*/
Rect() {}
/**
* Create a rectangle that contains the two given points.
*/
Rect(const glm::vec2 a, const glm::vec2 b) {
min = glm::min(a, b);
max = glm::max(a, b);
}
/** @name Information
* Details of the rectangle
*/
///@{
/**
* Return the dimensions of the rectangle.
*/
glm::vec2 Size() const { return max - min; }
/**
* Return the area of the rectangle.
*/
float Area() const {
auto sz = Size();
return sz.x * sz.y;
}
/**
* Returns the absolute-largest coordinate value of any contained
* point.
*/
float 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 Center() const { return 0.5f * (max + min); }
/**
* Does this rectangle contain (includes on border) the given point?
*/
bool 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 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 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 IsEmpty() const { return max.y <= min.y || max.x <= min.x; };
/**
* Does this recangle have finite bounds?
*/
bool IsFinite() const {
return glm::all(glm::isfinite(min)) && glm::all(glm::isfinite(max));
}
///@}
/** @name Modification
*/
///@{
/**
* Expand this rectangle (in place) to include the given point.
*/
void Union(const glm::vec2 p) {
min = glm::min(min, p);
max = glm::max(max, p);
}
/**
* Expand this rectangle to include the given 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 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& operator+=(const glm::vec2 shift) {
min += shift;
max += shift;
return *this;
}
/**
* Scale this rectangle by the given vector.
*/
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& 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 Transform(const glm::mat3x2& m) const {
Rect rect;
rect.min = m * glm::vec3(min, 1);
rect.max = m * glm::vec3(max, 1);
return rect;
}
///@}
};
/** @} */
/** @addtogroup Core
@@ -560,7 +401,7 @@ class Quality {
int nSegL = 2.0f * radius * glm::pi<float>() / circularEdgeLength_;
int nSeg = fmin(nSegA, nSegL) + 3;
nSeg -= nSeg % 4;
return std::max(nSeg, 3);
return nSeg;
}
};
/** @} */
@@ -611,12 +452,17 @@ struct ExecutionParams {
/// Suppresses printed errors regarding CW triangles. Has no effect if
/// processOverlaps is true.
bool suppressErrors = false;
/// Deterministic outputs. Will disable some parallel optimizations.
bool deterministic = false;
};
#ifdef MANIFOLD_DEBUG
inline std::ostream& operator<<(std::ostream& stream, const Box& box) {
return stream << "min: " << box.min.x << ", " << box.min.y << ", "
<< box.min.z << ", "
<< "max: " << box.max.x << ", " << box.max.y << ", "
<< box.max.z;
}
template <typename T>
inline std::ostream& operator<<(std::ostream& stream, const glm::tvec2<T>& v) {
return stream << "x = " << v.x << ", y = " << v.y;
@@ -640,16 +486,6 @@ inline std::ostream& operator<<(std::ostream& stream, const glm::mat4x3& mat) {
<< tam[2] << std::endl;
}
inline std::ostream& operator<<(std::ostream& stream, const Box& box) {
return stream << "min: " << box.min << ", "
<< "max: " << box.max;
}
inline std::ostream& operator<<(std::ostream& stream, const Rect& box) {
return stream << "min: " << box.min << ", "
<< "max: " << box.max;
}
/**
* Print the contents of this vector to standard output. Only exists if compiled
* with MANIFOLD_DEBUG flag.
+30 -66
View File
@@ -19,7 +19,7 @@
#include "par.h"
#include "public.h"
#include "utils.h"
#include "vec.h"
#include "vec_dh.h"
namespace manifold {
@@ -38,7 +38,7 @@ class SparseIndices {
defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || \
defined(__THUMBEL__) || defined(__AARCH64EL__) || defined(_MIPSEL) || \
defined(__MIPSEL) || defined(__MIPSEL__) || defined(__EMSCRIPTEN__) || \
defined(_WIN32)
defined(_MSC_VER)
static constexpr size_t pOffset = 1;
#else
#error "unknown architecture"
@@ -48,26 +48,23 @@ class SparseIndices {
}
SparseIndices() = default;
SparseIndices(size_t size) : data_(size * sizeof(int64_t)) {}
SparseIndices(size_t size) : data(size) {}
int size() const { return data_.size() / sizeof(int64_t); }
int size() const { return data.size(); }
Vec<int> Copy(bool use_q) const {
Vec<int> out(size());
VecDH<int> Copy(bool use_q) const {
VecDH<int> out(data.size());
int offset = pOffset;
if (use_q) offset = 1 - offset;
const int* p = ptr();
for_each(autoPolicy(out.size()), countAt(0), countAt((int)out.size()),
for_each(autoPolicy(data.size()), countAt(0), countAt((int)data.size()),
[&](int i) { out[i] = p[i * 2 + offset]; });
return out;
}
void Sort() {
VecView<int64_t> view = AsVec64();
stable_sort(autoPolicy(size()), view.begin(), view.end());
}
void Sort(ExecutionPolicy policy) { sort(policy, data.begin(), data.end()); }
void Resize(int size) { data_.resize(size * sizeof(int64_t), -1); }
void Resize(int size) { data.resize(size, -1); }
inline int& Get(int i, bool use_q) {
if (use_q)
@@ -83,61 +80,29 @@ class SparseIndices {
return ptr()[2 * i + pOffset];
}
inline int64_t GetPQ(int i) const {
VecView<const int64_t> view = AsVec64();
return view[i];
}
inline int64_t GetPQ(int i) const { return data[i]; }
inline void Set(int i, int p, int q) {
VecView<int64_t> view = AsVec64();
view[i] = EncodePQ(p, q);
}
inline void Set(int i, int p, int q) { data[i] = EncodePQ(p, q); }
inline void SetPQ(int i, int64_t pq) {
VecView<int64_t> view = AsVec64();
view[i] = pq;
}
inline void SetPQ(int i, int64_t pq) { data[i] = pq; }
VecView<int64_t> AsVec64() {
return VecView<int64_t>(reinterpret_cast<int64_t*>(data_.data()),
data_.size() / sizeof(int64_t));
}
const VecDH<int64_t>& AsVec64() const { return data; }
VecView<const int64_t> AsVec64() const {
return VecView<const int64_t>(
reinterpret_cast<const int64_t*>(data_.data()),
data_.size() / sizeof(int64_t));
}
inline void Add(int p, int q) { data.push_back(EncodePQ(p, q)); }
VecView<int32_t> AsVec32() {
return VecView<int32_t>(reinterpret_cast<int32_t*>(data_.data()),
data_.size() / sizeof(int32_t));
}
VecView<const int32_t> AsVec32() const {
return VecView<const int32_t>(
reinterpret_cast<const int32_t*>(data_.data()),
data_.size() / sizeof(int32_t));
}
inline void Add(int p, int q) {
for (int i = 0; i < sizeof(int64_t); ++i) data_.push_back(-1);
Set(size() - 1, p, q);
}
void Unique() {
Sort();
VecView<int64_t> view = AsVec64();
int newSize = std::unique(view.begin(), view.end()) - view.begin();
void Unique(ExecutionPolicy policy) {
Sort(policy);
int newSize =
unique<decltype(data.begin())>(policy, data.begin(), data.end()) -
data.begin();
Resize(newSize);
}
size_t RemoveZeros(Vec<int>& S) {
ASSERT(S.size() == size(), userErr,
size_t RemoveZeros(VecDH<int>& S) {
ASSERT(S.size() == data.size(), userErr,
"Different number of values than indicies!");
VecView<int64_t> view = AsVec64();
auto zBegin = zip(S.begin(), view.begin());
auto zEnd = zip(S.end(), view.end());
auto zBegin = zip(S.begin(), data.begin());
auto zEnd = zip(S.end(), data.end());
size_t size =
remove_if<decltype(zBegin)>(autoPolicy(S.size()), zBegin, zEnd,
[](thrust::tuple<int, int64_t> x) {
@@ -163,12 +128,11 @@ class SparseIndices {
};
template <typename T>
size_t KeepFinite(Vec<T>& v, Vec<int>& x) {
ASSERT(x.size() == size(), userErr,
size_t KeepFinite(VecDH<T>& v, VecDH<int>& x) {
ASSERT(x.size() == data.size(), userErr,
"Different number of values than indicies!");
VecView<int64_t> view = AsVec64();
auto zBegin = zip(v.begin(), x.begin(), view.begin());
auto zEnd = zip(v.end(), x.end(), view.end());
auto zBegin = zip(v.begin(), x.begin(), data.begin());
auto zEnd = zip(v.end(), x.end(), data.end());
size_t size = remove_if<decltype(zBegin)>(autoPolicy(v.size()), zBegin,
zEnd, firstNonFinite<T>()) -
zBegin;
@@ -191,10 +155,10 @@ class SparseIndices {
#endif
private:
Vec<char> data_;
inline int* ptr() { return reinterpret_cast<int32_t*>(data_.data()); }
VecDH<int64_t> data;
inline int* ptr() { return reinterpret_cast<int32_t*>(data.ptrD()); }
inline const int* ptr() const {
return reinterpret_cast<const int32_t*>(data_.data());
return reinterpret_cast<const int32_t*>(data.ptrD());
}
};
-59
View File
@@ -16,7 +16,6 @@
#pragma once
#include <atomic>
#include <mutex>
#include <unordered_map>
#ifdef MANIFOLD_DEBUG
#include <chrono>
@@ -24,7 +23,6 @@
#endif
#include "par.h"
#include "vec.h"
namespace manifold {
@@ -215,62 +213,5 @@ class ConcurrentSharedPtr {
std::shared_ptr<std::recursive_mutex> mutex =
std::make_shared<std::recursive_mutex>();
};
template <typename I = int, typename R = unsigned char>
struct UnionFind {
Vec<I> parents;
// we do union by rank
// note that we shift rank by 1, rank 0 means it is not connected to anything
// else
Vec<R> ranks;
UnionFind(I numNodes) : parents(numNodes), ranks(numNodes, 0) {
sequence(autoPolicy(numNodes), parents.begin(), parents.end());
}
I find(I x) {
while (parents[x] != x) {
parents[x] = parents[parents[x]];
x = parents[x];
}
return x;
}
void unionXY(I x, I y) {
if (x == y) return;
if (ranks[x] == 0) ranks[x] = 1;
if (ranks[y] == 0) ranks[y] = 1;
x = find(x);
y = find(y);
if (x == y) return;
if (ranks[x] < ranks[y]) std::swap(x, y);
if (ranks[x] == ranks[y]) ranks[x]++;
parents[y] = x;
}
I connectedComponents(std::vector<I>& components) {
components.resize(parents.size());
I lonelyNodes = 0;
std::unordered_map<I, I> toLabel;
for (size_t i = 0; i < parents.size(); ++i) {
// we optimize for connected component of size 1
// no need to put them into the hashmap
if (ranks[i] == 0) {
components[i] = static_cast<I>(toLabel.size()) + lonelyNodes++;
continue;
}
parents[i] = find(i);
auto iter = toLabel.find(parents[i]);
if (iter == toLabel.end()) {
I s = static_cast<I>(toLabel.size()) + lonelyNodes;
toLabel.insert(std::make_pair(parents[i], s));
components[i] = s;
} else {
components[i] = iter->second;
}
}
return toLabel.size() + lonelyNodes;
}
};
/** @} */
} // namespace manifold
-331
View File
@@ -1,331 +0,0 @@
// Copyright 2021 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 <exception>
#if TRACY_ENABLE && TRACY_MEMORY_USAGE
#include "tracy/Tracy.hpp"
#else
#define TracyAllocS(ptr, size, n) (void)0
#define TracyFreeS(ptr, n) (void)0
#endif
// #include "optional_assert.h"
#include "par.h"
#include "public.h"
namespace manifold {
/** @addtogroup Private
* @{
*/
template <typename T>
class Vec;
/**
* View for Vec, can perform offset operation.
* This will be invalidated when the original vector is dropped or changes
* length.
*/
template <typename T>
class VecView {
public:
using Iter = T *;
using IterC = const T *;
VecView(T *ptr_, int size_) : ptr_(ptr_), size_(size_) {}
VecView(const VecView &other) {
ptr_ = other.ptr_;
size_ = other.size_;
}
VecView &operator=(const VecView &other) {
ptr_ = other.ptr_;
size_ = other.size_;
return *this;
}
// allows conversion to a const VecView
operator VecView<const T>() const { return {ptr_, size_}; }
inline const T &operator[](int i) const {
if (i < 0 || i >= size_) throw std::out_of_range("Vec out of range");
return ptr_[i];
}
inline T &operator[](int i) {
if (i < 0 || i >= size_) throw std::out_of_range("Vec out of range");
return ptr_[i];
}
IterC cbegin() const { return ptr_; }
IterC cend() const { return ptr_ + size_; }
IterC begin() const { return cbegin(); }
IterC end() const { return cend(); }
Iter begin() { return ptr_; }
Iter end() { return ptr_ + size_; }
const T &front() const {
if (size_ == 0)
throw std::out_of_range("attempt to take the front of an empty vector");
return ptr_[0];
}
const T &back() const {
if (size_ == 0)
throw std::out_of_range("attempt to take the back of an empty vector");
return ptr_[size_ - 1];
}
T &front() {
if (size_ == 0)
throw std::out_of_range("attempt to take the front of an empty vector");
return ptr_[0];
}
T &back() {
if (size_ == 0)
throw std::out_of_range("attempt to take the back of an empty vector");
return ptr_[size_ - 1];
}
int size() const { return size_; }
bool empty() const { return size_ == 0; }
#ifdef MANIFOLD_DEBUG
void Dump() {
std::cout << "Vec = " << std::endl;
for (int i = 0; i < size(); ++i) {
std::cout << i << ", " << ptr_[i] << ", " << std::endl;
}
std::cout << std::endl;
}
#endif
protected:
T *ptr_ = nullptr;
int size_ = 0;
VecView() = default;
friend class Vec<T>;
friend class Vec<typename std::remove_const<T>::type>;
friend class VecView<typename std::remove_const<T>::type>;
};
/*
* Specialized vector implementation with multithreaded fill and uninitialized
* memory optimizations.
* Note that the constructor and resize function will not perform initialization
* if the parameter val is not set. Also, this implementation is a toy
* implementation that did not consider things like non-trivial
* constructor/destructor, please keep T trivial.
*/
template <typename T>
class Vec : public VecView<T> {
public:
Vec() {}
// Note that the vector constructed with this constructor will contain
// uninitialized memory. Please specify `val` if you need to make sure that
// the data is initialized.
Vec(int size) {
reserve(size);
this->size_ = size;
}
Vec(int size, T val) { resize(size, val); }
Vec(const Vec<T> &vec) {
this->size_ = vec.size();
this->capacity_ = this->size_;
auto policy = autoPolicy(this->size_);
if (this->size_ != 0) {
this->ptr_ = reinterpret_cast<T *>(malloc(this->size_ * sizeof(T)));
if (this->ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, vec.begin(), vec.end(), this->ptr_);
}
}
Vec(const std::vector<T> &vec) {
this->size_ = vec.size();
this->capacity_ = this->size_;
auto policy = autoPolicy(this->size_);
if (this->size_ != 0) {
this->ptr_ = reinterpret_cast<T *>(malloc(this->size_ * sizeof(T)));
if (this->ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, vec.begin(), vec.end(), this->ptr_);
}
}
Vec(Vec<T> &&vec) {
this->ptr_ = vec.ptr_;
this->size_ = vec.size_;
capacity_ = vec.capacity_;
vec.ptr_ = nullptr;
vec.size_ = 0;
vec.capacity_ = 0;
}
operator VecView<T>() { return {this->ptr_, this->size_}; }
operator VecView<const T>() const { return {this->ptr_, this->size_}; }
~Vec() {
if (this->ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(this->ptr_);
}
this->ptr_ = nullptr;
this->size_ = 0;
capacity_ = 0;
}
Vec<T> &operator=(const Vec<T> &other) {
if (&other == this) return *this;
if (this->ptr_ != nullptr) {
TracyFreeS(this->ptr_, 3);
free(this->ptr_);
}
this->size_ = other.size_;
capacity_ = other.size_;
auto policy = autoPolicy(this->size_);
if (this->size_ != 0) {
this->ptr_ = reinterpret_cast<T *>(malloc(this->size_ * sizeof(T)));
if (this->ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, other.begin(), other.end(), this->ptr_);
}
return *this;
}
Vec<T> &operator=(Vec<T> &&other) {
if (&other == this) return *this;
if (this->ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(this->ptr_);
}
this->size_ = other.size_;
capacity_ = other.capacity_;
this->ptr_ = other.ptr_;
other.ptr_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
return *this;
}
operator VecView<T>() const { return {this->ptr_, this->size_}; }
void swap(Vec<T> &other) {
std::swap(this->ptr_, other.ptr_);
std::swap(this->size_, other.size_);
std::swap(capacity_, other.capacity_);
}
inline void push_back(const T &val) {
if (this->size_ >= capacity_) {
// avoid dangling pointer in case val is a reference of our array
T val_copy = val;
reserve(capacity_ == 0 ? 128 : capacity_ * 2);
this->ptr_[this->size_++] = val_copy;
return;
}
this->ptr_[this->size_++] = val;
}
void reserve(int n) {
if (n > capacity_) {
T *newBuffer = reinterpret_cast<T *>(malloc(n * sizeof(T)));
if (newBuffer == nullptr) throw std::bad_alloc();
TracyAllocS(newBuffer, n * sizeof(T), 3);
if (this->size_ > 0)
uninitialized_copy(autoPolicy(this->size_), this->ptr_,
this->ptr_ + this->size_, newBuffer);
if (this->ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(this->ptr_);
}
this->ptr_ = newBuffer;
capacity_ = n;
}
}
void resize(int newSize, T val = T()) {
bool shrink = this->size_ > 2 * newSize;
reserve(newSize);
if (this->size_ < newSize) {
uninitialized_fill(autoPolicy(newSize - this->size_),
this->ptr_ + this->size_, this->ptr_ + newSize, val);
}
this->size_ = newSize;
if (shrink) shrink_to_fit();
}
void shrink_to_fit() {
T *newBuffer = nullptr;
if (this->size_ > 0) {
newBuffer = reinterpret_cast<T *>(malloc(this->size_ * sizeof(T)));
if (newBuffer == nullptr) throw std::bad_alloc();
TracyAllocS(newBuffer, size_ * sizeof(T), 3);
uninitialized_copy(autoPolicy(this->size_), this->ptr_,
this->ptr_ + this->size_, newBuffer);
}
if (this->ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(this->ptr_);
}
this->ptr_ = newBuffer;
capacity_ = this->size_;
}
VecView<T> view(int offset = 0, int length = -1) {
if (length == -1) {
length = this->size_ - offset;
if (length < 0) throw std::out_of_range("Vec::view out of range");
} else if (offset + length > this->size_ || offset < 0) {
throw std::out_of_range("Vec::view out of range");
} else if (length < 0) {
throw std::out_of_range("Vec::view negative length is not allowed");
}
return VecView<T>(this->ptr_ + offset, length);
}
VecView<const T> cview(int offset = 0, int length = -1) const {
if (length == -1) {
length = this->size_ - offset;
if (length < 0) throw std::out_of_range("Vec::cview out of range");
} else if (offset + length > this->size_ || offset < 0) {
throw std::out_of_range("Vec::cview out of range");
} else if (length < 0) {
throw std::out_of_range("Vec::cview negative length is not allowed");
}
return VecView<const T>(this->ptr_ + offset, length);
}
VecView<const T> view(int offset = 0, int length = -1) const {
return cview(offset, length);
}
T *data() { return this->ptr_; }
const T *data() const { return this->ptr_; }
private:
int capacity_ = 0;
};
/** @} */
} // namespace manifold
+268
View File
@@ -0,0 +1,268 @@
// Copyright 2021 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 <exception>
#if TRACY_ENABLE && TRACY_MEMORY_USAGE
#include <tracy/Tracy.hpp>
#else
#define TracyAllocS(ptr, size, n) (void)0
#define TracyFreeS(ptr, n) (void)0
#endif
// #include "optional_assert.h"
#include "par.h"
#include "public.h"
namespace manifold {
/** @addtogroup Private
* @{
*/
/*
* Specialized vector implementation with multithreaded fill and uninitialized
* memory optimizations.
* Note that the constructor and resize function will not perform initialization
* if the parameter val is not set. Also, this implementation is a toy
* implementation that did not consider things like non-trivial
* constructor/destructor, please keep T trivial.
*/
template <typename T>
class VecDH {
public:
using Iter = T *;
using IterC = const T *;
VecDH() {}
// Note that the vector constructed with this constructor will contain
// uninitialized memory. Please specify `val` if you need to make sure that
// the data is initialized.
VecDH(int size) { resize(size); }
VecDH(int size, T val) { resize(size, val); }
VecDH(const std::vector<T> &vec) {
size_ = vec.size();
capacity_ = size_;
auto policy = autoPolicy(size_);
if (size_ != 0) {
ptr_ = reinterpret_cast<T *>(malloc(size_ * sizeof(T)));
if (ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, vec.begin(), vec.end(), ptr_);
}
}
VecDH(const VecDH<T> &vec) {
size_ = vec.size_;
capacity_ = size_;
auto policy = autoPolicy(size_);
if (size_ != 0) {
ptr_ = reinterpret_cast<T *>(malloc(size_ * sizeof(T)));
if (ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, vec.begin(), vec.end(), ptr_);
}
}
VecDH(VecDH<T> &&vec) {
ptr_ = vec.ptr_;
size_ = vec.size_;
capacity_ = vec.capacity_;
vec.ptr_ = nullptr;
vec.size_ = 0;
vec.capacity_ = 0;
}
~VecDH() {
if (ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(ptr_);
}
ptr_ = nullptr;
size_ = 0;
capacity_ = 0;
}
VecDH<T> &operator=(const VecDH<T> &other) {
if (&other == this) return *this;
if (ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(ptr_);
}
size_ = other.size_;
capacity_ = other.size_;
auto policy = autoPolicy(size_);
if (size_ != 0) {
ptr_ = reinterpret_cast<T *>(malloc(size_ * sizeof(T)));
if (ptr_ == nullptr) throw std::bad_alloc();
TracyAllocS(ptr_, size_ * sizeof(T), 3);
uninitialized_copy(policy, other.begin(), other.end(), ptr_);
}
return *this;
}
VecDH<T> &operator=(VecDH<T> &&other) {
if (&other == this) return *this;
if (ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(ptr_);
}
size_ = other.size_;
capacity_ = other.capacity_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
return *this;
}
int size() const { return size_; }
void swap(VecDH<T> &other) {
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(capacity_, other.capacity_);
}
Iter begin() { return ptr_; }
Iter end() { return ptr_ + size_; }
IterC cbegin() const { return ptr_; }
IterC cend() const { return ptr_ + size_; }
IterC begin() const { return cbegin(); }
IterC end() const { return cend(); }
T *ptrD() { return ptr_; }
const T *cptrD() const { return ptr_; }
const T *ptrD() const { return cptrD(); }
T *ptrH() { return ptr_; }
const T *cptrH() const { return ptr_; }
const T *ptrH() const { return cptrH(); }
inline T &operator[](int i) { return ptr_[i]; }
inline const T &operator[](int i) const { return ptr_[i]; }
T &back() { return ptr_[size_ - 1]; }
const T &back() const { return ptr_[size_ - 1]; }
inline void push_back(const T &val) {
if (size_ >= capacity_) {
// avoid dangling pointer in case val is a reference of our array
T val_copy = val;
reserve(capacity_ == 0 ? 128 : capacity_ * 2);
ptr_[size_++] = val_copy;
return;
}
ptr_[size_++] = val;
}
void reserve(int n) {
if (n > capacity_) {
T *newBuffer = reinterpret_cast<T *>(malloc(n * sizeof(T)));
if (newBuffer == nullptr) throw std::bad_alloc();
TracyAllocS(newBuffer, n * sizeof(T), 3);
if (size_ > 0)
uninitialized_copy(autoPolicy(size_), ptr_, ptr_ + size_, newBuffer);
if (ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(ptr_);
}
ptr_ = newBuffer;
capacity_ = n;
}
}
void resize(int newSize, T val = T()) {
bool shrink = size_ > 2 * newSize;
reserve(newSize);
if (size_ < newSize) {
uninitialized_fill(autoPolicy(newSize - size_), ptr_ + size_,
ptr_ + newSize, val);
}
size_ = newSize;
if (shrink) shrink_to_fit();
}
void shrink_to_fit() {
T *newBuffer = nullptr;
if (size_ > 0) {
newBuffer = reinterpret_cast<T *>(malloc(size_ * sizeof(T)));
if (newBuffer == nullptr) throw std::bad_alloc();
TracyAllocS(newBuffer, size_ * sizeof(T), 3);
uninitialized_copy(autoPolicy(size_), ptr_, ptr_ + size_, newBuffer);
if (ptr_ != nullptr) {
TracyFreeS(ptr_, 3);
free(ptr_);
}
}
ptr_ = newBuffer;
capacity_ = size_;
}
#ifdef MANIFOLD_DEBUG
void Dump() const {
std::cout << "VecDH = " << std::endl;
for (int i = 0; i < size_; ++i) {
std::cout << i << ", " << ptr_[i] << ", " << std::endl;
}
std::cout << std::endl;
}
#endif
private:
int size_ = 0;
int capacity_ = 0;
T *ptr_ = nullptr;
};
template <typename T>
class VecDc {
public:
VecDc(const VecDH<T> &vec) : ptr_(vec.ptrD()), size_(vec.size()) {}
__host__ __device__ const T &operator[](int i) const { return ptr_[i]; }
__host__ __device__ int size() const { return size_; }
private:
T const *const ptr_;
const int size_;
};
template <typename T>
class VecD {
public:
VecD(VecDH<T> &vec) : ptr_(vec.ptrD()), size_(vec.size()) {}
__host__ __device__ T &operator[](int i) const { return ptr_[i]; }
__host__ __device__ int size() const { return size_; }
private:
T *ptr_;
int size_;
};
/** @} */
} // namespace manifold
+17 -12
View File
@@ -27,22 +27,27 @@ set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
set(INSTALL_GMOCK OFF CACHE BOOL "" FORCE)
include(FetchContent)
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
FIND_PACKAGE_ARGS NAMES GTest gtest
)
FetchContent_MakeAvailable(googletest)
find_package(GTest)
if(NOT GTest_FOUND)
message(STATUS "GTest not found, downloading from source")
include(FetchContent)
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(googletest)
endif()
if(NOT TARGET GTest::gtest_main)
add_library(GTest::gtest_main ALIAS gtest_main)
if(NOT TARGET GTest::GTest)
add_library(GTest::GTest ALIAS gtest)
add_library(GTest::Main ALIAS gtest_main)
endif()
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
target_link_libraries(${PROJECT_NAME} polygon GTest::gtest_main manifold sdf samples cross_section)
target_link_libraries(${PROJECT_NAME} polygon GTest::GTest manifold sdf samples samplesGPU cross_section)
if(MANIFOLD_CBIND)
target_link_libraries(${PROJECT_NAME} manifoldc)
+12 -7
View File
@@ -163,9 +163,11 @@ TEST(Boolean, Coplanar) {
MeshGL cylinderGL = WithPositionColors(cylinder);
cylinder = Manifold(cylinderGL);
Manifold cylinder2 = cylinder.Scale({0.8f, 0.8f, 1.0f}).Rotate(0, 0, 5);
Manifold cylinder2 = cylinder.Scale({0.5f, 0.5f, 1.0f})
.Rotate(0, 0, 15)
.Translate({0.25f, 0.25f, 0.0f});
Manifold out = cylinder - cylinder2;
ExpectMeshes(out, {{32, 64, 3, 48}});
ExpectMeshes(out, {{32, 64, 3, 49}});
EXPECT_EQ(out.NumDegenerateTris(), 0);
EXPECT_EQ(out.Genus(), 1);
@@ -187,9 +189,11 @@ TEST(Boolean, CoplanarProp) {
MeshGL cylinderGL = WithIndexColors(cylinder.GetMesh());
cylinder = Manifold(cylinderGL);
Manifold cylinder2 = cylinder.Scale({0.8f, 0.8f, 1.0f}).Rotate(0, 0, 5);
Manifold cylinder2 = cylinder.Scale({0.5f, 0.5f, 1.0f})
.Rotate(0, 0, 15)
.Translate({0.25f, 0.25f, 0.0f});
Manifold out = cylinder - cylinder2;
ExpectMeshes(out, {{52, 104, 3, 88}});
ExpectMeshes(out, {{42, 84, 3, 68}});
EXPECT_EQ(out.NumDegenerateTris(), 0);
EXPECT_EQ(out.Genus(), 1);
@@ -632,9 +636,9 @@ TEST(Boolean, BooleanVolumes) {
// m7 = m1 + m2 + m3
auto m1 = Manifold::Cube({1, 1, 1});
auto m2 = Manifold::Cube({2, 1, 1}).Transform(
glm::mat4x3(glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 0, 0))));
glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 0, 0)));
auto m4 = Manifold::Cube({4, 1, 1}).Transform(
glm::mat4x3(glm::translate(glm::mat4(1.0f), glm::vec3(3.0f, 0, 0))));
glm::translate(glm::mat4(1.0f), glm::vec3(3.0f, 0, 0)));
auto m3 = Manifold::Cube({3, 1, 1});
auto m7 = Manifold::Cube({7, 1, 1});
@@ -875,6 +879,7 @@ TEST(Boolean, Sweep) {
std::vector<Manifold> result;
for (int i = 0; i < numPoints; i++) {
// std::cerr << i << std::endl;
std::vector<Manifold> primitives =
cutterPrimitives(pathPoints[i], pathPoints[(i + 1) % numPoints],
pathPoints[(i + 2) % numPoints]);
@@ -901,4 +906,4 @@ TEST(Boolean, Sweep) {
#endif
PolygonParams().processOverlaps = false;
}
}
+4 -4
View File
@@ -78,7 +78,7 @@ TEST(CrossSection, Rect) {
float w = 10;
float h = 5;
auto rect = Rect({0, 0}, {w, h});
CrossSection cross(rect);
auto cross = rect.AsCrossSection();
auto area = rect.Area();
EXPECT_FLOAT_EQ(area, w * h);
@@ -104,7 +104,7 @@ TEST(CrossSection, Transform) {
0.0f, 3.0f, 0.0f, //
0.0f, 0.0f, 1.0f);
auto b = sq.Transform(glm::mat3x2(trans * scale * rot));
auto b = sq.Transform(trans * scale * rot);
auto b_copy = CrossSection(b);
auto ex_b = Manifold::Extrude(b, 1.).GetMesh();
@@ -124,8 +124,8 @@ TEST(CrossSection, Warp) {
EXPECT_EQ(sq.NumVert(), 4);
EXPECT_EQ(sq.NumContour(), 1);
// Identical(Manifold::Extrude(a, 1.).GetMesh(),
// Manifold::Extrude(b, 1.).GetMesh());
Identical(Manifold::Extrude(a, 1.).GetMesh(),
Manifold::Extrude(b, 1.).GetMesh());
}
TEST(CrossSection, Decompose) {
+1 -3
View File
@@ -14,8 +14,6 @@
#include "manifold.h"
#include <algorithm>
#include "cross_section.h"
#include "test.h"
@@ -644,7 +642,7 @@ TEST(Manifold, Invalid) {
auto invalid = Manifold::Error::InvalidConstruction;
auto circ = CrossSection::Circle(10.);
auto empty_circ = CrossSection::Circle(-2.);
auto empty_sq = CrossSection::Square(glm::vec2(0.0f));
auto empty_sq = CrossSection::Square(glm::vec3(0.0f));
EXPECT_EQ(Manifold::Sphere(0).Status(), invalid);
EXPECT_EQ(Manifold::Cylinder(0, 5).Status(), invalid);
+4 -1596
View File
File diff suppressed because it is too large Load Diff
+2 -21
View File
@@ -229,7 +229,8 @@ TEST(Samples, Sponge1) {
TEST(Samples, Sponge4) {
Manifold sponge = MengerSponge(4);
CheckNormals(sponge);
EXPECT_LE(sponge.NumDegenerateTris(), 8);
// FIXME: limit NumDegenerateTris
EXPECT_LE(sponge.NumDegenerateTris(), 40000);
EXPECT_EQ(sponge.Genus(), 26433); // should be 1:5, 2:81, 3:1409, 4:26433
CheckGL(sponge);
@@ -267,23 +268,3 @@ TEST(Samples, SelfIntersect) {
manifold::PolygonParams().processOverlaps = false;
}
#endif
TEST(Samples, CondensedMatter16) {
// FIXME: it should be geometrically valid
manifold::PolygonParams().processOverlaps = true;
Manifold cm = CondensedMatter(16);
CheckGL(cm);
// FIXME: normals should be correct
// CheckNormals(cm);
manifold::PolygonParams().processOverlaps = false;
}
TEST(Samples, CondensedMatter64) {
// FIXME: it should be geometrically valid
manifold::PolygonParams().processOverlaps = true;
Manifold cm = CondensedMatter(64);
CheckGL(cm);
// FIXME: normals should be correct
// CheckNormals(cm);
manifold::PolygonParams().processOverlaps = false;
}
+3 -3
View File
@@ -24,7 +24,7 @@
using namespace manifold;
struct CubeVoid {
float operator()(glm::vec3 p) const {
__host__ __device__ float operator()(glm::vec3 p) const {
const glm::vec3 min = p + glm::vec3(1);
const glm::vec3 max = glm::vec3(1) - p;
const float min3 = glm::min(min.x, glm::min(min.y, min.z));
@@ -34,7 +34,7 @@ struct CubeVoid {
};
struct Layers {
float operator()(glm::vec3 p) const {
__host__ __device__ float operator()(glm::vec3 p) const {
int a = glm::mod(glm::round(2 * p.z), 4.0f);
return a == 0 ? 1 : (a == 2 ? -1 : 0);
}
@@ -114,4 +114,4 @@ TEST(SDF, Resize) {
EXPECT_EQ(layers.Status(), Manifold::Error::NoError);
EXPECT_EQ(layers.Genus(), -8);
}
}
+1 -2
View File
@@ -11,7 +11,6 @@
// 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 <algorithm>
#include "manifold.h"
#include "polygon.h"
@@ -127,7 +126,7 @@ Mesh Csaszar() {
}
struct GyroidSDF {
float operator()(glm::vec3 p) const {
__host__ __device__ float operator()(glm::vec3 p) const {
const glm::vec3 min = p;
const glm::vec3 max = glm::vec3(glm::two_pi<float>()) - p;
const float min3 = glm::min(min.x, glm::min(min.y, min.z));