indicatrix-solid 0.9.0

Pure-CPU solid rasterizer and 2D faceting diagram for a design's SolidMesh: raster, diagram2d, facet_map, mesh_cache, edges_layer, pixel_font, and the pure replan planner. No GUI toolkit, no threads, no filesystem -- see the crate's own doc comment. Shared by the desktop editor and the wasm web app.
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
//! Unit tests for [`super::FacetMap`]'s construction, accessors, overlay flags and
//! meet-pair resolution.

use super::*;
use indicatrix::geometry::meet_solver::{MeetConstraint, SolvedTier};
use indicatrix_cut_core::{
    ConstraintTier, Design, PreformSpec, ScheduleMeta,
    design::{ConcaveTier, ConcaveTool, ToolMotion},
};
use std::collections::BTreeSet;

/// A synthetic "RBC-445"-style design: the tier table
/// `StandardGemCuts::standard_round_brilliant` hardcodes as raw planes,
/// reauthored as [`ConstraintTier`]s so [`Design::planes_from_solved`] derives
/// the identical arrangement through the tier -> schedule -> plane path this
/// module mirrors. Every tier pinned via `ScaleReference`, so the design solves
/// trivially.
fn standard_round_brilliant_design() -> Design {
    const GIRDLE_INDICES: [f64; 16] = [
        0.0, 6.0, 12.0, 18.0, 24.0, 30.0, 36.0, 42.0, 48.0, 54.0, 60.0, 66.0, 72.0, 78.0, 84.0,
        90.0,
    ];
    const BREAK_INDICES: [f64; 16] = [
        95.0, 1.0, 11.0, 13.0, 23.0, 25.0, 35.0, 37.0, 47.0, 49.0, 59.0, 61.0, 71.0, 73.0, 83.0,
        85.0,
    ];
    const MAIN_INDICES: [f64; 8] = [0.0, 12.0, 24.0, 36.0, 48.0, 60.0, 72.0, 84.0];
    const STAR_INDICES: [f64; 8] = [6.0, 18.0, 30.0, 42.0, 54.0, 66.0, 78.0, 90.0];

    fn tier(name: &str, angle_deg: f64, indices: &[f64], mast: f64) -> ConstraintTier {
        ConstraintTier {
            angle_deg,
            name: name.to_string(),
            indices: indices.to_vec(),
            constraint: MeetConstraint::ScaleReference(mast),
            imported_meet: None,
            original_notes: None,
            detached: Vec::new(),
        }
    }

    let tiers = vec![
        tier("Table", 0.0, &[], 0.32),
        tier("Star", 15.0, &STAR_INDICES, 0.45),
        tier("Crown Main", 34.5, &MAIN_INDICES, 0.59),
        tier("Upper Girdle", 41.0, &BREAK_INDICES, 0.67),
        tier("Girdle", 90.0, &GIRDLE_INDICES, 1.0),
        tier("Pavilion Main", -41.0, &MAIN_INDICES, 0.67),
        tier("Lower Girdle", -42.5, &BREAK_INDICES, 0.68),
        tier("Culet", -0.0, &[], 0.88),
    ];

    Design::new(
        PreformSpec::block(2.0, 1.0, 2.0),
        ScheduleMeta {
            gemcad_version: "GemCad 5.0".to_string(),
            gear_teeth: 96,
            gear_reference_angle: 0.0,
            symmetry_order: 8,
            mirror: true,
            refractive_index: 1.54,
            headers: Vec::new(),
            footnotes: Vec::new(),
        },
        tiers,
    )
}

#[test]
fn plane_count_matches_design_planes_on_the_standard_round_brilliant() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let planes = design.planes_from_solved(&solved);
    let map = FacetMap::from_design(&design, &solved);

    assert_eq!(map.facets.len(), planes.len());
    assert_eq!(map.preform_plane_count(), design.preform.planes().len());
}

#[test]
fn preform_planes_map_to_no_tier() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);

    for facet_id in 0..map.preform_plane_count() {
        assert_eq!(map.tier_of(facet_id), None);
    }
}

#[test]
fn orbit_sizes_match_each_tiers_index_count() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);

    for (tier_index, tier) in design.tiers.iter().enumerate() {
        let expected = tier.indices.len().max(1);
        assert_eq!(
            map.facets_of_tier(tier_index).len(),
            expected,
            "tier {tier_index} ({})",
            tier.name
        );
    }
}

#[test]
fn every_mapped_facets_normal_carries_its_tiers_own_elevation_angle() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let planes = design.planes_from_solved(&solved);
    let map = FacetMap::from_design(&design, &solved);

    for (facet_id, &(normal, _offset)) in planes.iter().enumerate().skip(map.preform_plane_count())
    {
        let tier_index = map
            .tier_of(facet_id)
            .expect("every non-preform facet must map to a tier");
        let tier = &design.tiers[tier_index];
        let theta = tier.angle_deg.abs().to_radians();
        // The tier's elevation alone fixes the normal's y-component magnitude to
        // `cos(theta)`, regardless of azimuth (x/z split `sin(theta)` between them).
        assert!(
            (normal.y.abs() - theta.cos()).abs() < 1e-5,
            "facet {facet_id} (tier {tier_index} {}): normal.y={}, expected +-{}",
            tier.name,
            normal.y,
            theta.cos()
        );
        let horizontal = normal.x.hypot(normal.z);
        assert!(
            (horizontal - theta.sin()).abs() < 1e-5,
            "facet {facet_id} (tier {tier_index} {}): horizontal={horizontal}, expected {}",
            tier.name,
            theta.sin()
        );
    }
}

#[test]
fn overlay_flags_mark_the_pending_and_selected_tiers_and_nothing_else_by_default() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);
    let n_d = design.effective_refractive_index();

    // Neither tier is steep enough to window at diamond's critical angle
    // (~24.4 deg), so `flagged` should be empty -- this only pins the
    // pending/selected wiring.
    let flags = map.overlay_flags(&design, n_d, Some(2), &BTreeSet::from([5]));

    for &facet_id in map.facets_of_tier(5) {
        assert!(flags.pending[facet_id as usize]);
    }
    for &facet_id in map.facets_of_tier(2) {
        assert!(flags.selected[facet_id as usize]);
    }
    for &facet_id in map.facets_of_tier(3) {
        assert!(!flags.pending[facet_id as usize]);
        assert!(!flags.selected[facet_id as usize]);
    }
    assert!(
        flags.flagged.iter().all(|&f| !f),
        "diamond RBC must not window"
    );
}

/// A MULTI-tier `pending_tiers` set must mark every one of its members, not
/// just the first -- a batch nudge/offset dirties several tiers at once and
/// every one of them must read as pending in the viewport.
#[test]
fn overlay_flags_marks_every_member_of_a_multi_tier_pending_set() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);
    let n_d = design.effective_refractive_index();

    let flags = map.overlay_flags(&design, n_d, None, &BTreeSet::from([2, 5]));

    for &facet_id in map.facets_of_tier(2) {
        assert!(flags.pending[facet_id as usize], "tier 2 must be pending");
    }
    for &facet_id in map.facets_of_tier(5) {
        assert!(flags.pending[facet_id as usize], "tier 5 must be pending");
    }
    for &facet_id in map.facets_of_tier(3) {
        assert!(
            !flags.pending[facet_id as usize],
            "tier 3 must not be pending"
        );
    }
}

#[test]
fn hover_text_omits_the_margin_clause_for_crown_and_girdle_facets() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);
    let n_d = design.effective_refractive_index();

    // Tier 1 is "Star" (crown), tier 5 is "Pavilion Main" (pavilion) --
    // see `standard_round_brilliant_design`'s tier list.
    let crown_facet = map.facets_of_tier(1)[0] as usize;
    let pavilion_facet = map.facets_of_tier(5)[0] as usize;

    let crown_text = map.hover_text(crown_facet, n_d);
    let pavilion_text = map.hover_text(pavilion_facet, n_d);
    assert!(
        !crown_text.contains("margin"),
        "a crown facet must not claim a windowing margin: {crown_text}"
    );
    assert!(
        pavilion_text.contains("margin"),
        "a pavilion facet must still report its margin: {pavilion_text}"
    );
}

#[test]
fn index_on_gear_matches_the_tiers_own_index_and_is_zero_for_preform() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);

    assert_eq!(map.index_on_gear(0), 0, "a preform plane carries no index");
    // Tier 2 ("Crown Main") lists index 0.0 first; its first surviving facet
    // must report exactly that tooth.
    let first_main_facet = map.facets_of_tier(2)[0] as usize;
    assert_eq!(map.index_on_gear(first_main_facet), 0);
}

#[test]
fn meeting_facet_pairs_cross_products_a_meet_nameds_two_orbits() {
    // A minimal fabricated design -- not solved for real geometry -- purely to
    // exercise `Design::facet_meets`'s tier-name resolution feeding
    // `meeting_facet_pairs`'s cross product. `solved` is fabricated too (a
    // fixed mast per tier): `facet_meets` never reads it, and `FacetMap::
    // from_design` only reads it for the (here, irrelevant) plane offset.
    fn tier(
        name: &str,
        angle_deg: f64,
        indices: &[f64],
        constraint: MeetConstraint,
    ) -> ConstraintTier {
        ConstraintTier {
            angle_deg,
            name: name.to_string(),
            indices: indices.to_vec(),
            constraint,
            imported_meet: None,
            original_notes: None,
            detached: Vec::new(),
        }
    }
    let tiers = vec![
        tier("Table", 0.0, &[], MeetConstraint::ScaleReference(0.3)),
        tier(
            "Star",
            15.0,
            &[6.0, 18.0, 30.0, 42.0],
            MeetConstraint::MeetNamed(vec!["Table".to_string()]),
        ),
    ];
    let design = Design::new(
        PreformSpec::block(2.0, 1.0, 2.0),
        ScheduleMeta {
            gemcad_version: "GemCad 5.0".to_string(),
            gear_teeth: 96,
            gear_reference_angle: 0.0,
            symmetry_order: 8,
            mirror: true,
            refractive_index: 1.54,
            headers: Vec::new(),
            footnotes: Vec::new(),
        },
        tiers,
    );
    let fabricated_solved: Vec<SolvedTier> = design
        .tiers
        .iter()
        .map(|_| SolvedTier {
            mast: 1.0,
            strategy: indicatrix::geometry::meet_solver::SolveStrategy::ScaleReference,
            detail: String::new(),
        })
        .collect();
    let map = FacetMap::from_design(&design, &fabricated_solved);

    let pairs = map.meeting_facet_pairs(&design);
    // Table (orbit size 1) x Star (orbit size 4) = 4 pairs, every one
    // involving Table's single facet id.
    assert_eq!(pairs.len(), 4, "got: {pairs:?}");
    let table_facet = map.facets_of_tier(0)[0];
    for &(a, b) in &pairs {
        assert!(
            a == table_facet || b == table_facet,
            "every pair must involve Table's facet: {a},{b}"
        );
    }
}

#[test]
fn hover_text_reports_a_preform_plane_distinctly_from_a_facet() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);
    let n_d = design.effective_refractive_index();

    assert_eq!(map.hover_text(0, n_d), "Preform");
    let facet_text = map.hover_text(map.preform_plane_count(), n_d);
    assert!(facet_text.contains("Table"), "got: {facet_text}");
    assert!(facet_text.contains("index 0"), "got: {facet_text}");
}

// --- Does the 2D diagram apply a tier's cheater offset? ---
//
// `crown_project`/`pavilion_project`/`profile_project` project `SolidMesh`
// vertex positions directly, with no separate azimuth recomputation anywhere
// in the fill/edge passes (the module's own `index_to_azimuth`-based
// `wheel_direction` is used ONLY for the decorative index-wheel ticks, never
// for a facet's own body), so a cheater offset baked into
// `Design::planes_from_solved` (`design/export.rs::apply_cheater_offsets`)
// does reach the picture. This test proves it by actually rendering both a
// plain and a cheatered diagram from the SAME round-brilliant fixture every
// other test in this file uses, and comparing the two `DiagramFrame`s.
#[test]
fn cheater_offset_moves_only_its_own_tiers_facets_in_the_2d_diagram() {
    use super::super::diagram2d::{DiagramConfig, DiagramStyle, render_diagram};
    use indicatrix::geometry::stone_metrics::{SolidStatus, build_solid_mesh};

    let mut design = standard_round_brilliant_design();
    let cheatered_tier = design
        .tiers
        .iter()
        .position(|t| t.name == "Crown Main")
        .expect("fixture must have a Crown Main tier");
    // Tiers whose facets share no plane with Crown Main and are nowhere near
    // it in the schedule -- these must render byte-identically whichever way
    // the cheater offset is set. (Crown Main's own immediate neighbours,
    // Star and Upper Girdle, are deliberately excluded: a real rotation also
    // moves the shared EDGE with an adjacent tier, so asserting pixel
    // equality for them would be asserting something not actually true of
    // the geometry.)
    let unrelated_tier_names = ["Table", "Girdle", "Pavilion Main", "Lower Girdle", "Culet"];

    let solved = design.solve().expect("every tier is pinned");
    let map = FacetMap::from_design(&design, &solved);

    let plain_planes = design.planes_from_solved(&solved);
    design.cheater_offsets_deg.insert(cheatered_tier, 0.5);
    let cheatered_planes = design.planes_from_solved(&solved);
    // Sanity check on the precondition this test actually exercises: the
    // rotation must have landed on the planes at all (core-level behaviour
    // `design/export.rs`'s own tests already cover in depth; asserted here
    // only so a regression there fails loudly in THIS test too, rather than
    // this test silently passing because nothing differed upstream).
    assert_ne!(
        plain_planes, cheatered_planes,
        "the cheater offset must change at least one plane"
    );

    let plain_mesh = match build_solid_mesh(&plain_planes) {
        SolidStatus::Closed(m) => m,
        other => panic!("plain fixture must close: {other:?}"),
    };
    let cheatered_mesh = match build_solid_mesh(&cheatered_planes) {
        SolidStatus::Closed(m) => m,
        other => panic!("cheatered fixture must close: {other:?}"),
    };

    #[expect(
        clippy::cast_possible_truncation,
        reason = "DiagramConfig stores the angle as f32; a reference angle in degrees is in the normal float range"
    )]
    let gear_reference_angle = design.meta.gear_reference_angle as f32;
    let config = DiagramConfig {
        width: 300,
        height: 300,
        gear_teeth: design.meta.gear_teeth_abs(),
        gear_reference_angle,
        symmetry_order: design.meta.symmetry_order,
        mirror: design.meta.mirror,
    };
    let style = DiagramStyle::default();
    let plain_frame = render_diagram(&plain_mesh, &config, &style);
    let cheatered_frame = render_diagram(&cheatered_mesh, &config, &style);

    let unrelated_facet_ids: std::collections::BTreeSet<usize> = (0..map.facets.len())
        .filter(|&id| {
            map.tier_of(id)
                .is_some_and(|t| unrelated_tier_names.contains(&design.tiers[t].name.as_str()))
        })
        .collect();
    let cheatered_facet_ids: std::collections::BTreeSet<usize> = (0..map.facets.len())
        .filter(|&id| map.tier_of(id) == Some(cheatered_tier))
        .collect();
    assert!(!unrelated_facet_ids.is_empty());
    assert!(!cheatered_facet_ids.is_empty());

    let mut unrelated_tier_pixel_differs = false;
    let mut cheatered_tier_pixel_differs = false;
    for y in 0..config.height {
        for x in 0..config.width {
            let plain_pick = plain_frame.pick_at(x, y).map(|id| id as usize);
            let cheatered_pick = cheatered_frame.pick_at(x, y).map(|id| id as usize);
            if plain_pick == cheatered_pick {
                continue;
            }
            // A differing pixel is attributed to whichever facet was
            // painted there in EITHER render (a facet whose edge shrank
            // shows up as the OTHER frame's facet id instead, and vice
            // versa).
            for id in [plain_pick, cheatered_pick].into_iter().flatten() {
                if unrelated_facet_ids.contains(&id) {
                    unrelated_tier_pixel_differs = true;
                }
                if cheatered_facet_ids.contains(&id) {
                    cheatered_tier_pixel_differs = true;
                }
            }
        }
    }

    assert!(
        cheatered_tier_pixel_differs,
        "the cheatered tier's own facet(s) must visibly move in the diagram -- \
         if this fails, diagram2d.rs is not reading the already-rotated planes \
         `Design::planes_from_solved` produces"
    );
    assert!(
        !unrelated_tier_pixel_differs,
        "a cheater offset on Crown Main must not move any pixel belonging to a \
         tier that shares no plane with it"
    );
}

/// A design of pinned tiers on the 96-tooth wheel, with no reference angle.
fn pinned_design(tiers: Vec<(f64, Vec<f64>, f64)>) -> Design {
    let tiers = tiers
        .into_iter()
        .enumerate()
        .map(|(i, (angle_deg, indices, mast))| ConstraintTier {
            angle_deg,
            name: format!("T{i}"),
            indices,
            constraint: MeetConstraint::ScaleReference(mast),
            imported_meet: None,
            original_notes: None,
            detached: Vec::new(),
        })
        .collect();
    Design::new(
        PreformSpec::block(2.0, 1.0, 2.0),
        ScheduleMeta {
            gemcad_version: "GemCad 5.0".to_string(),
            gear_teeth: 96,
            gear_reference_angle: 0.0,
            symmetry_order: 1,
            mirror: false,
            refractive_index: 1.54,
            headers: Vec::new(),
            footnotes: Vec::new(),
        },
        tiers,
    )
}

/// Shallow tiers put adjacent indices only a fraction of a degree apart in
/// normal space; each is still its own facet, in the map exactly as in the
/// plane list it indexes.
#[test]
fn a_shallow_tier_keeps_all_96_facets() {
    let indices: Vec<f64> = (0..96).map(f64::from).collect();
    for angle in [1.0, 2.0, 3.5] {
        let design = pinned_design(vec![(angle, indices.clone(), 0.5)]);
        let solved = design.solve().expect("the tier is pinned");
        let map = FacetMap::from_design(&design, &solved);

        assert_eq!(
            map.facets_of_tier(0).len(),
            96,
            "angle {angle}: every index must keep its own entry"
        );
        assert_eq!(
            map.facet_count(),
            design.planes_from_solved(&solved).len(),
            "angle {angle}: the map must cover exactly the plane list"
        );
    }
}

/// A tier repeated verbatim is the same half-space twice: the first copy keeps
/// the entry and the second contributes none.
#[test]
fn a_duplicated_tier_yields_one_entry() {
    let design = pinned_design(vec![(41.0, vec![12.0], 0.67), (41.0, vec![12.0], 0.67)]);
    let solved = design.solve().expect("both tiers are pinned");
    let map = FacetMap::from_design(&design, &solved);

    assert_eq!(map.facets_of_tier(0).len(), 1);
    assert_eq!(map.facets_of_tier(1), &[] as &[u32]);
    assert_eq!(
        map.facet_count() - map.preform_plane_count(),
        1,
        "only the first copy may add a facet"
    );
}

/// An index listed twice inside one tier collapses to a single entry.
#[test]
fn an_index_listed_twice_in_a_tier_yields_one_entry() {
    let design = pinned_design(vec![(41.0, vec![12.0, 12.0], 0.67)]);
    let solved = design.solve().expect("the tier is pinned");
    let map = FacetMap::from_design(&design, &solved);

    assert_eq!(map.facets_of_tier(0).len(), 1);
}

/// One pavilion-side cylinder tier with three placements, for the concave tests.
fn dimple_tier() -> ConcaveTier {
    ConcaveTier {
        name: "Dimple".to_string(),
        angle_deg: -35.0,
        indices: vec![0.0, 32.0, 64.0],
        instructions: String::new(),
        tool: ConcaveTool::Cylinder,
        tool_azimuth_deg: 30.0,
        displacement: [0.0, 0.0, 0.0],
        diameter_ratio: 0.25,
        tool_angle_deg: None,
        motion: ToolMotion::Reciprocating,
    }
}

#[test]
fn concave_facets_get_ids_above_the_flat_ones_with_kind_hover_label_and_block() {
    let mut design = standard_round_brilliant_design();
    design.concave_tiers.push(dimple_tier());
    let solved = design.solve().expect("every tier is pinned");
    let flat = FacetMap::from_design(&design, &solved);
    let map = FacetMap::from_design_with_tools(&design, &solved, &[(0, 0), (0, 2)]);
    let first = flat.facet_count();

    assert_eq!(map.facet_count(), first + 2);
    assert_eq!(map.kind_of(0), FacetKind::Flat);
    assert_eq!(
        map.kind_of(first),
        FacetKind::Concave {
            tier: 0,
            placement: 0
        }
    );
    assert_eq!(
        map.kind_of(first + 1),
        FacetKind::Concave {
            tier: 0,
            placement: 2
        }
    );
    assert_eq!(
        map.kind_of(first + 2),
        FacetKind::Flat,
        "out of range is Flat"
    );
    assert_eq!(
        map.tier_of(first),
        None,
        "a concave facet belongs to no flat tier"
    );
    assert_eq!(map.hover_text(first, 1.54), "Dimple CYL θ 30.0° D 0.250");
    assert_eq!(map.facet_label(first + 1), "Dimple 64");
    let blocks = map.tool_facet_blocks();
    assert_eq!(blocks.len(), map.facet_count());
    assert_eq!(blocks[0], None);
    assert_eq!(blocks[first], Some(Block::Pavilion));
    assert_eq!(
        map.overlay_flags(&design, 1.54, None, &BTreeSet::new())
            .flagged
            .len(),
        map.facet_count(),
        "the overlay flags cover the concave ids"
    );
}

/// A concave row is selected by its table position (`tiers.len() + concave index`): that
/// tints exactly the tool facets of that concave tier, no flat facet, and a flat selection
/// tints no tool facet.
#[test]
fn selecting_a_concave_row_tints_exactly_its_tool_facets() {
    let mut design = standard_round_brilliant_design();
    design.concave_tiers.push(dimple_tier());
    let mut second = dimple_tier();
    second.name = "Second".to_string();
    design.concave_tiers.push(second);
    design.ensure_concave_tier_ids();
    let solved = design.solve().expect("every tier is pinned");
    let flat_count = FacetMap::from_design(&design, &solved).facet_count();
    let map = FacetMap::from_design_with_tools(&design, &solved, &[(0, 0), (0, 2), (1, 0)]);
    let tier_count = design.tiers.len();

    let first = map.overlay_flags(&design, 1.54, Some(tier_count), &BTreeSet::new());
    let tinted: Vec<usize> = (0..map.facet_count())
        .filter(|&id| first.selected[id])
        .collect();
    assert_eq!(tinted, vec![flat_count, flat_count + 1]);

    let second = map.overlay_flags(&design, 1.54, Some(tier_count + 1), &BTreeSet::new());
    let tinted: Vec<usize> = (0..map.facet_count())
        .filter(|&id| second.selected[id])
        .collect();
    assert_eq!(tinted, vec![flat_count + 2]);

    let flat = map.overlay_flags(&design, 1.54, Some(0), &BTreeSet::new());
    assert!(
        (flat_count..map.facet_count()).all(|id| !flat.selected[id]),
        "a flat selection leaves the tool facets alone"
    );
    assert!(
        map.facets_of_tier(0)
            .iter()
            .all(|&id| flat.selected[id as usize])
    );

    let past_the_end = map.overlay_flags(&design, 1.54, Some(tier_count + 2), &BTreeSet::new());
    assert!(past_the_end.selected.iter().all(|&on| !on));
}

/// The planes of a partly cut stone are the finished stone's with the hidden tiers'
/// slices removed, so a map for the cut must number exactly those planes -- not the
/// finished stone's, whose ids shift as soon as a hidden tier sat before a shown one.
#[test]
fn a_cut_map_numbers_the_planes_the_partly_cut_stone_is_drawn_from() {
    let mut design = standard_round_brilliant_design();
    design.concave_tiers.push(dimple_tier());
    let solved = design.solve().expect("every tier is pinned");
    let finished = FacetMap::from_design(&design, &solved);

    // The table, the upper girdle and the pavilion main are not cut yet.
    let hidden = [0_usize, 3, 5];
    let visible: Vec<bool> = (0..design.tiers.len())
        .map(|tier| !hidden.contains(&tier))
        .collect();
    let drawn = design
        .try_planes_for_visible_tiers(&solved, &visible)
        .expect("the masts match the design");
    let cut = FacetMap::from_design_cut(&design, &solved, &[], Some(&visible));

    assert_eq!(cut.facet_count(), drawn.len());
    assert_eq!(cut.preform_plane_count(), finished.preform_plane_count());
    for tier in 0..design.tiers.len() {
        if hidden.contains(&tier) {
            assert!(cut.facets_of_tier(tier).is_empty(), "tier {tier} is hidden");
            continue;
        }
        assert_eq!(
            cut.facets_of_tier(tier).len(),
            finished.facets_of_tier(tier).len(),
            "tier {tier} keeps all its facets"
        );
        for &id in cut.facets_of_tier(tier) {
            assert_eq!(cut.tier_of(id as usize), Some(tier));
        }
    }
    // The star follows the hidden table (one plane), so each id moved down by one.
    assert_eq!(cut.facets_of_tier(1)[0] + 1, finished.facets_of_tier(1)[0]);
    // The flat facets number the drawn planes after the preform's, each exactly once.
    let mut every: Vec<u32> = (0..design.tiers.len())
        .flat_map(|tier| cut.facets_of_tier(tier).iter().copied())
        .collect();
    every.sort_unstable();
    let to_u32 = |n: usize| u32::try_from(n).expect("a test plane count fits u32");
    let expected: Vec<u32> = (to_u32(cut.preform_plane_count())..to_u32(drawn.len())).collect();
    assert_eq!(every, expected);

    // Concave facets start after the DRAWN planes, not the finished stone's.
    let with_tools = FacetMap::from_design_cut(&design, &solved, &[(0, 0), (0, 2)], Some(&visible));
    assert_eq!(with_tools.facet_count(), drawn.len() + 2);
    assert_eq!(
        with_tools.kind_of(drawn.len()),
        FacetKind::Concave {
            tier: 0,
            placement: 0
        }
    );
    assert_eq!(with_tools.kind_of(drawn.len() + 2), FacetKind::Flat);

    // No restriction is the finished stone, tools included.
    let all = FacetMap::from_design_cut(&design, &solved, &[(0, 0)], None);
    assert_eq!(all.facet_count(), finished.facet_count() + 1);
}

/// A restriction that hides nothing changes nothing.
#[test]
fn a_cut_map_with_every_tier_visible_is_the_finished_map() {
    let design = standard_round_brilliant_design();
    let solved = design.solve().expect("every tier is pinned");
    let finished = FacetMap::from_design(&design, &solved);
    let all_visible = vec![true; design.tiers.len()];
    let cut = FacetMap::from_design_cut(&design, &solved, &[], Some(&all_visible));
    assert_eq!(cut.facet_count(), finished.facet_count());
    for tier in 0..design.tiers.len() {
        assert_eq!(cut.facets_of_tier(tier), finished.facets_of_tier(tier));
    }
    for id in 0..finished.facet_count() {
        assert_eq!(cut.tier_of(id), finished.tier_of(id));
        assert_eq!(cut.index_on_gear(id), finished.index_on_gear(id));
    }
}

#[test]
fn from_design_with_no_placements_is_exactly_from_design() {
    let mut design = standard_round_brilliant_design();
    design.concave_tiers.push(dimple_tier());
    let solved = design.solve().expect("every tier is pinned");
    let plain = FacetMap::from_design(&design, &solved);
    let with_none = FacetMap::from_design_with_tools(&design, &solved, &[]);
    assert_eq!(with_none.facet_count(), plain.facet_count());
    for id in 0..plain.facet_count() {
        assert_eq!(with_none.kind_of(id), FacetKind::Flat);
        assert_eq!(with_none.hover_text(id, 1.54), plain.hover_text(id, 1.54));
        assert_eq!(with_none.facet_label(id), plain.facet_label(id));
    }
}