polyscope-core 0.5.9

Core abstractions for polyscope-rs: traits, registry, and state management
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
//! Global state management for polyscope.

use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};

use glam::Vec3;

use crate::error::{PolyscopeError, Result};
use crate::gizmo::GizmoConfig;
use crate::group::Group;
use crate::options::Options;
use crate::quantity::Quantity;
use crate::registry::Registry;
use crate::slice_plane::SlicePlane;

/// Callback type for file drop events.
pub type FileDropCallback = Box<dyn FnMut(&[std::path::PathBuf]) + Send + Sync>;

/// A deferred request to load a material from disk.
#[derive(Debug, Clone)]
pub enum MaterialLoadRequest {
    /// Load a static material from a single file.
    Static { name: String, path: String },
    /// Load a blendable material from 4 files (R, G, B, K channels).
    Blendable {
        name: String,
        filenames: [String; 4],
    },
}

/// Global context singleton.
static CONTEXT: OnceLock<RwLock<Context>> = OnceLock::new();

/// The global context containing all polyscope state.
pub struct Context {
    /// Whether polyscope has been initialized.
    pub initialized: bool,

    /// The structure registry.
    pub registry: Registry,

    /// Groups for organizing structures.
    pub groups: HashMap<String, Group>,

    /// Slice planes for cutting through geometry.
    pub slice_planes: HashMap<String, SlicePlane>,

    /// Gizmo configuration for transformation controls.
    pub gizmo_config: GizmoConfig,

    /// Currently selected structure (`type_name`, name) for gizmo operations.
    pub selected_structure: Option<(String, String)>,

    /// Currently selected slice plane for gizmo operations.
    pub selected_slice_plane: Option<String>,

    /// Global options.
    pub options: Options,

    /// Representative length scale for all registered structures.
    pub length_scale: f32,

    /// Axis-aligned bounding box for all registered structures.
    pub bounding_box: (Vec3, Vec3),

    /// Floating quantities (not attached to any structure).
    pub floating_quantities: Vec<Box<dyn Quantity>>,

    /// Callback invoked when files are dropped onto the window.
    pub file_drop_callback: Option<FileDropCallback>,

    /// Deferred material load requests (processed by App each frame).
    pub material_load_queue: Vec<MaterialLoadRequest>,
}

impl Default for Context {
    fn default() -> Self {
        Self {
            initialized: false,
            registry: Registry::new(),
            groups: HashMap::new(),
            slice_planes: HashMap::new(),
            gizmo_config: GizmoConfig::default(),
            selected_structure: None,
            selected_slice_plane: None,
            options: Options::default(),
            length_scale: 1.0,
            bounding_box: (Vec3::ZERO, Vec3::ONE),
            floating_quantities: Vec::new(),
            file_drop_callback: None,
            material_load_queue: Vec::new(),
        }
    }
}

impl Context {
    /// Computes the center of the bounding box.
    #[must_use]
    pub fn center(&self) -> Vec3 {
        (self.bounding_box.0 + self.bounding_box.1) * 0.5
    }

    /// Updates the global bounding box and length scale from all structures.
    ///
    /// Respects the `auto_compute_scene_extents` option: when disabled, this
    /// is a no-op and the user controls extents manually. Matches C++ Polyscope's
    /// `updateStructureExtents()` guard behavior.
    pub fn update_extents(&mut self) {
        if !self.options.auto_compute_scene_extents {
            return;
        }
        self.recompute_extents();
    }

    /// Unconditionally recomputes extents from all registered structures.
    ///
    /// Called by `update_extents()` when auto-compute is enabled, and also
    /// called directly when the user re-enables auto-compute.
    pub fn recompute_extents(&mut self) {
        let mut min = Vec3::splat(f32::MAX);
        let mut max = Vec3::splat(f32::MIN);
        let mut has_extent = false;

        for structure in self.registry.iter() {
            if let Some((bb_min, bb_max)) = structure.bounding_box() {
                min = min.min(bb_min);
                max = max.max(bb_max);
                has_extent = true;
            }
        }

        if has_extent {
            self.bounding_box = (min, max);
            self.length_scale = (max - min).length();

            // Handle degenerate bounding box (all points coincide).
            // Matches C++ Polyscope commit 3198ab5 — tolerance 1e-3.
            if min == max {
                let offset_scale = if self.length_scale == 0.0 {
                    1e-3
                } else {
                    self.length_scale * 1e-3
                };
                let offset = Vec3::splat(offset_scale / 2.0);
                self.bounding_box = (min - offset, max + offset);
            }
        } else {
            self.bounding_box = (Vec3::ZERO, Vec3::ONE);
            self.length_scale = 1.0;
        }
    }

    /// Creates a new group.
    pub fn create_group(&mut self, name: &str) -> &mut Group {
        self.groups
            .entry(name.to_string())
            .or_insert_with(|| Group::new(name))
    }

    /// Gets a group by name.
    #[must_use]
    pub fn get_group(&self, name: &str) -> Option<&Group> {
        self.groups.get(name)
    }

    /// Gets a mutable group by name.
    pub fn get_group_mut(&mut self, name: &str) -> Option<&mut Group> {
        self.groups.get_mut(name)
    }

    /// Removes a group by name.
    pub fn remove_group(&mut self, name: &str) -> Option<Group> {
        self.groups.remove(name)
    }

    /// Returns true if a group with the given name exists.
    #[must_use]
    pub fn has_group(&self, name: &str) -> bool {
        self.groups.contains_key(name)
    }

    /// Returns all group names.
    #[must_use]
    pub fn group_names(&self) -> Vec<&str> {
        self.groups
            .keys()
            .map(std::string::String::as_str)
            .collect()
    }

    /// Checks if a structure should be visible, combining its own enabled state
    /// with group visibility.
    ///
    /// A structure is visible if:
    /// - Its own `is_enabled()` returns true, AND
    /// - It's not in any disabled group (checked via `is_structure_visible_in_groups`)
    #[must_use]
    pub fn is_structure_visible(&self, structure: &dyn crate::Structure) -> bool {
        structure.is_enabled()
            && self.is_structure_visible_in_groups(structure.type_name(), structure.name())
    }

    /// Checks if a structure should be visible based on its group membership.
    ///
    /// A structure is visible if:
    /// - It's not in any group, or
    /// - All of its ancestor groups are enabled
    #[must_use]
    pub fn is_structure_visible_in_groups(&self, type_name: &str, name: &str) -> bool {
        // Find all groups that contain this structure
        for group in self.groups.values() {
            if group.contains_structure(type_name, name) {
                // Check if this group and all its ancestors are enabled
                if !self.is_group_and_ancestors_enabled(group.name()) {
                    return false;
                }
            }
        }
        true
    }

    /// Checks if a group and all its ancestors are enabled.
    fn is_group_and_ancestors_enabled(&self, group_name: &str) -> bool {
        let mut current = group_name;
        while let Some(group) = self.groups.get(current) {
            if !group.is_enabled() {
                return false;
            }
            if let Some(parent) = group.parent_group() {
                current = parent;
            } else {
                break;
            }
        }
        true
    }

    // ========================================================================
    // Slice Plane Management
    // ========================================================================

    /// Adds a new slice plane.
    pub fn add_slice_plane(&mut self, name: &str) -> &mut SlicePlane {
        self.slice_planes
            .entry(name.to_string())
            .or_insert_with(|| SlicePlane::new(name))
    }

    /// Gets a slice plane by name.
    #[must_use]
    pub fn get_slice_plane(&self, name: &str) -> Option<&SlicePlane> {
        self.slice_planes.get(name)
    }

    /// Gets a mutable slice plane by name.
    pub fn get_slice_plane_mut(&mut self, name: &str) -> Option<&mut SlicePlane> {
        self.slice_planes.get_mut(name)
    }

    /// Removes a slice plane by name.
    pub fn remove_slice_plane(&mut self, name: &str) -> Option<SlicePlane> {
        self.slice_planes.remove(name)
    }

    /// Returns true if a slice plane with the given name exists.
    #[must_use]
    pub fn has_slice_plane(&self, name: &str) -> bool {
        self.slice_planes.contains_key(name)
    }

    /// Returns all slice plane names.
    #[must_use]
    pub fn slice_plane_names(&self) -> Vec<&str> {
        self.slice_planes
            .keys()
            .map(std::string::String::as_str)
            .collect()
    }

    /// Returns the number of slice planes.
    #[must_use]
    pub fn num_slice_planes(&self) -> usize {
        self.slice_planes.len()
    }

    /// Returns an iterator over all slice planes.
    pub fn slice_planes(&self) -> impl Iterator<Item = &SlicePlane> {
        self.slice_planes.values()
    }

    /// Returns an iterator over all enabled slice planes.
    pub fn enabled_slice_planes(&self) -> impl Iterator<Item = &SlicePlane> {
        self.slice_planes.values().filter(|sp| sp.is_enabled())
    }

    // ========================================================================
    // Gizmo and Selection Management
    // ========================================================================

    /// Selects a structure for gizmo manipulation.
    /// This deselects any selected slice plane (mutual exclusion).
    pub fn select_structure(&mut self, type_name: &str, name: &str) {
        self.selected_slice_plane = None; // Mutual exclusion
        self.selected_structure = Some((type_name.to_string(), name.to_string()));
    }

    /// Deselects the current structure.
    pub fn deselect_structure(&mut self) {
        self.selected_structure = None;
    }

    /// Returns the currently selected structure, if any.
    #[must_use]
    pub fn selected_structure(&self) -> Option<(&str, &str)> {
        self.selected_structure
            .as_ref()
            .map(|(t, n)| (t.as_str(), n.as_str()))
    }

    /// Returns whether a structure is selected.
    #[must_use]
    pub fn has_selection(&self) -> bool {
        self.selected_structure.is_some()
    }

    /// Selects a slice plane for gizmo manipulation.
    /// This deselects any selected structure (mutual exclusion).
    pub fn select_slice_plane(&mut self, name: &str) {
        self.selected_structure = None; // Mutual exclusion
        self.selected_slice_plane = Some(name.to_string());
    }

    /// Deselects the current slice plane.
    pub fn deselect_slice_plane(&mut self) {
        self.selected_slice_plane = None;
    }

    /// Returns the currently selected slice plane name, if any.
    #[must_use]
    pub fn selected_slice_plane(&self) -> Option<&str> {
        self.selected_slice_plane.as_deref()
    }

    /// Returns whether a slice plane is selected.
    #[must_use]
    pub fn has_slice_plane_selection(&self) -> bool {
        self.selected_slice_plane.is_some()
    }

    /// Returns the gizmo configuration.
    #[must_use]
    pub fn gizmo(&self) -> &GizmoConfig {
        &self.gizmo_config
    }

    /// Returns the mutable gizmo configuration.
    pub fn gizmo_mut(&mut self) -> &mut GizmoConfig {
        &mut self.gizmo_config
    }
}

/// Initializes the global context.
///
/// This should be called once at the start of the program.
pub fn init_context() -> Result<()> {
    let context = RwLock::new(Context::default());

    CONTEXT
        .set(context)
        .map_err(|_| PolyscopeError::AlreadyInitialized)?;

    with_context_mut(|ctx| {
        ctx.initialized = true;
    });

    Ok(())
}

/// Returns whether the context has been initialized.
pub fn is_initialized() -> bool {
    CONTEXT
        .get()
        .and_then(|lock| lock.read().ok())
        .is_some_and(|ctx| ctx.initialized)
}

/// Access the global context for reading.
///
/// # Panics
///
/// Panics if polyscope has not been initialized.
pub fn with_context<F, R>(f: F) -> R
where
    F: FnOnce(&Context) -> R,
{
    let lock = CONTEXT.get().expect("polyscope not initialized");
    let guard = lock.read().expect("context lock poisoned");
    f(&guard)
}

/// Access the global context for writing.
///
/// # Panics
///
/// Panics if polyscope has not been initialized.
pub fn with_context_mut<F, R>(f: F) -> R
where
    F: FnOnce(&mut Context) -> R,
{
    let lock = CONTEXT.get().expect("polyscope not initialized");
    let mut guard = lock.write().expect("context lock poisoned");
    f(&mut guard)
}

/// Try to access the global context for reading.
///
/// Returns `None` if polyscope has not been initialized.
pub fn try_with_context<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&Context) -> R,
{
    let lock = CONTEXT.get()?;
    let guard = lock.read().ok()?;
    Some(f(&guard))
}

/// Try to access the global context for writing.
///
/// Returns `None` if polyscope has not been initialized.
pub fn try_with_context_mut<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&mut Context) -> R,
{
    let lock = CONTEXT.get()?;
    let mut guard = lock.write().ok()?;
    Some(f(&mut guard))
}

/// Shuts down the global context.
///
/// Note: Due to `OnceLock` semantics, the context cannot be re-initialized
/// after shutdown in the same process.
pub fn shutdown_context() {
    if let Some(lock) = CONTEXT.get() {
        if let Ok(mut ctx) = lock.write() {
            ctx.initialized = false;
            ctx.registry.clear();
            ctx.groups.clear();
            ctx.slice_planes.clear();
            ctx.selected_structure = None;
            ctx.selected_slice_plane = None;
            ctx.floating_quantities.clear();
            ctx.material_load_queue.clear();
        }
    }
}