voxelops 0.1.0

Processing of dense voxel grids for scientific/medical data: thresholding, morphology (erode/dilate), and surface mesh extraction.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! # voxelops
//!
//! Operations on dense 3D voxel grids, aimed at scientific and medical data
//! (MRI/CT volumes, microscopy, simulation output) rather than game rendering.
//!
//! v0.1 features:
//! - [`VoxelGrid<T>`]: a dense grid with physical spacing and origin metadata
//! - [`VoxelGrid::threshold`]: segmentation into a boolean mask
//! - Binary morphology on masks: [`Mask::erode`] / [`Mask::dilate`] /
//!   [`Mask::open`] / [`Mask::close`] (6-connectivity)
//! - [`Mask::to_mesh`]: extract a triangle surface mesh (culled boundary
//!   faces) in physical coordinates, exportable to Wavefront OBJ
//!
//! ```
//! use voxelops::VoxelGrid;
//!
//! // An 8x8x8 volume with a bright 4x4x4 cube in the middle.
//! let mut vol = VoxelGrid::filled([8, 8, 8], 0.0f32);
//! for z in 2..6 { for y in 2..6 { for x in 2..6 {
//!     vol[[x, y, z]] = 100.0;
//! }}}
//!
//! let mask = vol.threshold(50.0);
//! assert_eq!(mask.count(), 4 * 4 * 4);
//!
//! let eroded = mask.erode();
//! assert_eq!(eroded.count(), 2 * 2 * 2);
//!
//! let mesh = mask.to_mesh();
//! assert_eq!(mesh.triangles.len(), 6 * 4 * 4 * 2); // 6 cube faces, 16 quads each
//! let obj = mesh.to_obj();
//! assert!(obj.starts_with("v "));
//! ```
//!
//! # Conventions
//!
//! - Voxel data is stored **x-fastest** (row-major over `[z][y][x]`);
//!   [`VoxelGrid::as_slice`] exposes it in that order for interop with existing
//!   volume readers.
//! - Indexing is `grid[[x, y, z]]`; use [`VoxelGrid::get`] for a bounds-checked
//!   [`Option`].
//! - Erosion treats out-of-bounds as background, so voxels touching the grid
//!   boundary always erode.
//! - Mesh vertices sit on **grid corners**, not voxel centres, and are placed
//!   at `origin + index * spacing`. A single voxel therefore yields a closed
//!   cube of 8 vertices and 12 triangles.
//!
//! The crate has no dependencies and forbids `unsafe`.

#![deny(missing_docs)]
#![forbid(unsafe_code)]

use std::ops::{Index, IndexMut};

/// A dense 3D voxel grid with physical metadata.
///
/// Data is stored in x-fastest (row-major over `[z][y][x]`) order.
#[derive(Clone, Debug, PartialEq)]
pub struct VoxelGrid<T> {
    dims: [usize; 3],
    /// Physical size of one voxel along each axis (e.g. millimetres).
    pub spacing: [f64; 3],
    /// Physical position of the corner of voxel `[0, 0, 0]`.
    pub origin: [f64; 3],
    data: Vec<T>,
}

/// A binary segmentation mask; alias of [`VoxelGrid<bool>`].
pub type Mask = VoxelGrid<bool>;

impl<T: Clone> VoxelGrid<T> {
    /// Creates a grid of the given dimensions `[nx, ny, nz]` filled with `value`,
    /// unit spacing and zero origin.
    #[must_use]
    pub fn filled(dims: [usize; 3], value: T) -> Self {
        Self {
            dims,
            spacing: [1.0; 3],
            origin: [0.0; 3],
            data: vec![value; dims[0] * dims[1] * dims[2]],
        }
    }

    /// Creates a grid from raw x-fastest data.
    ///
    /// Returns `None` if `data.len() != nx * ny * nz`.
    #[must_use]
    pub fn from_vec(dims: [usize; 3], data: Vec<T>) -> Option<Self> {
        if data.len() != dims[0] * dims[1] * dims[2] {
            return None;
        }
        Some(Self {
            dims,
            spacing: [1.0; 3],
            origin: [0.0; 3],
            data,
        })
    }

    /// Sets physical voxel spacing (builder style).
    #[must_use]
    pub fn with_spacing(mut self, spacing: [f64; 3]) -> Self {
        self.spacing = spacing;
        self
    }

    /// Sets physical origin (builder style).
    #[must_use]
    pub fn with_origin(mut self, origin: [f64; 3]) -> Self {
        self.origin = origin;
        self
    }
}

impl<T> VoxelGrid<T> {
    /// Grid dimensions `[nx, ny, nz]`.
    #[must_use]
    pub fn dims(&self) -> [usize; 3] {
        self.dims
    }

    /// Total number of voxels.
    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the grid holds no voxels.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Raw data slice in x-fastest order.
    #[must_use]
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    #[inline]
    fn idx(&self, [x, y, z]: [usize; 3]) -> usize {
        debug_assert!(x < self.dims[0] && y < self.dims[1] && z < self.dims[2]);
        (z * self.dims[1] + y) * self.dims[0] + x
    }

    /// Returns the voxel at `[x, y, z]`, or `None` if out of bounds.
    #[must_use]
    pub fn get(&self, p: [usize; 3]) -> Option<&T> {
        (p[0] < self.dims[0] && p[1] < self.dims[1] && p[2] < self.dims[2])
            .then(|| &self.data[self.idx(p)])
    }

    /// Iterates over `([x, y, z], &value)` pairs.
    pub fn iter(&self) -> impl Iterator<Item = ([usize; 3], &T)> {
        let [nx, ny, _] = self.dims;
        self.data.iter().enumerate().map(move |(i, v)| {
            let x = i % nx;
            let y = (i / nx) % ny;
            let z = i / (nx * ny);
            ([x, y, z], v)
        })
    }
}

impl<T> Index<[usize; 3]> for VoxelGrid<T> {
    type Output = T;
    fn index(&self, p: [usize; 3]) -> &T {
        let i = self.idx(p);
        &self.data[i]
    }
}

impl<T> IndexMut<[usize; 3]> for VoxelGrid<T> {
    fn index_mut(&mut self, p: [usize; 3]) -> &mut T {
        let i = self.idx(p);
        &mut self.data[i]
    }
}

impl<T: PartialOrd> VoxelGrid<T> {
    /// Segments the volume: voxels with `value >= level` become `true`.
    #[must_use]
    pub fn threshold(&self, level: T) -> Mask {
        Mask {
            dims: self.dims,
            spacing: self.spacing,
            origin: self.origin,
            data: self.data.iter().map(|v| *v >= level).collect(),
        }
    }
}

/// The six face-adjacent neighbour offsets (6-connectivity).
const NEIGHBOURS: [[isize; 3]; 6] = [
    [-1, 0, 0],
    [1, 0, 0],
    [0, -1, 0],
    [0, 1, 0],
    [0, 0, -1],
    [0, 0, 1],
];

impl Mask {
    /// Number of `true` voxels.
    #[must_use]
    pub fn count(&self) -> usize {
        self.data.iter().filter(|&&v| v).count()
    }

    #[inline]
    fn is_set(&self, x: isize, y: isize, z: isize) -> bool {
        if x < 0 || y < 0 || z < 0 {
            return false;
        }
        let p = [x as usize, y as usize, z as usize];
        self.get(p).copied().unwrap_or(false)
    }

    fn morph(&self, dilate: bool) -> Mask {
        let mut out = self.clone();
        for ([x, y, z], v) in self.iter() {
            let (xi, yi, zi) = (x as isize, y as isize, z as isize);
            let any_neigh = |target: bool| {
                NEIGHBOURS
                    .iter()
                    .any(|d| self.is_set(xi + d[0], yi + d[1], zi + d[2]) == target)
            };
            let i = (z * self.dims[1] + y) * self.dims[0] + x;
            out.data[i] = if dilate {
                *v || any_neigh(true)
            } else {
                // Erosion: out-of-bounds counts as background, so surface
                // voxels of the grid are always eroded.
                *v && !any_neigh(false)
            };
        }
        out
    }

    /// Binary erosion with a 6-connected structuring element.
    #[must_use]
    pub fn erode(&self) -> Mask {
        self.morph(false)
    }

    /// Binary dilation with a 6-connected structuring element.
    #[must_use]
    pub fn dilate(&self) -> Mask {
        self.morph(true)
    }

    /// Morphological opening (erosion then dilation): removes small specks.
    #[must_use]
    pub fn open(&self) -> Mask {
        self.erode().dilate()
    }

    /// Morphological closing (dilation then erosion): fills small holes.
    #[must_use]
    pub fn close(&self) -> Mask {
        self.dilate().erode()
    }

    /// Extracts the boundary surface as a triangle mesh in *physical*
    /// coordinates (respecting `spacing` and `origin`).
    ///
    /// Every voxel face between a `true` voxel and background (or the grid
    /// boundary) emits two triangles with outward-facing winding. Vertices are
    /// deduplicated.
    #[must_use]
    pub fn to_mesh(&self) -> Mesh {
        use std::collections::HashMap;
        let mut verts: Vec<[f64; 3]> = Vec::new();
        let mut lookup: HashMap<[usize; 3], u32> = HashMap::new();
        let mut tris: Vec<[u32; 3]> = Vec::new();

        let vertex = |lookup: &mut HashMap<[usize; 3], u32>,
                          verts: &mut Vec<[f64; 3]>,
                          gp: [usize; 3]| {
            *lookup.entry(gp).or_insert_with(|| {
                let id = verts.len() as u32;
                verts.push([
                    self.origin[0] + gp[0] as f64 * self.spacing[0],
                    self.origin[1] + gp[1] as f64 * self.spacing[1],
                    self.origin[2] + gp[2] as f64 * self.spacing[2],
                ]);
                id
            })
        };

        for ([x, y, z], &v) in self.iter() {
            if !v {
                continue;
            }
            let (xi, yi, zi) = (x as isize, y as isize, z as isize);
            for d in NEIGHBOURS {
                if self.is_set(xi + d[0], yi + d[1], zi + d[2]) {
                    continue; // interior face, culled
                }
                // Corner of the exposed face in grid-vertex coordinates.
                let base = [
                    x + usize::from(d[0] > 0),
                    y + usize::from(d[1] > 0),
                    z + usize::from(d[2] > 0),
                ];
                // Two axes spanning the face (the axes where d == 0).
                let axes: Vec<usize> = (0..3).filter(|&a| d[a] == 0).collect();
                let (a, b) = (axes[0], axes[1]);
                let mut quad = [base; 4];
                quad[1][a] += 1;
                quad[2][a] += 1;
                quad[2][b] += 1;
                quad[3][b] += 1;
                let ids: Vec<u32> = quad
                    .iter()
                    .map(|&gp| vertex(&mut lookup, &mut verts, gp))
                    .collect();
                // Outward winding: flip for negative-direction faces.
                let outward = d.iter().sum::<isize>() > 0;
                // Axis pairs (y,z), (x,z), (x,y): (x,z) has opposite handedness.
                let flip = (a == 0 && b == 2) ^ outward;
                if flip {
                    tris.push([ids[0], ids[1], ids[2]]);
                    tris.push([ids[0], ids[2], ids[3]]);
                } else {
                    tris.push([ids[2], ids[1], ids[0]]);
                    tris.push([ids[3], ids[2], ids[0]]);
                }
            }
        }
        Mesh {
            vertices: verts,
            triangles: tris,
        }
    }
}

/// An indexed triangle mesh in physical coordinates.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Mesh {
    /// Vertex positions.
    pub vertices: Vec<[f64; 3]>,
    /// Triangles as triples of vertex indices.
    pub triangles: Vec<[u32; 3]>,
}

impl Mesh {
    /// Serializes the mesh to Wavefront OBJ text.
    #[must_use]
    pub fn to_obj(&self) -> String {
        let mut s = String::new();
        for v in &self.vertices {
            s.push_str(&format!("v {} {} {}\n", v[0], v[1], v[2]));
        }
        for t in &self.triangles {
            // OBJ indices are 1-based.
            s.push_str(&format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1));
        }
        s
    }

    /// Total surface area of the mesh.
    #[must_use]
    pub fn surface_area(&self) -> f64 {
        self.triangles
            .iter()
            .map(|t| {
                let [a, b, c] = t.map(|i| self.vertices[i as usize]);
                let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
                let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
                let cross = [
                    u[1] * v[2] - u[2] * v[1],
                    u[2] * v[0] - u[0] * v[2],
                    u[0] * v[1] - u[1] * v[0],
                ];
                0.5 * (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt()
            })
            .sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cube_mask(n: usize, lo: usize, hi: usize) -> Mask {
        let mut m = Mask::filled([n, n, n], false);
        for z in lo..hi {
            for y in lo..hi {
                for x in lo..hi {
                    m[[x, y, z]] = true;
                }
            }
        }
        m
    }

    #[test]
    fn threshold_counts() {
        let mut vol = VoxelGrid::filled([4, 4, 4], 0i32);
        vol[[1, 1, 1]] = 10;
        vol[[2, 2, 2]] = 5;
        let mask = vol.threshold(5);
        assert_eq!(mask.count(), 2);
        assert!(mask[[1, 1, 1]] && mask[[2, 2, 2]]);
    }

    #[test]
    fn erosion_shrinks_dilation_grows() {
        let m = cube_mask(8, 2, 6); // 4^3 cube
        assert_eq!(m.count(), 64);
        assert_eq!(m.erode().count(), 8); // 2^3
        assert_eq!(m.dilate().count(), 64 + 6 * 16); // + one 4x4 layer per face
        // Opening is anti-extensive (never adds voxels); with a 6-connected
        // cross element it shaves the cube's corners, so it strictly shrinks.
        let opened = m.open();
        assert!(opened.count() < m.count());
        assert!(opened
            .iter()
            .all(|(p, &v)| !v || m[p]), "open() must be a subset");
        // Closing a solid cube is identity (nothing to fill).
        assert_eq!(m.close(), m);
    }

    #[test]
    fn erosion_at_grid_boundary_erodes() {
        let m = Mask::filled([3, 3, 3], true);
        // Only the centre voxel has all 6 neighbours inside the grid set.
        assert_eq!(m.erode().count(), 1);
        assert!(m.erode()[[1, 1, 1]]);
    }

    #[test]
    fn single_voxel_mesh_is_closed_cube() {
        let mut m = Mask::filled([3, 3, 3], false);
        m[[1, 1, 1]] = true;
        let mesh = m.to_mesh();
        assert_eq!(mesh.vertices.len(), 8);
        assert_eq!(mesh.triangles.len(), 12);
        assert!((mesh.surface_area() - 6.0).abs() < 1e-9);
    }

    #[test]
    fn mesh_respects_spacing_and_origin() {
        let mut m = Mask::filled([2, 2, 2], false)
            .with_spacing([2.0, 2.0, 2.0])
            .with_origin([10.0, 0.0, 0.0]);
        m[[0, 0, 0]] = true;
        let mesh = m.to_mesh();
        assert!((mesh.surface_area() - 6.0 * 4.0).abs() < 1e-9);
        assert!(mesh.vertices.iter().all(|v| v[0] >= 10.0));
    }

    #[test]
    fn interior_faces_are_culled() {
        let m = cube_mask(6, 1, 5); // 4^3 cube
        let mesh = m.to_mesh();
        // 6 faces * 16 exposed quads * 2 triangles
        assert_eq!(mesh.triangles.len(), 192);
        assert!((mesh.surface_area() - 6.0 * 16.0).abs() < 1e-9);
    }

    #[test]
    fn obj_export_shape() {
        let mut m = Mask::filled([2, 2, 2], false);
        m[[0, 0, 0]] = true;
        let obj = m.to_mesh().to_obj();
        assert_eq!(obj.matches("\nf ").count() + 1, 1 + 12); // 12 face lines
        assert!(!obj.contains("f 0")); // 1-based indices
    }
}