sesmesh 1.2.0

Solvent Excluded Surface (Connolly surface) meshing for molecular structures
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
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
// sesmesh — Solvent Excluded Surface meshes for molecules
// Copyright (c) 2026 Ugo Varetto
// SPDX-License-Identifier: MIT OR Apache-2.0

//! The mesh stage with classification, gathering and field sampling on a
//! HIP device (Plan T11.3′, docs/gpu-prior-art.md §3.2 and §5.2).
//!
//! The arrangement is uploaded once ([`Resident`]): the frame-local `f32`
//! copies the CPU kernels compute, the blocker tables and the CPU's three
//! cell grids. Bricks then go through in batches of whole mesh chunks. For
//! each batch the device classifies the sub-blocks, gathers their candidates
//! and samples every brick sample; the CPU threads mesh the chunks from those
//! values, refining vertices in `f64` as on the CPU. The device fills a
//! ring of [`Batch`] buffers ahead of the meshing threads, which take chunks
//! in order and wait only for their own batch.
//!
//! The device repeats the CPU's `f64` classification and gathering tests in
//! `f32` with a slack above the `f32` error on the inclusive side: its
//! uniform sub-blocks are a subset of the CPU's and its lists supersets.
//! Every sample the CPU evaluates gets the CPU's value bit for bit; samples
//! in sub-blocks that only the device evaluates get their value instead of
//! `±band`, with the same sign. Meshing reads the signs and the values at
//! crossing-edge ends, so the mesh equals the CPU back end's.
//!
//! Fast mode ([`crate::RefineMode::Fast`], Plan T11.5′, docs/gpu-prior-art.md
//! §5.4) also refines the crossing edges on the device, in `f32`
//! ([`DeviceEdges`]); the CPU places the vertices from the results and
//! refines in `f64` only the edges the device did not converge on. The
//! connectivity is the exact path's; positions differ in the last bits.

use std::sync::atomic::{AtomicU64, Ordering};

use sesmesh_gpu::hip::{
    ArrangementRef, Batch, BatchParams, Device, EDGE_CONVERGED, FEATURE_BEYOND, FEATURE_CIRCLE,
    FEATURE_SHIFT, FEATURE_SOLVENT, FEATURE_SPHERE, FEATURE_VERTEX, GridRef, RefineRef, Resident,
};

use super::{Engine, INSIDE_TOL};
use crate::control::{Control, Stage};
use crate::error::{Error, Result};
use crate::field::lattice::CLASSIFY_EPS;
use crate::field::{Feature, SurfaceKind};
use crate::geom::{CellGrid, Status, Vec3};
use crate::mesh::extract::{MAX_BISECT, MAX_ITER, TOL};
use crate::par;

/// Bricks per mesh chunk on the device path (at most).
///
/// A batch is a number of chunks, and the device's first batch is not
/// overlapped by meshing: short chunks keep it short. The mesh
/// does not depend on the chunk length (the assembly numbers vertices and
/// triangles in brick order).
const DEVICE_CHUNK: usize = 64;

/// Chunk length of the device path for `bricks` bricks.
pub(crate) fn device_chunk(bricks: usize) -> usize {
    par::chunk_len(bricks).min(DEVICE_CHUNK)
}

/// Bricks per batch in fast mode.
///
/// With refinement the device bounds the mesh stage, and it runs larger
/// launches better than it gains from overlapping a short first batch
/// (fast mode, 16 threads, mesh stage with batches of 1 024 → 8 192
/// bricks: 1AON at 0.25 Å 595 → 526 ms, 3J3Q at 1 Å 5.21 → 4.72 s; batches
/// doubling from 1 024 to 8 192 bricks were 0.5–10 % slower than 8 192
/// throughout; `docs/05-gpu-hip.md` §12).
const FAST_BATCH_BRICKS: usize = 8192;

/// Chunks per batch.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Batching {
    pub(crate) chunks: usize,
}

impl Batching {
    /// The batching of the mesh stage for chunks of `chunk` bricks, with
    /// (`refine`) or without device refinement: one chunk per thread
    /// ([`Batching::default`]), or with refinement at least
    /// [`FAST_BATCH_BRICKS`] bricks.
    pub(crate) fn mesh(refine: bool, chunk: usize) -> Self {
        let threads = par::threads();
        Self {
            chunks: if refine {
                threads.max(FAST_BATCH_BRICKS / chunk.max(1))
            } else {
                threads
            },
        }
    }
}

impl Default for Batching {
    /// One chunk per thread: without device refinement the CPU bounds the
    /// mesh stage, small batches keep the device's first batch (which no
    /// meshing overlaps) short, and the pipeline has no per-batch barrier
    /// (1AON at 0.25 Å, 16 threads: 1.46 s mesh stage; 1.48 s with 4 chunks
    /// per thread, 1.51 s with 16).
    fn default() -> Self {
        Self {
            chunks: par::threads(),
        }
    }
}

fn device_error(e: &sesmesh_gpu::Error) -> Error {
    Error::Backend(format!("hip: {e}"))
}

/// The device's refinement of one brick's crossing edges (fast mode): views
/// into its refined [`Batch`].
#[derive(Debug, Clone, Copy)]
pub(crate) struct DeviceEdges<'a> {
    /// First result of each of the brick's sub-blocks, then the end (9
    /// entries, indices into the batch's results). A sub-block's edges are
    /// those whose lower sample lies in it (`(v / sub).min(1)` per axis), in
    /// `mesh_brick`'s order.
    pub(crate) offsets: &'a [u32],
    t: &'a [f32],
    features: &'a [u32],
    closest: &'a [f32],
    evals: &'a [u32],
}

impl<'a> DeviceEdges<'a> {
    /// Brick `i` of `batch`, if it was refined.
    pub(super) fn of(batch: &'a Batch<'_>, i: usize) -> Option<Self> {
        batch.refined().then(|| Self {
            offsets: &batch.edge_offsets()[8 * i..8 * i + 9],
            t: batch.edge_params(),
            features: batch.edge_features(),
            closest: batch.edge_closest(),
            evals: batch.edge_evals(),
        })
    }

    /// Result `k`: the edge parameter of the last evaluation, its feature and
    /// closest point (relative to the brick origin), and the evaluations.
    /// `None` where Newton / Illinois did not converge or a value is out of
    /// range (invalid input only): the CPU refines those edges.
    pub(crate) fn get(&self, engine: &Engine, k: usize) -> Option<(f64, Feature, Vec3, u32)> {
        let evals = *self.evals.get(k)?;
        if evals & EDGE_CONVERGED == 0 {
            return None;
        }
        let t = f64::from(*self.t.get(k)?);
        if !(0.0..=1.0).contains(&t) {
            return None;
        }
        let f = self.features[k];
        let id = f & ((1 << FEATURE_SHIFT) - 1);
        let a = &engine.field.arr;
        let below = |n: usize| (id as usize) < n;
        let feature = match f >> FEATURE_SHIFT {
            FEATURE_SOLVENT => Feature::Solvent,
            FEATURE_BEYOND => Feature::Beyond,
            FEATURE_SPHERE if below(a.centers.len()) => Feature::Sphere(id),
            FEATURE_CIRCLE if below(a.circles.len()) => Feature::Circle(id),
            FEATURE_VERTEX if below(a.vertices.len()) => Feature::Vertex(id),
            _ => return None,
        };
        let q = &self.closest[3 * k..3 * k + 3];
        let q = Vec3::new(f64::from(q[0]), f64::from(q[1]), f64::from(q[2]));
        Some((t, feature, q, evals & !EDGE_CONVERGED))
    }
}

/// Residuals of the frame-local `f32` copies (`f64` minus `f32`) of the
/// sphere centres, circle centres and SAS vertices, x, y, z each.
struct Residuals([[Vec<f32>; 3]; 3]);

impl Residuals {
    fn new(e: &Engine) -> Self {
        let frame = e.lattice.frame_origin();
        let lo = |points: &mut dyn Iterator<Item = Vec3>| {
            let mut out: [Vec<f32>; 3] = Default::default();
            for c in points {
                let d = c - frame;
                for (v, x) in out.iter_mut().zip([d.x, d.y, d.z]) {
                    v.push((x - f64::from(x as f32)) as f32);
                }
            }
            out
        };
        let a = &e.field.arr;
        Self([
            lo(&mut a.centers.iter().copied()),
            lo(&mut a.circles.iter().map(|c| c.center)),
            lo(&mut a.vertices.iter().map(|v| v.position)),
        ])
    }

    fn as_ref(&self, e: &Engine) -> RefineRef<'_> {
        let h = e.lattice.h;
        let h_hi = h as f32;
        let r = |k: usize| std::array::from_fn(|i| self.0[k][i].as_slice());
        RefineRef {
            sphere_lo: r(0),
            circle_lo: r(1),
            vertex_lo: r(2),
            h_hi,
            h_lo: (h - f64::from(h_hi)) as f32,
            tol: TOL as f32,
            max_iter: MAX_ITER as u32,
            max_bisect: MAX_BISECT as u32,
        }
    }
}

/// The arrangement as the CPU kernels see it: frame-local `f32` copies,
/// laid out for [`ArrangementRef`].
pub(super) struct HostArrangement {
    sphere: [Vec<f32>; 7],
    status: Vec<u32>,
    circle: [Vec<f32>; 10],
    vertex: [Vec<f32>; 3],
}

fn grid(g: &CellGrid, frame: Vec3) -> GridRef<'_> {
    let (origin, cell, dims, starts, items) = g.parts();
    let o = origin - frame;
    GridRef {
        origin: [o.x as f32, o.y as f32, o.z as f32],
        cell: cell as f32,
        dims: dims.map(|d| u32::try_from(d).expect("fewer than 2^32 cells per axis")),
        starts,
        items,
    }
}

impl Engine {
    /// Whether the device path can sample this engine's field: the `f32`
    /// kernels are in use and bricks split into 2×2×2 sub-blocks.
    pub(crate) fn device_ok(&self) -> bool {
        self.f32_ok && self.sub_blocks() == 8
    }

    /// The frame-local `f32` arrangement ([`Engine::device_ok`] engines).
    pub(super) fn host_arrangement(&self) -> HostArrangement {
        let a = &self.field.arr;
        let frame = self.lattice.frame_origin();
        let mut sphere: [Vec<f32>; 7] = Default::default();
        for v in &mut sphere {
            v.reserve_exact(a.centers.len());
        }
        for k in 0..a.centers.len() {
            let c = a.centers[k] - frame;
            let r32 = a.expanded[k] as f32;
            let rt = (r32 - INSIDE_TOL).max(0.0);
            let row = [
                c.x as f32,
                c.y as f32,
                c.z as f32,
                r32,
                r32 * r32,
                rt * rt,
                a.radii[k] as f32,
            ];
            for (v, x) in sphere.iter_mut().zip(row) {
                v.push(x);
            }
        }
        let status = a
            .status
            .iter()
            .map(|s| match s {
                Status::Exposed => 0,
                Status::Buried => 1,
                Status::Contained => 2,
            })
            .collect();
        let mut circle: [Vec<f32>; 10] = Default::default();
        for c in &a.circles {
            let m = c.center - frame;
            let row = [
                m.x as f32,
                m.y as f32,
                m.z as f32,
                c.axis.x as f32,
                c.axis.y as f32,
                c.axis.z as f32,
                c.e1.x as f32,
                c.e1.y as f32,
                c.e1.z as f32,
                c.radius as f32,
            ];
            for (v, x) in circle.iter_mut().zip(row) {
                v.push(x);
            }
        }
        let mut vertex: [Vec<f32>; 3] = Default::default();
        for v in &a.vertices {
            let q = v.position - frame;
            for (d, x) in vertex.iter_mut().zip([q.x as f32, q.y as f32, q.z as f32]) {
                d.push(x);
            }
        }
        HostArrangement {
            sphere,
            status,
            circle,
            vertex,
        }
    }

    /// Uploads the arrangement to `device`, with what fast-mode refinement
    /// needs if `refine`.
    ///
    /// # Errors
    /// [`Error::Backend`] if an allocation or copy fails.
    pub(super) fn resident_for<'d>(
        &self,
        device: &'d Device,
        refine: bool,
    ) -> Result<Resident<'d>> {
        let mut r = self.resident(device)?;
        if refine {
            let lo = Residuals::new(self);
            r.set_refinement(&lo.as_ref(self))
                .map_err(|e| device_error(&e))?;
        }
        Ok(r)
    }

    /// Uploads the arrangement to `device`.
    ///
    /// # Errors
    /// [`Error::Backend`] if an allocation or copy fails.
    pub(super) fn resident<'d>(&self, device: &'d Device) -> Result<Resident<'d>> {
        let host = self.host_arrangement();
        let a = &self.field.arr;
        let fo = self.lattice.frame_origin();
        let aref = ArrangementRef {
            sphere: std::array::from_fn(|i| host.sphere[i].as_slice()),
            status: &host.status,
            neighbors: a.neighbors.parts(),
            circle: std::array::from_fn(|i| host.circle[i].as_slice()),
            circle_blockers: a.circle_blockers.parts(),
            vertex: std::array::from_fn(|i| host.vertex[i].as_slice()),
            sphere_grid: grid(&a.cells, fo),
            circle_grid: grid(&self.field.circle_cells, fo),
            vertex_grid: grid(&self.field.vertex_cells, fo),
            max_expanded: a.max_expanded as f32,
            rho_max: self.field.rho_max as f32,
        };
        Resident::new(device, &aref).map_err(|e| device_error(&e))
    }

    /// The device's batch parameters: the CPU's radii and margins
    /// (`lattice::uniform_sign`, `gather_ses`, `gather_spheres`) in `f32`,
    /// and the slack added to every `f32` decision.
    pub(super) fn batch_params(&self) -> BatchParams {
        let b = u32::try_from(self.lattice.b).expect("brick edge fits u32");
        let sub = b / 2;
        let h = self.lattice.h;
        let probe = self.field.probe;
        let band = self.band;
        let rho = 0.5 * 3f64.sqrt() * f64::from(sub) * h;
        let ses = self.field.kind == SurfaceKind::Ses;
        let reach = if ses { probe + band + rho } else { band + rho };
        let margin = rho + CLASSIFY_EPS;
        let cutoffc = (probe + margin + CLASSIFY_EPS) as f32;
        let cutoff = (probe + band) as f32;
        // f32 error of frame-local distances: a few ulps of the largest
        // coordinate, far below the slack (docs/gpu-prior-art.md §3.2).
        let m = self.coord_max.clamp(1.0, 1e6) as f32;
        let ulp = f32::from_bits(m.to_bits() + 1) - m;
        BatchParams {
            ses,
            probe: probe as f32,
            band: band as f32,
            cutoff2: cutoff * cutoff,
            rho: rho as f32,
            reach: reach as f32,
            margin: margin as f32,
            slack: 1e-3 + 16.0 * ulp,
            cutoffc2: cutoffc * cutoffc,
            h: h as f32,
            b,
            sub,
            near: false,
        }
    }

    /// Brick origins relative to the `f32` frame, in lattice units.
    pub(super) fn frame_origins(&self, bricks: &[[i32; 3]]) -> Vec<[i32; 3]> {
        let frame = self.lattice.frame();
        bricks
            .iter()
            .map(|&k| {
                let o = self.lattice.brick_origin(k);
                [0, 1, 2].map(|a| {
                    i32::try_from(o[a] - frame[a]).expect("frame-local brick origins fit i32")
                })
            })
            .collect()
    }
}

/// Progress over the bricks of a stage.
struct Progress<'a, 'c> {
    control: &'a Control<'c>,
    stage: Stage,
    done: AtomicU64,
    step: u64,
    total: u64,
}

impl Progress<'_, '_> {
    fn brick(&self) {
        if self.control.has_progress() {
            let d = self.done.fetch_add(1, Ordering::Relaxed) + 1;
            if d.is_multiple_of(self.step) && d < self.total {
                self.control.report(self.stage, d, self.total);
            }
        }
    }
}

/// Batch buffers in the ring: the device fills up to `RING - 1` batches
/// ahead of the oldest batch still being meshed.
const RING: usize = 3;

/// Pipeline state shared by the device thread and the meshing threads.
#[derive(Default)]
struct Pipeline {
    /// Batches the device has finished.
    ready: usize,
    /// Chunks meshed, per batch.
    meshed: Vec<usize>,
    /// The device thread has stopped (error or cancellation).
    stopped: bool,
    error: Option<Error>,
}

/// Waits on `cv` with a short timeout, so cancellation is seen promptly
/// even without a notification.
fn wait<'a, T>(
    cv: &std::sync::Condvar,
    g: std::sync::MutexGuard<'a, T>,
) -> std::sync::MutexGuard<'a, T> {
    cv.wait_timeout(g, std::time::Duration::from_millis(5))
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .0
}

fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

impl Engine {
    /// [`Engine::fold_brick_chunks_with`] with the field sampled on
    /// `device` ([`Engine::device_ok`] engines): same arguments, the same
    /// signs and crossing-edge values, hence the same meshes.
    ///
    /// A device thread classifies, gathers and samples batches of
    /// `batching.chunks` chunks into a ring of [`RING`] buffers, in order,
    /// and with `refine` also refines their crossing edges in `f32` (`f`
    /// then gets each brick's [`DeviceEdges`]). The pool's threads take
    /// chunks in order and mesh each as soon as its batch is ready; a buffer
    /// is reused once all its chunks are meshed. No thread waits for a whole
    /// batch to be meshed.
    ///
    /// # Errors
    /// [`Error::Cancelled`]; [`Error::Backend`] if a device operation fails.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn fold_brick_chunks_hip<A, I, F>(
        &self,
        device: &Device,
        batching: Batching,
        refine: bool,
        bricks: &[[i32; 3]],
        chunk: usize,
        control: &Control<'_>,
        stage: Stage,
        init: I,
        f: F,
    ) -> Result<Vec<A>>
    where
        A: Send,
        I: Fn() -> A + Sync + Send,
        F: Fn(&mut A, [i32; 3], &[f32], Option<&DeviceEdges<'_>>) + Sync + Send,
    {
        use std::sync::atomic::AtomicUsize;
        use std::sync::{Condvar, Mutex, RwLock};

        debug_assert!(self.device_ok(), "no device path for this engine");
        let total = bricks.len() as u64;
        let progress = Progress {
            control,
            stage,
            done: AtomicU64::new(0),
            step: (total / 100).max(1),
            total,
        };
        control.report(stage, 0, total);
        let chunk = chunk.max(1);
        let chunks = bricks.len().div_ceil(chunk);
        if chunks == 0 {
            control.report(stage, total, total);
            return Ok(Vec::new());
        }
        let resident = self.resident_for(device, refine)?;
        let p = self.batch_params();
        control.check()?;
        let per_batch = batching.chunks.clamp(1, chunks);
        let batches = chunks.div_ceil(per_batch);
        let chunks_of = |k: usize| (k * per_batch)..chunks.min((k + 1) * per_batch);
        let bricks_of = |k: usize| {
            let c = chunks_of(k);
            (c.start * chunk)..bricks.len().min(c.end * chunk)
        };
        let ring = (0..RING.min(batches))
            .map(|_| Batch::new(device).map(RwLock::new))
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| device_error(&e))?;
        let state = Mutex::new(Pipeline {
            meshed: vec![0; batches],
            ..Pipeline::default()
        });
        let cv = Condvar::new();
        let next = AtomicUsize::new(0);

        // Device thread: batch k into ring slot k % RING, once every chunk of
        // batch k − RING has been meshed.
        let produce = || {
            for k in 0..batches {
                let mut g = lock(&state);
                while k >= RING
                    && g.meshed[k - RING] < chunks_of(k - RING).len()
                    && !g.stopped
                    && !control.is_cancelled()
                {
                    g = wait(&cv, g);
                }
                if g.stopped || control.is_cancelled() {
                    break;
                }
                drop(g);
                let origins = self.frame_origins(&bricks[bricks_of(k)]);
                let mut slot = ring[k % RING]
                    .write()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                let ran = resident.run(&p, &origins, &mut slot).and_then(|_| {
                    if refine {
                        resident.refine(&p, &mut slot)?;
                    }
                    Ok(())
                });
                drop(slot);
                let mut g = lock(&state);
                match ran {
                    Ok(_) => g.ready = k + 1,
                    Err(e) => {
                        g.error = Some(device_error(&e));
                        break;
                    }
                }
                drop(g);
                cv.notify_all();
            }
            lock(&state).stopped = true;
            cv.notify_all();
        };

        // Meshing threads: chunks in order, each from its batch's slot.
        let consume = |_: usize| {
            let mut mine = Vec::new();
            let n = self.samples_per_brick();
            'chunks: loop {
                if control.is_cancelled() {
                    break;
                }
                let c = next.fetch_add(1, Ordering::Relaxed);
                if c >= chunks {
                    break;
                }
                let k = c / per_batch;
                let mut g = lock(&state);
                while g.ready <= k {
                    if g.stopped || control.is_cancelled() {
                        break 'chunks;
                    }
                    g = wait(&cv, g);
                }
                drop(g);
                let slot = ring[k % RING]
                    .read()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                let first = bricks_of(k).start;
                let mut acc = init();
                for i in par::chunk_range(bricks.len(), chunk, c) {
                    if control.is_cancelled() {
                        break 'chunks;
                    }
                    let edges = DeviceEdges::of(&slot, i - first);
                    f(
                        &mut acc,
                        bricks[i],
                        &slot.brick_values(i - first)[..n],
                        edges.as_ref(),
                    );
                    progress.brick();
                }
                drop(slot);
                mine.push((c, acc));
                let mut g = lock(&state);
                g.meshed[k] += 1;
                let free = g.meshed[k] == chunks_of(k).len();
                drop(g);
                if free {
                    cv.notify_all();
                }
            }
            mine
        };

        let parts = std::thread::scope(|scope| {
            let device_side = scope.spawn(produce);
            let parts = par::map(par::threads(), consume);
            // Wake the device thread if the meshing threads stopped early.
            cv.notify_all();
            if device_side.join().is_err() {
                lock(&state).error = Some(Error::Internal("hip: device thread panicked".into()));
            }
            parts
        });
        if let Some(e) = lock(&state).error.take() {
            return Err(e);
        }
        control.check()?;
        let mut parts: Vec<(usize, A)> = parts.into_iter().flatten().collect();
        if parts.len() != chunks {
            return Err(Error::Internal(format!(
                "hip: {} of {chunks} chunks meshed",
                parts.len()
            )));
        }
        parts.sort_unstable_by_key(|p| p.0);
        control.report(stage, total, total);
        Ok(parts.into_iter().map(|p| p.1).collect())
    }
}

#[cfg(test)]
mod tests {
    use sesmesh_gpu::hip::Runtime;
    use sesmesh_testkit::clusters::{Cluster, Rng, cage, random_box, random_chain};

    use super::*;
    use crate::field::{ScratchPool, SesField, SimdLevel};
    use crate::geom::Sphere;
    use crate::mesh::extract::{BrickMesh, ChunkMesh, assemble, mesh_brick, mesh_brick_device};
    use crate::surface::RefineMode;

    /// Device 0, or `None` (skip) without one unless `SESMESH_GPU_REQUIRE=1`.
    fn device() -> Option<Device> {
        match Runtime::load().and_then(|r| r.open(0)) {
            Ok(d) => Some(d),
            // Skipped silently: the library denies printing, also in tests.
            Err(_) if std::env::var("SESMESH_GPU_REQUIRE").as_deref() != Ok("1") => None,
            Err(e) => panic!("{e}"),
        }
    }

    fn spheres(c: &Cluster) -> (Vec<Sphere>, f64) {
        let s = c
            .centers
            .iter()
            .zip(&c.radii)
            .map(|(&p, &r)| Sphere::new(p, r))
            .collect();
        (s, c.probe)
    }

    /// Crambin (`data/1crn.cif`) with the default selection and radii.
    fn crambin() -> (Vec<Sphere>, f64) {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/1crn.cif");
        let structure = crate::io::read_path(&path, &crate::io::ReadOptions::default()).unwrap();
        let mut d = crate::Diagnostics::new();
        let atoms = structure
            .select(&crate::Selection::default(), &mut d)
            .unwrap();
        let radii =
            crate::radii::assign(&atoms, &crate::radii::RadiusOptions::default(), &mut d).unwrap();
        (Sphere::from_atoms(&atoms, &radii).unwrap(), 1.4)
    }

    fn engine((spheres, probe): &(Vec<Sphere>, f64), kind: SurfaceKind, h: f64) -> Engine {
        let field = SesField::new(spheres, *probe, kind).unwrap();
        Engine::new(field, h, 10, SimdLevel::Auto).unwrap()
    }

    fn clusters() -> Vec<(Vec<Sphere>, f64)> {
        let mut rng = Rng::new(11);
        vec![
            spheres(&random_chain(&mut rng, 60)),
            spheres(&random_box(&mut rng, 80, 14.0)),
            spheres(&cage(7.0, 1.6, 1.4)),
            crambin(),
        ]
    }

    const BATCHINGS: [Batching; 3] = [
        Batching { chunks: 1 },
        Batching { chunks: 2 },
        Batching { chunks: usize::MAX },
    ];

    #[test]
    fn fast_mode_has_larger_batches() {
        let threads = par::threads();
        assert_eq!(Batching::mesh(false, 64).chunks, threads);
        assert_eq!(Batching::mesh(true, 64).chunks, threads.max(128));
        assert_eq!(
            Batching::mesh(true, 0).chunks,
            threads.max(FAST_BATCH_BRICKS)
        );
    }

    /// Per-brick sample values, chunk by chunk.
    fn collect(acc: &mut Vec<Vec<f32>>, _: [i32; 3], v: &[f32]) {
        acc.push(v.to_vec());
    }

    fn collect_dev(acc: &mut Vec<Vec<f32>>, k: [i32; 3], v: &[f32], _: Option<&DeviceEdges<'_>>) {
        collect(acc, k, v);
    }

    /// Every sample has the CPU's sign, and the CPU's value bit for bit
    /// unless the CPU gave it `±band` (a sub-block only the device samples).
    #[test]
    fn device_values_match_cpu_values() {
        let Some(device) = device() else { return };
        let pool = ScratchPool::default();
        let control = Control::new();
        for c in &clusters() {
            for kind in [SurfaceKind::Ses, SurfaceKind::Sas, SurfaceKind::Vdw] {
                for h in [0.3, 0.7] {
                    let e = engine(c, kind, h);
                    let band = e.band as f32;
                    let (_, bricks) = e.surface_bricks().unwrap();
                    let chunk = par::chunk_len(bricks.len()).max(3);
                    let cpu = e
                        .fold_brick_chunks_with(
                            &bricks,
                            chunk,
                            &control,
                            Stage::Mesh,
                            &pool,
                            Vec::new,
                            collect,
                        )
                        .unwrap();
                    let (mut same, mut uniform) = (0usize, 0usize);
                    for batching in BATCHINGS.into_iter().chain([Batching::default()]) {
                        let gpu = e
                            .fold_brick_chunks_hip(
                                &device,
                                batching,
                                false,
                                &bricks,
                                chunk,
                                &control,
                                Stage::Mesh,
                                Vec::new,
                                collect_dev,
                            )
                            .unwrap();
                        assert_eq!(gpu.len(), cpu.len());
                        for (g, c) in gpu.iter().flatten().zip(cpu.iter().flatten()) {
                            for (&d, &v) in g.iter().zip(c) {
                                assert_eq!(d < 0.0, v < 0.0, "{kind:?} h {h} {batching:?}");
                                if d.to_bits() == v.to_bits() {
                                    same += 1;
                                } else {
                                    assert_eq!(v.abs(), band, "{kind:?} h {h} {batching:?}");
                                    uniform += 1;
                                }
                            }
                        }
                    }
                    assert!(same > 20 * uniform, "{kind:?} h {h}: {same} {uniform}");
                }
            }
        }
    }

    /// The device path's meshes equal the CPU path's, for any batch size.
    #[test]
    fn device_meshes_equal_cpu_meshes() {
        let Some(device) = device() else { return };
        let pool = ScratchPool::default();
        let control = Control::new();
        for c in &clusters() {
            for kind in [SurfaceKind::Ses, SurfaceKind::Sas, SurfaceKind::Vdw] {
                let e = engine(c, kind, 0.4);
                let (_, bricks) = e.surface_bricks().unwrap();
                let push = |m: &mut ChunkMesh, key, values: &[f32]| {
                    m.push(&e, key, values, RefineMode::Exact);
                };
                let chunk = par::chunk_len(bricks.len());
                let parts = e
                    .fold_brick_chunks_with(
                        &bricks,
                        chunk,
                        &control,
                        Stage::Mesh,
                        &pool,
                        ChunkMesh::default,
                        push,
                    )
                    .unwrap();
                let cpu = assemble(&bricks, chunk, parts).unwrap();
                assert!(!cpu.triangles.is_empty());
                let chunk = device_chunk(bricks.len());
                for batching in BATCHINGS {
                    let parts = e
                        .fold_brick_chunks_hip(
                            &device,
                            batching,
                            false,
                            &bricks,
                            chunk,
                            &control,
                            Stage::Mesh,
                            ChunkMesh::default,
                            |m, key, values, edges| {
                                assert!(edges.is_none());
                                push(m, key, values);
                            },
                        )
                        .unwrap();
                    let gpu = assemble(&bricks, chunk, parts).unwrap();
                    let what = format!("{kind:?} {batching:?}");
                    assert_eq!(gpu.positions, cpu.positions, "{what}");
                    assert_eq!(gpu.normals, cpu.normals, "{what}");
                    assert_eq!(gpu.triangles, cpu.triangles, "{what}");
                    assert_eq!(gpu.vertex_atom, cpu.vertex_atom, "{what}");
                    assert_eq!(gpu.vertex_patch, cpu.vertex_patch, "{what}");
                }
            }
        }
    }

    #[test]
    fn cancellation_stops_device_batches() {
        let Some(device) = device() else { return };
        let mut rng = Rng::new(3);
        let e = engine(
            &spheres(&random_box(&mut rng, 60, 12.0)),
            SurfaceKind::Ses,
            0.4,
        );
        let (_, bricks) = e.surface_bricks().unwrap();
        let flag = std::sync::atomic::AtomicBool::new(true);
        let control = Control::new().with_cancel(&flag);
        for refine in [false, true] {
            let r = e.fold_brick_chunks_hip(
                &device,
                Batching::default(),
                refine,
                &bricks,
                4,
                &control,
                Stage::Mesh,
                Vec::new,
                collect_dev,
            );
            assert!(matches!(r, Err(Error::Cancelled)));
        }
    }

    /// Fast mode: the exact path's triangles, vertices as close to the
    /// surface, the same output for any batch size.
    #[test]
    fn fast_meshes_match_exact_meshes() {
        let Some(device) = device() else { return };
        let pool = ScratchPool::default();
        let control = Control::new();
        for c in &clusters() {
            for kind in [SurfaceKind::Ses, SurfaceKind::Sas, SurfaceKind::Vdw] {
                let e = engine(c, kind, 0.4);
                let (_, bricks) = e.surface_bricks().unwrap();
                let chunk = par::chunk_len(bricks.len());
                let parts = e
                    .fold_brick_chunks_with(
                        &bricks,
                        chunk,
                        &control,
                        Stage::Mesh,
                        &pool,
                        ChunkMesh::default,
                        |m: &mut ChunkMesh, key, values: &[f32]| {
                            m.push(&e, key, values, RefineMode::Exact);
                        },
                    )
                    .unwrap();
                let cpu = assemble(&bricks, chunk, parts).unwrap();
                let chunk = device_chunk(bricks.len());
                let mut first: Option<crate::mesh::Mesh> = None;
                for batching in BATCHINGS {
                    let parts = e
                        .fold_brick_chunks_hip(
                            &device,
                            batching,
                            true,
                            &bricks,
                            chunk,
                            &control,
                            Stage::Mesh,
                            ChunkMesh::default,
                            |m, key, values, edges| {
                                m.push_device(&e, key, values, edges.expect("refined batch"));
                            },
                        )
                        .unwrap();
                    let fast = assemble(&bricks, chunk, parts).unwrap();
                    let what = format!("{kind:?} {batching:?}");
                    assert_eq!(fast.triangles, cpu.triangles, "{what}");
                    let f = |p: [f32; 3]| e.field.value(p.map(f64::from)).abs();
                    let worst = |m: &crate::mesh::Mesh| {
                        m.positions.iter().map(|&p| f(p)).fold(0.0, f64::max)
                    };
                    assert!(worst(&fast) <= worst(&cpu) + 1e-5, "{what}");
                    let far = fast
                        .positions
                        .iter()
                        .zip(&cpu.positions)
                        .filter(|(a, b)| {
                            let d = (0..3).map(|i| f64::from(a[i] - b[i]).powi(2)).sum::<f64>();
                            d.sqrt() > 1e-4
                        })
                        .count();
                    assert!(far * 1000 <= cpu.positions.len(), "{what}: {far}");
                    match &first {
                        None => first = Some(fast),
                        Some(m) => {
                            assert_eq!(fast.positions, m.positions, "{what}");
                            assert_eq!(fast.normals, m.normals, "{what}");
                            assert_eq!(fast.vertex_atom, m.vertex_atom, "{what}");
                            assert_eq!(fast.vertex_patch, m.vertex_patch, "{what}");
                        }
                    }
                }
            }
        }
    }

    /// Edges the device did not converge on are refined on the CPU: with no
    /// converged edge, fast meshing gives the exact path's bricks.
    #[test]
    fn unconverged_edges_are_refined_exactly() {
        let e = engine(&crambin(), SurfaceKind::Ses, 0.4);
        let (_, bricks) = e.surface_bricks().unwrap();
        let mut s = e.scratch();
        let n = e.samples_per_brick();
        let (t, feat, q) = (vec![0.5f32; 3000], vec![0u32; 3000], vec![0f32; 9000]);
        let evals = vec![3u32; 3000];
        for &key in bricks.iter().step_by(7) {
            e.evaluate(key, &mut s);
            let values = &s.values[..n];
            let mut exact = BrickMesh::default();
            mesh_brick(&e, key, values, RefineMode::Exact, &mut exact);
            // Every sub-block owns at most 3·5³ = 375 edges.
            let offsets: Vec<u32> = (0..9).map(|sb| sb * 375).collect();
            let edges = DeviceEdges {
                offsets: &offsets,
                t: &t,
                features: &feat,
                closest: &q,
                evals: &evals,
            };
            let mut fast = BrickMesh::default();
            mesh_brick_device(&e, key, values, &edges, &mut fast);
            assert_eq!(fast.vertices(), exact.vertices());
            assert_eq!(fast.triangles(), exact.triangles());
            assert_eq!(fast.evals, exact.evals);
            assert_eq!(fast.cpu_refined as usize, exact.vertices().0.len());
        }
    }
}