Skip to main content

runmat_runtime/builtins/plotting/
mod.rs

1//! Plotting builtins backed by the runmat-plot renderer.
2
3#[path = "core/common.rs"]
4pub(crate) mod common;
5#[path = "core/context.rs"]
6pub mod context;
7#[path = "core/engine.rs"]
8pub(crate) mod engine;
9#[path = "core/gpu_helpers.rs"]
10pub(crate) mod gpu_helpers;
11#[path = "core/perf.rs"]
12pub(crate) mod perf;
13#[path = "core/point.rs"]
14pub(crate) mod point;
15#[path = "core/properties.rs"]
16pub(crate) mod properties;
17#[path = "core/state.rs"]
18pub(crate) mod state;
19#[path = "core/style.rs"]
20pub(crate) mod style;
21#[path = "core/web.rs"]
22pub mod web;
23
24#[path = "type_resolvers.rs"]
25pub(crate) mod type_resolvers;
26
27#[path = "ops/addpoints.rs"]
28pub(crate) mod addpoints;
29#[path = "ops/ancestor.rs"]
30pub(crate) mod ancestor;
31#[path = "ops/animatedline.rs"]
32pub(crate) mod animatedline;
33#[path = "ops/area.rs"]
34pub(crate) mod area;
35#[path = "ops/axes.rs"]
36pub(crate) mod axes;
37#[path = "ops/axis_scale.rs"]
38pub(crate) mod axis_scale;
39#[path = "ops/axis_tick_angle.rs"]
40pub(crate) mod axis_tick_angle;
41#[path = "ops/axis_tick_format.rs"]
42pub(crate) mod axis_tick_format;
43#[path = "ops/axis_tick_labels.rs"]
44pub(crate) mod axis_tick_labels;
45#[path = "ops/axis_ticks.rs"]
46pub(crate) mod axis_ticks;
47#[path = "ops/bar.rs"]
48pub(crate) mod bar;
49#[path = "ops/caxis.rs"]
50pub(crate) mod caxis;
51#[path = "ops/clf.rs"]
52pub(crate) mod clf;
53#[path = "ops/clim.rs"]
54pub(crate) mod clim;
55#[path = "ops/close.rs"]
56pub(crate) mod close;
57#[path = "ops/cmds.rs"]
58pub(crate) mod cmds;
59#[path = "ops/colormap_arrays.rs"]
60pub(crate) mod colormap_arrays;
61#[path = "ops/colororder.rs"]
62pub(crate) mod colororder;
63#[path = "ops/contour.rs"]
64pub(crate) mod contour;
65#[path = "ops/contour3.rs"]
66pub(crate) mod contour3;
67#[path = "ops/contourf.rs"]
68pub(crate) mod contourf;
69#[path = "ops/copyobj.rs"]
70pub(crate) mod copyobj;
71#[path = "ops/daspect.rs"]
72pub(crate) mod daspect;
73#[path = "ops/data_tip_text_row.rs"]
74pub(crate) mod data_tip_text_row;
75#[path = "ops/datacursormode.rs"]
76pub(crate) mod datacursormode;
77#[path = "ops/drawnow.rs"]
78pub(crate) mod drawnow;
79#[path = "ops/errorbar.rs"]
80pub(crate) mod errorbar;
81#[path = "ops/fcontour.rs"]
82pub(crate) mod fcontour;
83#[path = "ops/figure.rs"]
84pub(crate) mod figure;
85#[path = "ops/figure_persistence.rs"]
86pub(crate) mod figure_persistence;
87#[path = "ops/fill3.rs"]
88pub(crate) mod fill3;
89#[path = "ops/findobj.rs"]
90pub(crate) mod findobj;
91#[path = "ops/fsurf.rs"]
92pub(crate) mod fsurf;
93#[path = "ops/gca.rs"]
94pub(crate) mod gca;
95#[path = "ops/gcf.rs"]
96pub(crate) mod gcf;
97#[path = "ops/get.rs"]
98pub(crate) mod get;
99#[path = "ops/gobjects.rs"]
100pub(crate) mod gobjects;
101#[path = "ops/groot.rs"]
102pub(crate) mod groot;
103#[path = "ops/heatmap.rs"]
104pub(crate) mod heatmap;
105#[path = "ops/hist.rs"]
106pub mod hist;
107#[path = "ops/histogram.rs"]
108pub(crate) mod histogram;
109#[path = "ops/histogram2.rs"]
110pub(crate) mod histogram2;
111#[path = "ops/hold.rs"]
112pub(crate) mod hold;
113#[path = "ops/image.rs"]
114pub(crate) mod image;
115#[path = "ops/imagesc.rs"]
116pub(crate) mod imagesc;
117#[path = "ops/imshow.rs"]
118pub(crate) mod imshow;
119#[path = "ops/isgraphics.rs"]
120pub(crate) mod isgraphics;
121#[path = "ops/ishandle.rs"]
122pub(crate) mod ishandle;
123#[path = "ops/legend.rs"]
124pub(crate) mod legend;
125#[path = "ops/line.rs"]
126pub(crate) mod line;
127#[path = "ops/linkaxes.rs"]
128pub(crate) mod linkaxes;
129#[path = "ops/loglog.rs"]
130pub(crate) mod loglog;
131#[path = "ops/mesh.rs"]
132pub(crate) mod mesh;
133#[path = "ops/meshc.rs"]
134pub(crate) mod meshc;
135#[path = "ops/common/mod.rs"]
136pub(crate) mod op_common;
137#[path = "ops/opengl.rs"]
138pub(crate) mod opengl;
139#[path = "ops/pan.rs"]
140pub(crate) mod pan;
141#[path = "ops/patch.rs"]
142pub(crate) mod patch;
143#[path = "ops/pie.rs"]
144pub(crate) mod pie;
145#[path = "ops/plot.rs"]
146pub(crate) mod plot;
147#[path = "ops/plot3.rs"]
148pub(crate) mod plot3;
149#[path = "ops/plotmatrix.rs"]
150pub(crate) mod plotmatrix;
151#[path = "ops/plotyy.rs"]
152pub(crate) mod plotyy;
153#[path = "ops/polarhistogram.rs"]
154pub(crate) mod polarhistogram;
155#[path = "ops/polarplot.rs"]
156pub(crate) mod polarplot;
157#[path = "ops/polarscatter.rs"]
158pub(crate) mod polarscatter;
159#[path = "ops/print.rs"]
160pub(crate) mod print;
161#[path = "ops/quiver.rs"]
162pub(crate) mod quiver;
163#[path = "ops/quiver3.rs"]
164pub(crate) mod quiver3;
165#[path = "ops/ribbon.rs"]
166pub(crate) mod ribbon;
167#[path = "ops/scatter.rs"]
168pub(crate) mod scatter;
169#[path = "ops/scatter3.rs"]
170pub(crate) mod scatter3;
171#[path = "ops/scatterplot.rs"]
172pub(crate) mod scatterplot;
173#[path = "ops/semilogx.rs"]
174pub(crate) mod semilogx;
175#[path = "ops/semilogy.rs"]
176pub(crate) mod semilogy;
177#[path = "ops/set.rs"]
178pub(crate) mod set;
179#[path = "ops/sgtitle.rs"]
180pub(crate) mod sgtitle;
181#[path = "ops/sphere.rs"]
182pub(crate) mod sphere;
183#[path = "ops/stackedplot.rs"]
184pub(crate) mod stackedplot;
185#[path = "ops/stairs.rs"]
186pub(crate) mod stairs;
187#[path = "ops/stem.rs"]
188pub(crate) mod stem;
189#[path = "ops/subplot.rs"]
190pub(crate) mod subplot;
191#[path = "ops/subtitle.rs"]
192pub(crate) mod subtitle;
193#[path = "ops/suptitle.rs"]
194pub(crate) mod suptitle;
195#[path = "ops/surf.rs"]
196pub(crate) mod surf;
197#[path = "ops/surfc.rs"]
198pub(crate) mod surfc;
199#[path = "ops/text.rs"]
200pub(crate) mod text;
201#[path = "ops/textscatter.rs"]
202pub(crate) mod textscatter;
203#[path = "ops/title.rs"]
204pub(crate) mod title;
205#[path = "ops/triplot.rs"]
206pub(crate) mod triplot;
207#[path = "ops/view.rs"]
208pub(crate) mod view;
209#[path = "ops/waitbar.rs"]
210pub(crate) mod waitbar;
211#[path = "ops/wordcloud.rs"]
212pub(crate) mod wordcloud;
213#[path = "ops/xlabel.rs"]
214pub(crate) mod xlabel;
215#[path = "ops/xlim.rs"]
216pub(crate) mod xlim;
217#[path = "ops/xline.rs"]
218pub(crate) mod xline;
219#[path = "ops/xscale.rs"]
220pub(crate) mod xscale;
221#[path = "ops/xtickangle.rs"]
222pub(crate) mod xtickangle;
223#[path = "ops/xtickformat.rs"]
224pub(crate) mod xtickformat;
225#[path = "ops/xticklabels.rs"]
226pub(crate) mod xticklabels;
227#[path = "ops/xticks.rs"]
228pub(crate) mod xticks;
229#[path = "ops/ylabel.rs"]
230pub(crate) mod ylabel;
231#[path = "ops/ylim.rs"]
232pub(crate) mod ylim;
233#[path = "ops/yline.rs"]
234pub(crate) mod yline;
235#[path = "ops/yscale.rs"]
236pub(crate) mod yscale;
237#[path = "ops/ytickangle.rs"]
238pub(crate) mod ytickangle;
239#[path = "ops/ytickformat.rs"]
240pub(crate) mod ytickformat;
241#[path = "ops/yticklabels.rs"]
242pub(crate) mod yticklabels;
243#[path = "ops/yticks.rs"]
244pub(crate) mod yticks;
245#[path = "ops/zlabel.rs"]
246pub(crate) mod zlabel;
247#[path = "ops/zlim.rs"]
248pub(crate) mod zlim;
249#[path = "ops/zoom.rs"]
250pub(crate) mod zoom;
251
252pub use perf::{
253    set_scatter_target_points, set_scene_export_budget_bytes, set_surface_vertex_budget,
254};
255pub use properties::resolve_plot_handle;
256pub use state::{
257    clear_figure, clone_figure, close_figure, configure_subplot, current_axes_state,
258    current_figure_handle, figure_handles, import_figure, install_figure_observer, link_axes,
259    new_figure_handle, record_recent_figure, reset_hold_state_for_run, reset_plot_state,
260    reset_recent_figures, select_axes_for_figure, select_figure, set_hold, take_recent_figures,
261    FigureAxesState, FigureError, FigureEventKind, FigureEventView, FigureHandle, HoldMode,
262    LinkAxesMode,
263};
264#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
265use std::cell::RefCell;
266use std::collections::HashMap;
267#[cfg(feature = "plot-core")]
268use std::sync::atomic::{AtomicU64, Ordering};
269use std::sync::{Mutex, OnceLock};
270use web::present_figure_on_surface as web_present_figure_on_surface;
271use web::present_geometry_scene_on_surface as web_present_geometry_scene_on_surface;
272pub use web::{
273    bind_surface_to_figure, clear_closed_figure_surfaces, detach_surface, fit_surface_extents,
274    get_surface_camera_state, install_surface, invalidate_surface_revisions,
275    pick_geometry_scene_region, present_surface, render_current_scene, reset_surface_camera,
276    resize_surface, set_geometry_scene_presentation, set_plot_theme_config,
277    set_surface_camera_state, web_renderer_ready, PlotCameraProjection, PlotCameraState,
278    PlotSurfaceCameraState,
279};
280
281#[doc(hidden)]
282pub use state::PlotTestLockGuard;
283
284#[doc(hidden)]
285pub fn lock_plot_test_context() -> PlotTestLockGuard {
286    state::lock_plot_test_registry()
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub enum RuntimePlottingMode {
291    Auto,
292    Interactive,
293    Static,
294}
295
296#[cfg(feature = "gui")]
297pub fn set_runtime_plotting_mode(mode: RuntimePlottingMode) {
298    let mapped = match mode {
299        RuntimePlottingMode::Auto => engine::native::RuntimePlottingMode::Auto,
300        RuntimePlottingMode::Interactive => engine::native::RuntimePlottingMode::Interactive,
301        RuntimePlottingMode::Static => engine::native::RuntimePlottingMode::Static,
302    };
303    engine::native::set_runtime_plotting_mode(mapped);
304}
305
306#[cfg(not(feature = "gui"))]
307pub fn set_runtime_plotting_mode(_mode: RuntimePlottingMode) {}
308
309#[cfg(all(target_arch = "wasm32", feature = "plot-web"))]
310pub use web::{handle_plot_surface_event, take_surface_host_actions, PlotSurfaceHostAction};
311
312pub(crate) fn plotting_error(builtin: &str, message: impl Into<String>) -> crate::RuntimeError {
313    crate::build_runtime_error(message)
314        .with_builtin(builtin)
315        .build()
316}
317
318pub(crate) fn plotting_error_with_source(
319    builtin: &str,
320    message: impl Into<String>,
321    source: impl std::error::Error + Send + Sync + 'static,
322) -> crate::RuntimeError {
323    crate::build_runtime_error(message)
324        .with_builtin(builtin)
325        .with_source(source)
326        .build()
327}
328
329#[cfg(feature = "plot-core")]
330pub async fn export_figure_scene(handle: FigureHandle) -> crate::BuiltinResult<Option<Vec<u8>>> {
331    export_figure_scene_with_policy(
332        handle,
333        runmat_plot::event::resolve_scene_export_policy(Some(perf::scene_export_budget_bytes())),
334    )
335    .await
336}
337
338#[cfg(feature = "plot-core")]
339pub async fn export_figure_scene_with_policy(
340    handle: FigureHandle,
341    policy: runmat_plot::event::SceneExportPolicy,
342) -> crate::BuiltinResult<Option<Vec<u8>>> {
343    let Some(figure) = clone_figure(handle) else {
344        return Ok(None);
345    };
346    let scene = runmat_plot::event::FigureScene::capture_for_export(&figure, policy)
347        .await
348        .map_err(|err| {
349            crate::replay_error_with_source(
350                crate::ReplayErrorKind::ExportRejected,
351                "invalid figure scene content",
352                err,
353            )
354        })?;
355    crate::replay::export_figure_scene_payload_with_limits(
356        &scene,
357        crate::replay::limits::ReplayLimits {
358            max_scene_payload_bytes: policy.max_scene_bytes,
359            ..crate::replay::limits::ReplayLimits::default()
360        },
361    )
362    .map(Some)
363}
364
365#[cfg(feature = "plot-core")]
366pub fn import_figure_scene(bytes: &[u8]) -> crate::BuiltinResult<Option<FigureHandle>> {
367    let scene = crate::replay::import_figure_scene_payload(bytes)?;
368    let figure = scene.into_figure().map_err(|err| {
369        crate::replay_error_with_source(
370            crate::ReplayErrorKind::ImportRejected,
371            "invalid figure scene content",
372            std::io::Error::new(std::io::ErrorKind::InvalidData, err),
373        )
374    })?;
375    let handle = import_figure(figure);
376    register_imported_figure(handle.as_u32());
377    Ok(Some(handle))
378}
379
380#[cfg(feature = "plot-core")]
381pub fn import_geometry_scene_payload(bytes: &[u8]) -> crate::BuiltinResult<Option<u32>> {
382    let scene = crate::replay::import_figure_scene_payload(bytes)?;
383    let hash = geometry_scene_payload_hash(bytes);
384    let scene_id = format!("geometry-scene-payload:{hash:016x}");
385    let scene = scene.into_geometry_scene(scene_id, hash).map_err(|err| {
386        crate::replay_error_with_source(
387            crate::ReplayErrorKind::ImportRejected,
388            "invalid geometry scene content",
389            std::io::Error::new(std::io::ErrorKind::InvalidData, err),
390        )
391    })?;
392    import_geometry_scene(scene).map(Some)
393}
394
395#[cfg(feature = "plot-core")]
396pub async fn import_figure_scene_async(bytes: &[u8]) -> crate::BuiltinResult<Option<FigureHandle>> {
397    let scene = crate::replay::import_figure_scene_payload_async(bytes).await?;
398    let figure = scene.into_figure().map_err(|err| {
399        crate::replay_error_with_source(
400            crate::ReplayErrorKind::ImportRejected,
401            "invalid figure scene content",
402            std::io::Error::new(std::io::ErrorKind::InvalidData, err),
403        )
404    })?;
405    let handle = import_figure(figure);
406    register_imported_figure(handle.as_u32());
407    Ok(Some(handle))
408}
409
410#[cfg(feature = "plot-core")]
411pub async fn import_figure_scene_from_path_async(
412    path: &str,
413) -> crate::BuiltinResult<Option<FigureHandle>> {
414    let bytes = runmat_filesystem::read_async(path).await.map_err(|err| {
415        crate::replay_error_with_source(
416            crate::ReplayErrorKind::ImportRejected,
417            format!("failed to read figure scene payload '{path}'"),
418            err,
419        )
420    })?;
421    import_figure_scene_async(&bytes).await
422}
423
424#[cfg(feature = "plot-core")]
425pub fn import_geometry_scene(scene: runmat_plot::GeometryScene) -> crate::BuiltinResult<u32> {
426    let handle = NEXT_GEOMETRY_SCENE_HANDLE.fetch_add(1, Ordering::Relaxed) as u32;
427    insert_geometry_scene(handle, scene)?;
428    register_imported_geometry_scene(handle);
429    Ok(handle)
430}
431
432#[cfg(feature = "plot-core")]
433pub fn clone_geometry_scene(handle: u32) -> Option<runmat_plot::GeometryScene> {
434    get_geometry_scene(handle)
435}
436
437#[cfg(feature = "plot-core")]
438pub fn append_geometry_scene_chunks(
439    handle: u32,
440    chunks: Vec<runmat_plot::GeometrySceneChunk>,
441    overlay: Option<runmat_plot::GeometrySceneOverlay>,
442) -> crate::BuiltinResult<()> {
443    with_geometry_scene_mut(handle, |scene| {
444        if !chunks.is_empty() {
445            scene.append_chunks(chunks);
446        }
447        if let Some(overlay) = overlay {
448            let merged = merge_geometry_scene_overlay(scene, overlay);
449            scene.set_overlay(merged);
450        }
451    })
452}
453
454#[cfg(feature = "plot-core")]
455pub fn close_geometry_scene(handle: u32) -> bool {
456    remove_geometry_scene(handle)
457}
458
459#[cfg(feature = "plot-core")]
460pub fn export_geometry_scene(handle: u32) -> crate::BuiltinResult<Option<Vec<u8>>> {
461    let Some(scene) = clone_geometry_scene(handle) else {
462        return Ok(None);
463    };
464    let scene = runmat_plot::event::FigureScene::from_geometry_scene(&scene);
465    crate::replay::export_figure_scene_payload(&scene).map(Some)
466}
467
468#[cfg(feature = "plot-core")]
469pub fn present_geometry_scene_on_surface(surface_id: u32, handle: u32) -> crate::BuiltinResult<()> {
470    let Some(scene) = clone_geometry_scene(handle) else {
471        return Err(crate::build_runtime_error(format!(
472            "geometry scene handle {handle} does not exist"
473        ))
474        .with_builtin("plot")
475        .build());
476    };
477    web_present_geometry_scene_on_surface(surface_id, handle, scene)?;
478    if take_imported_geometry_scene(handle) {
479        let _ = reset_surface_camera(surface_id);
480    }
481    Ok(())
482}
483
484pub fn present_figure_on_surface(surface_id: u32, handle: u32) -> crate::BuiltinResult<()> {
485    web_present_figure_on_surface(surface_id, handle)?;
486    if take_imported_figure(handle) {
487        let _ = reset_surface_camera(surface_id);
488    }
489    Ok(())
490}
491
492#[cfg(feature = "plot-core")]
493pub fn import_runtime_figure(figure: runmat_plot::plots::Figure) -> u32 {
494    let handle = state::import_figure(figure);
495    register_imported_figure(handle.as_u32());
496    handle.as_u32()
497}
498
499type ImportedFigureRegistry = Mutex<HashMap<u32, ()>>;
500#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
501type GeometrySceneRegistry = Mutex<HashMap<u32, runmat_plot::GeometryScene>>;
502#[cfg(feature = "plot-core")]
503type ImportedGeometrySceneRegistry = Mutex<HashMap<u32, ()>>;
504
505#[cfg(feature = "plot-core")]
506static NEXT_GEOMETRY_SCENE_HANDLE: AtomicU64 = AtomicU64::new(1);
507
508#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
509thread_local! {
510    static GEOMETRY_SCENE_REGISTRY: RefCell<HashMap<u32, runmat_plot::GeometryScene>> =
511        RefCell::new(HashMap::new());
512}
513
514#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
515fn geometry_scene_registry() -> &'static GeometrySceneRegistry {
516    static REGISTRY: OnceLock<GeometrySceneRegistry> = OnceLock::new();
517    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
518}
519
520#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
521fn insert_geometry_scene(
522    handle: u32,
523    scene: runmat_plot::GeometryScene,
524) -> crate::BuiltinResult<()> {
525    let mut guard = geometry_scene_registry().lock().map_err(|_| {
526        crate::build_runtime_error("geometry scene registry lock poisoned")
527            .with_builtin("plot")
528            .build()
529    })?;
530    guard.insert(handle, scene);
531    Ok(())
532}
533
534#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
535fn insert_geometry_scene(
536    handle: u32,
537    scene: runmat_plot::GeometryScene,
538) -> crate::BuiltinResult<()> {
539    GEOMETRY_SCENE_REGISTRY.with(|registry| {
540        registry.borrow_mut().insert(handle, scene);
541    });
542    Ok(())
543}
544
545#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
546fn get_geometry_scene(handle: u32) -> Option<runmat_plot::GeometryScene> {
547    geometry_scene_registry().lock().ok()?.get(&handle).cloned()
548}
549
550#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
551fn get_geometry_scene(handle: u32) -> Option<runmat_plot::GeometryScene> {
552    GEOMETRY_SCENE_REGISTRY.with(|registry| registry.borrow().get(&handle).cloned())
553}
554
555#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
556fn with_geometry_scene_mut(
557    handle: u32,
558    update: impl FnOnce(&mut runmat_plot::GeometryScene),
559) -> crate::BuiltinResult<()> {
560    let mut guard = geometry_scene_registry().lock().map_err(|_| {
561        crate::build_runtime_error("geometry scene registry lock poisoned")
562            .with_builtin("plot")
563            .build()
564    })?;
565    let scene = guard.get_mut(&handle).ok_or_else(|| {
566        crate::build_runtime_error(format!("geometry scene handle {handle} does not exist"))
567            .with_builtin("plot")
568            .build()
569    })?;
570    update(scene);
571    Ok(())
572}
573
574#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
575fn with_geometry_scene_mut(
576    handle: u32,
577    update: impl FnOnce(&mut runmat_plot::GeometryScene),
578) -> crate::BuiltinResult<()> {
579    GEOMETRY_SCENE_REGISTRY.with(|registry| {
580        let mut registry = registry.borrow_mut();
581        let scene = registry.get_mut(&handle).ok_or_else(|| {
582            crate::build_runtime_error(format!("geometry scene handle {handle} does not exist"))
583                .with_builtin("plot")
584                .build()
585        })?;
586        update(scene);
587        Ok(())
588    })
589}
590
591#[cfg(all(feature = "plot-core", not(target_arch = "wasm32")))]
592fn remove_geometry_scene(handle: u32) -> bool {
593    geometry_scene_registry()
594        .lock()
595        .ok()
596        .and_then(|mut guard| guard.remove(&handle))
597        .is_some()
598}
599
600#[cfg(all(feature = "plot-core", target_arch = "wasm32"))]
601fn remove_geometry_scene(handle: u32) -> bool {
602    GEOMETRY_SCENE_REGISTRY.with(|registry| registry.borrow_mut().remove(&handle).is_some())
603}
604
605#[cfg(feature = "plot-core")]
606fn geometry_scene_payload_hash(bytes: &[u8]) -> u64 {
607    const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
608    const FNV_PRIME: u64 = 0x100000001b3;
609    let mut hash = FNV_OFFSET_BASIS;
610    for byte in bytes {
611        hash ^= u64::from(*byte);
612        hash = hash.wrapping_mul(FNV_PRIME);
613    }
614    hash
615}
616
617#[cfg(feature = "plot-core")]
618fn merge_geometry_scene_overlay(
619    scene: &runmat_plot::GeometryScene,
620    incoming: runmat_plot::GeometrySceneOverlay,
621) -> runmat_plot::GeometrySceneOverlay {
622    let Some(mut current) = scene.overlay.clone() else {
623        let mut overlay = incoming;
624        overlay.vertex_count = scene.vertex_count();
625        overlay.triangle_count = scene.triangle_count();
626        return overlay;
627    };
628
629    current.status = incoming.status;
630    current.quality_label = incoming.quality_label.or(current.quality_label);
631    current.format = incoming.format.or(current.format);
632    current.source_label = incoming.source_label.or(current.source_label);
633    current.allow_create_fea_study =
634        current.allow_create_fea_study || incoming.allow_create_fea_study;
635    current.byte_count = incoming.byte_count.or(current.byte_count);
636    current.mesh_count = current.mesh_count.max(incoming.mesh_count);
637    current.vertex_count = scene.vertex_count();
638    current.triangle_count = scene.triangle_count();
639    current.progress_percent = incoming.progress_percent;
640
641    if current.assembly_nodes.is_empty() {
642        current.assembly_nodes = incoming.assembly_nodes;
643    }
644
645    merge_region_summaries(&mut current.regions, incoming.regions);
646    current.region_count = current.regions.len();
647    current.mapped_region_count = current.region_count;
648    merge_warnings(&mut current.warnings, incoming.warnings);
649    current
650}
651
652#[cfg(feature = "plot-core")]
653fn merge_region_summaries(
654    current: &mut Vec<runmat_plot::GeometrySceneRegionSummary>,
655    incoming: Vec<runmat_plot::GeometrySceneRegionSummary>,
656) {
657    let mut positions = HashMap::<String, usize>::with_capacity(current.len() + incoming.len());
658    for (index, region) in current.iter().enumerate() {
659        positions.insert(region.region_id.clone(), index);
660    }
661    for region in incoming {
662        if let Some(index) = positions.get(&region.region_id).copied() {
663            current[index].triangle_count = current[index]
664                .triangle_count
665                .saturating_add(region.triangle_count);
666        } else {
667            positions.insert(region.region_id.clone(), current.len());
668            current.push(region);
669        }
670    }
671}
672
673#[cfg(feature = "plot-core")]
674fn merge_warnings(current: &mut Vec<String>, incoming: Vec<String>) {
675    for warning in incoming {
676        if !current.iter().any(|item| item == &warning) {
677            current.push(warning);
678        }
679    }
680}
681
682fn imported_figure_registry() -> &'static ImportedFigureRegistry {
683    static REGISTRY: OnceLock<ImportedFigureRegistry> = OnceLock::new();
684    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
685}
686
687fn register_imported_figure(handle: u32) {
688    if let Ok(mut map) = imported_figure_registry().lock() {
689        map.insert(handle, ());
690    }
691}
692
693fn take_imported_figure(handle: u32) -> bool {
694    imported_figure_registry()
695        .lock()
696        .ok()
697        .and_then(|mut map| map.remove(&handle))
698        .is_some()
699}
700
701#[cfg(feature = "plot-core")]
702fn imported_geometry_scene_registry() -> &'static ImportedGeometrySceneRegistry {
703    static REGISTRY: OnceLock<ImportedGeometrySceneRegistry> = OnceLock::new();
704    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
705}
706
707#[cfg(feature = "plot-core")]
708pub fn register_imported_geometry_scene(handle: u32) {
709    if let Ok(mut map) = imported_geometry_scene_registry().lock() {
710        map.insert(handle, ());
711    }
712}
713
714#[cfg(feature = "plot-core")]
715fn take_imported_geometry_scene(handle: u32) -> bool {
716    imported_geometry_scene_registry()
717        .lock()
718        .ok()
719        .and_then(|mut map| map.remove(&handle))
720        .is_some()
721}
722
723#[cfg(feature = "plot-core")]
724pub use engine::{
725    render_figure_png_bytes, render_figure_png_bytes_with_axes_cameras,
726    render_figure_png_bytes_with_camera, render_figure_rgba_bytes,
727    render_figure_rgba_bytes_with_axes_cameras, render_figure_rgba_bytes_with_camera,
728    render_figure_snapshot, render_figure_snapshot_with_camera_state,
729    render_geometry_scene_snapshot,
730};
731
732pub mod ops {
733    pub use super::hist;
734}
735
736#[cfg(test)]
737pub(crate) mod tests {
738    use super::state;
739
740    pub(crate) fn ensure_plot_test_env() {
741        state::disable_rendering_for_tests();
742    }
743
744    pub(crate) fn lock_plot_registry() -> state::PlotTestLockGuard {
745        state::lock_plot_test_registry()
746    }
747}