pub mod axes;
pub mod camera;
pub mod curve;
pub mod drawable;
pub mod field_color;
pub mod mesh_draw;
pub mod overlay;
pub mod revolve;
pub mod subdivide;
#[cfg(feature = "viz-interactive")]
pub mod window;
use crate::containers::field::Field as _;
use crate::error::{PyrucastError, Result};
use crate::viz::drawable::Drawable;
use std::path::Path;
pub use field_color::Colormap;
pub use revolve::Revolve;
#[derive(Debug, Clone, Copy)]
pub struct View {
pub yaw: f64,
pub pitch: f64,
pub scale: f64,
pub target: Option<crate::atoms::Point3>,
pub show_axes: bool,
pub revolve: Option<Revolve>,
}
impl View {
pub fn front() -> Self {
Self {
yaw: 0.0,
pitch: 0.0,
scale: 1.0,
target: None,
show_axes: true,
revolve: None,
}
}
pub fn top() -> Self {
Self {
yaw: 0.0,
pitch: 90.0,
scale: 1.0,
target: None,
show_axes: true,
revolve: None,
}
}
pub fn side() -> Self {
Self {
yaw: 90.0,
pitch: 0.0,
scale: 1.0,
target: None,
show_axes: true,
revolve: None,
}
}
pub fn iso() -> Self {
Self {
yaw: 45.0,
pitch: 35.264_389_682_754_654,
scale: 1.0,
target: None,
show_axes: true,
revolve: None,
}
}
}
impl Default for View {
fn default() -> Self {
Self::iso()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MeshStyle {
#[default]
Surface,
Wireframe,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ColorScale {
pub cmap: Colormap,
pub vmin: Option<f64>,
pub vmax: Option<f64>,
}
impl ColorScale {
pub fn resolve(&self, data_min: f64, data_max: f64) -> (f64, f64) {
(self.vmin.unwrap_or(data_min), self.vmax.unwrap_or(data_max))
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum SaveFormat {
Png,
Svg,
}
impl SaveFormat {
pub(crate) fn from_path(path: &Path) -> Result<Self> {
match path
.extension()
.and_then(|e| e.to_str())
.map(|s| s.to_ascii_lowercase())
{
Some(ref s) if s == "png" => Ok(SaveFormat::Png),
Some(ref s) if s == "svg" => Ok(SaveFormat::Svg),
Some(other) => Err(PyrucastError::Message(format!(
"unsupported viz extension: \"{}\" (expected .png or .svg)",
other
))),
None => Err(PyrucastError::Message(
"viz output path has no extension (expected .png or .svg)".into(),
)),
}
}
}
pub(crate) const DEFAULT_WIDTH: u32 = 800;
pub(crate) const DEFAULT_HEIGHT: u32 = 600;
pub(crate) fn check_revolve<D: Drawable>(object: &D, view: &View) -> Result<()> {
if view.revolve.is_some() && !object.is_axisymmetric() {
return Err(PyrucastError::Message(
"revolve: the plotted geometry is not axisymmetric — build it on \
Coords::axisymmetric() (Python: Coords.axisymmetric()), whose \
abscissa is the radius the sweep turns around"
.into(),
));
}
Ok(())
}
pub(crate) fn render<D: Drawable>(
object: &D,
view: Option<View>,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
let view = view.unwrap_or_default();
check_revolve(object, &view)?;
match save {
Some(path) => render_to_file(object, view, path, title),
None => {
#[cfg(feature = "viz-interactive")]
{
window::run_interactive(object, view, title)
}
#[cfg(not(feature = "viz-interactive"))]
{
let _ = title;
Err(PyrucastError::Message(
"interactive viz disabled — recompile with --features viz-interactive \
or pass an output path to save a PNG/SVG"
.into(),
))
}
}
}
}
pub(crate) fn render_submesh_styled(
sm: &crate::containers::mesh::SubMesh,
view: Option<View>,
save: Option<&Path>,
style: MeshStyle,
title: Option<&str>,
) -> Result<()> {
match style {
MeshStyle::Surface => render(sm, view, save, title),
MeshStyle::Wireframe => render(&mesh_draw::SubMeshWire(sm), view, save, title),
}
}
pub(crate) fn render_mesh_styled(
mesh: &crate::containers::mesh::Mesh,
view: Option<View>,
save: Option<&Path>,
style: MeshStyle,
title: Option<&str>,
) -> Result<()> {
match style {
MeshStyle::Surface => render(mesh, view, save, title),
MeshStyle::Wireframe => render(&mesh_draw::MeshWire(mesh), view, save, title),
}
}
pub enum FieldArg<'a> {
Node(&'a crate::containers::node_field::NodeField),
Element(&'a crate::containers::element_field::ElementField),
}
impl FieldArg<'_> {
fn data(&self) -> Result<field_color::FieldData> {
Ok(match self {
FieldArg::Node(f) => field_color::FieldData::Node(f.view()?),
FieldArg::Element(f) => field_color::FieldData::Element(f.view()?),
})
}
}
#[allow(clippy::too_many_arguments)] pub(crate) fn render_mesh_with_field(
mesh: &crate::containers::mesh::Mesh,
field: FieldArg<'_>,
component: Option<&str>,
scale: ColorScale,
smooth: usize,
view: Option<View>,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
let view = view.unwrap_or_default();
check_revolve(mesh, &view)?;
let data = field.data()?;
let resolved = field_color::resolve_component(&data, component)?;
match save {
Some(path) => {
let drawable = field_color::MeshFieldView {
mesh,
field: &data,
component: resolved,
scale,
smooth,
};
render_to_file(&drawable, view, path, title)
}
None => {
#[cfg(feature = "viz-interactive")]
{
window::run_interactive_mesh_field(
mesh, &data, resolved, scale, smooth, view, title,
)
}
#[cfg(not(feature = "viz-interactive"))]
{
Err(PyrucastError::Message(
"interactive viz disabled — recompile with --features viz-interactive \
or pass an output path to save a PNG/SVG"
.into(),
))
}
}
}
}
#[allow(clippy::too_many_arguments)] pub fn render_submesh_with_field(
submesh: &crate::store::Handle<crate::containers::mesh::SubMesh>,
field: FieldArg<'_>,
component: Option<&str>,
scale: ColorScale,
smooth: usize,
view: Option<View>,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
let view = view.unwrap_or_default();
check_revolve(&*crate::store::read(submesh)?, &view)?;
let data = field.data()?;
let resolved = field_color::resolve_component(&data, component)?;
match save {
Some(path) => {
let drawable = field_color::SubMeshFieldView {
submesh,
field: &data,
component: resolved,
scale,
smooth,
};
render_to_file(&drawable, view, path, title)
}
None => {
#[cfg(feature = "viz-interactive")]
{
window::run_interactive_submesh_field(
submesh, &data, resolved, scale, smooth, view, title,
)
}
#[cfg(not(feature = "viz-interactive"))]
{
Err(PyrucastError::Message(
"interactive viz disabled — recompile with --features viz-interactive \
or pass an output path to save a PNG/SVG"
.into(),
))
}
}
}
}
pub(crate) fn node_field_points(
field: &crate::containers::node_field::NodeField,
component: &str,
) -> Result<Vec<(crate::atoms::Point3, f64)>> {
use crate::viz::mesh_draw::pad3;
let view = field.view()?;
let coords = field.coords()?;
let c = crate::store::read(&coords)?;
let mut points = Vec::new();
for nid in field.node_ids()? {
if let Some(val) = view.value_opt(nid, component) {
points.push((pad3(c.coord(nid)?), val));
}
}
Ok(points)
}
pub(crate) fn node_field_is_axisymmetric(field: &crate::containers::node_field::NodeField) -> bool {
field
.coords()
.and_then(|c| Ok(crate::store::read(&c)?.is_axisymmetric()))
.unwrap_or(false)
}
#[cfg(feature = "viz-interactive")]
pub(crate) fn node_field_bbox(
field: &crate::containers::node_field::NodeField,
) -> Result<crate::viz::camera::Bbox3> {
use crate::viz::mesh_draw::pad3;
let coords = field.coords()?;
let c = crate::store::read(&coords)?;
let mut bb = crate::viz::camera::Bbox3::empty();
for nid in field.node_ids()? {
bb.extend(pad3(c.coord(nid)?));
}
Ok(bb)
}
pub(crate) fn render_node_field_points(
field: &crate::containers::node_field::NodeField,
component: Option<&str>,
scale: ColorScale,
view: Option<View>,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
let data = field_color::FieldData::Node(field.view()?);
let resolved = field_color::resolve_component(&data, component)?.to_string();
drop(data);
let points = node_field_points(field, &resolved)?;
let drawable = field_color::NodeFieldPointsView {
points,
component: &resolved,
scale,
axisymmetric: node_field_is_axisymmetric(field),
};
render(&drawable, view, save, title)
}
pub enum FrameField {
Node(crate::containers::node_field::NodeField),
Element(crate::containers::element_field::ElementField),
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn render_evolution_field(
mesh: Option<&crate::containers::mesh::Mesh>,
frames: &[FrameField],
abscissas: &[f64],
abscissa_label: &str,
component: Option<&str>,
scale: ColorScale,
smooth: usize,
frame: Option<usize>,
view: Option<View>,
save: Option<&Path>,
) -> Result<()> {
if frames.is_empty() {
return Err(PyrucastError::Message(
"evolution plot: no tabulated frame".into(),
));
}
match save {
Some(path) => {
let k = frame.unwrap_or(frames.len() - 1);
if k >= frames.len() {
return Err(PyrucastError::Message(format!(
"evolution plot: frame {} out of range (have {})",
k,
frames.len()
)));
}
render_one_frame(
mesh,
&frames[k],
component,
scale,
smooth,
view,
Some(path),
None,
)
}
None => {
#[cfg(feature = "viz-interactive")]
{
window::run_interactive_evolution(
mesh,
frames,
abscissas,
abscissa_label,
component,
scale,
smooth,
view.unwrap_or_default(),
None,
)
}
#[cfg(not(feature = "viz-interactive"))]
{
let _ = (abscissas, abscissa_label, smooth);
Err(PyrucastError::Message(
"interactive viz disabled — recompile with --features viz-interactive \
or pass an output path to save a PNG/SVG"
.into(),
))
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn render_one_frame(
mesh: Option<&crate::containers::mesh::Mesh>,
frame: &FrameField,
component: Option<&str>,
scale: ColorScale,
smooth: usize,
view: Option<View>,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
match (mesh, frame) {
(Some(m), FrameField::Node(f)) => render_mesh_with_field(
m,
FieldArg::Node(f),
component,
scale,
smooth,
view,
save,
title,
),
(Some(m), FrameField::Element(f)) => render_mesh_with_field(
m,
FieldArg::Element(f),
component,
scale,
smooth,
view,
save,
title,
),
(None, FrameField::Node(f)) => {
render_node_field_points(f, component, scale, view, save, title)
}
(None, FrameField::Element(_)) => Err(PyrucastError::Message(
"evolution plot: element-field frames require a mesh".into(),
)),
}
}
pub(crate) fn render_curve(
series: Vec<(String, Vec<(f64, f64)>)>,
x_label: &str,
y_label: &str,
title: &str,
view: Option<View>,
save: Option<&Path>,
) -> Result<()> {
let plot = curve::CurvePlot {
series,
x_label: x_label.to_string(),
y_label: y_label.to_string(),
title: title.to_string(),
};
let mut view = view.unwrap_or_default();
view.show_axes = false;
view.revolve = None;
render(&plot, Some(view), save, None)
}
fn draw_object<DB, D>(
area: &plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
object: &D,
view: &View,
) -> Result<()>
where
DB: plotters::prelude::DrawingBackend,
DB::ErrorType: 'static,
D: Drawable,
{
object.draw_on(area, view).map_err(|e| match e {
PyrucastError::Message(m) => PyrucastError::Message(format!("plotters: {m}")),
other => other,
})?;
if view.show_axes {
axes::draw_gizmo(area, view)?;
}
Ok(())
}
fn draw_root<DB, D>(
area: &plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
object: &D,
view: &View,
title: Option<&str>,
) -> Result<()>
where
DB: plotters::prelude::DrawingBackend,
DB::ErrorType: 'static,
D: Drawable,
{
use plotters::prelude::*;
let map_err = |e: Box<dyn std::error::Error + Send + Sync>| {
PyrucastError::Message(format!("plotters: {e}"))
};
area.fill(&WHITE).map_err(|e| map_err(Box::new(e)))?;
match title {
Some(t) => {
let (_, h) = area.dim_in_pixel();
let split_at = h.saturating_sub(overlay::FIGURE_TITLE_BAND) as i32;
let (main, footer) = area.split_vertically(split_at);
draw_object(&main, object, view)?;
overlay::draw_figure_title(&footer, t)?;
}
None => draw_object(area, object, view)?,
}
Ok(())
}
fn render_to_file<D: Drawable>(
object: &D,
view: View,
path: &Path,
title: Option<&str>,
) -> Result<()> {
use plotters::prelude::*;
let fmt = SaveFormat::from_path(path)?;
let w = DEFAULT_WIDTH;
let h = DEFAULT_HEIGHT;
let map_err = |e: Box<dyn std::error::Error + Send + Sync>| {
PyrucastError::Message(format!("plotters: {e}"))
};
let title = title.filter(|t| !t.trim().is_empty());
match fmt {
SaveFormat::Png => {
let backend = BitMapBackend::new(path, (w, h));
let area = backend.into_drawing_area();
draw_root(&area, object, &view, title)?;
area.present().map_err(|e| map_err(Box::new(e)))?;
}
SaveFormat::Svg => {
let backend = SVGBackend::new(path, (w, h));
let area = backend.into_drawing_area();
draw_root(&area, object, &view, title)?;
area.present().map_err(|e| map_err(Box::new(e)))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets_match_documented_angles() {
assert_eq!(View::front().yaw, 0.0);
assert_eq!(View::front().pitch, 0.0);
assert_eq!(View::top().pitch, 90.0);
assert_eq!(View::side().yaw, 90.0);
let iso = View::iso();
assert_eq!(iso.yaw, 45.0);
assert!((iso.pitch - 35.264_389_682_754_654).abs() < 1e-12);
}
#[test]
fn default_is_iso() {
let d = View::default();
let iso = View::iso();
assert_eq!(d.yaw, iso.yaw);
assert_eq!(d.pitch, iso.pitch);
assert_eq!(d.scale, iso.scale);
}
#[test]
fn save_format_from_path() {
use std::path::PathBuf;
assert!(matches!(
SaveFormat::from_path(&PathBuf::from("a.png")).unwrap(),
SaveFormat::Png
));
assert!(matches!(
SaveFormat::from_path(&PathBuf::from("a.PNG")).unwrap(),
SaveFormat::Png
));
assert!(matches!(
SaveFormat::from_path(&PathBuf::from("a.svg")).unwrap(),
SaveFormat::Svg
));
assert!(SaveFormat::from_path(&PathBuf::from("a.jpg")).is_err());
assert!(SaveFormat::from_path(&PathBuf::from("noext")).is_err());
}
}