diff --git a/PARALLEL.md b/PARALLEL.md new file mode 100644 index 0000000..ebb2a5e --- /dev/null +++ b/PARALLEL.md @@ -0,0 +1,495 @@ +# Parallel marching cubes + +`mcubes.marching_cubes` and `mcubes.marching_cubes_func` accept a `num_threads` +argument. The volume is swept in several passes — classify the cubes, prefix sum +their vertex counts, place the vertices, emit the triangles — and each pass runs +on all requested threads. The extracted mesh is identical whatever the thread +count. + +```python +vertices, triangles = mcubes.marching_cubes(volume, isovalue, num_threads=4) +``` + +`num_threads=0` (the default) uses one thread per CPU core and `1` keeps the +whole computation on the calling thread. + +| | old | new, 4 threads | +|---|---|---| +| binary 100³ (README `binary.jpg`) | 19.3 ms | **4.2 ms** (4.6×) | +| smoothed 100³ (README `smooth.jpg`) | 19.2 ms | **4.1 ms** (4.6×) | +| sphere 256³ | 310 ms | **80 ms** (3.9×) | + +--- + +## 1. Background + +### 1.1 Standard marching cubes + +The grid has `numx × numy × numz` scalar samples, i.e. `nx × ny × nz` cells +(`nx = numx - 1`, …). Cube `(i, j, k)` has eight corners at the grid nodes +`(i + dx, j + dy, k + dz)` for `dx, dy, dz ∈ {0, 1}`, numbered so that bit `m` of +the cube index refers to corner `m`: + +``` + v7 ---------- v6 edges: 0: v0-v1 1: v1-v2 2: v2-v3 3: v3-v0 + / | /| 4: v4-v5 5: v5-v6 6: v6-v7 7: v7-v4 + v4 ---------- v5 | 8: v0-v4 9: v1-v5 10: v2-v6 11: v3-v7 + | | | | + | v3 ---------| v2 v0=(0,0,0) v1=(1,0,0) v2=(1,1,0) v3=(0,1,0) + | / | / v4=(0,0,1) v5=(1,0,1) v6=(1,1,1) v7=(0,1,1) + v0 ---------- v1 +``` + +`cube_index` marks the corners below the isovalue, `edge_table[cube_index]` marks +the edges crossing the surface, and `triangle_table[cube_index]` lists the +triangles as triples of edge ids. A vertex is placed on each crossing edge by +linear interpolation between its two corners. + +### 1.2 Why the original implementation could not be parallelised + +A naive implementation emits three vertices per triangle, which duplicates every +vertex six times and destroys the mesh. The original code avoided duplicates by +sweeping the volume in a fixed order and remembering, in three small index +buffers, which vertex had already been created for the edges shared with the +previously visited cubes: + +``` +v[4] = f(x, y, lower[2]); ... // 4 evaluations per row +for k: // rolling reuse along z + v[0] = v[4]; ... + v[4] = f(x, y, z_dz); ... // 4 evaluations per cube + ... edge 6: create vertex, write shared_indices_x[...] + ... edge 0: if (j == 0 && k == 0) create, else read shared_indices_x[...] +``` + +Two things make this inherently sequential: + +* the shared-index buffers are written by one cube and read by the next, so the + visitation order *is* the algorithm; and +* vertices are appended to a `std::vector` with `push_back`, so the final vertex + numbering follows the sweep order. + +Every cube is also evaluated four times per grid node (the rolling window fetches +a whole new `z` layer per cube), which is why `marching_cubes_func` had to pay 4× +the Python callbacks, and the `push_back` growth dominates on dense fields. + +--- + +## 2. Algorithm design + +The parallel formulation replaces "create a vertex the first time an edge is +seen" with "**give every edge exactly one owning cube, then fill in the counts, +offsets and positions in independent passes**". + +### 2.1 Edge ownership + +Every cell edge lies along one axis and is shared by up to four cubes. Pick one +owner per edge line: + +> **A cube owns the three edges that start at its minimum corner: edge 0 (`v0→v1`, +> +x), edge 3 (`v3→v0`, +y) and edge 8 (`v0→v4`, +z).** + +For an interior cube these three edges are the `x` line at `(j, k)`, the `y` line +at `(i, k)` and the `z` line at `(i, j)`; the other nine edges belong to +neighbouring cubes at `+x`, `+y` and `+z`. Three properties follow: + +* an edge crossing the surface is reported identically by all cubes that share + it (same two corner values, hence the same `edge_table` bit), so the owner + always sees the bit that a neighbour would have seen; +* the three owned edges of a cube are disjoint from those of every other cube, + so no two cubes can create the same vertex; and +* all neighbour lookups go in the `+x`, `+y`, `+z` direction, so no negative + indices are ever formed. + +The rule has to hold for the edges on the upper boundary too. Those lie on the +maximum face of the last cube, which does not own them by the rule above. + +### 2.2 The ghost layer + +The fix is to extend the cube grid by one cell at the top-right boundary of every +axis. The domain becomes `(nx+1) × (ny+1) × (nz+1)` cubes, of which those with +`i == nx`, `j == ny` or `k == nz` are **ghosts**: they cover no volume, they own +edges, and they never emit a triangle. + +``` + i = 0 i = nx-1 i = nx + j = ny [ ghost ] [ ghost ] [ ghost ] ghost row: owns the x lines + ... [ real ] [ real ] [ ghost ] and z lines at j = ny + j = 0 [ real ] [ real ] [ ghost ] ghost column: owns the y + lines and z lines at i = nx +``` + +Now the ownership rule is uniform over the whole extended box: every edge of the +volume is the minimum-corner edge of exactly one cube, real or ghost. Ghost cubes +own only the edges that lie *on* the boundary plane, which is precisely what is +needed, and their invalid edges never fire because the corner reads clamp: + +> A corner index that would leave the grid is clamped to the boundary node. The +> two endpoints of such an edge are then the same node, so both are below (or +> both above) the isovalue and `edge_table` reports no crossing for it. + +That single convention removes every boundary special case: no masks, no +`if (j == 0)` branches, and no per-axis bookkeeping in the hot loop. + +Edges are resolved to their owner with a fixed table (`owner edge` is the edge id +the owner uses, and the rank is its ordinal among the owner's vertices): + +| edge | line | owner cube | owner edge | +| ---- | ---- | ---------- | ---------- | +| 0 | x at (j, k) | (i, j, k) | 0 | +| 1 | y at (i+1, k) | (i+1, j, k) | 3 | +| 2 | x at (j+1, k) | (i, j+1, k) | 0 | +| 3 | y at (i, k) | (i, j, k) | 3 | +| 4 | x at (j, k+1) | (i, j, k+1) | 0 | +| 5 | y at (i+1, k+1) | (i+1, j, k+1) | 3 | +| 6 | x at (j+1, k+1) | (i, j+1, k+1) | 0 | +| 7 | y at (i, k+1) | (i, j, k+1) | 3 | +| 8 | z at (i, j) | (i, j, k) | 8 | +| 9 | z at (i+1, j) | (i+1, j, k) | 8 | +| 10 | z at (i+1, j+1) | (i+1, j+1, k) | 8 | +| 11 | z at (i, j+1) | (i, j+1, k) | 8 | + +Because each owner has at most three vertices, its rank is a couple of bit tests: +`rank(0) = 0`, `rank(3) = (edges & 1)`, `rank(8) = (edges & 1) + (edges & 8)`. + +### 2.3 Why a ghost layer instead of boundary cases + +The reference this work started from +([AIHoloImager `MarchingCubes.cpp`](https://github.com/gongminmin/AIHoloImager/blob/3186611474345c3f0d752752512fd4d02efec9a8/Source/Lib/Source/MeshGen/MarchingCubes.cpp)) +uses the same three owned edges but patches the boundary with extra owned sets per +axis — `x == max` also owns `{1, 9}`, `y == max` owns `{2, 11}`, `z == max` owns +`{4, 7}`. Three edge classes (5, 6 and 10) are then never owned by any cube and are +resolved through diagonal-neighbour lookups whose `(x+1, …, z+1)` indices run past +the end of the flat arrays — or address an unrelated cube — when the cube already +sits on two maximum faces. The ghost layer makes those edges ordinary +minimum-corner edges, so the whole class of double-boundary special cases +disappears. + +### 2.4 The five passes + +`c(i, j, k) = ((i·(ny+1)) + j)·(nz+1) + k` addresses the extended grid. + +``` +pass 1 (parallel, per row of cubes along z) + cube_index[c] = bits of the 8 clamped corner values <= isovalue + vertex_offset[c] = number of set bits among {0, 3, 8} of edge_table + polygon_offset[c] = 0 for ghosts, num_indices_table[cube_index] otherwise + +pass 2 (parallel scan) + vertex_offset := exclusive prefix sum of vertex counts -> V + polygon_offset := exclusive prefix sum of polygon counts -> F·3 + +pass 3 (parallel) for every cube owning vertices, write its 1..3 vertices at + vertex_offset[c] + rank + +pass 4 (parallel) for every real cube, resolve its 12 edge vertices through + the owner table above and copy triangle_table[ci] scaled + by polygon_offset[c] +``` + +Pass 2 is what makes the later passes parallel: every cube gets a private output +range, so pass 3 and pass 4 never write the same location, and pass 4 can resolve +any edge because *all* vertices already exist. + +### 2.5 Determinism + +Output order is defined by the sweep, not by the schedule: + +* vertices are numbered in extended-cube order (pass 2's scan is order-preserving); +* within a cube, vertices follow the fixed rank order 0, 3, 8; +* triangles are emitted in real-cube order, in `triangle_table` order. + +Threads only partition ranges, and every pass is a pure function of the grid, so +1 thread and 24 threads produce byte-identical arrays. This is verified in +§4.2 and by `test_num_threads_array` / `test_num_threads_func`. + +### 2.6 Cost model + +Memory, transient unless stated otherwise: + +| | size | +| --- | --- | +| per extended cube | 9 B — `u8` cube index + two `u32` offsets (9 MB at 100³, 153 MB at 256³) | +| per vertex | 24 B (3 × `double`, returned) | +| per polygon index | 8 B (`size_t`, freed once the NumPy array is filled) | + +Work: pass 1 reads every grid node once (four reads per cube, reused along the +row) and stores three words; pass 3 re-reads four corner values for the cubes +that own a vertex; pass 4 touches no grid data at all. So the volume is streamed +twice and the total cost is `O(N + V + F)`. + +The second stream is why the multi-pass version does more memory traffic than the +old single sweep — but it writes into pre-sized arrays instead of growing a +`std::vector`, which more than pays for it: the implementation below is 1.6–2.2× +faster than the old sweep even on a single thread (see §4.3). + +--- + +## 3. Implementation + +### 3.1 File map + +| file | role | +| --- | --- | +| `mcubes/src/marchingcubes.h` | `thread_pool`, `exclusive_scan`, `marching_cubes_grid` (the five passes), `marching_cubes` entry point with `num_threads` | +| `mcubes/src/marchingcubes.cpp` | `edge_table`, `triangle_table`, `num_indices_table` (precalculated index counts per cube configuration), interpolation | +| `mcubes/src/pywrapper.cpp` | array/`func` entry points, dtype dispatch, GIL release, grid sampling for `marching_cubes_func` | +| `mcubes/src/_mcubes.pyx` | public `marching_cubes(volume, isovalue, num_threads=0)` | +| `setup.py` | `-pthread` on POSIX (needed to link `std::thread`) | + +### 3.2 Thread pool + +`private_::thread_pool` keeps `num_threads - 1` workers alive for the duration of +one call; the calling thread joins in, so a pool of one never spawns a thread. + +`parallel_for(count, body)` splits `[0, count)` into grain-sized chunks published +through one `std::function`, and workers steal chunks with an atomic counter, so +an uneven pass still balances. Completion uses a generation counter plus a +pending-worker count; a throwing body is captured in an `exception_ptr` and +rethrown by `parallel_for` after all workers are idle, so an exception can never +deadlock the pool. + +Threads are only created when the volume is worth it +(`(nx+1)(ny+1)(nz+1) >= 2^15`); below that the pool is built with one thread and +everything runs inline, so small volumes pay nothing for the machinery. + +### 3.3 Parallel prefix sum + +`exclusive_scan` is a two-level scan over `u32` counts, in place: each worker sums +a grain, the grain sums are scanned serially, then each worker writes its offsets +starting from its grain base. It falls back to a serial loop below 65 536 +elements or with one thread, and raises `RuntimeError` if the total exceeds +`2^32` (the offset arrays are 32 bit). + +### 3.4 Classification pass + +The inner loop walks whole `z` rows so the four corners shared with the next cube +stay in registers, which keeps the grid traffic at ~1 read per node: + +```cpp +double v4 = value_at(i, j, 0), v5 = value_at(i1, j, 0), + v6 = value_at(i1, j1, 0), v7 = value_at(i, j1, 0); +for(size_t k=0; k= 0`). +* The GIL is released (RAII `gil_release`) around the whole computation. +* The array path dispatches the dtype **once** into a typed strided reader + (`array_value_at`), so `bool` masks, integer volumes and `float64` all read + at the same speed, and negative strides / Fortran order work unchanged. Input + that is byte-swapped or unaligned is first converted to a native, aligned + `double` copy, because the reader dereferences the buffer directly. +* A grid whose element count would overflow `size_t` is rejected with a + `RuntimeError` before anything is allocated. +* `marching_cubes_func` evaluates `f(x, y, z)` **once per grid node** into a + `double` buffer — 4× fewer Python callbacks than the old rolling window — and + then runs the same parallel core on that buffer. Sampling must stay on the + calling thread because it calls back into Python. If `f` raises or returns a + non-number, the call aborts and re-raises that exception instead of building a + surface with the failing nodes replaced by `0.0`. + +### 3.8 Numerical behaviour + +Vertices are placed with the original formula +`(x2-x1)*(isovalue-f1)/(f2-f1) + x1`, but each owned edge is always interpolated +from its low corner, whereas the old code used the direction implied by the edge +table. The two are algebraically identical; they differ by at most 1 ULP when +floating point rounding lands differently. Integer and boolean volumes are +bit-identical (the weight is exactly `0.5`), and floating point volumes agree to +`≤ 3.6e-15` in absolute terms (§4.1). + +--- + +## 4. Validation + +Machine: Windows 11, 24 logical cores, MSVC 19.51, Python 3.11, NumPy 2.4. + +### 4.1 Mesh equivalence + +Compared against the previous implementation, order-independently (vertex +positions plus the set of triangles expressed by their corner coordinates): + +| corpus | result | +| --- | --- | +| 200 random volumes (noise, integer fields, sinusoids, spheres, quantised) | 200/200 identical triangle soup | +| 16 dtype/layout cases (`bool`, all int widths, `float32/64`, Fortran order, strided, negative strides; `longdouble` is `float64` on Windows) | identical soup; max vertex deviation `0` for `bool`/integer, `3.55e-15` for `float32/64` | +| 10 fixed cases (empty, sphere, torus, noise, 2×2×2, boundary-touching) | identical soup and counts | + +Topology is also asserted in the test suite: for a 40³ sphere `V - E + F = 2`, all +indices are in range, and no triangle is degenerate. + +`python -m pytest -q` → 20 passed, `flake8 .` → clean. + +### 4.2 Regenerated illustrations + +`images/binary.jpg`, `images/smooth.jpg` and `images/smoothing_overview.png` were +rebuilt from the meshes of §5 with an orthographic z-buffer renderer using the +same framing, grey background and top lighting, once from the old build and once +from the new one: + +| image | old vs new | new vs committed image | +| --- | --- | --- | +| `binary.jpg` | 0 of 65 536 pixels differ | silhouette IoU 0.91, grey correlation 0.67 | +| `smooth.jpg` | 9 of 65 536, each by 1 grey level | silhouette IoU 0.92, grey correlation 0.75 | +| `smoothing_overview.png` | 1 of 271 040, by 1 grey level | same 2×2 layout, panels and labels | + +The handful of 1-level pixels come from §3.8: 53 of 11 646 vertices of the +smoothed mesh differ by ≤ 1.4e-14, which flips a depth tie on a shared edge where +the surface is saturating. The remaining difference to the committed images is +lighting and camera only — the originals were produced by another renderer (and +the overview was assembled by hand in Inkscape). + +Rendering with 1, 2, 4 and 8 threads produces byte-identical images. + +### 4.3 Performance + +Best of 2–7 runs, timing the `marching_cubes` call only. Run-to-run variation on +this machine reaches 7–20 % for the 100³ cases, so treat differences below ~10 % +as noise. + +| workload | old (1 t) | new 1 t | new 2 t | **new 4 t** | new 8 t | new auto (24 t) | **4 t vs old** | +| --- | --- | --- | --- | --- | --- | --- | --- | +| binary 100³ (`binary.jpg`) | 19.33 | 9.31 | 6.18 | **4.17** | 3.44 | 3.73 | **4.64×** | +| smoothed 100³ (`smooth.jpg`) | 19.21 | 8.56 | 5.75 | **4.14** | 3.22 | 3.78 | **4.64×** | +| sphere 128³ (`float64`) | 34.51 | 19.46 | 12.92 | **8.83** | 7.96 | 8.49 | **3.91×** | +| sphere 256³ (`int64`) | 310.11 | 153.33 | 107.83 | **80.24** | 73.22 | 72.31 | **3.86×** | +| dense noise 160³ | 564.69 | 341.38 | 261.72 | **228.49** | 223.35 | 223.37 | **2.47×** | +| `marching_cubes_func` 100³ | 947.08 | 249.92 | 248.74 | **257.03** | 254.33 | 262.72 | **3.68×** | + +All times in milliseconds. + +Reading the table: + +* **Threads help most for sparse surfaces** (`4.6×` on both 100³ cases), which are + dominated by the grid reads in passes 1 and 3. +* **Dense fields saturate memory bandwidth** — the noise volume generates 6.1 M + vertices and 12.9 M indices, so 4 threads give only `2.5×` and the curve is flat + from 8 threads on. +* **The `func` API barely benefits from threads**: the GIL-bound Python callbacks + in the sampling loop dominate and run on one thread, so its 1–24 thread columns + are all within noise. Its `3.7×` win over the old implementation comes from + evaluating each grid node once instead of four times. +* **One thread is already faster than the old sweep everywhere** (1.65–2.24×, and + 3.8× for `func`): the passes cost an extra stream over the volume but remove the + `push_back` growth and the shared-index bookkeeping. +* Auto (24 threads) is not the best choice for memory-bound volumes on a large + machine; it helps sparse surfaces slightly and is within noise elsewhere. + +--- + +## 5. Reproducing + +```bash +python -m pip install -e . +python -m pytest -q +``` + +The meshes behind the illustrations: + +```python +import numpy as np, mcubes + +x, y, z = np.mgrid[:100, :100, :100] +binary_sphere = (x - 50)**2 + (y - 50)**2 + (z - 50)**2 - 25**2 < 0 +vertices, triangles = mcubes.marching_cubes(binary_sphere, 0.5, num_threads=4) + +smoothed_sphere = mcubes.smooth(binary_sphere) +vertices, triangles = mcubes.marching_cubes(smoothed_sphere, 0, num_threads=4) +``` + +A timing harness for any volume and thread count: + +```python +import time, numpy as np, mcubes + +x, y, z = np.mgrid[:256, :256, :256] +volume = (x - 128)**2 + (y - 128)**2 + (z - 128)**2 - 96**2 + +for num_threads in (1, 2, 4, 8, 0): + times = [] + for _ in range(5): + start = time.perf_counter() + mcubes.marching_cubes(volume, 0.0, num_threads=num_threads) + times.append(time.perf_counter() - start) + print(f"{num_threads:2d} threads: {min(times) * 1000:6.1f} ms") +``` + +--- + +## 6. Notes and limitations + +* **Scratch memory** is 9 bytes per extended cube — ~9 MB for 100³ and ~153 MB for + 256³ — on top of the vertices (24 B each) and the polygon buffer (8 B per index + while the call runs). The arrays are allocated whatever the thread count, so a + volume that only just fits in memory today may need a smaller grid here. +* **32-bit offsets.** Vertex and polygon counts above `2^32` raise + `RuntimeError: Mesh is too large for 32 bit indices.` A 4096³ smooth surface + produces roughly 5·10⁸ indices, still an order of magnitude below the limit. +* **Small volumes stay serial** below 32 768 cubes; `num_threads` has no effect + there and no threads are created. +* **Nested parallelism.** Each call builds its own pool, so calling + `marching_cubes` from inside another thread pool multiplies the thread count; + pass a smaller `num_threads` in that case. +* **The C++ entry point changed contract.** `mc::marching_cubes` now takes a + `value_at(i, j, k)` callable that receives **grid node indices**, not physical + coordinates, and it may be called from several threads at once when + `num_threads > 1`. A lambda written against the old coordinate-based signature + still compiles but would return the wrong field, so C++ callers that pass their + own callable must adapt it. The Python API is unaffected: + `mcubes.marching_cubes_func` still calls `f(x, y, z)` with coordinates. The + lookup tables (`edge_table`, `triangle_table`, `num_indices_table`) are now + declared `const`, so code that wrote to them no longer compiles. +* The polygon buffer is still returned as `NPY_ULONG`, matching the previous + behaviour (32-bit indices on Windows, 64-bit elsewhere). diff --git a/README.md b/README.md index 94cb451..81e588c 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,23 @@ a `NumPy` array: Note that using a function to represent the volumetric data is **much** slower than using a `NumPy` array. +## Parallel processing + +Both `mcubes.marching_cubes` and `mcubes.marching_cubes_func` accept a +`num_threads` argument. The default, `0`, uses one thread per CPU core and `1` +runs the algorithm on the calling thread only. The extracted mesh is the same +for every value, so the argument only affects speed: + +```Python + >>> vertices, triangles = mcubes.marching_cubes(u, 0, num_threads=4) +``` + +The volume is swept in several passes (classify the cubes, prefix sum their +vertex counts, place the vertices, and finally emit the triangles), and each +pass runs in parallel. Vertices are owned by exactly one cube, which is what +makes the passes independent of each other. See [PARALLEL.md](PARALLEL.md) for +the algorithm, the implementation notes and the benchmarks. + ## Smoothing binary arrays ![Overview](images/smoothing_overview.png "Overview of mcubes.smooth") diff --git a/mcubes/src/_mcubes.pyx b/mcubes/src/_mcubes.pyx index ab0707c..2b944ef 100644 --- a/mcubes/src/_mcubes.pyx +++ b/mcubes/src/_mcubes.pyx @@ -14,17 +14,32 @@ cimport numpy as np np.import_array() cdef extern from "pywrapper.h": - cdef object c_marching_cubes "marching_cubes"(np.ndarray, double) except + - cdef object c_marching_cubes_func "marching_cubes_func"(tuple, tuple, int, int, int, object, double) except + + cdef object c_marching_cubes "marching_cubes"(np.ndarray, double, int) except + + cdef object c_marching_cubes_func "marching_cubes_func"(tuple, tuple, int, int, int, object, double, int) except + -def marching_cubes(np.ndarray volume, float isovalue): - - verts, faces = c_marching_cubes(volume, isovalue) +def marching_cubes(np.ndarray volume, float isovalue, int num_threads=0): + """Extract the isosurface of a 3D volume. + + ``num_threads`` selects how many threads the algorithm may use. The default + of 0 uses one thread per CPU core, and 1 keeps it single-threaded. The + result does not depend on this value. + """ + + if num_threads < 0: + raise ValueError("num_threads cannot be negative") + + verts, faces = c_marching_cubes(volume, isovalue, num_threads) verts.shape = (-1, 3) faces.shape = (-1, 3) return verts, faces -def marching_cubes_func(tuple lower, tuple upper, int numx, int numy, int numz, object f, double isovalue): +def marching_cubes_func(tuple lower, tuple upper, int numx, int numy, int numz, object f, double isovalue, int num_threads=0): + """Extract the isosurface of a volume given as a function ``f(x, y, z)``. + + ``num_threads`` selects how many threads the algorithm may use. The default + of 0 uses one thread per CPU core, and 1 keeps it single-threaded. The + result does not depend on this value. + """ if any(l_i >= u_i for l_i, u_i in zip(lower, upper)): raise ValueError("lower coordinates cannot be larger than upper coordinates") @@ -32,7 +47,10 @@ def marching_cubes_func(tuple lower, tuple upper, int numx, int numy, int numz, if numx < 2 or numy < 2 or numz < 2: raise ValueError("numx, numy, numz cannot be smaller than 2") - verts, faces = c_marching_cubes_func(lower, upper, numx, numy, numz, f, isovalue) + if num_threads < 0: + raise ValueError("num_threads cannot be negative") + + verts, faces = c_marching_cubes_func(lower, upper, numx, numy, numz, f, isovalue, num_threads) verts.shape = (-1, 3) faces.shape = (-1, 3) return verts, faces diff --git a/mcubes/src/marchingcubes.cpp b/mcubes/src/marchingcubes.cpp index 18deeb1..92b613c 100644 --- a/mcubes/src/marchingcubes.cpp +++ b/mcubes/src/marchingcubes.cpp @@ -1,334 +1,323 @@ - -#include "marchingcubes.h" - -namespace mc -{ - -int edge_table[256] = -{ - 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, - 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, - 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, - 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, - 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, - 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, - 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, - 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, - 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, - 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, - 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, - 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, - 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, - 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, - 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, - 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 -}; - -int triangle_table[256][16] = -{ - {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, - {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, - {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, - {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, - {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, - {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, - {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, - {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, - {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, - {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, - {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, - {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, - {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, - {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, - {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, - {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, - {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, - {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, - {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, - {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, - {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, - {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, - {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, - {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, - {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, - {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, - {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, - {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, - {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, - {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, - {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, - {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, - {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, - {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, - {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, - {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, - {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, - {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, - {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, - {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, - {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, - {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, - {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, - {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, - {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, - {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, - {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, - {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, - {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, - {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, - {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, - {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, - {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, - {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, - {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, - {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, - {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, - {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, - {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, - {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, - {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, - {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, - {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, - {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, - {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, - {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, - {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, - {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, - {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, - {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, - {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, - {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, - {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, - {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, - {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, - {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, - {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, - {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, - {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, - {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, - {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, - {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, - {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, - {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, - {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, - {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, - {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, - {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, - {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, - {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, - {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, - {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, - {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, - {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, - {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, - {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, - {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, - {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, - {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, - {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, - {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, - {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, - {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, - {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, - {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, - {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, - {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, - {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, - {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, - {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, - {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, - {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, - {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, - {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, - {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, - {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, - {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, - {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, - {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, - {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, - {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, - {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, - {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, - {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, - {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, - {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, - {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, - {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, - {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, - {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, - {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, - {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, - {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, - {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, - {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, - {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, - {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, - {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, - {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, - {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, - {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, - {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, - {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, - {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, - {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, - {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, - {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, - {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, - {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, - {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, - {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, - {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, - {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, - {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, - {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, - {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} -}; - -namespace private_ -{ - -double mc_isovalue_interpolation(double isovalue, double f1, double f2, - double x1, double x2) -{ - if(f2==f1) - return (x2+x1)/2; - - return (x2-x1)*(isovalue-f1)/(f2-f1) + x1; -} - -size_t mc_add_vertex(double x1, double y1, double z1, double c2, - int axis, double f1, double f2, double isovalue, std::vector* vertices) -{ - size_t vertex_index = vertices->size() / 3; - if(axis == 0) - { - double x = mc_isovalue_interpolation(isovalue, f1, f2, x1, c2); - vertices->push_back(x); - vertices->push_back(y1); - vertices->push_back(z1); - return vertex_index; - } - if(axis == 1) - { - double y = mc_isovalue_interpolation(isovalue, f1, f2, y1, c2); - vertices->push_back(x1); - vertices->push_back(y); - vertices->push_back(z1); - return vertex_index; - } - if(axis == 2) - { - double z = mc_isovalue_interpolation(isovalue, f1, f2, z1, c2); - vertices->push_back(x1); - vertices->push_back(y1); - vertices->push_back(z); - return vertex_index; - } - - // This should not happen. - return -1; -} - -} - -} + +#include "marchingcubes.h" + +namespace mc +{ + +const int edge_table[256] = +{ + 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, + 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, + 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, + 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, + 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, + 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, + 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, + 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, + 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, + 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, + 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, + 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, + 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, + 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, + 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, + 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 +}; + +const int triangle_table[256][16] = +{ + {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, + {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, + {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, + {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, + {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, + {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, + {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, + {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, + {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, + {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, + {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, + {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, + {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, + {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, + {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, + {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, + {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, + {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, + {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, + {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, + {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, + {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, + {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, + {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, + {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, + {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, + {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, + {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, + {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, + {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, + {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, + {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, + {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, + {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, + {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, + {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, + {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, + {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, + {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, + {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, + {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, + {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, + {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, + {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, + {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, + {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, + {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, + {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, + {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, + {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, + {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, + {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, + {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, + {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, + {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, + {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, + {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, + {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, + {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, + {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, + {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, + {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, + {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, + {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, + {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, + {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, + {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, + {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, + {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, + {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, + {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, + {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, + {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, + {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, + {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, + {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, + {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, + {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, + {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, + {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, + {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, + {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, + {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, + {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, + {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, + {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, + {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, + {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, + {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, + {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, + {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, + {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, + {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, + {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, + {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, + {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, + {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, + {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, + {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, + {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, + {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, + {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, + {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, + {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, + {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, + {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, + {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, + {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, + {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, + {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, + {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, + {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, + {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, + {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, + {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, + {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, + {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, + {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, + {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, + {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, + {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, + {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, + {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, + {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, + {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, + {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, + {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, + {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, + {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, + {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, + {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, + {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, + {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, + {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, + {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, + {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, + {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, + {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, + {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, + {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, + {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, + {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, + {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, + {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, + {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, + {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, + {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, + {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, + {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, + {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, + {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, + {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, + {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, + {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, + {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, + {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, + {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, + {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, + {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, + {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, + {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, + {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, + {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, + {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, + {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, + {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, + {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, + {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, + {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, + {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, + {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, + {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, + {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, + {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, + {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, + {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, + {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, + {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, + {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, + {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} +}; + +// Number of polygon indices of each cube configuration, i.e. the entries of +// triangle_table[cube_index] before its -1 terminator. +const int num_indices_table[256] = +{ + 0, 3, 3, 6, 3, 6, 6, 9, 3, 6, 6, 9, 6, 9, 9, 6, + 3, 6, 6, 9, 6, 9, 9, 12, 6, 9, 9, 12, 9, 12, 12, 9, + 3, 6, 6, 9, 6, 9, 9, 12, 6, 9, 9, 12, 9, 12, 12, 9, + 6, 9, 9, 6, 9, 12, 12, 9, 9, 12, 12, 9, 12, 15, 15, 6, + 3, 6, 6, 9, 6, 9, 9, 12, 6, 9, 9, 12, 9, 12, 12, 9, + 6, 9, 9, 12, 9, 12, 12, 15, 9, 12, 12, 15, 12, 15, 15, 12, + 6, 9, 9, 12, 9, 12, 6, 9, 9, 12, 12, 15, 12, 15, 9, 6, + 9, 12, 12, 9, 12, 15, 9, 6, 12, 15, 15, 12, 15, 6, 12, 3, + 3, 6, 6, 9, 6, 9, 9, 12, 6, 9, 9, 12, 9, 12, 12, 9, + 6, 9, 9, 12, 9, 12, 12, 15, 9, 6, 12, 9, 12, 9, 15, 6, + 6, 9, 9, 12, 9, 12, 12, 15, 9, 12, 12, 15, 12, 15, 15, 12, + 9, 12, 12, 9, 12, 15, 15, 12, 12, 9, 15, 6, 15, 12, 6, 3, + 6, 9, 9, 12, 9, 12, 12, 15, 9, 12, 12, 15, 6, 9, 9, 6, + 9, 12, 12, 15, 12, 15, 15, 6, 12, 9, 15, 12, 9, 6, 12, 3, + 9, 12, 12, 15, 12, 15, 9, 12, 12, 15, 15, 6, 9, 12, 6, 3, + 6, 9, 9, 6, 9, 12, 6, 3, 9, 6, 12, 3, 6, 3, 3, 0, +}; + +namespace private_ +{ + +double mc_isovalue_interpolation(double isovalue, double f1, double f2, + double x1, double x2) +{ + if(f2==f1) + return (x2+x1)/2; + + return (x2-x1)*(isovalue-f1)/(f2-f1) + x1; +} + +} + +} diff --git a/mcubes/src/marchingcubes.h b/mcubes/src/marchingcubes.h index 10b44a6..4617dd6 100644 --- a/mcubes/src/marchingcubes.h +++ b/mcubes/src/marchingcubes.h @@ -1,217 +1,587 @@ - -#ifndef _MARCHING_CUBES_H -#define _MARCHING_CUBES_H - -#include -#include -#include - -namespace mc -{ - -extern int edge_table[256]; -extern int triangle_table[256][16]; - -namespace private_ -{ - -double mc_isovalue_interpolation(double isovalue, double f1, double f2, - double x1, double x2); -size_t mc_add_vertex(double x1, double y1, double z1, double c2, - int axis, double f1, double f2, double isovalue, std::vector* vertices); -} - -template -void marching_cubes(const vector3& lower, const vector3& upper, - int numx, int numy, int numz, formula f, double isovalue, - std::vector& vertices, std::vector& polygons) -{ - using coord_type = typename vector3::value_type; - using size_type = typename vector3::size_type; - using namespace private_; - - // Some initial checks - if(numx < 2 || numy < 2 || numz < 2) - return; - - if(!std::equal(std::begin(lower), std::end(lower), std::begin(upper), - [](double a, double b)->bool {return a <= b;})) - return; - - // numx, numy and numz are the numbers of evaluations in each direction - --numx; --numy; --numz; - - coord_type dx = (upper[0] - lower[0]) / static_cast(numx); - coord_type dy = (upper[1] - lower[1]) / static_cast(numy); - coord_type dz = (upper[2] - lower[2]) / static_cast(numz); - - const int num_shared_indices = 2 * (numy + 1) * (numz + 1); - std::vector shared_indices_x(num_shared_indices); - std::vector shared_indices_y(num_shared_indices); - std::vector shared_indices_z(num_shared_indices); - auto _offset = [&](size_t i, size_t j, size_t k){return i*(numy+1)*(numz+1) + j*(numz+1) + k;}; - - for(int i=0; i indices; - if(edges & 0x040) - { - size_t index = mc_add_vertex(x_dx, y_dy, z_dz, x, 0, v[6], v[7], isovalue, &vertices); - indices[6] = index; - shared_indices_x[_offset(i_mod_2_inv, j+1, k+1)] = index; - } - if(edges & 0x020) - { - size_t index = mc_add_vertex(x_dx, y, z_dz, y_dy, 1, v[5], v[6], isovalue, &vertices); - indices[5] = index; - shared_indices_y[_offset(i_mod_2_inv, j+1, k+1)] = index; - } - if(edges & 0x400) - { - size_t index = mc_add_vertex(x_dx, y_dy, z, z_dz, 2, v[2], v[6], isovalue, &vertices); - indices[10] = index; - shared_indices_z[_offset(i_mod_2_inv, j+1, k+1)] = index; - } - - if(edges & 0x001) - { - if(j == 0 && k == 0) - { - size_t index = mc_add_vertex(x, y, z, x_dx, 0, v[0], v[1], isovalue, &vertices); - indices[0] = index; - } - else - indices[0] = shared_indices_x[_offset(i_mod_2_inv, j, k)]; - } - if(edges & 0x002) - { - if(k == 0) - { - size_t index = mc_add_vertex(x_dx, y, z, y_dy, 1, v[1], v[2], isovalue, &vertices); - indices[1] = index; - shared_indices_y[_offset(i_mod_2_inv, j+1, k)] = index; - } - else - indices[1] = shared_indices_y[_offset(i_mod_2_inv, j+1, k)]; - } - if(edges & 0x004) - { - if(k == 0) - { - size_t index = mc_add_vertex(x_dx, y_dy, z, x, 0, v[2], v[3], isovalue, &vertices); - indices[2] = index; - shared_indices_x[_offset(i_mod_2_inv, j+1, k)] = index; - } - else - indices[2] = shared_indices_x[_offset(i_mod_2_inv, j+1, k)]; - } - if(edges & 0x008) - { - if(i == 0 && k == 0) - { - size_t index = mc_add_vertex(x, y_dy, z, y, 1, v[3], v[0], isovalue, &vertices); - indices[3] = index; - } - else - indices[3] = shared_indices_y[_offset(i_mod_2, j+1, k)]; - } - if(edges & 0x010) - { - if(j == 0) - { - size_t index = mc_add_vertex(x, y, z_dz, x_dx, 0, v[4], v[5], isovalue, &vertices); - indices[4] = index; - shared_indices_x[_offset(i_mod_2_inv, j, k+1)] = index; - } - else - indices[4] = shared_indices_x[_offset(i_mod_2_inv, j, k+1)]; - } - if(edges & 0x080) - { - if(i == 0) - { - size_t index = mc_add_vertex(x, y_dy, z_dz, y, 1, v[7], v[4], isovalue, &vertices); - indices[7] = index; - shared_indices_y[_offset(i_mod_2, j+1, k+1)] = index; - } - else - indices[7] = shared_indices_y[_offset(i_mod_2, j+1, k+1)]; - } - if(edges & 0x100) - { - if(i == 0 && j == 0) - { - size_t index = mc_add_vertex(x, y, z, z_dz, 2, v[0], v[4], isovalue, &vertices); - indices[8] = index; - } - else - indices[8] = shared_indices_z[_offset(i_mod_2, j, k+1)]; - } - if(edges & 0x200) - { - if(j == 0) - { - size_t index = mc_add_vertex(x_dx, y, z, z_dz, 2, v[1], v[5], isovalue, &vertices); - indices[9] = index; - shared_indices_z[_offset(i_mod_2_inv, j, k+1)] = index; - } - else - indices[9] = shared_indices_z[_offset(i_mod_2_inv, j, k+1)]; - } - if(edges & 0x800) - { - if(i == 0) - { - size_t index = mc_add_vertex(x, y_dy, z, z_dz, 2, v[3], v[7], isovalue, &vertices); - indices[11] = index; - shared_indices_z[_offset(i_mod_2, j+1, k+1)] = index; - } - else - indices[11] = shared_indices_z[_offset(i_mod_2, j+1, k+1)]; - } - - int tri; - int* triangle_table_ptr = triangle_table[cubeindex]; - for(int m=0; tri = triangle_table_ptr[m], tri != -1; ++m) - polygons.push_back(indices[tri]); - } - } - } - -} - -} - -#endif // _MARCHING_CUBES_H +#ifndef _MARCHING_CUBES_H +#define _MARCHING_CUBES_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mc +{ + +extern const int edge_table[256]; +extern const int triangle_table[256][16]; +extern const int num_indices_table[256]; + +namespace private_ +{ + +double mc_isovalue_interpolation(double isovalue, double f1, double f2, + double x1, double x2); + +inline int default_num_threads() +{ + static const int num = []() -> int + { + const unsigned int hardware = std::thread::hardware_concurrency(); + return hardware == 0 ? 1 : static_cast(hardware); + }(); + return num; +} + +// Minimal fixed size thread pool. The thread creating the pool takes part in +// every parallel loop, so a pool of one runs everything serially without +// spawning any thread at all. +class thread_pool +{ +public: + explicit thread_pool(int num_threads) + : next_(0), num_pending_(0), generation_(0), stop_(false) + { + int requested = num_threads > 0 ? num_threads : default_num_threads(); + requested = std::min(requested, 512); + const size_t num_workers = requested > 1 ? static_cast(requested - 1) : 0; + workers_.reserve(num_workers); + try + { + for(size_t i=0; i lock(mutex_); + stop_ = true; + } + wake_.notify_all(); + for(size_t i=0; i lock(mutex_); + stop_ = true; + } + wake_.notify_all(); + for(size_t i=0; i(workers_.size()) + 1; } + + // Calls body(first, last) on disjoint sub-ranges covering [0, count). + template + void parallel_for(size_t count, const body_type& body) + { + if(count == 0) + return; + + const size_t total = static_cast(size()); + if(total <= 1) + { + body(static_cast(0), count); + return; + } + + // A few chunks per thread, so that the atomic counter can rebalance a + // pass whose rows have very different costs. + const size_t num_parts = std::min(total * 4, count); + const size_t grain = (count + num_parts - 1) / num_parts; + const size_t num_grains = (count + grain - 1) / grain; + + // A throwing body must not leave the other threads waiting forever. + std::exception_ptr error; + std::mutex error_mutex; + + next_ = 0; + { + std::lock_guard lock(mutex_); + job_ = [&]() + { + for(;;) + { + const size_t g = next_.fetch_add(1, std::memory_order_relaxed); + if(g >= num_grains) + return; + const size_t begin = g * grain; + const size_t end = std::min(count, begin + grain); + try + { + body(begin, end); + } + catch(...) + { + std::lock_guard elock(error_mutex); + if(!error) + error = std::current_exception(); + return; + } + } + }; + num_pending_ = workers_.size(); + ++generation_; + } + wake_.notify_all(); + job_(); + { + std::unique_lock lock(mutex_); + done_.wait(lock, [this]() { return num_pending_ == 0; }); + job_ = nullptr; + } + + if(error) + std::rethrow_exception(error); + } + +private: + void worker_loop() + { + std::uint64_t seen = 0; + for(;;) + { + std::function job; + { + std::unique_lock lock(mutex_); + wake_.wait(lock, [this, seen]() { return stop_ || generation_ != seen; }); + if(stop_) + return; + seen = generation_; + try + { + job = job_; + } + catch(...) + { + // The copy may allocate; nothing to run, but the decrement + // below must still happen or the caller waits forever. + job = nullptr; + } + } + if(job) + job(); + { + std::lock_guard lock(mutex_); + --num_pending_; + if(num_pending_ == 0) + done_.notify_one(); + } + } + } + + std::vector workers_; + std::mutex mutex_; + std::condition_variable wake_; + std::condition_variable done_; + std::function job_; + std::atomic next_; + size_t num_pending_; + std::uint64_t generation_; + bool stop_; +}; + +// Turns per element counts into exclusive prefix offsets, in place, and returns +// the total. +inline std::uint32_t exclusive_scan(std::uint32_t* data, size_t count, + thread_pool& pool) +{ + if(count == 0) + return 0; + + const std::uint64_t max_value = 0xFFFFFFFFull; + + if(pool.size() <= 1 || count < (1u << 16)) + { + std::uint64_t sum = 0; + for(size_t i=0; i(sum); + sum += value; + } + if(sum > max_value) + throw std::runtime_error("Mesh is too large for 32 bit indices."); + return static_cast(sum); + } + + const size_t num_grains = static_cast(pool.size()) * 4; + const size_t grain = (count + num_grains - 1) / num_grains; + const size_t real_grains = (count + grain - 1) / grain; + std::vector grain_sums(real_grains); + + pool.parallel_for(real_grains, [&](size_t first, size_t last) + { + for(size_t g=first; g max_value) + throw std::runtime_error("Mesh is too large for 32 bit indices."); + + pool.parallel_for(real_grains, [&](size_t first, size_t last) + { + for(size_t g=first; g(grain_sums[g]); + const size_t stop = std::min(count, (g + 1) * grain); + for(size_t i=g*grain; i(total); +} + +// A cube owns the three edges that start at its minimum corner. Every edge of +// the volume is such an edge of exactly one cube, so every crossing yields +// exactly one vertex and the passes below are independent of each other. +inline std::uint32_t owned_edge_count(int edges) +{ + return static_cast(((edges & 0x001) ? 1 : 0) + + ((edges & 0x008) ? 1 : 0) + ((edges & 0x100) ? 1 : 0)); +} + +inline std::uint32_t owned_edge_rank(int edges, int edge) +{ + switch(edge) + { + case 0: + return 0; + case 3: + return (edges & 0x001) ? 1u : 0u; + case 8: + return ((edges & 0x001) ? 1u : 0u) + ((edges & 0x008) ? 1u : 0u); + default: + break; + } + assert(false && "owned_edge_rank supports only edges 0, 3 and 8"); + return 0; +} + +// Count-then-fill marching cubes over a regular grid. +// +// value_at(i, j, k) returns the scalar field at grid node (i, j, k) and must be +// callable concurrently. The grid holds numx * numy * numz nodes, spanning +// [x0, x0 + dx * (numx - 1)] and likewise for the other axes. +// +// The volume is swept in passes that are individually parallel: +// 1. classify every cube and count the vertices it owns, +// 2. prefix sum those counts into vertex offsets, +// 3. compute every vertex position, +// 4. prefix sum the polygon counts into polygon offsets, +// 5. emit the polygons. +template +void marching_cubes_grid(const value_at_type& value_at, + size_t numx, size_t numy, size_t numz, + double x0, double y0, double z0, + double dx, double dy, double dz, + double isovalue, int num_threads, + std::vector& vertices, std::vector& polygons) +{ + if(numx < 2 || numy < 2 || numz < 2) + return; + + const size_t nx = numx - 1; + const size_t ny = numy - 1; + const size_t nz = numz - 1; + + // One extra layer of "ghost" cubes past the upper boundary of each axis + // owns the edges lying on that boundary. Ghost cubes create vertices but + // never polygons, so the ownership rule above holds for the whole extended + // box and no axis needs a special case. + const size_t cx = nx + 1; + const size_t cy = ny + 1; + const size_t cz = nz + 1; + const size_t num_cubes = cx * cy * cz; + const size_t num_rows = cx * cy; + + std::vector xs(numx), ys(numy), zs(numz); + for(size_t i=0; i(i); + for(size_t j=0; j(j); + for(size_t k=0; k(k); + + // Marching cubes is memory bound; spawning threads for a small volume costs + // more than it saves. + const size_t parallel_threshold = 1u << 15; + thread_pool pool(num_cubes < parallel_threshold ? 1 : num_threads); + + std::vector cube_index(num_cubes); + std::vector vertex_offset(num_cubes); + std::vector polygon_offset(num_cubes); + + // Pass 1: classify cubes and count the vertices they own. + pool.parallel_for(num_rows, [&](size_t row_first, size_t row_last) + { + for(size_t row=row_first; row(ci); + vertex_offset[cube] = owned_edge_count(edge_table[ci]); + polygon_offset[cube] = (has_x && has_y && has_z) + ? static_cast(num_indices_table[ci]) : 0; + } + } + }); + + // Pass 2: turn the per cube counts into offsets. + const std::uint32_t num_vertices = exclusive_scan( + vertex_offset.data(), num_cubes, pool); + const std::uint32_t num_polygon_indices = exclusive_scan( + polygon_offset.data(), num_cubes, pool); + + vertices.resize(static_cast(num_vertices) * 3); + polygons.resize(static_cast(num_polygon_indices)); + + // Pass 3: compute the position of every vertex. + pool.parallel_for(num_rows, [&](size_t row_first, size_t row_last) + { + for(size_t row=row_first; row(vertex_offset[cube]) * 3]; + + if(edges & 0x001) + { + const double v1 = value_at(i1, j, k); + *vertex++ = mc_isovalue_interpolation(isovalue, v0, v1, xi, xi1); + *vertex++ = yj; + *vertex++ = zs[k]; + } + if(edges & 0x008) + { + const double v3 = value_at(i, j1, k); + *vertex++ = xi; + *vertex++ = mc_isovalue_interpolation(isovalue, v3, v0, yj1, yj); + *vertex++ = zs[k]; + } + if(edges & 0x100) + { + const double v4 = value_at(i, j, k1); + *vertex++ = xi; + *vertex++ = yj; + *vertex++ = mc_isovalue_interpolation(isovalue, v0, v4, zs[k], zs[k1]); + } + } + } + }); + + // Pass 4: emit polygons, resolving the vertex of every shared edge through + // the cube that owns it. + pool.parallel_for(num_rows, [&](size_t row_first, size_t row_last) + { + for(size_t row=row_first; row= nx || j >= ny) + continue; + + size_t cube = row * cz; + for(size_t k=0; k(num_indices_table[ci]); + if(num_indices == 0) + continue; + + const int edges = edge_table[ci]; + const size_t cube_j1 = cube + cz; + const size_t cube_k1 = cube + 1; + const size_t cube_i1 = cube + cy * cz; + + std::uint32_t index[12] = {}; + index[0] = vertex_offset[cube]; + index[3] = vertex_offset[cube] + owned_edge_rank(edges, 3); + index[8] = vertex_offset[cube] + owned_edge_rank(edges, 8); + + // x edges, owned by the +y and +z neighbours + if(edges & 0x004) index[2] = vertex_offset[cube_j1]; + if(edges & 0x010) index[4] = vertex_offset[cube_k1]; + if(edges & 0x040) index[6] = vertex_offset[cube_j1 + 1]; + // y edges, owned by the +x and +z neighbours + if(edges & 0x002) + index[1] = vertex_offset[cube_i1] + + owned_edge_rank(edge_table[cube_index[cube_i1]], 3); + if(edges & 0x020) + index[5] = vertex_offset[cube_i1 + 1] + + owned_edge_rank(edge_table[cube_index[cube_i1 + 1]], 3); + if(edges & 0x080) + index[7] = vertex_offset[cube_k1] + + owned_edge_rank(edge_table[cube_index[cube_k1]], 3); + // z edges, owned by the +x and +y neighbours + if(edges & 0x200) + index[9] = vertex_offset[cube_i1] + + owned_edge_rank(edge_table[cube_index[cube_i1]], 8); + if(edges & 0x400) + index[10] = vertex_offset[cube_i1 + cz] + + owned_edge_rank(edge_table[cube_index[cube_i1 + cz]], 8); + if(edges & 0x800) + index[11] = vertex_offset[cube_j1] + + owned_edge_rank(edge_table[cube_index[cube_j1]], 8); + + const int* triangles = triangle_table[ci]; + size_t* polygon = &polygons[polygon_offset[cube]]; + for(size_t m=0; m= 8 nodes. +// Vertices are emitted in (i, j, k) cube order; polygons index into them. +// +// Memory: besides the output mesh (24 bytes per vertex, sizeof(size) per polygon +// index), the algorithm allocates 9 bytes per (numx * numy * numz) cube of its +// extended grid, e.g. ~9 MB for a 100^3 node grid and ~153 MB for 256^3. These +// buffers are allocated whatever num_threads is. +template +void marching_cubes(const vector3& lower, const vector3& upper, + int numx, int numy, int numz, value_at_type value_at, double isovalue, + std::vector& vertices, std::vector& polygons, + int num_threads = 0) +{ + using coord_type = typename vector3::value_type; + + // Some initial checks + if(numx < 2 || numy < 2 || numz < 2) + return; + + if(!std::equal(std::begin(lower), std::end(lower), std::begin(upper), + [](coord_type a, coord_type b)->bool {return a <= b;})) + return; + + // numx, numy and numz are the numbers of evaluations in each direction + const int num_cells_x = numx - 1; + const int num_cells_y = numy - 1; + const int num_cells_z = numz - 1; + + const double x0 = static_cast(lower[0]); + const double y0 = static_cast(lower[1]); + const double z0 = static_cast(lower[2]); + const double dx = static_cast( + (upper[0] - lower[0]) / static_cast(num_cells_x)); + const double dy = static_cast( + (upper[1] - lower[1]) / static_cast(num_cells_y)); + const double dz = static_cast( + (upper[2] - lower[2]) / static_cast(num_cells_z)); + + private_::marching_cubes_grid(value_at, + static_cast(numx), static_cast(numy), static_cast(numz), + x0, y0, z0, dx, dy, dz, isovalue, num_threads, vertices, polygons); +} + +} + +#endif // _MARCHING_CUBES_H diff --git a/mcubes/src/pywrapper.cpp b/mcubes/src/pywrapper.cpp index a9ee87a..01bc66d 100644 --- a/mcubes/src/pywrapper.cpp +++ b/mcubes/src/pywrapper.cpp @@ -1,118 +1,304 @@ - -#include "pywrapper.h" - -#include "marchingcubes.h" - -#include -#include - - -PyObject* marching_cubes_func(PyObject* lower, PyObject* upper, - int numx, int numy, int numz, PyObject* pyfunc, double isovalue) -{ - std::vector vertices; - std::vector polygons; - - // Copy the lower and upper coordinates to a C array. - std::array lower_; - std::array upper_; - for(int i=0; i<3; ++i) - { - PyObject* l = PySequence_GetItem(lower, i); - if(l == NULL) - throw std::runtime_error("len(lower) < 3"); - PyObject* u = PySequence_GetItem(upper, i); - if(u == NULL) - { - Py_DECREF(l); - throw std::runtime_error("len(upper) < 3"); - } - - lower_[i] = PyFloat_AsDouble(l); - upper_[i] = PyFloat_AsDouble(u); - - Py_DECREF(l); - Py_DECREF(u); - if(lower_[i]==-1.0 || upper_[i]==-1.0) - { - if(PyErr_Occurred()) - throw std::runtime_error("unknown error"); - } - } - - auto pyfunc_to_cfunc = [&](double x, double y, double z) -> double { - PyObject* res = PyObject_CallFunction(pyfunc, "(d,d,d)", x, y, z); - if(res == NULL) - return 0.0; - - double result = PyFloat_AsDouble(res); - Py_DECREF(res); - return result; - }; - - // Marching cubes. - mc::marching_cubes(lower_, upper_, numx, numy, numz, pyfunc_to_cfunc, isovalue, vertices, polygons); - - // Copy the result to two Python ndarrays. - npy_intp size_vertices = vertices.size(); - npy_intp size_polygons = polygons.size(); - PyArrayObject* verticesarr = reinterpret_cast(PyArray_SimpleNew(1, &size_vertices, NPY_DOUBLE)); - PyArrayObject* polygonsarr = reinterpret_cast(PyArray_SimpleNew(1, &size_polygons, NPY_ULONG)); - - std::vector::const_iterator it = vertices.begin(); - for(int i=0; it!=vertices.end(); ++i, ++it) - *reinterpret_cast(PyArray_GETPTR1(verticesarr, i)) = *it; - std::vector::const_iterator it2 = polygons.begin(); - for(int i=0; it2!=polygons.end(); ++i, ++it2) - *reinterpret_cast(PyArray_GETPTR1(polygonsarr, i)) = *it2; - - PyObject* res = Py_BuildValue("(O,O)", verticesarr, polygonsarr); - Py_XDECREF(verticesarr); - Py_XDECREF(polygonsarr); - return res; -} - - -PyObject* marching_cubes(PyArrayObject* arr, double isovalue) -{ - if(PyArray_NDIM(arr) != 3) - throw std::runtime_error("Only three-dimensional arrays are supported."); - - // Prepare data. - npy_intp* shape = PyArray_DIMS(arr); - std::array lower{0, 0, 0}; - std::array upper{shape[0]-1, shape[1]-1, shape[2]-1}; - long numx = upper[0] - lower[0] + 1; - long numy = upper[1] - lower[1] + 1; - long numz = upper[2] - lower[2] + 1; - std::vector vertices; - std::vector polygons; - - auto pyarray_to_cfunc = [&](long x, long y, long z) -> double { - const npy_intp c[3] = {x, y, z}; - return PyArray_SafeGet(arr, c); - }; - - // Marching cubes. - mc::marching_cubes(lower, upper, numx, numy, numz, pyarray_to_cfunc, isovalue, - vertices, polygons); - - // Copy the result to two Python ndarrays. - npy_intp size_vertices = vertices.size(); - npy_intp size_polygons = polygons.size(); - PyArrayObject* verticesarr = reinterpret_cast(PyArray_SimpleNew(1, &size_vertices, NPY_DOUBLE)); - PyArrayObject* polygonsarr = reinterpret_cast(PyArray_SimpleNew(1, &size_polygons, NPY_ULONG)); - - std::vector::const_iterator it = vertices.begin(); - for(int i=0; it!=vertices.end(); ++i, ++it) - *reinterpret_cast(PyArray_GETPTR1(verticesarr, i)) = *it; - std::vector::const_iterator it2 = polygons.begin(); - for(int i=0; it2!=polygons.end(); ++i, ++it2) - *reinterpret_cast(PyArray_GETPTR1(polygonsarr, i)) = *it2; - - PyObject* res = Py_BuildValue("(O,O)", verticesarr, polygonsarr); - Py_XDECREF(verticesarr); - Py_XDECREF(polygonsarr); - - return res; -} +#include "pywrapper.h" + +#include "marchingcubes.h" + +#include +#include +#include +#include +#include + +namespace +{ + +// Releases the GIL for as long as it is in scope, so that the marching cubes +// passes can run on other threads and other Python threads can make progress. +class gil_release +{ +public: + gil_release() : state_(PyEval_SaveThread()) {} + ~gil_release() { PyEval_RestoreThread(state_); } + + gil_release(const gil_release&) = delete; + gil_release& operator=(const gil_release&) = delete; + +private: + PyThreadState* state_; +}; + +// Reads the volume without touching the Python C API, so it is safe to call +// from several threads at once. Requires native byte order and an aligned +// buffer; marching_cubes() converts anything else before reaching this point. +template +class array_value_at +{ +public: + explicit array_value_at(PyArrayObject* arr) + : data_(static_cast(PyArray_DATA(arr))) + { + const npy_intp* strides = PyArray_STRIDES(arr); + stride_[0] = strides[0]; + stride_[1] = strides[1]; + stride_[2] = strides[2]; + } + + double operator()(size_t i, size_t j, size_t k) const + { + const npy_intp offset = static_cast(i) * stride_[0] + + static_cast(j) * stride_[1] + + static_cast(k) * stride_[2]; + return static_cast(*reinterpret_cast(data_ + offset)); + } + +private: + const char* data_; + npy_intp stride_[3]; +}; + +// Owns a reference; used for the converted copy of a byte-swapped or unaligned +// input array. +class array_ref +{ +public: + explicit array_ref(PyArrayObject* obj = NULL) : obj_(obj) {} + ~array_ref() { Py_XDECREF(obj_); } + + array_ref(const array_ref&) = delete; + array_ref& operator=(const array_ref&) = delete; + + PyArrayObject* get() const { return obj_; } + +private: + PyArrayObject* obj_; +}; + +PyObject* build_result(const std::vector& vertices, + const std::vector& polygons) +{ + npy_intp size_vertices = static_cast(vertices.size()); + npy_intp size_polygons = static_cast(polygons.size()); + PyArrayObject* verticesarr = reinterpret_cast( + PyArray_SimpleNew(1, &size_vertices, NPY_DOUBLE)); + PyArrayObject* polygonsarr = reinterpret_cast( + PyArray_SimpleNew(1, &size_polygons, NPY_ULONG)); + if(verticesarr == NULL || polygonsarr == NULL) + { + Py_XDECREF(verticesarr); + Py_XDECREF(polygonsarr); + return NULL; + } + + if(!vertices.empty()) + std::memcpy(PyArray_DATA(verticesarr), vertices.data(), + vertices.size() * sizeof(double)); + unsigned long* polygons_out = + static_cast(PyArray_DATA(polygonsarr)); + for(size_t i=0; i(polygons[i]); + + PyObject* res = Py_BuildValue("(O,O)", verticesarr, polygonsarr); + Py_XDECREF(verticesarr); + Py_XDECREF(polygonsarr); + return res; +} + +} // namespace + + +PyObject* marching_cubes_func(PyObject* lower, PyObject* upper, + int numx, int numy, int numz, PyObject* pyfunc, double isovalue, + int num_threads) +{ + std::vector vertices; + std::vector polygons; + + // Copy the lower and upper coordinates to a C array. + std::array lower_; + std::array upper_; + for(int i=0; i<3; ++i) + { + PyObject* l = PySequence_GetItem(lower, i); + if(l == NULL) + throw std::runtime_error("len(lower) < 3"); + PyObject* u = PySequence_GetItem(upper, i); + if(u == NULL) + { + Py_DECREF(l); + throw std::runtime_error("len(upper) < 3"); + } + + // PyFloat_AsDouble returns -1.0 on failure, which is also a valid + // coordinate, so the error indicator is what decides. + lower_[i] = PyFloat_AsDouble(l); + if(PyErr_Occurred()) + { + Py_DECREF(l); + Py_DECREF(u); + throw std::runtime_error("lower coordinates must be numbers"); + } + upper_[i] = PyFloat_AsDouble(u); + if(PyErr_Occurred()) + { + Py_DECREF(l); + Py_DECREF(u); + throw std::runtime_error("upper coordinates must be numbers"); + } + + Py_DECREF(l); + Py_DECREF(u); + } + + if(numx < 2 || numy < 2 || numz < 2) + throw std::runtime_error("numx, numy and numz must be at least 2."); + + // Sample the field at every grid node. Each node is visited once (and only + // once), which lets the marching cubes core run without the GIL. The + // spacing must stay bit-identical to what mc::marching_cubes() recomputes + // from (upper - lower) / (n - 1), because the sampled values are attached + // to those node positions when a vertex is interpolated. + const double dx = (upper_[0] - lower_[0]) / (numx - 1); + const double dy = (upper_[1] - lower_[1]) / (numy - 1); + const double dz = (upper_[2] - lower_[2]) / (numz - 1); + + const size_t nx = static_cast(numx); + const size_t ny = static_cast(numy); + const size_t nz = static_cast(numz); + if(nx > (std::numeric_limits::max() / ny) / nz) + throw std::runtime_error("the requested grid is too large"); + // 8 bytes per node on top of the core's own buffers (128 MB at 256^3). + std::vector grid(nx * ny * nz); + + for(int i=0; i(i) * ny + static_cast(j)) * nz + + static_cast(k)] = value; + } + } + } + + auto grid_value_at = [&](size_t i, size_t j, size_t k) -> double { + return grid[(i * ny + j) * nz + k]; + }; + + { + gil_release release; + mc::marching_cubes(lower_, upper_, numx, numy, numz, grid_value_at, + isovalue, vertices, polygons, num_threads); + } + + return build_result(vertices, polygons); +} + + +template +PyObject* marching_cubes_typed(PyArrayObject* arr, double isovalue, int num_threads) +{ + npy_intp* shape = PyArray_DIMS(arr); + std::array lower{0, 0, 0}; + std::array upper{shape[0]-1, shape[1]-1, shape[2]-1}; + int numx = static_cast(upper[0] - lower[0] + 1); + int numy = static_cast(upper[1] - lower[1] + 1); + int numz = static_cast(upper[2] - lower[2] + 1); + std::vector vertices; + std::vector polygons; + + array_value_at value_at(arr); + + { + gil_release release; + mc::marching_cubes(lower, upper, numx, numy, numz, value_at, isovalue, + vertices, polygons, num_threads); + } + + return build_result(vertices, polygons); +} + + +PyObject* marching_cubes(PyArrayObject* arr, double isovalue, int num_threads) +{ + if(PyArray_NDIM(arr) != 3) + throw std::runtime_error("Only three-dimensional arrays are supported."); + + const npy_intp* shape = PyArray_DIMS(arr); + for(int d=0; d<3; ++d) + { + if(shape[d] > std::numeric_limits::max()) + throw std::runtime_error("array dimension is too large"); + } + + if(!PyArray_ISNOTSWAPPED(arr) || !PyArray_ISALIGNED(arr)) + { + // The reader below dereferences the buffer as a native value_type, so a + // byte-swapped or unaligned input gets a native, aligned double copy. + array_ref native(reinterpret_cast(PyArray_FROM_OTF( + reinterpret_cast(arr), NPY_DOUBLE, + NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_ALIGNED | NPY_ARRAY_NOTSWAPPED))); + if(native.get() == NULL) + return NULL; + return marching_cubes_typed(native.get(), isovalue, num_threads); + } + + switch(PyArray_TYPE(arr)) + { case NPY_BOOL: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_BYTE: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_SHORT: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_INT: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_LONG: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_LONGLONG: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_UBYTE: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_USHORT: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_UINT: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_ULONG: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_ULONGLONG: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_FLOAT: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_DOUBLE: + return marching_cubes_typed(arr, isovalue, num_threads); + case NPY_LONGDOUBLE: + return marching_cubes_typed(arr, isovalue, num_threads); + default: + break; + } + + // Any other dtype that numpy can safely cast (float16, and whatever gets + // added later) takes the same native double copy as the byte-swapped and + // unaligned inputs above, so support does not depend on the memory layout. + // Dtypes that cannot be cast safely (complex, object, strings) make + // PyArray_FROM_OTF raise a TypeError. + array_ref converted(reinterpret_cast(PyArray_FROM_OTF( + reinterpret_cast(arr), NPY_DOUBLE, + NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_ALIGNED | NPY_ARRAY_NOTSWAPPED))); + if(converted.get() == NULL) + return NULL; + return marching_cubes_typed(converted.get(), isovalue, num_threads); +} diff --git a/mcubes/src/pywrapper.h b/mcubes/src/pywrapper.h index 7c74b26..8657a36 100644 --- a/mcubes/src/pywrapper.h +++ b/mcubes/src/pywrapper.h @@ -7,8 +7,11 @@ #include -PyObject* marching_cubes(PyArrayObject* arr, double isovalue); +// Both entry points take num_threads: <= 0 lets the core pick one thread per +// CPU core, 1 keeps the computation single-threaded. The Python layer +// additionally rejects negative values. +PyObject* marching_cubes(PyArrayObject* arr, double isovalue, int num_threads); PyObject* marching_cubes_func(PyObject* lower, PyObject* upper, - int numx, int numy, int numz, PyObject* f, double isovalue); + int numx, int numy, int numz, PyObject* f, double isovalue, int num_threads); #endif // _PYWRAPPER_H diff --git a/setup.py b/setup.py index ff500b6..7b2b538 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- import runpy +import sys from setuptools import setup @@ -13,6 +14,13 @@ __version__ = runpy.run_path("mcubes/version.py")["__version__"] +def compile_args(): + # The core uses std::thread, which needs an explicit pthread link on Linux. + if sys.platform == "win32": + return [] + return ["-std=c++11", "-Wall", "-pthread"] + + def extensions(): numpy_include_dir = numpy.get_include() @@ -25,7 +33,8 @@ def extensions(): "mcubes/src/marchingcubes.cpp" ], language="c++", - extra_compile_args=['-std=c++11', '-Wall'], + extra_compile_args=compile_args(), + extra_link_args=["-pthread"] if sys.platform != "win32" else [], include_dirs=[numpy_include_dir], depends=[ "mcubes/src/marchingcubes.h", diff --git a/test_mcubes.py b/test_mcubes.py index 4fa95dd..f1de0bc 100644 --- a/test_mcubes.py +++ b/test_mcubes.py @@ -72,3 +72,178 @@ def func(x, y, z): with pytest.raises(Exception): mcubes.marching_cubes_func((-1.5, -1.5, -1.5), (1.5, 1.5), 10, 10, 10, func, 0) + + +def test_num_threads_invalid(): + + levelset = np.zeros((10, 10, 10)) + + with pytest.raises(ValueError): + mcubes.marching_cubes(levelset, 0.5, num_threads=-1) + + def func(x, y, z): + return x**2 + y**2 + z**2 - 1 + + with pytest.raises(ValueError): + mcubes.marching_cubes_func( + (-1.5, -1.5, -1.5), (1.5, 1.5, 1.5), 10, 10, 10, func, 0, num_threads=-1 + ) + + +@pytest.mark.parametrize("num_threads", [1, 2, 3, 8]) +def test_num_threads_array(num_threads): + # A volume large enough to take the parallel path. + x, y, z = np.mgrid[:60, :52, :44] + volume = (x - 30) ** 2 + (y - 26) ** 2 + (z - 22) ** 2 - 18**2 + + vertices, triangles = mcubes.marching_cubes(volume, 0.0, num_threads=1) + vertices_threaded, triangles_threaded = mcubes.marching_cubes( + volume, 0.0, num_threads=num_threads + ) + + assert len(vertices) > 0 + assert_array_equal(vertices, vertices_threaded) + assert_array_equal(triangles, triangles_threaded) + + +@pytest.mark.parametrize("num_threads", [1, 2, 3, 8]) +def test_num_threads_func(num_threads): + def func(x, y, z): + return (x - 6)**2 + (y - 6)**2 + (z - 6)**2 - 25 + + vertices, triangles = mcubes.marching_cubes_func( + (0, 0, 0), (12, 12, 12), 40, 40, 40, func, 0.0, num_threads=1 + ) + vertices_threaded, triangles_threaded = mcubes.marching_cubes_func( + (0, 0, 0), (12, 12, 12), 40, 40, 40, func, 0.0, num_threads=num_threads + ) + + assert len(vertices) > 0 + assert_array_equal(vertices, vertices_threaded) + assert_array_equal(triangles, triangles_threaded) + + +def test_closed_sphere(): + # Every edge of a closed surface is shared by exactly two triangles, so + # V - E + F must be 2 for a sphere and 0 for a torus. This catches any + # duplicated or dropped vertex. + x, y, z = np.mgrid[:40, :40, :40] + sphere = (x - 20) ** 2 + (y - 20) ** 2 + (z - 20) ** 2 - 12**2 + vertices, triangles = mcubes.marching_cubes(sphere, 0.0, num_threads=4) + + edges = np.sort( + np.concatenate([triangles[:, [0, 1]], triangles[:, [1, 2]], triangles[:, [2, 0]]]), + axis=1, + ) + num_edges = len(np.unique(edges, axis=0)) + + assert triangles.min() >= 0 + assert triangles.max() < len(vertices) + assert len(vertices) - num_edges + len(triangles) == 2 + + +class CallbackError(Exception): + pass + + +def test_func_exception_propagates(): + # A failing callback must abort with its own exception, not silently produce + # a surface with the failing nodes replaced by 0.0. + def func(x, y, z): + if x > 1: + raise CallbackError("callback failed") + return 0.0 + + with pytest.raises(CallbackError): + mcubes.marching_cubes_func((0, 0, 0), (2, 2, 2), 5, 5, 5, func, 0.0) + + +def test_func_bad_return_value(): + def func(x, y, z): + return "not a number" + + with pytest.raises(TypeError): + mcubes.marching_cubes_func((0, 0, 0), (2, 2, 2), 5, 5, 5, func, 0.0) + + +def test_func_grid_overflow(): + with pytest.raises(RuntimeError): + mcubes.marching_cubes_func( + (0, 0, 0), (1, 1, 1), 1 << 22, 1 << 22, 1 << 22, lambda x, y, z: 0.0, 0.0 + ) + + +def test_non_native_byte_order(): + x, y, z = np.mgrid[:12, :12, :12] + volume = (x - 6)**2 + (y - 6)**2 + (z - 6)**2 - 4**2 + ref_vertices, ref_triangles = mcubes.marching_cubes(volume, 0.0, num_threads=1) + + swapped = volume.astype(volume.dtype.newbyteorder()) + assert not swapped.dtype.isnative + + vertices, triangles = mcubes.marching_cubes(swapped, 0.0, num_threads=2) + assert_allclose(vertices, ref_vertices) + assert_array_equal(triangles, ref_triangles) + + +def test_unaligned_input(): + x, y, z = np.mgrid[:12, :12, :12] + volume = ((x - 6)**2 + (y - 6)**2 + (z - 6)**2 - 4**2).astype(np.float64) + ref_vertices, ref_triangles = mcubes.marching_cubes(volume, 0.0, num_threads=1) + + raw = np.zeros(volume.nbytes + 8, dtype=np.uint8) + unaligned = raw[1:1 + volume.nbytes].view(np.float64).reshape(volume.shape) + unaligned[...] = volume + assert not unaligned.flags["ALIGNED"] + + vertices, triangles = mcubes.marching_cubes(unaligned, 0.0, num_threads=2) + assert_allclose(vertices, ref_vertices) + assert_array_equal(triangles, ref_triangles) + + +def test_dtype_support_is_layout_independent(): + # Every dtype numpy can safely cast must be accepted, whether or not the + # array happens to be native-endian and aligned. + x, y, z = np.mgrid[:10, :10, :10] + field = (x - 5)**2 + (y - 5)**2 + (z - 5)**2 - 3**2 + ref_vertices, ref_triangles = mcubes.marching_cubes(field.astype(np.float64), 0.0, num_threads=1) + + # float16 has 11 mantissa bits, so these integer values are exact. + half = field.astype(np.float16) + for volume in (half, half.astype(half.dtype.newbyteorder())): + vertices, triangles = mcubes.marching_cubes(volume, 0.0, num_threads=2) + assert_allclose(vertices, ref_vertices) + assert_array_equal(triangles, ref_triangles) + + complex_volume = np.zeros((4, 4, 4), dtype=np.complex128) + for volume in (complex_volume, complex_volume.astype(complex_volume.dtype.newbyteorder())): + with pytest.raises(TypeError): + mcubes.marching_cubes(volume, 0.0) + + +def test_every_cube_configuration(): + # Exercises all 256 entries of num_indices_table through triangle_table. A + # count that is too large would make the polygon copy loop step past the -1 + # terminator and emit an out-of-range or repeated index. + # + # Cubes number their corners around each z face, not as a bit mask. + corners = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), + (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)] + + for cube_index in range(256): + volume = np.empty((2, 2, 2)) + for corner, (di, dj, dk) in enumerate(corners): + # 0.0 is at or below the isovalue, so the corner is inside when its + # bit is set and the cube index equals cube_index. + volume[di, dj, dk] = 0.0 if (cube_index >> corner) & 1 else 1.0 + + vertices, triangles = mcubes.marching_cubes(volume, 0.5, num_threads=1) + + assert len(vertices) <= 12, cube_index + if len(triangles) == 0: + continue + assert triangles.min() >= 0, cube_index + assert triangles.max() < len(vertices), cube_index + assert np.all(triangles[:, 0] != triangles[:, 1]), cube_index + assert np.all(triangles[:, 1] != triangles[:, 2]), cube_index + assert np.all(triangles[:, 0] != triangles[:, 2]), cube_index