indicatrix-solid 0.7.2

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
//! The top-level diagram render entry points and one panel's whole draw pass:
//! caption, index wheel, facet fill/edges, labels -- see the parent module's doc
//! comment for the panel conventions this implements.

use super::{
    DiagramConfig, DiagramFrame, DiagramLayout, DiagramStyle, PanelKind,
    fill::{bounds, draw_edge, draw_meet_marker, fill_polygon, meet_marker_points, shade},
    labels::{draw_panel_labels, draw_text, text_size},
    layout::{
        PanelLayout, compute_layout, compute_single_panel_layout, crown_project, crown_visible,
        facet_normals, pavilion_project, pavilion_visible, profile_project, profile_visible,
    },
    legend::{draw_index_wheel, draw_selected_index_radials, draw_symmetry_and_mirror_lines},
    simplify_ring,
};
use crate::raster::{largest_piece_label_spots, screen_centroid, simplified_edge_flags};
use glam::{DVec3, Vec3};
use indicatrix::geometry::{meet_solver::Block, stone_metrics::SolidMesh};

/// Renders `mesh` into a three-panel [`DiagramFrame`] per the parent module's doc
/// comment.
///
/// Never panics on an empty mesh (draws background only, per-panel captions and
/// index wheels still appear).
#[must_use]
pub fn render_diagram(
    mesh: &SolidMesh,
    config: &DiagramConfig,
    style: &DiagramStyle,
) -> DiagramFrame {
    let mut frame = DiagramFrame::blank(config.width, config.height, style.background);
    if config.width == 0 || config.height == 0 {
        return frame;
    }
    let layouts = compute_layout(mesh, config.width, config.height);
    let facet_normal = facet_normals(mesh);
    let wheel = WheelConfig {
        gear_teeth: config.gear_teeth.max(1),
        gear_reference_angle: config.gear_reference_angle,
        symmetry_order: config.symmetry_order,
        mirror: config.mirror,
    };
    frame.layout = DiagramLayout {
        panels: layouts.to_vec(),
        enlarged: false,
        gear_teeth: wheel.gear_teeth,
        gear_reference_angle: wheel.gear_reference_angle,
    };
    // Resolved once, panel-agnostic -- `render_panel` below only needs to
    // filter by which side of the girdle a point falls on, not recompute it.
    let marker_points =
        meet_marker_points(mesh, &style.meet_marker_pairs, mesh_diagonal(mesh) * 1e-4);

    let mut dedup_scratch: Vec<DVec3> = Vec::new();
    let mut ring_scratch: Vec<DVec3> = Vec::new();

    for layout in &layouts {
        render_panel(
            &mut frame,
            mesh,
            layout,
            layout.kind.caption(),
            &facet_normal,
            wheel,
            style,
            &mut dedup_scratch,
            &mut ring_scratch,
            &marker_points,
        );
    }

    frame
}

/// The "enlarge this panel" mode: renders `mesh` as a SINGLE panel filling the
/// whole frame.
///
/// Everything else matches [`render_diagram`]'s fixed three-column layout: the same
/// style, the same meet-marker and index-radial passes, and the same pick, panel and
/// tooth buffer contract. `gui::solid_preview::diagram_wiring`'s hover and click
/// callbacks therefore work against a frame from either function identically, since
/// both go through the same [`render_panel`] into the same [`DiagramFrame`].
#[must_use]
pub fn render_diagram_single_panel(
    mesh: &SolidMesh,
    config: &DiagramConfig,
    style: &DiagramStyle,
    panel: PanelKind,
) -> DiagramFrame {
    render_single(mesh, config, style, panel, panel.caption())
}

/// The stone's end view as a single panel filling the frame: the profile panel drawn for
/// `mesh` turned a quarter turn about the stone's axis (world `+Y`).
///
/// The profile panel ([`render_diagram_single_panel`] with [`PanelKind::Profile`]) looks from
/// world `+Z` towards `-Z`. This view looks from world `-X` towards `+X`, so the two side
/// views of a printed sheet show the stone from two directions a quarter turn apart. The
/// frame carries the caption `END`. Facet ids are unchanged, so picking and labels agree
/// with the other panels.
///
/// Additive: [`PanelKind`] gains no variant, so nothing that matches on it changes.
#[must_use]
pub fn render_diagram_end_view(
    mesh: &SolidMesh,
    config: &DiagramConfig,
    style: &DiagramStyle,
) -> DiagramFrame {
    render_single(
        &turned_quarter(mesh),
        config,
        style,
        PanelKind::Profile,
        "END",
    )
}

/// `mesh` rotated a quarter turn about world `+Y`, so that world `-X` becomes `+Z`
/// (`(x, y, z)` becomes `(z, y, -x)`, a proper rotation).
fn turned_quarter(mesh: &SolidMesh) -> SolidMesh {
    let turn = |p: DVec3| DVec3::new(p.z, p.y, -p.x);
    SolidMesh {
        positions: mesh.positions.iter().map(|&p| turn(p)).collect(),
        normals: mesh.normals.iter().map(|&n| turn(n)).collect(),
        facet_id: mesh.facet_id.clone(),
        indices: mesh.indices.clone(),
        rings: mesh
            .rings
            .iter()
            .map(|(id, ring)| (*id, ring.iter().map(|&p| turn(p)).collect()))
            .collect(),
        piece_normals: mesh
            .piece_normals
            .as_ref()
            .map(|pieces| pieces.iter().map(|&n| turn(n)).collect()),
        edge_visible: mesh.edge_visible.clone(),
    }
}

/// The body of [`render_diagram_single_panel`] with the caption passed in.
fn render_single(
    mesh: &SolidMesh,
    config: &DiagramConfig,
    style: &DiagramStyle,
    panel: PanelKind,
    caption: &str,
) -> DiagramFrame {
    let mut frame = DiagramFrame::blank(config.width, config.height, style.background);
    if config.width == 0 || config.height == 0 {
        return frame;
    }
    let layout = compute_single_panel_layout(mesh, config.width, config.height, panel);
    let facet_normal = facet_normals(mesh);
    let wheel = WheelConfig {
        gear_teeth: config.gear_teeth.max(1),
        gear_reference_angle: config.gear_reference_angle,
        symmetry_order: config.symmetry_order,
        mirror: config.mirror,
    };
    frame.layout = DiagramLayout {
        panels: vec![layout],
        enlarged: true,
        gear_teeth: wheel.gear_teeth,
        gear_reference_angle: wheel.gear_reference_angle,
    };
    let marker_points =
        meet_marker_points(mesh, &style.meet_marker_pairs, mesh_diagonal(mesh) * 1e-4);

    let mut dedup_scratch: Vec<DVec3> = Vec::new();
    let mut ring_scratch: Vec<DVec3> = Vec::new();
    render_panel(
        &mut frame,
        mesh,
        &layout,
        caption,
        &facet_normal,
        wheel,
        style,
        &mut dedup_scratch,
        &mut ring_scratch,
        &marker_points,
    );
    frame
}

/// The mesh's own bounding-box diagonal, in world units -- the scale
/// [`meet_marker_points`]'s vertex-matching tolerance is fractioned from
/// (mirrors [`simplify_ring`]'s own scale-relative merge tolerance). `1e-6` for
/// an empty mesh so a zero tolerance never turns into "everything matches".
fn mesh_diagonal(mesh: &SolidMesh) -> f64 {
    let Some(&first) = mesh.positions.first() else {
        return 1e-6;
    };
    let (mut lo, mut hi) = (first, first);
    for &p in &mesh.positions {
        lo = lo.min(p);
        hi = hi.max(p);
    }
    (hi - lo).length().max(1e-6)
}

/// The index-wheel/symmetry parameters every panel draw needs, bundled purely
/// so [`render_panel`]'s own parameter list doesn't keep growing every time a
/// new wheel-relative overlay (the symmetry/mirror lines, on top of the index
/// wheel itself) needs another `DiagramConfig` field mirrored down.
#[derive(Debug, Clone, Copy)]
pub struct WheelConfig {
    /// Number of teeth on the index gear.
    pub gear_teeth: u32,
    /// Reference angle of the index gear, in degrees.
    pub gear_reference_angle: f32,
    /// Rotational symmetry order of the schedule.
    pub symmetry_order: u32,
    /// Whether the schedule carries mirror symmetry.
    pub mirror: bool,
}

/// One panel's whole draw pass: caption, index wheel, facet fill/edges, labels --
/// split out of [`render_diagram`] purely to keep that function short; see the
/// parent module's doc comment for the panel conventions this implements.
#[expect(
    clippy::too_many_arguments,
    reason = "a flat parameter list mirroring render_diagram's own locals -- there is \
              exactly one call site, so a bundling struct would only add indirection"
)]
fn render_panel(
    frame: &mut DiagramFrame,
    mesh: &SolidMesh,
    layout: &PanelLayout,
    caption: &str,
    facet_normal: &[Option<DVec3>],
    wheel: WheelConfig,
    style: &DiagramStyle,
    dedup_scratch: &mut Vec<DVec3>,
    ring_scratch: &mut Vec<DVec3>,
    marker_points: &[DVec3],
) {
    let (cap_w, _) = text_size(caption, 1);
    draw_text(
        frame,
        layout.center_x - cap_w as f32 / 2.0,
        2.0,
        caption,
        1,
        style.wheel_color,
        None,
    );

    if layout.kind.has_index_wheel() {
        draw_symmetry_and_mirror_lines(frame, layout, wheel, style);
        draw_index_wheel(
            frame,
            layout,
            wheel.gear_teeth,
            wheel.gear_reference_angle,
            style.wheel_color,
        );
    }

    let visible: fn(Vec3) -> bool = match layout.kind {
        PanelKind::Crown => crown_visible,
        PanelKind::Pavilion => pavilion_visible,
        PanelKind::Profile => profile_visible,
    };
    let project: fn(DVec3, &PanelLayout) -> (f32, f32, f32) = match layout.kind {
        PanelKind::Crown => crown_project,
        PanelKind::Pavilion => pavilion_project,
        PanelKind::Profile => profile_project,
    };

    let fill_ctx = PanelRenderCtx {
        mesh,
        layout,
        facet_normal,
        style,
        visible,
        project,
    };
    let (edge_points, edge_ranges, label_spots, edge_hidden) =
        fill_panel_facets(frame, &fill_ctx, dedup_scratch, ring_scratch);
    draw_panel_edges(
        frame,
        layout,
        style,
        &edge_points,
        &edge_ranges,
        &edge_hidden,
    );
    draw_panel_labels(frame, layout, style, label_spots);

    if layout.kind.has_index_wheel() {
        draw_selected_index_radials(
            frame,
            layout,
            wheel.gear_teeth,
            wheel.gear_reference_angle,
            style,
            &edge_ranges,
        );
    }

    // Meet-point markers -- crown-side points on the crown panel,
    // pavilion-side points on the pavilion panel (a profile panel shows no
    // index-wheel-relative content and is skipped, same set as the radials
    // above). See `meet_marker_points`'s own doc comment for how a point here
    // was resolved from `DiagramStyle::meet_marker_pairs`.
    let on_this_panel: fn(f64) -> bool = match layout.kind {
        PanelKind::Crown => |y| y >= 0.0,
        PanelKind::Pavilion => |y| y <= 0.0,
        PanelKind::Profile => |_| false,
    };
    for &point in marker_points {
        if !on_this_panel(point.y) {
            continue;
        }
        let screen = project(point, layout);
        draw_meet_marker(frame, screen, style.meet_marker_color, layout.clip);
    }
}

/// The immutable per-panel context [`fill_panel_facets`] needs, bundled purely to
/// keep that function (and its caller, [`render_panel`]) under clippy's
/// argument-count limit.
struct PanelRenderCtx<'a> {
    mesh: &'a SolidMesh,
    layout: &'a PanelLayout,
    facet_normal: &'a [Option<DVec3>],
    style: &'a DiagramStyle,
    visible: fn(Vec3) -> bool,
    project: fn(DVec3, &PanelLayout) -> (f32, f32, f32),
}

/// [`fill_panel_facets`]'s own output: the flattened edge-segment points, each
/// facet's `(facet_id, start, count)` range into them, and each facet's
/// `(facet_id, cx, cy, w, h)` label spot. Named purely so that function's return
/// type doesn't trip clippy's `type_complexity` lint.
type PanelFillOutput = (
    Vec<(f32, f32, f32)>,
    Vec<(usize, usize, usize)>,
    Vec<(usize, f32, f32, f32, f32)>, // facet_id, cx, cy, w, h
    Vec<bool>, // parallel to the edge points: segment not drawn (concave seams only)
);

/// Whether `panel` may show a concave tool facet whose tier is in `block`.
///
/// Crown and pavilion tool pieces belong to their own panel only; the profile
/// (side elevation) panel shows every piece its normal predicate accepts, since it
/// is depth-tested along `z` and has no crown/pavilion side of its own. A girdle
/// block has no crown/pavilion panel.
const fn panel_shows_block(panel: PanelKind, block: Block) -> bool {
    matches!(
        (panel, block),
        (PanelKind::Crown, Block::Crown)
            | (PanelKind::Pavilion, Block::Pavilion)
            | (PanelKind::Profile, _)
    )
}

/// The facet fill pass of [`render_panel`]'s "two passes, exactly like
/// `raster::SolidRasterizer::render`" scheme: fills every visible facet, and
/// collects the edge segments/label spots the caller's later passes
/// ([`draw_panel_edges`]/[`draw_panel_labels`]) draw on top -- so an edge is
/// depth-tested against the complete panel rather than only the facets drawn before
/// it. Split out of `render_panel` purely to keep that function under clippy's
/// function-length lint.
fn fill_panel_facets(
    frame: &mut DiagramFrame,
    ctx: &PanelRenderCtx<'_>,
    dedup_scratch: &mut Vec<DVec3>,
    ring_scratch: &mut Vec<DVec3>,
) -> PanelFillOutput {
    let mut edge_points: Vec<(f32, f32, f32)> = Vec::new();
    let mut edge_ranges: Vec<(usize, usize, usize)> = Vec::new();
    let mut label_spots: Vec<(usize, f32, f32, f32, f32)> = Vec::new();
    let mut edge_hidden: Vec<bool> = Vec::new();
    let mut piece_centroids: Vec<(f32, f32, f32)> = Vec::new();

    for (ring_index, (facet_id, ring)) in ctx.mesh.rings.iter().enumerate() {
        // A concave mesh carries one normal per ring (a facet has several pieces and a
        // tool piece is curved); the planar path keeps its per-facet table.
        let normal_f64 = ctx.mesh.piece_normals.as_ref().map_or_else(
            || ctx.facet_normal.get(*facet_id).copied().flatten(),
            |pieces| pieces.get(ring_index).copied(),
        );
        let Some(normal_f64) = normal_f64 else {
            continue;
        };
        let normal = to_vec3(normal_f64);
        if !(ctx.visible)(normal) {
            continue;
        }
        if let Some(block) = ctx.style.tool_facet_block.get(*facet_id).copied().flatten()
            && !panel_shows_block(ctx.layout.kind, block)
        {
            continue;
        }
        simplify_ring(ring, dedup_scratch, ring_scratch);
        if ring_scratch.len() < 3 {
            continue;
        }
        let screen: Vec<(f32, f32, f32)> = ring_scratch
            .iter()
            .map(|&p| (ctx.project)(p, ctx.layout))
            .collect();

        let color = shade(normal, ctx.style);
        fill_polygon(
            frame,
            &screen,
            *facet_id,
            color,
            ctx.style,
            ctx.layout.clip,
            ctx.layout.kind.tag(),
        );
        edge_ranges.push((*facet_id, edge_points.len(), screen.len()));
        edge_points.extend_from_slice(&screen);
        if let Some(visible) = &ctx.mesh.edge_visible {
            let flags = simplified_edge_flags(
                ring,
                ring_scratch,
                visible.get(ring_index).map_or(&[], Vec::as_slice),
            );
            edge_hidden.extend(flags.into_iter().map(|drawn| !drawn));
            piece_centroids.push(screen_centroid(&screen));
        }

        let (min_x, max_x, min_y, max_y) = bounds(&screen);
        let (cx, cy) = (min_x.midpoint(max_x), min_y.midpoint(max_y));
        label_spots.push((*facet_id, cx, cy, max_x - min_x, max_y - min_y));
    }
    if ctx.mesh.piece_normals.is_some() {
        label_spots = largest_piece_label_spots(&label_spots, &piece_centroids);
    }

    (edge_points, edge_ranges, label_spots, edge_hidden)
}

/// Which of [`draw_panel_edges`]'s ordered passes an edge segment belongs to --
/// mirrors `raster::EdgePass` exactly (see that type's doc comment for why later
/// passes must win a shared edge, and for the pass ordering rationale).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EdgePass {
    /// None of the below: the plain `edge_color`, drawn first.
    Ordinary,
    /// The one facet named in `style.hovered`.
    Hovered,
    /// A facet listed in `style.multi_selected`, not otherwise highlighted.
    MultiSelected,
    /// A facet listed in `style.moved` (its tier's mast moved during a drag), not
    /// selected or pending -- a selection or pending highlight still wins its edges.
    Moved,
    /// `selected` (a whole tier) and not otherwise highlighted.
    Selected,
    /// The one facet named in `style.selected_facet`.
    SelectedFacet,
    /// `pending`: drawn last, so it wins over every other pass too.
    Pending,
}

/// The edge-draw pass of [`render_panel`]'s "two passes" scheme -- see
/// [`fill_panel_facets`]'s doc comment. Split out of `render_panel` purely to keep
/// that function under clippy's function-length lint.
///
/// Draws in [`EdgePass`]'s six ordered sub-passes rather than once per facet, and
/// every highlighted sub-pass uses a wider stroke, so a highlighted facet's
/// boundary reads as a clean, intentional outline instead of being
/// half-overpainted by a neighbouring ordinary facet's dark edge.
fn draw_panel_edges(
    frame: &mut DiagramFrame,
    layout: &PanelLayout,
    style: &DiagramStyle,
    edge_points: &[(f32, f32, f32)],
    edge_ranges: &[(usize, usize, usize)],
    edge_hidden: &[bool],
) {
    let is_selected = |facet_id: usize| style.selected.get(facet_id).copied().unwrap_or(false);
    let is_pending = |facet_id: usize| style.pending.get(facet_id).copied().unwrap_or(false);
    let is_hovered = |facet_id: usize| style.hovered == Some(facet_id as u32);
    let is_selected_facet = |facet_id: usize| style.selected_facet == Some(facet_id as u32);
    let is_multi_selected = |facet_id: usize| style.multi_selected.contains(&(facet_id as u32));
    let is_moved = |facet_id: usize| style.moved.contains(&(facet_id as u32));

    for pass in [
        EdgePass::Ordinary,
        EdgePass::Hovered,
        EdgePass::MultiSelected,
        EdgePass::Moved,
        EdgePass::Selected,
        EdgePass::SelectedFacet,
        EdgePass::Pending,
    ] {
        for &(facet_id, start, count) in edge_ranges {
            let selected = is_selected(facet_id);
            let pending = is_pending(facet_id);
            let hovered = is_hovered(facet_id);
            let selected_facet = is_selected_facet(facet_id);
            let multi_selected = is_multi_selected(facet_id);
            let moved = is_moved(facet_id);
            let highlighted = selected || pending || hovered || selected_facet || moved;
            let (draw_this_pass, color, width) = match pass {
                EdgePass::Ordinary => (!highlighted && !multi_selected, style.edge_color, 1),
                EdgePass::Hovered => (hovered && !pending && !selected_facet, style.hover_color, 2),
                EdgePass::MultiSelected => (
                    multi_selected && !selected && !pending && !selected_facet,
                    style.multi_selected_color,
                    2,
                ),
                EdgePass::Moved => (
                    moved && !selected && !pending && !selected_facet,
                    style.moved_color,
                    2,
                ),
                EdgePass::Selected => (
                    selected && !pending && !selected_facet,
                    style.selected_color,
                    2,
                ),
                EdgePass::SelectedFacet => {
                    (selected_facet && !pending, style.selected_facet_color, 3)
                }
                EdgePass::Pending => (pending, style.pending_color, 2),
            };
            if !draw_this_pass {
                continue;
            }
            let pts = &edge_points[start..start + count];
            for (i, &a) in pts.iter().enumerate() {
                if edge_hidden.get(start + i).copied().unwrap_or(false) {
                    continue;
                }
                let b = pts[(i + 1) % count];
                draw_edge(frame, a, b, color, layout.clip, width);
            }
        }
    }
}

const fn to_vec3(v: DVec3) -> Vec3 {
    Vec3::new(v.x as f32, v.y as f32, v.z as f32)
}