use std::fmt;
use std::str::FromStr;
use super::render::{RenderFrameOutput, RenderedFramePixels};
use super::types::RenderError;
use super::volume::PlaneParams;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Region {
pub x: i64,
pub y: i64,
pub width: u32,
pub height: u32,
}
impl Region {
pub fn new(x: i64, y: i64, width: u32, height: u32) -> Self {
Self {
x,
y,
width,
height,
}
}
pub fn right(&self) -> i64 {
self.x + i64::from(self.width)
}
pub fn bottom(&self) -> i64 {
self.y + i64::from(self.height)
}
pub fn clamp_to(&self, width: u64, height: u64) -> Result<Region, RenderError> {
if self.width == 0 || self.height == 0 {
return Err(RenderError::InvalidRegion(format!(
"{self} has zero width or height"
)));
}
let width = i64::try_from(width).unwrap_or(i64::MAX);
let height = i64::try_from(height).unwrap_or(i64::MAX);
let left = self.x.clamp(0, width);
let top = self.y.clamp(0, height);
let right = self.right().clamp(0, width);
let bottom = self.bottom().clamp(0, height);
if right <= left || bottom <= top {
return Err(RenderError::InvalidRegion(format!(
"{self} lies entirely outside the {width}x{height} image"
)));
}
Ok(Region::new(
left,
top,
(right - left) as u32,
(bottom - top) as u32,
))
}
pub fn covers(&self, width: u64, height: u64) -> bool {
self.x <= 0 && self.y <= 0 && self.right() >= width as i64 && self.bottom() >= height as i64
}
}
impl fmt::Display for Region {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"region {},{},{},{}",
self.x, self.y, self.width, self.height
)
}
}
impl FromStr for Region {
type Err = RenderError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let invalid = || {
RenderError::InvalidRegion(format!(
"'{text}' is not X,Y,WIDTH,HEIGHT (integers, width and height > 0)"
))
};
let parts: Vec<&str> = text.split(',').map(str::trim).collect();
let [x, y, width, height] = parts.as_slice() else {
return Err(invalid());
};
let x = x.parse::<i64>().map_err(|_| invalid())?;
let y = y.parse::<i64>().map_err(|_| invalid())?;
let width = width.parse::<u32>().map_err(|_| invalid())?;
let height = height.parse::<u32>().map_err(|_| invalid())?;
if width == 0 || height == 0 {
return Err(invalid());
}
Ok(Region::new(x, y, width, height))
}
}
pub(crate) fn crop_rendered_frame(
frame: RenderedFramePixels,
region: Option<&Region>,
) -> Result<RenderedFramePixels, RenderError> {
let Some(region) = region else {
return Ok(frame);
};
let clamped = region.clamp_to(u64::from(frame.width), u64::from(frame.height))?;
if clamped.covers(u64::from(frame.width), u64::from(frame.height)) {
return Ok(frame);
}
let expected = usize::from(frame.width)
.checked_mul(usize::from(frame.height))
.and_then(|pixels| pixels.checked_mul(usize::from(frame.samples_per_pixel)))
.unwrap_or(usize::MAX);
if frame.bytes.len() < expected {
return Err(RenderError::InvalidPixelDataLength {
expected,
actual: frame.bytes.len(),
});
}
let bytes = crop_interleaved(
&frame.bytes,
usize::from(frame.width),
usize::from(frame.samples_per_pixel),
&clamped,
);
Ok(RenderedFramePixels {
width: clamped.width as u16,
height: clamped.height as u16,
samples_per_pixel: frame.samples_per_pixel,
bytes,
})
}
pub(crate) fn crop_raw_output(
mut output: RenderFrameOutput,
region: Option<&Region>,
planar: bool,
) -> Result<RenderFrameOutput, RenderError> {
let Some(region) = region else {
return Ok(output);
};
let clamped = region.clamp_to(u64::from(output.width), u64::from(output.height))?;
if clamped.covers(u64::from(output.width), u64::from(output.height)) {
return Ok(output);
}
if !output.bits_allocated.is_multiple_of(8) {
return Err(RenderError::InvalidRegion(format!(
"raw output can't be cropped at BitsAllocated {}",
output.bits_allocated
)));
}
let bytes_per_pixel =
usize::from(output.samples_per_pixel) * usize::from(output.bits_allocated / 8);
let expected = usize::from(output.width) * usize::from(output.height) * bytes_per_pixel;
if output.bytes.len() < expected {
return Err(RenderError::InvalidPixelDataLength {
expected,
actual: output.bytes.len(),
});
}
let samples = usize::from(output.samples_per_pixel);
output.bytes = if planar && samples > 1 {
let bytes_per_sample = usize::from(output.bits_allocated / 8);
let plane_len = expected / samples;
let mut out =
Vec::with_capacity(clamped.width as usize * clamped.height as usize * bytes_per_pixel);
for plane in output.bytes[..expected].chunks_exact(plane_len) {
out.extend(crop_interleaved(
plane,
usize::from(output.width),
bytes_per_sample,
&clamped,
));
}
out
} else {
crop_interleaved(
&output.bytes,
usize::from(output.width),
bytes_per_pixel,
&clamped,
)
};
output.width = clamped.width as u16;
output.height = clamped.height as u16;
Ok(output)
}
fn crop_interleaved(bytes: &[u8], width: usize, stride: usize, region: &Region) -> Vec<u8> {
let row_len = region.width as usize * stride;
let mut out = Vec::with_capacity(row_len * region.height as usize);
for row in region.y as usize..region.bottom() as usize {
let start = (row * width + region.x as usize) * stride;
out.extend_from_slice(&bytes[start..start + row_len]);
}
out
}
pub fn plane_params_for_region(
params: &PlaneParams,
region: &Region,
) -> Result<PlaneParams, RenderError> {
let clamped = region.clamp_to(
u64::from(params.output_width),
u64::from(params.output_height),
)?;
let normalize = |v: [f64; 3]| {
let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if length > 0.0 {
[v[0] / length, v[1] / length, v[2] / length]
} else {
v
}
};
let row_dir = normalize(params.row_dir);
let col_dir = normalize(params.col_dir);
let dx =
(clamped.x as f64 + f64::from(clamped.width) / 2.0) - f64::from(params.output_width) / 2.0;
let dy = (clamped.y as f64 + f64::from(clamped.height) / 2.0)
- f64::from(params.output_height) / 2.0;
let mut shifted = params.clone();
for axis in 0..3 {
shifted.origin[axis] = params.origin[axis]
+ row_dir[axis] * dx * params.spacing_mm
+ col_dir[axis] * dy * params.spacing_mm;
}
shifted.output_width = clamped.width;
shifted.output_height = clamped.height;
Ok(shifted)
}