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,
Svgz,
}
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(ref s) if s == "svgz" => Ok(SaveFormat::Svgz),
Some(other) => Err(PyrucastError::Message(format!(
"unsupported viz extension: \"{}\" (expected .png, .svg or .svgz)",
other
))),
None => Err(PyrucastError::Message(
"viz output path has no extension (expected .png, .svg or .svgz)".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: View,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
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: 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: 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: View,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
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::handle::Handle<crate::containers::mesh::SubMesh>,
field: FieldArg<'_>,
component: Option<&str>,
scale: ColorScale,
smooth: usize,
view: View,
save: Option<&Path>,
title: Option<&str>,
) -> Result<()> {
check_revolve(&*submesh.read(), &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::aggregate::Aggregate;
use crate::containers::field::SubField;
use crate::containers::node_field::{first_rows, SubNodeField};
use crate::viz::mesh_draw::pad3;
let mut held: Vec<(crate::atoms::NodeId, f64)> = Vec::new();
{
let guards: Vec<crate::handle::ReadGuard<SubNodeField>> =
field.iter().map(|h| h.read()).collect();
let zones: Vec<(&SubNodeField, usize)> = guards
.iter()
.filter_map(|g| Some((&**g, g.component_index(component)?)))
.collect();
let only: Vec<&SubNodeField> = zones.iter().map(|&(z, _)| z).collect();
first_rows(&only, |z, rows| {
let (zone, ci) = zones[z];
let (values, width) = (zone.values(), zone.component_count());
rows.for_each(|row, p| held.push((p, values[row * width + ci])));
});
}
let coords = field.coords()?;
let c = coords.read();
held.into_iter()
.map(|(nid, val)| Ok((pad3(c.position(nid)?), val)))
.collect()
}
pub(crate) fn node_field_is_axisymmetric(field: &crate::containers::node_field::NodeField) -> bool {
field
.coords()
.map(|c| c.read().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 = coords.read();
let mut bb = crate::viz::camera::Bbox3::empty();
for h in field {
let zone = h.read();
let support = zone.support();
let support = support.read();
for &nid in zone.nodes_with(&support) {
bb.extend(pad3(c.position(nid)?));
}
}
Ok(bb)
}
pub(crate) fn render_node_field_points(
field: &crate::containers::node_field::NodeField,
component: Option<&str>,
scale: ColorScale,
view: 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: View,
save: Option<&Path>,
title: Option<&str>,
) -> 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),
title,
)
}
None => {
#[cfg(feature = "viz-interactive")]
{
window::run_interactive_evolution(
mesh,
frames,
abscissas,
abscissa_label,
component,
scale,
smooth,
view,
title,
)
}
#[cfg(not(feature = "viz-interactive"))]
{
let _ = (abscissas, abscissa_label, smooth, title);
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: 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: 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;
view.show_axes = false;
view.revolve = None;
render(&plot, 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 | SaveFormat::Svgz => {
let mut markup = String::new();
{
let backend = SVGBackend::with_string(&mut markup, (w, h));
let area = backend.into_drawing_area();
draw_root(&area, object, &view, title)?;
area.present().map_err(|e| map_err(Box::new(e)))?;
}
let markup = shrink_svg(&markup);
if matches!(fmt, SaveFormat::Svgz) {
use std::io::Write as _;
let file = std::fs::File::create(path)?;
let mut gz = flate2::write::GzEncoder::new(file, flate2::Compression::default());
gz.write_all(markup.as_bytes())?;
gz.finish()?;
} else {
std::fs::write(path, markup)?;
}
}
}
Ok(())
}
fn shrink_svg(markup: &str) -> String {
let out = markup.replace(" opacity=\"1\"", "");
let out = pin_implicit_stroke_widths(&out.replace("<polyline fill=\"none\" ", "<polyline "));
let prevailing = ["0", "1", "2"]
.into_iter()
.max_by_key(|w| out.matches(&format!(" stroke-width=\"{w}\"")).count())
.expect("the list is not empty");
let out = out.replace(&format!(" stroke-width=\"{prevailing}\""), "");
out.replacen(
"<svg ",
&format!("<svg fill=\"none\" stroke-width=\"{prevailing}\" "),
1,
)
}
fn pin_implicit_stroke_widths(markup: &str) -> String {
let mut out = String::with_capacity(markup.len());
for piece in markup.split_inclusive('>') {
match piece.rfind(if piece.ends_with("/>") { "/>" } else { ">" }) {
Some(cut) if piece.contains("stroke=\"#") && !piece.contains("stroke-width=") => {
out.push_str(&piece[..cut]);
out.push_str(" stroke-width=\"1\"");
out.push_str(&piece[cut..]);
}
_ => out.push_str(piece),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn node_field_points_draws_each_node_holding_the_component_once() {
use crate::aggregate::Aggregate;
use crate::atoms::Node;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::NodeField;
use crate::coords::Coords;
use crate::handle::Handle;
let coords = Handle::new(Coords::new(1).unwrap());
let n: Vec<Node> = (0..4)
.map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
.collect();
let mut mesh = Mesh::empty();
for zone in [&n[0..2], &n[1..3], &n[3..4]] {
mesh.add_sub(Handle::new(SubMesh::poi1_from_nodes(zone).unwrap()))
.unwrap();
}
let t = vec!["T".to_string()];
let f = NodeField::with(&mesh, &[t.clone(), t, vec!["Q".into()]]).unwrap();
for (z, values) in [(0, [1.0, 2.0]), (1, [2.0, 3.0])] {
let mut zone = f.get(z).unwrap().write();
for (row, v) in values.into_iter().enumerate() {
zone.set(row, 0, v).unwrap();
}
}
let points = node_field_points(&f, "T").unwrap();
let drawn: Vec<(f64, f64)> = points.iter().map(|(p, v)| (p.x, *v)).collect();
assert_eq!(drawn, vec![(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]);
}
#[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!(matches!(
SaveFormat::from_path(&PathBuf::from("a.svgz")).unwrap(),
SaveFormat::Svgz
));
assert!(SaveFormat::from_path(&PathBuf::from("a.jpg")).is_err());
assert!(SaveFormat::from_path(&PathBuf::from("noext")).is_err());
assert!(SaveFormat::from_path(&PathBuf::from("a.svg.gz")).is_err());
}
#[test]
fn shrink_svg_hoists_what_every_tag_repeats() {
let markup = concat!(
r#"<svg width="8" height="8" xmlns="http://www.w3.org/2000/svg">"#,
r##"<polyline fill="none" opacity="1" stroke="#000000" stroke-width="2" points="0,0 1,1 "/>"##,
r##"<polyline fill="none" opacity="1" stroke="#000000" stroke-width="2" points="1,1 2,0 "/>"##,
r##"<polyline fill="none" opacity="1" stroke="#FF0000" stroke-width="1" points="0,2 2,2 "/>"##,
r##"<polygon opacity="1" fill="#B4C8E6" points="0,0 1,0 1,1 "/>"##,
"</svg>",
);
let out = super::shrink_svg(markup);
assert!(!out.contains("opacity=\"1\""), "opacity is the SVG default");
assert!(
out.contains(r#"<svg fill="none" stroke-width="2""#),
"fill and the prevailing width move onto the root"
);
assert!(
out.contains(r##"<polyline stroke="#000000" points="0,0 1,1 "/>"##),
"an edge at the prevailing width states neither"
);
assert!(out.contains(r##"<polyline stroke="#FF0000" stroke-width="1""##));
assert!(out.contains(r##"<polygon fill="#B4C8E6""##));
}
#[test]
fn shrink_svg_pins_an_implicit_width_before_hoisting() {
let markup = concat!(
r#"<svg width="8" height="8">"#,
r##"<rect fill="none" stroke="#6E6E6E" x="0" y="0" width="4" height="4"/>"##,
r##"<polyline stroke="#000000" stroke-width="2" points="0,0 1,1 "/>"##,
r##"<polyline stroke="#000000" stroke-width="2" points="1,1 2,2 "/>"##,
"</svg>",
);
let out = super::shrink_svg(markup);
assert!(
out.contains(r#"<svg fill="none" stroke-width="2""#),
"the mesh width still gets hoisted"
);
assert!(
out.contains(
r##"stroke="#6E6E6E" x="0" y="0" width="4" height="4" stroke-width="1"/>"##
),
"the rectangle is pinned to the default it was riding"
);
}
}