automesh 0.4.9

Automatic mesh generation.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
use super::{
    ErrorWrapper,
    io::{extension, invalid_input, read_segmentation, write_mesh},
    metrics::write_metrics,
    remesh::apply_remesh_subcommand,
    smooth::{MeshSmoothCommands, apply_smoothing_method},
};
use clap::Subcommand;
use conspire::{
    geometry::{
        Coordinate, Coordinates,
        grid::{Gradient, MarchingCubes, Voxels},
        mesh::{
            Class, Connectivity, Finish, Fitting, Freedom, Marching, Mesh, Placement, Tessellation,
        },
        ntree::{Balance, Balancing, CurvatureSizing, Dualization, Octree, Pairing},
        segmentation::Segmentation,
    },
    math::{Tensor, TensorVec},
    units::Length,
};
use std::{collections::HashSet, path::Path, time::Instant};

#[derive(Subcommand)]
pub enum MeshSubcommand {
    /// Creates an all-hexahedral mesh from a segmentation or tessellation
    Hex(MeshArgs),
    /// Creates a hex-dominant mesh from a tessellation, polyhedral at the boundary
    Hexdom(MeshArgs),
    /// Creates a polyhedral mesh from a tessellation
    Poly(MeshArgs),
    /// Creates an all-tetrahedral mesh from a tessellation
    Tet(MeshArgs),
    /// Creates all-triangular isosurface(s) from a segmentation
    Tri(MeshArgs),
}

#[derive(clap::Args)]
pub struct MeshArgs {
    #[command(subcommand)]
    pub smoothing: Option<MeshSmoothCommands>,

    /// Segmentation (npy | spn) or tessellation (stl) input file
    #[arg(long, short, value_name = "FILE")]
    pub input: String,

    /// Mesh output file (exo | inp | mesh | off | stl | vtu)
    #[arg(long, short, value_name = "FILE")]
    pub output: String,

    /// Defeature clusters with less than NUM voxels
    #[arg(long, short, value_name = "NUM")]
    pub defeature: Option<usize>,

    /// Number of voxels in the x-direction (spn)
    #[arg(long, short = 'x', value_name = "NEL")]
    pub nelx: Option<usize>,

    /// Number of voxels in the y-direction (spn)
    #[arg(long, short = 'y', value_name = "NEL")]
    pub nely: Option<usize>,

    /// Number of voxels in the z-direction (spn)
    #[arg(long, short = 'z', value_name = "NEL")]
    pub nelz: Option<usize>,

    /// Voxel IDs to remove from the mesh (npy | spn)
    #[arg(long, num_args = 1.., short, value_delimiter = ' ', value_name = "ID")]
    pub remove: Option<Vec<usize>>,

    /// Scaling (> 0.0) in the x-direction, applied before translation
    #[arg(default_value_t = 1.0, long, value_name = "SCALE")]
    pub xscale: f64,

    /// Scaling (> 0.0) in the y-direction, applied before translation
    #[arg(default_value_t = 1.0, long, value_name = "SCALE")]
    pub yscale: f64,

    /// Scaling (> 0.0) in the z-direction, applied before translation
    #[arg(default_value_t = 1.0, long, value_name = "SCALE")]
    pub zscale: f64,

    /// Translation in the x-direction
    #[arg(
        long,
        default_value_t = 0.0,
        allow_negative_numbers = true,
        value_name = "VAL"
    )]
    pub xtranslate: f64,

    /// Translation in the y-direction
    #[arg(
        long,
        default_value_t = 0.0,
        allow_negative_numbers = true,
        value_name = "VAL"
    )]
    pub ytranslate: f64,

    /// Translation in the z-direction
    #[arg(
        long,
        default_value_t = 0.0,
        allow_negative_numbers = true,
        value_name = "VAL"
    )]
    pub ztranslate: f64,

    /// Octree refinement scale for dualizing a tessellation (stl) input
    #[arg(long, default_value_t = 5.0, short = 's', value_name = "SCALE")]
    pub scale: f64,

    /// Uniform mesh of the given element size instead of an octree (stl)
    #[arg(long, short = 'u', value_name = "SPACING")]
    pub uniform: Option<f64>,

    /// Chord-error tolerance for curvature-driven refinement [default: disabled]
    #[arg(long, short = 't', value_name = "TOL")]
    pub tolerance: Option<f64>,

    /// Uses strong balancing instead of the default weak balancing
    #[arg(action, long)]
    pub strong: bool,

    /// Cuts the uniform lattice with marching cubes and inflates it onto the surface (stl)
    #[arg(action, long, requires = "uniform")]
    pub inflate: bool,

    /// Cuts the uniform lattice with marching cubes, leaving the boundary as cut (stl)
    #[arg(action, conflicts_with = "inflate", long, requires = "uniform")]
    pub marching: bool,

    /// Snaps the buffer layer onto the surface instead of a soft fit
    #[arg(action, long)]
    pub snap: bool,

    /// Replaces shell hexahedra below this minimum scaled Jacobian along
    /// features with pyramids and refits, snapping both fits under --snap
    /// [default: disabled]
    #[arg(conflicts_with_all = ["inflate", "marching"], long, value_name = "MSJ")]
    pub pyramids: Option<f64>,

    /// Level difference allowed between neighboring octree cells (poly)
    #[arg(long, default_value_t = 1, short = 'l', value_name = "NUM")]
    pub levels: usize,

    /// Quality metrics output file (csv | npy)
    #[arg(long, value_name = "FILE")]
    pub metrics: Option<String>,

    /// Isosurface method for triangles from a segmentation (tri)
    #[arg(long, value_enum, default_value_t = Cubes::Cuberille, value_name = "METHOD")]
    pub cubes: Cubes,
}

#[derive(Clone, Copy, clap::ValueEnum)]
pub enum Cubes {
    /// Faces of the voxels, shared between materials
    Cuberille,
    /// Smooth isosurface of each material
    Marching,
}

pub enum Element {
    Hexahedra,
    HexDominant,
    Polyhedra,
    Tetrahedra,
    Triangles,
}

fn read_voxels(args: &MeshArgs, quiet: bool) -> Result<Voxels<u8>, ErrorWrapper> {
    match extension(&args.input) {
        Some("npy") | Some("spn") => {
            let mut voxels =
                read_segmentation(&args.input, args.nelx, args.nely, args.nelz, quiet)?;
            if let Some(min) = args.defeature {
                let time = Instant::now();
                crate::echo!(
                    quiet,
                    " \x1b[1;96mDefeaturing\x1b[0m clusters of {min} voxels or less"
                );
                voxels = voxels.defeature(min)?;
                crate::echo!(quiet, "        \x1b[1;92mDone\x1b[0m {:?}", time.elapsed());
            }
            Ok(voxels)
        }
        extension => Err(invalid_input(&args.input, extension)),
    }
}

fn finish(mut mesh: Mesh<3>, args: MeshArgs, quiet: bool) -> Result<(), ErrorWrapper> {
    if let Some(MeshSmoothCommands::Smooth {
        remeshing,
        iterations,
        method,
        pass_band,
        scale,
        hierarchical,
    }) = args.smoothing
    {
        apply_smoothing_method(
            &mut mesh,
            iterations,
            method,
            pass_band,
            scale,
            hierarchical,
            quiet,
        )?;
        if let Some(subcommand) = remeshing {
            mesh = apply_remesh_subcommand(mesh, subcommand, quiet)?;
        }
    }
    if let Some(file) = &args.metrics {
        write_metrics(&mesh, file, quiet)?;
    }
    write_mesh(&args.output, mesh, quiet)
}

pub fn mesh(element: Element, args: MeshArgs, quiet: bool) -> Result<(), ErrorWrapper> {
    match (&element, extension(&args.input)) {
        (Element::Hexahedra, Some("stl")) => return hexahedralize(args, quiet),
        (Element::Tetrahedra, Some("stl")) => return tetrahedralize(args, quiet),
        (element @ (Element::HexDominant | Element::Polyhedra), Some("stl")) => {
            return cut(args, element, quiet);
        }
        (Element::HexDominant | Element::Polyhedra | Element::Tetrahedra, extension) => {
            return Err(invalid_input(&args.input, extension));
        }
        _ => {}
    }
    if args.uniform.is_some() {
        return Err(ErrorWrapper::from(
            "Uniform lattice meshing applies to tessellation (stl) inputs only",
        ));
    }
    let voxels = read_voxels(&args, quiet)?;
    let time = Instant::now();
    let mesh = match element {
        Element::Hexahedra => {
            crate::echo!(quiet, "     \x1b[1;96mMeshing\x1b[0m voxels into hexahedra");
            let remove: Option<Vec<u8>> = args
                .remove
                .as_ref()
                .map(|ids| ids.iter().map(|&id| id as u8).collect());
            let scale = Coordinate::from([args.xscale, args.yscale, args.zscale]);
            let translate = Coordinate::from([args.xtranslate, args.ytranslate, args.ztranslate]);
            let segmentation = Segmentation::new(voxels, scale, translate);
            Mesh::from_segmentation(segmentation, remove.as_deref())
        }
        Element::HexDominant | Element::Polyhedra => {
            unreachable!("cutting requires a tessellation input")
        }
        Element::Tetrahedra => unreachable!("tetrahedralizing requires a tessellation input"),
        Element::Triangles => {
            crate::echo!(quiet, "     \x1b[1;96mMeshing\x1b[0m voxels into triangles");
            let voxels = remove_materials(voxels, args.remove.as_deref());
            let mesh = match args.cubes {
                Cubes::Cuberille => Mesh::from(Tessellation::from(voxels)),
                Cubes::Marching => marching(&voxels)?,
            };
            scaled(
                mesh,
                [args.xscale, args.yscale, args.zscale],
                [args.xtranslate, args.ytranslate, args.ztranslate],
            )
        }
    };
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );
    finish(mesh, args, quiet)
}

/// Meshes a tessellation (stl) input into an all-hexahedral mesh.
///
/// A background mesh of the enclosed volume is built first — the dual of an
/// octree fitted to the surface, or a uniform lattice under `--uniform` — and
/// trimmed to the surface. A buffer layer is then fitted onto the surface.
/// Buffering is timed on its own because it dominates the total by far, while
/// the steps building the background are lumped together as one.
fn hexahedralize(args: MeshArgs, quiet: bool) -> Result<(), ErrorWrapper> {
    crate::echo!(quiet, "     \x1b[1;96mReading\x1b[0m {}", args.input);
    let mut time = Instant::now();
    let tessellation = Tessellation::try_from(Path::new(&args.input))?;
    crate::echo!(quiet, "        \x1b[1;92mDone\x1b[0m {:?}", time.elapsed());
    if args.inflate || args.marching {
        return marching_hex(args, tessellation, quiet);
    }
    let fitting = if args.snap {
        Fitting::Snap
    } else {
        Fitting::Soft
    };

    crate::echo!(
        quiet,
        "     \x1b[1;96mMeshing\x1b[0m hexahedra {}",
        if args.uniform.is_some() {
            "uniformly"
        } else {
            "adaptively"
        }
    );
    time = Instant::now();
    let mut mesh = if let Some(spacing) = args.uniform {
        tessellation.lattice_background(Length::meters(spacing))?.0
    } else {
        let balancing = if args.strong {
            Balancing::Strong(1)
        } else {
            Balancing::Weak(1)
        };
        let mut octree = Octree::<u16, usize>::from_features(
            &tessellation,
            args.scale,
            CurvatureSizing {
                tolerance: args.tolerance.map(Length::meters),
                ..Default::default()
            },
            0,
        )?;
        octree.equilibrate(balancing, Pairing::Regular)?;
        octree.dualize()
    };
    tessellation.trim(&mut mesh)?;
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );

    crate::echo!(
        quiet,
        "   \x1b[1;96mBuffering\x1b[0m hexahedra onto geometry"
    );
    time = Instant::now();
    let mesh = if let Some(threshold) = args.pyramids {
        mesh.buffer_targeted(&tessellation, fitting, threshold)?
    } else {
        mesh.buffer(&tessellation, fitting)?
    };
    let mesh = scaled(
        mesh,
        [args.xscale, args.yscale, args.zscale],
        [args.xtranslate, args.ytranslate, args.ztranslate],
    );
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );
    finish(mesh, args, quiet)
}

/// Cuts a uniform lattice with marching cubes along a tessellation.
///
/// The lattice is cut along the surface and split into hexahedra. Under
/// `--inflate` every node is then fitted onto the surface, and the boundary is
/// snapped onto it under `--snap`. Under `--marching` the boundary is left as
/// cut. No buffer layer is inserted, so the element count is set by the
/// lattice alone.
///
/// Each lattice cell is split into eight hexahedra, so the lattice is laid at
/// twice the requested element size.
fn marching_hex(
    args: MeshArgs,
    tessellation: Tessellation,
    quiet: bool,
) -> Result<(), ErrorWrapper> {
    if args.marching && args.snap {
        return Err(ErrorWrapper::from(
            "Snapping applies to an inflated mesh, not one left as cut",
        ));
    }
    let size = args
        .uniform
        .expect("marching cubes requires a uniform element size");
    crate::echo!(quiet, "     \x1b[1;96mMeshing\x1b[0m hexahedra uniformly");
    let mut time = Instant::now();
    let mut mesh = tessellation.marching_hex(
        Length::meters(size * 2.0),
        Marching {
            placement: Placement::Crossing(0.2),
            finish: Finish::Cut,
        },
    )?;
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );
    if args.inflate {
        crate::echo!(
            quiet,
            "   \x1b[1;96mInflating\x1b[0m hexahedra onto geometry"
        );
        time = Instant::now();
        mesh.inflate(
            &tessellation,
            Freedom::Whole,
            if args.snap {
                Fitting::Snap
            } else {
                Fitting::Soft
            },
        )?;
        crate::echo!(
            quiet,
            "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
            time.elapsed(),
            mesh.number_of_elements(),
            mesh.number_of_nodes()
        );
    }
    let mesh = scaled(
        mesh,
        [args.xscale, args.yscale, args.zscale],
        [args.xtranslate, args.ytranslate, args.ztranslate],
    );
    finish(mesh, args, quiet)
}

/// Meshes a tessellation (stl) input into an all-tetrahedral mesh.
///
/// The tetrahedral counterpart of [`hexahedralize`]. A background tetrahedral
/// mesh of the enclosed volume is built — six tetrahedra per cell of an octree
/// fitted to the surface, or of a uniform lattice under `--uniform` — and
/// trimmed to the surface. A buffer layer of tetrahedra is then fitted onto
/// the surface. As in the hexahedral path, buffering is timed on its own.
fn tetrahedralize(args: MeshArgs, quiet: bool) -> Result<(), ErrorWrapper> {
    crate::echo!(quiet, "     \x1b[1;96mReading\x1b[0m {}", args.input);
    let mut time = Instant::now();
    let tessellation = Tessellation::try_from(Path::new(&args.input))?;
    crate::echo!(quiet, "        \x1b[1;92mDone\x1b[0m {:?}", time.elapsed());
    let fitting = if args.snap {
        Fitting::Snap
    } else {
        Fitting::Soft
    };

    crate::echo!(
        quiet,
        "     \x1b[1;96mMeshing\x1b[0m tetrahedra {}",
        if args.uniform.is_some() {
            "uniformly"
        } else {
            "adaptively"
        }
    );
    time = Instant::now();
    let (mut mesh, _classes) = if let Some(spacing) = args.uniform {
        tessellation.lattice_tet_background(Length::meters(spacing))?
    } else {
        tessellation.octree_tet_background(
            Balancing::Strong(1),
            Pairing::None,
            args.scale,
            args.tolerance.map(Length::meters),
        )?
    };
    tessellation.trim(&mut mesh)?;
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );

    crate::echo!(
        quiet,
        "   \x1b[1;96mBuffering\x1b[0m tetrahedra onto geometry"
    );
    time = Instant::now();
    let mesh = mesh.buffer_tets(&tessellation, fitting)?;
    let mesh = scaled(
        mesh,
        [args.xscale, args.yscale, args.zscale],
        [args.xtranslate, args.ytranslate, args.ztranslate],
    );
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );
    finish(mesh, args, quiet)
}

/// Cuts an octree fitted to a tessellation (stl) input to the surface.
///
/// [`Element::Polyhedra`] cuts the octree itself, while [`Element::HexDominant`]
/// cuts its dual, leaving hexahedra everywhere but at the boundary.
fn cut(args: MeshArgs, element: &Element, quiet: bool) -> Result<(), ErrorWrapper> {
    crate::echo!(quiet, "     \x1b[1;96mReading\x1b[0m {}", args.input);
    let mut time = Instant::now();
    let tessellation = Tessellation::try_from(Path::new(&args.input))?;
    crate::echo!(quiet, "        \x1b[1;92mDone\x1b[0m {:?}", time.elapsed());
    let polyhedral = matches!(element, Element::Polyhedra);
    if polyhedral && args.uniform.is_some() {
        return Err(ErrorWrapper::from(
            "Uniform lattice meshing applies to mesh hex and mesh hexdom only",
        ));
    }
    if !polyhedral && args.levels != 1 {
        return Err(ErrorWrapper::from(
            "Dualization requires 2:1 balancing, so levels applies to mesh poly only",
        ));
    }

    crate::echo!(
        quiet,
        "     \x1b[1;96mMeshing\x1b[0m {} {}",
        if polyhedral { "polyhedra" } else { "hexahedra" },
        if args.uniform.is_some() {
            "uniformly"
        } else {
            "adaptively"
        }
    );
    time = Instant::now();
    let (background, classes) = if let Some(spacing) = args.uniform {
        tessellation.lattice_background(Length::meters(spacing))
    } else {
        let balancing = if args.strong {
            Balancing::Strong(args.levels)
        } else {
            Balancing::Weak(args.levels)
        };
        if polyhedral {
            tessellation.octree_background(balancing, args.scale)
        } else {
            tessellation.dual_background(balancing, args.scale)
        }
    }?;
    let (elements, nodes) = retained(&background, &classes);
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{elements} elements, {nodes} nodes]\x1b[0m",
        time.elapsed()
    );

    crate::echo!(
        quiet,
        "   \x1b[1;96mBuffering\x1b[0m polyhedra onto geometry"
    );
    time = Instant::now();
    let mesh = if polyhedral {
        tessellation.cut_polyhedral(background, &classes)
    } else {
        tessellation.cut(background, &classes)
    }?;
    let mesh = scaled(
        mesh,
        [args.xscale, args.yscale, args.zscale],
        [args.xtranslate, args.ytranslate, args.ztranslate],
    );
    crate::echo!(
        quiet,
        "        \x1b[1;92mDone\x1b[0m {:?} \x1b[2m[{} elements, {} nodes]\x1b[0m",
        time.elapsed(),
        mesh.number_of_elements(),
        mesh.number_of_nodes()
    );
    finish(mesh, args, quiet)
}

/// Counts the background cells the cut will keep, and the nodes they use.
///
/// A background mesh spans the whole octree or lattice, so most of its cells
/// can lie outside the tessellation and be discarded by the cut. Counting only
/// what survives keeps this step comparable to the one that follows it, and to
/// the hexahedral path, where trimming drops those cells before they are
/// counted at all.
fn retained(background: &Mesh<3>, classes: &[Class]) -> (usize, usize) {
    let mut nodes = HashSet::new();
    let elements = background
        .connectivities()
        .iter()
        .flatten()
        .zip(classes)
        .filter(|(_, class)| !matches!(class, Class::Outside))
        .inspect(|(element, _)| nodes.extend(element.iter().copied()))
        .count();
    (elements, nodes.len())
}

/// Zeroes out (treats as void) any voxels whose material is in `remove`.
fn remove_materials(voxels: Voxels<u8>, remove: Option<&[usize]>) -> Voxels<u8> {
    match remove {
        Some(remove) if !remove.is_empty() => {
            let nel = *voxels.nel();
            let data = voxels
                .data()
                .iter()
                .map(|&block| {
                    if remove.contains(&(block as usize)) {
                        0
                    } else {
                        block
                    }
                })
                .collect();
            Voxels::new(data, nel)
        }
        _ => voxels,
    }
}

/// Extracts a closed marching cubes isosurface of each nonzero material.
///
/// Each material is padded with void so its surface closes at the grid
/// boundary. Interfaces are represented once per adjacent material.
fn marching(voxels: &Voxels<u8>) -> Result<Mesh<3>, ErrorWrapper> {
    let [nx, ny, nz] = *voxels.nel();
    let padded = [nz + 2, ny + 2, nx + 2];
    let mut materials: Vec<u8> = voxels.data().iter().copied().filter(|&m| m != 0).collect();
    materials.sort_unstable();
    materials.dedup();
    let extractor = MarchingCubes {
        gradient: Gradient::Ascent,
        degenerate: false,
        ..Default::default()
    };
    let mut coordinates = Coordinates::new();
    let mut connectivities = Vec::with_capacity(materials.len());
    for material in materials {
        let mut data = vec![0.0; padded.iter().product()];
        for k in 0..nz {
            for j in 0..ny {
                for i in 0..nx {
                    if voxels.data()[voxels.flat([i, j, k])] == material {
                        data[((k + 1) * padded[1] + j + 1) * padded[2] + i + 1] = 1.0;
                    }
                }
            }
        }
        let surface = extractor
            .extract(&Voxels::new_row_major(data, padded), None)
            .map_err(ErrorWrapper::from)?;
        let offset = coordinates.len();
        for vertex in surface.vertices.iter() {
            coordinates.push(Coordinate::from([
                vertex[0] + Length::meters(-0.5),
                vertex[1] + Length::meters(-0.5),
                vertex[2] + Length::meters(-0.5),
            ]));
        }
        let faces: Vec<[usize; 3]> = surface
            .faces
            .iter()
            .map(|face| face.map(|node| node + offset))
            .collect();
        connectivities.push(Connectivity::Triangular(faces.into()));
    }
    Ok(Mesh::from((connectivities, coordinates)))
}

/// Applies per-axis scaling (before translation) to the mesh coordinates.
fn scaled(mesh: Mesh<3>, scale: [f64; 3], translate: [f64; 3]) -> Mesh<3> {
    if scale == [1.0, 1.0, 1.0] && translate == [0.0, 0.0, 0.0] {
        return mesh;
    }
    let (connectivities, coordinates) = mesh.into();
    let coordinates: Coordinates<3> = coordinates
        .iter()
        .map(|coordinate| {
            Coordinate::from([
                coordinate[0] * scale[0] + Length::meters(translate[0]),
                coordinate[1] * scale[1] + Length::meters(translate[1]),
                coordinate[2] * scale[2] + Length::meters(translate[2]),
            ])
        })
        .collect();
    Mesh::from((connectivities.into_members(), coordinates))
}