use crate::{sys, Error, ImageSpec, PixelFormat, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeepChannel {
name: String,
format: PixelFormat,
}
impl DeepChannel {
pub fn name(&self) -> &str {
&self.name
}
pub fn format(&self) -> PixelFormat {
self.format
}
}
pub struct DeepImage {
inner: cxx::UniquePtr<sys::deepdata::DeepData>,
origin: [i32; 3],
dimensions: [u32; 3],
channels: Vec<DeepChannel>,
}
unsafe impl Send for DeepImage {}
impl DeepImage {
pub fn new(spec: &ImageSpec) -> Result<Self> {
if !spec.is_deep() {
return Err(Error::InvalidImageSpec(
"a deep image needs a specification marked deep; see ImageSpec::as_deep".to_owned(),
));
}
let pixels = spec.pixel_count()?;
if pixels > i32::MAX as usize {
return Err(Error::InvalidImageSpec(format!(
"a deep image is limited to {} pixels, and this spec has {pixels}",
i32::MAX
)));
}
let native_spec = spec.to_sys()?;
let Some(native_spec) = native_spec.as_ref() else {
return Err(Error::InvalidImageSpec(
"OpenImageIO could not allocate an image specification".to_owned(),
));
};
let mut inner = sys::deepdata::deepdata_default();
let Some(pinned) = inner.as_mut() else {
return Err(Error::operation(
"create deep image",
"OpenImageIO could not allocate deep data".to_owned(),
));
};
let mut error = String::new();
if !sys::deepdata::deepdata_init_from_spec(pinned, native_spec, &mut error) {
return Err(Error::operation("create deep image", error));
}
Self::from_parts(inner, spec)
}
pub fn set_sample_count(&mut self, x: i32, y: i32, count: u32) -> Result<()> {
let pixel = self.pixel_index(x, y)?;
let count = i32::try_from(count)
.map_err(|_| Error::InvalidRoi("sample count exceeds i32::MAX".to_owned()))?;
let mut error = String::new();
if !sys::deepdata::deepdata_set_samples(self.inner_mut(), pixel, count, &mut error) {
return Err(Error::operation("set deep sample count", error));
}
Ok(())
}
pub fn set_value(
&mut self,
x: i32,
y: i32,
channel: u32,
sample: u32,
value: f32,
) -> Result<()> {
let (pixel, channel, sample) = self.address(x, y, channel, sample)?;
let mut error = String::new();
if !sys::deepdata::deepdata_set_deep_value(
self.inner_mut(),
pixel,
channel,
sample,
value,
&mut error,
) {
return Err(Error::operation("set deep value", error));
}
Ok(())
}
pub fn set_value_uint(
&mut self,
x: i32,
y: i32,
channel: u32,
sample: u32,
value: u32,
) -> Result<()> {
let (pixel, channel, sample) = self.address(x, y, channel, sample)?;
let mut error = String::new();
if !sys::deepdata::deepdata_set_deep_value_uint(
self.inner_mut(),
pixel,
channel,
sample,
value,
&mut error,
) {
return Err(Error::operation("set deep value", error));
}
Ok(())
}
pub fn sort_samples(&mut self, x: i32, y: i32) -> Result<()> {
let pixel = self.pixel_index(x, y)?;
self.require_z("sort deep samples")?;
self.require_stack_scratch("sort deep samples", self.samples_at(pixel))?;
sys::deepdata::deepdata_sort(self.inner_mut(), pixel);
Ok(())
}
pub fn merge_overlap_samples(&mut self, x: i32, y: i32) -> Result<()> {
let pixel = self.pixel_index(x, y)?;
self.require_z("merge overlapping samples")?;
sys::deepdata::deepdata_merge_overlaps(self.inner_mut(), pixel);
Ok(())
}
pub fn merge_pixel_from(
&mut self,
x: i32,
y: i32,
src: &DeepImage,
src_x: i32,
src_y: i32,
) -> Result<()> {
let pixel = self.pixel_index(x, y)?;
let src_pixel = src.pixel_index(src_x, src_y)?;
self.require_z("merge deep pixels")?;
if src.z_channel().is_none() {
return Err(Error::operation(
"merge deep pixels",
"the source has no Z channel".to_owned(),
));
}
if !sys::deepdata::deepdata_same_channeltypes(self.inner(), src.inner()) {
return Err(Error::operation(
"merge deep pixels",
"the images disagree on channel types; merging reads the source's \
samples with this image's layout"
.to_owned(),
));
}
let before = self
.samples_at(pixel)
.saturating_add(src.samples_at(src_pixel));
let combined = before
.saturating_mul(before)
.saturating_mul(2)
.saturating_add(before);
self.require_stack_scratch("merge deep pixels", combined)?;
let src_pixel = i32::try_from(src_pixel)
.map_err(|_| Error::InvalidRoi("source pixel index exceeds i32::MAX".to_owned()))?;
sys::deepdata::deepdata_merge_deep_pixels(self.inner_mut(), pixel, src.inner(), src_pixel);
Ok(())
}
pub fn opaque_depth(&self, x: i32, y: i32) -> Result<Option<f32>> {
let pixel = self.pixel_index(x, y)?;
let depth = sys::deepdata::deepdata_opaque_z(self.inner(), pixel);
Ok((depth != f32::MAX).then_some(depth))
}
pub fn occlusion_cull_samples(&mut self, x: i32, y: i32) -> Result<()> {
let pixel = self.pixel_index(x, y)?;
if sys::deepdata::deepdata_a_channel(self.inner()) < 0 {
return Err(Error::operation(
"occlusion cull",
"the image has no alpha channel to test opacity with".to_owned(),
));
}
sys::deepdata::deepdata_occlusion_cull(self.inner_mut(), pixel);
Ok(())
}
pub fn split_samples(&mut self, x: i32, y: i32, depth: f32) -> Result<bool> {
let pixel = self.pixel_index(x, y)?;
Ok(sys::deepdata::deepdata_split(
self.inner_mut(),
pixel,
depth,
))
}
fn samples_at(&self, pixel: i64) -> u64 {
sys::deepdata::deepdata_samples(self.inner(), pixel).max(0) as u64
}
fn require_z(&self, operation: &'static str) -> Result<()> {
if self.z_channel().is_none() {
return Err(Error::operation(
operation,
"the image has no Z channel".to_owned(),
));
}
Ok(())
}
fn require_stack_scratch(&self, operation: &'static str, samples: u64) -> Result<()> {
let sample_bytes = sys::deepdata::deepdata_samplesize(self.inner()).max(1) as u64;
let bytes = samples.saturating_mul(sample_bytes.saturating_add(4));
const SCRATCH_LIMIT: u64 = 256 * 1024;
if bytes > SCRATCH_LIMIT {
return Err(Error::operation(
operation,
format!(
"this pixel's samples need {bytes} bytes of per-call stack \
scratch, over the {SCRATCH_LIMIT}-byte bound"
),
));
}
Ok(())
}
pub(crate) fn native(&self) -> &sys::deepdata::DeepData {
self.inner()
}
fn inner_mut(&mut self) -> std::pin::Pin<&mut sys::deepdata::DeepData> {
self.inner
.as_mut()
.expect("DeepImage invariant violated: null native pointer")
}
pub(crate) fn from_parts(
inner: cxx::UniquePtr<sys::deepdata::DeepData>,
spec: &ImageSpec,
) -> Result<Self> {
if inner.is_null() {
return Err(Error::operation(
"read deep image",
"OpenImageIO returned no deep data".to_owned(),
));
}
let channel_count = sys::deepdata::deepdata_channels(inner.as_ref().expect("non-null"));
let mut channels = Vec::with_capacity(channel_count.max(0) as usize);
for index in 0..channel_count {
let native = inner.as_ref().expect("non-null");
channels.push(DeepChannel {
name: sys::deepdata::deepdata_channelname(native, index),
format: PixelFormat::from_sys(&sys::deepdata::deepdata_channeltype(native, index)),
});
}
Ok(Self {
inner,
origin: spec.origin(),
dimensions: spec.dimensions(),
channels,
})
}
pub fn dimensions(&self) -> [u32; 3] {
self.dimensions
}
pub fn origin(&self) -> [i32; 3] {
self.origin
}
pub fn channels(&self) -> &[DeepChannel] {
&self.channels
}
pub fn channel_count(&self) -> u32 {
self.channels.len() as u32
}
pub fn pixel_count(&self) -> u64 {
sys::deepdata::deepdata_pixels(self.inner()).max(0) as u64
}
pub fn z_channel(&self) -> Option<u32> {
self.channel_index(sys::deepdata::deepdata_z_channel(self.inner()))
}
pub fn z_back_channel(&self) -> Option<u32> {
self.channel_index(sys::deepdata::deepdata_z_back_channel(self.inner()))
}
pub fn alpha_channel(&self) -> Option<u32> {
self.channel_index(sys::deepdata::deepdata_a_channel(self.inner()))
}
pub fn sample_count(&self, x: i32, y: i32) -> Result<u32> {
let pixel = self.pixel_index(x, y)?;
Ok(sys::deepdata::deepdata_samples(self.inner(), pixel).max(0) as u32)
}
pub fn value(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<f32> {
let (pixel, channel, sample) = self.address(x, y, channel, sample)?;
Ok(sys::deepdata::deepdata_deep_value(
self.inner(),
pixel,
channel,
sample,
))
}
pub fn value_uint(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<u32> {
let (pixel, channel, sample) = self.address(x, y, channel, sample)?;
Ok(sys::deepdata::deepdata_deep_value_uint(
self.inner(),
pixel,
channel,
sample,
))
}
pub fn samples(&self, x: i32, y: i32, channel: u32) -> Result<Vec<f32>> {
let count = self.sample_count(x, y)?;
(0..count)
.map(|sample| self.value(x, y, channel, sample))
.collect()
}
fn channel_index(&self, index: i32) -> Option<u32> {
let index = u32::try_from(index).ok()?;
((index as usize) < self.channels.len()).then_some(index)
}
fn pixel_index(&self, x: i32, y: i32) -> Result<i64> {
for (axis, coordinate, start, size) in [
("x", x, self.origin[0], self.dimensions[0]),
("y", y, self.origin[1], self.dimensions[1]),
] {
let end = i64::from(start) + i64::from(size);
if i64::from(coordinate) < i64::from(start) || i64::from(coordinate) >= end {
return Err(Error::InvalidRegion {
axis,
message: format!(
"coordinate {coordinate} lies outside the data window {start}..{end}"
),
});
}
}
let column = i64::from(x) - i64::from(self.origin[0]);
let row = i64::from(y) - i64::from(self.origin[1]);
Ok(row * i64::from(self.dimensions[0]) + column)
}
fn address(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<(i64, i32, i32)> {
let pixel = self.pixel_index(x, y)?;
if channel as usize >= self.channels.len() {
return Err(Error::InvalidRoi(format!(
"channel {channel} is outside the image's {} channels",
self.channels.len()
)));
}
let count = sys::deepdata::deepdata_samples(self.inner(), pixel).max(0) as u32;
if sample >= count {
return Err(Error::InvalidRoi(format!(
"sample {sample} is outside the {count} samples at ({x}, {y})"
)));
}
let channel = i32::try_from(channel)
.map_err(|_| Error::InvalidRoi("channel index exceeds i32::MAX".to_owned()))?;
let sample = i32::try_from(sample)
.map_err(|_| Error::InvalidRoi("sample index exceeds i32::MAX".to_owned()))?;
Ok((pixel, channel, sample))
}
fn inner(&self) -> &sys::deepdata::DeepData {
self.inner
.as_ref()
.expect("DeepImage invariant violated: null native pointer")
}
}
impl std::fmt::Debug for DeepImage {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("DeepImage")
.field("dimensions", &self.dimensions)
.field("channels", &self.channels.len())
.field("pixels", &self.pixel_count())
.finish_non_exhaustive()
}
}