use std::path::{Path, PathBuf};
use crate::{path_to_utf8, sys, AttributeValue, Error, ImageBuf, PixelFormat, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WrapMode {
#[default]
Default,
Black,
Clamp,
Periodic,
Mirror,
}
impl WrapMode {
fn code(self) -> i32 {
match self {
Self::Default => 0,
Self::Black => 1,
Self::Clamp => 2,
Self::Periodic => 3,
Self::Mirror => 4,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum MipMode {
#[default]
Default,
None,
OneLevel,
Trilinear,
Anisotropic,
}
impl MipMode {
fn code(self) -> i32 {
match self {
Self::Default => 0,
Self::None => 1,
Self::OneLevel => 2,
Self::Trilinear => 3,
Self::Anisotropic => 4,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum InterpolationMode {
Closest,
Bilinear,
Bicubic,
#[default]
SmartBicubic,
}
impl InterpolationMode {
fn code(self) -> i32 {
match self {
Self::Closest => 0,
Self::Bilinear => 1,
Self::Bicubic => 2,
Self::SmartBicubic => 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum TextureMode {
#[default]
Texture,
Shadow,
LatLongEnvironment,
LightProbe,
BumpWithSlopes,
}
impl TextureMode {
fn code(self) -> i32 {
match self {
Self::Texture => 0,
Self::Shadow => 1,
Self::LatLongEnvironment => 2,
Self::LightProbe => 3,
Self::BumpWithSlopes => 4,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TextureConfig {
format: Option<PixelFormat>,
tile: Option<[u32; 3]>,
attributes: Vec<(String, AttributeValue)>,
}
impl TextureConfig {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_format(mut self, format: PixelFormat) -> Self {
self.format = Some(format);
self
}
#[must_use]
pub fn with_tile_size(mut self, dimensions: [u32; 3]) -> Self {
self.tile = Some(dimensions);
self
}
#[must_use]
pub fn with_compression(self, compression: &str) -> Self {
self.with_attribute("compression", compression)
}
#[must_use]
pub fn with_wrap_modes(self, s_wrap: WrapMode, t_wrap: WrapMode) -> Self {
let modes = format!("{},{}", s_wrap.name(), t_wrap.name());
self.with_attribute("wrapmodes", modes)
}
#[must_use]
pub fn with_filter(self, filter_name: &str) -> Self {
self.with_attribute("maketx:filtername", filter_name)
}
#[must_use]
pub fn with_mipmap(self, enabled: bool) -> Self {
self.with_attribute("maketx:nomipmap", i32::from(!enabled))
}
#[must_use]
pub fn with_resize_to_power_of_two(self, enabled: bool) -> Self {
self.with_attribute("maketx:resize", i32::from(enabled))
}
#[must_use]
pub fn with_constant_color_detect(self, enabled: bool) -> Self {
self.with_attribute("maketx:constant_color_detect", i32::from(enabled))
}
#[must_use]
pub fn with_monochrome_detect(self, enabled: bool) -> Self {
self.with_attribute("maketx:monochrome_detect", i32::from(enabled))
}
#[must_use]
pub fn with_opaque_detect(self, enabled: bool) -> Self {
self.with_attribute("maketx:opaque_detect", i32::from(enabled))
}
#[must_use]
pub fn with_unpremult(self, enabled: bool) -> Self {
self.with_attribute("maketx:unpremult", i32::from(enabled))
}
#[must_use]
pub fn with_color_conversion(self, from_space: &str, to_space: &str) -> Self {
self.with_attribute("maketx:incolorspace", from_space)
.with_attribute("maketx:outcolorspace", to_space)
}
#[must_use]
pub fn with_channel_count(self, channels: u32) -> Self {
let channels = i32::try_from(channels.min(Self::MAX_CHANNELS)).unwrap_or(i32::MAX);
self.with_attribute("maketx:nchannels", channels)
}
pub const MAX_CHANNELS: u32 = 1024;
#[must_use]
pub fn with_sharpen(self, amount: f32) -> Self {
self.with_attribute("maketx:sharpen", amount)
}
#[must_use]
pub fn with_highlight_compensation(self, enabled: bool) -> Self {
self.with_attribute("maketx:highlightcomp", i32::from(enabled))
}
#[must_use]
pub fn with_nan_check(self, enabled: bool) -> Self {
self.with_attribute("maketx:checknan", i32::from(enabled))
}
pub fn with_attribute(
mut self,
name: impl Into<String>,
value: impl Into<AttributeValue>,
) -> Self {
let name = name.into();
let value = value.into();
match self.attributes.iter_mut().find(|(key, _)| *key == name) {
Some(existing) => existing.1 = value,
None => self.attributes.push((name, value)),
}
self
}
fn to_sys(&self) -> Result<cxx::UniquePtr<sys::imageio::ImageSpec>> {
let mut spec = sys::imageio::imagespec_from_resolution(0, 0, 0);
let Some(mut pinned) = spec.as_mut() else {
return Err(Error::InvalidImageSpec(
"OpenImageIO could not allocate an image specification".to_owned(),
));
};
if let Some(format) = self.format {
if format == PixelFormat::Other {
return Err(Error::InvalidImageSpec(
"a texture needs a concrete pixel format; leave it unset to keep the input's"
.to_owned(),
));
}
sys::imageio::imagespec_set_format(pinned.as_mut(), format.to_sys());
}
if let Some(tile) = self.tile {
let dimension = |name: &'static str, value: u32| {
i32::try_from(value).map_err(|_| {
Error::InvalidImageSpec(format!("{name} {value} exceeds i32::MAX"))
})
};
sys::imageio::imagespec_set_tile_size(
pinned.as_mut(),
dimension("tile width", tile[0])?,
dimension("tile height", tile[1])?,
dimension("tile depth", tile[2])?,
);
}
for (name, value) in &self.attributes {
value.write(pinned.as_mut(), name)?;
}
if !self.attributes.iter().any(|(name, _)| name == "Software") {
AttributeValue::from("OpenImageIO oiio-bind").write(pinned.as_mut(), "Software")?;
}
Ok(spec)
}
}
pub fn make_texture(
mode: TextureMode,
input_path: &Path,
output_path: &Path,
config: &TextureConfig,
) -> Result<()> {
let input = path_to_utf8(input_path)?;
let output = path_to_utf8(output_path)?;
let config = config.to_sys()?;
let Some(config) = config.as_ref() else {
return Err(Error::InvalidImageSpec(
"OpenImageIO could not allocate an image specification".to_owned(),
));
};
let mut message = String::new();
let succeeded = unsafe {
sys::imagebufalgo::imagebufalgo_make_texture_from_file(
mode.code(),
input,
output,
config,
&mut message,
)
};
if succeeded {
Ok(())
} else {
Err(Error::operation("make texture", message))
}
}
pub fn make_texture_from_buffer(
mode: TextureMode,
source: &ImageBuf,
output_path: &Path,
config: &TextureConfig,
) -> Result<()> {
let output = path_to_utf8(output_path)?;
let config = config.to_sys()?;
let Some(config) = config.as_ref() else {
return Err(Error::InvalidImageSpec(
"OpenImageIO could not allocate an image specification".to_owned(),
));
};
let mut message = String::new();
let succeeded = unsafe {
sys::imagebufalgo::imagebufalgo_make_texture_from_buffer(
mode.code(),
source.inner(),
output,
config,
&mut message,
)
};
if succeeded {
Ok(())
} else {
Err(Error::operation("make texture", message))
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TextureOptions {
pub first_channel: u32,
pub subimage: u32,
pub s_wrap: WrapMode,
pub t_wrap: WrapMode,
pub mip_mode: MipMode,
pub interpolation: InterpolationMode,
pub s_blur: f32,
pub t_blur: f32,
pub s_width: f32,
pub t_width: f32,
pub fill: f32,
pub conservative_filter: bool,
pub anisotropic: u16,
pub missing_color: Option<Vec<f32>>,
}
impl Default for TextureOptions {
fn default() -> Self {
Self {
first_channel: 0,
subimage: 0,
s_wrap: WrapMode::default(),
t_wrap: WrapMode::default(),
mip_mode: MipMode::default(),
interpolation: InterpolationMode::default(),
s_blur: 0.0,
t_blur: 0.0,
s_width: 1.0,
t_width: 1.0,
fill: 0.0,
conservative_filter: true,
anisotropic: 32,
missing_color: None,
}
}
}
impl TextureOptions {
fn to_sys(&self) -> Result<sys::texture::TextureLookupOptions> {
Ok(sys::texture::TextureLookupOptions {
first_channel: i32::try_from(self.first_channel).map_err(|_| {
Error::InvalidImageSpec("first channel exceeds i32::MAX".to_owned())
})?,
subimage: i32::try_from(self.subimage)
.map_err(|_| Error::InvalidImageSpec("subimage exceeds i32::MAX".to_owned()))?,
s_wrap: self.s_wrap.code(),
t_wrap: self.t_wrap.code(),
mip_mode: self.mip_mode.code(),
interp_mode: self.interpolation.code(),
s_blur: self.s_blur,
t_blur: self.t_blur,
s_width: self.s_width,
t_width: self.t_width,
fill: self.fill,
conservative_filter: self.conservative_filter,
anisotropic: self.anisotropic,
})
}
}
pub struct TextureHandle<'system> {
system: &'system TextureSystem,
inner: *mut sys::texture::TextureHandle,
}
unsafe impl Send for TextureHandle<'_> {}
unsafe impl Sync for TextureHandle<'_> {}
impl TextureHandle<'_> {
pub fn filename(&self) -> String {
let inner = self.inner;
self.system.with_system(|system| {
unsafe { sys::texture::texturesystem_handle_filename(system, inner) }
})
}
pub fn is_good(&self) -> bool {
let inner = self.inner;
self.system.with_system(|system| {
unsafe { sys::texture::texturesystem_handle_good(system, inner) }
})
}
fn exists(&self) -> bool {
let inner = self.inner;
self.system.with_system(|system| {
unsafe { sys::texture::texturesystem_handle_exists(system, inner) }
})
}
pub fn texture(
&self,
options: &TextureOptions,
s: f32,
t: f32,
derivatives: Derivatives,
result: &mut [f32],
) -> Result<()> {
if result.is_empty() {
return Err(Error::InvalidRoi(
"a texture lookup needs at least one channel".to_owned(),
));
}
let missing_color = TextureSystem::validate_missing_color(options, result.len())?;
let options = options.to_sys()?;
let inner = self.inner;
let mut error = String::new();
let succeeded = self.system.with_system(|system| {
unsafe {
sys::texture::texturesystem_texture_by_handle(
system,
inner,
&options,
missing_color,
s,
t,
derivatives.dsdx,
derivatives.dtdx,
derivatives.dsdy,
derivatives.dtdy,
result,
&mut error,
)
}
});
if succeeded {
Ok(())
} else {
if error.is_empty() {
error = self
.system
.with_system(sys::texture::texturesystem_geterror);
}
Err(Error::operation("texture lookup", error))
}
}
pub fn environment(
&self,
options: &TextureOptions,
direction: [f32; 3],
d_dx: [f32; 3],
d_dy: [f32; 3],
result: &mut [f32],
) -> Result<()> {
if result.is_empty() {
return Err(Error::InvalidRoi(
"an environment lookup needs at least one channel".to_owned(),
));
}
let missing_color = TextureSystem::validate_missing_color(options, result.len())?;
let options = options.to_sys()?;
let inner = self.inner;
let mut error = String::new();
let succeeded = self.system.with_system(|system| {
unsafe {
sys::texture::texturesystem_environment_by_handle(
system,
inner,
&options,
missing_color,
direction[0],
direction[1],
direction[2],
d_dx[0],
d_dx[1],
d_dx[2],
d_dy[0],
d_dy[1],
d_dy[2],
result,
&mut error,
)
}
});
if succeeded {
Ok(())
} else {
if error.is_empty() {
error = self
.system
.with_system(sys::texture::texturesystem_geterror);
}
Err(Error::operation("environment lookup", error))
}
}
}
impl std::fmt::Debug for TextureHandle<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("TextureHandle")
.field("filename", &self.filename())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UdimInventory {
pub tiles: Vec<Option<PathBuf>>,
pub u_tiles: u32,
pub v_tiles: u32,
}
impl UdimInventory {
pub fn tile(&self, u: u32, v: u32) -> Option<&Path> {
if u >= self.u_tiles || v >= self.v_tiles {
return None;
}
self.tiles
.get((u + v * self.u_tiles) as usize)
.and_then(|tile| tile.as_deref())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct Derivatives {
pub dsdx: f32,
pub dtdx: f32,
pub dsdy: f32,
pub dtdy: f32,
}
impl Derivatives {
pub fn uniform(width: f32) -> Self {
Self {
dsdx: width,
dtdx: 0.0,
dsdy: 0.0,
dtdy: width,
}
}
#[must_use]
pub fn with_dsdx(mut self, dsdx: f32) -> Self {
self.dsdx = dsdx;
self
}
#[must_use]
pub fn with_dtdx(mut self, dtdx: f32) -> Self {
self.dtdx = dtdx;
self
}
#[must_use]
pub fn with_dsdy(mut self, dsdy: f32) -> Self {
self.dsdy = dsdy;
self
}
#[must_use]
pub fn with_dtdy(mut self, dtdy: f32) -> Self {
self.dtdy = dtdy;
self
}
pub fn point() -> Self {
Self::default()
}
}
pub struct TextureSystem {
inner: cxx::SharedPtr<sys::texture::TextureSystem>,
}
unsafe impl Send for TextureSystem {}
unsafe impl Sync for TextureSystem {}
impl TextureSystem {
pub fn new() -> Result<Self> {
Self::create()
}
pub fn texture(
&self,
texture_path: &Path,
options: &TextureOptions,
s: f32,
t: f32,
derivatives: Derivatives,
result: &mut [f32],
) -> Result<()> {
if result.is_empty() {
return Err(Error::InvalidRoi(
"a texture lookup needs at least one channel".to_owned(),
));
}
let missing_color = Self::validate_missing_color(options, result.len())?;
let filename = path_to_utf8(texture_path)?;
let options = options.to_sys()?;
let mut error = String::new();
let succeeded = self.with_system(|system| {
sys::texture::texturesystem_texture(
system,
filename,
&options,
missing_color,
s,
t,
derivatives.dsdx,
derivatives.dtdx,
derivatives.dsdy,
derivatives.dtdy,
result,
&mut error,
)
});
if succeeded {
Ok(())
} else {
if error.is_empty() {
error = self.with_system(sys::texture::texturesystem_geterror);
}
Err(Error::operation("texture lookup", error))
}
}
pub fn environment(
&self,
texture_path: &Path,
options: &TextureOptions,
direction: [f32; 3],
d_dx: [f32; 3],
d_dy: [f32; 3],
result: &mut [f32],
) -> Result<()> {
if result.is_empty() {
return Err(Error::InvalidRoi(
"an environment lookup needs at least one channel".to_owned(),
));
}
let missing_color = Self::validate_missing_color(options, result.len())?;
let filename = path_to_utf8(texture_path)?;
let options = options.to_sys()?;
let mut error = String::new();
let succeeded = self.with_system(|system| {
sys::texture::texturesystem_environment(
system,
filename,
&options,
missing_color,
direction[0],
direction[1],
direction[2],
d_dx[0],
d_dx[1],
d_dx[2],
d_dy[0],
d_dy[1],
d_dy[2],
result,
&mut error,
)
});
if succeeded {
Ok(())
} else {
if error.is_empty() {
error = self.with_system(sys::texture::texturesystem_geterror);
}
Err(Error::operation("environment lookup", error))
}
}
pub fn handle(&self, texture_path: &Path) -> Result<TextureHandle<'_>> {
let filename = path_to_utf8(texture_path)?;
let inner = self.with_system(|system| {
unsafe { sys::texture::texturesystem_get_texture_handle(system, filename) }
});
if inner.is_null() {
return Err(Error::OpenImage {
path: texture_path.to_path_buf(),
message: "the texture system could not resolve the name".to_owned(),
});
}
let handle = TextureHandle {
system: self,
inner,
};
if !handle.is_good() || !handle.exists() {
return Err(Error::OpenImage {
path: texture_path.to_path_buf(),
message: "the texture system could not open or read the file".to_owned(),
});
}
Ok(handle)
}
pub fn is_udim(&self, texture_path: &Path) -> Result<bool> {
let filename = path_to_utf8(texture_path)?;
Ok(self.with_system(|system| sys::texture::texturesystem_is_udim(system, filename)))
}
pub fn resolve_udim(&self, pattern: &Path, s: f32, t: f32) -> Result<Option<PathBuf>> {
let filename = path_to_utf8(pattern)?;
let resolved = self
.with_system(|system| sys::texture::texturesystem_resolve_udim(system, filename, s, t));
Ok((!resolved.is_empty()).then(|| PathBuf::from(resolved)))
}
pub fn inventory_udim(&self, pattern: &Path) -> Result<UdimInventory> {
let filename = path_to_utf8(pattern)?;
let mut filenames = Vec::new();
let mut u_tiles = 0_i32;
let mut v_tiles = 0_i32;
self.with_system(|system| {
sys::texture::texturesystem_inventory_udim(
system,
filename,
&mut filenames,
&mut u_tiles,
&mut v_tiles,
);
});
Ok(UdimInventory {
tiles: filenames
.into_iter()
.map(|name| (!name.is_empty()).then(|| PathBuf::from(name)))
.collect(),
u_tiles: u_tiles.max(0) as u32,
v_tiles: v_tiles.max(0) as u32,
})
}
fn validate_missing_color(options: &TextureOptions, channels: usize) -> Result<&[f32]> {
match &options.missing_color {
None => Ok(&[]),
Some(color) if color.len() == channels => Ok(color),
Some(color) => Err(Error::InvalidRoi(format!(
"the missing color holds {} values for a {channels}-channel lookup",
color.len()
))),
}
}
pub fn resolution(&self, texture_path: &Path) -> Result<[u32; 2]> {
let filename = path_to_utf8(texture_path)?;
let mut resolution = [0_i32; 2];
let succeeded = self.with_system(|system| {
sys::texture::texturesystem_resolution(system, filename, &mut resolution)
});
if !succeeded {
return Err(Error::OpenImage {
path: texture_path.to_path_buf(),
message: self.with_system(sys::texture::texturesystem_geterror),
});
}
Ok([resolution[0].max(0) as u32, resolution[1].max(0) as u32])
}
pub fn set_max_memory_mb(&mut self, megabytes: f32) -> Result<()> {
if !megabytes.is_finite() || megabytes <= 0.0 {
return Err(Error::InvalidCacheSetting {
name: "max_memory_MB",
value: megabytes.to_string(),
});
}
let succeeded = self.with_system(|system| {
sys::texture::texturesystem_attribute_float(system, "max_memory_MB", megabytes)
});
if succeeded {
Ok(())
} else {
Err(Error::operation(
"configure texture system",
self.with_system(sys::texture::texturesystem_geterror),
))
}
}
pub fn set_max_open_files(&mut self, count: u32) -> Result<()> {
let count = i32::try_from(count).map_err(|_| Error::InvalidCacheSetting {
name: "max_open_files",
value: count.to_string(),
})?;
let succeeded = self.with_system(|system| {
sys::texture::texturesystem_attribute_int(system, "max_open_files", count)
});
if succeeded {
Ok(())
} else {
Err(Error::operation(
"configure texture system",
self.with_system(sys::texture::texturesystem_geterror),
))
}
}
pub fn invalidate(&mut self, texture_path: &Path, force: bool) -> Result<()> {
let filename = path_to_utf8(texture_path)?;
self.with_system(|system| {
sys::texture::texturesystem_invalidate(system, filename, force);
});
Ok(())
}
pub fn invalidate_all(&mut self, force: bool) {
self.with_system(|system| {
sys::texture::texturesystem_invalidate_all(system, force);
});
}
pub fn stats(&mut self) -> String {
let inner = self.inner.clone();
let Some(system) = inner.as_ref() else {
return String::new();
};
sys::texture::texturesystem_getstats(system, 1)
}
fn create() -> Result<Self> {
let inner = sys::texture::texturesystem_create(false);
if inner.is_null() {
return Err(Error::operation(
"create texture system",
"OpenImageIO returned a null texture system".to_owned(),
));
}
Ok(Self { inner })
}
fn with_system<R>(
&self,
operation: impl FnOnce(std::pin::Pin<&mut sys::texture::TextureSystem>) -> R,
) -> R {
let mut system = self.inner.clone();
operation(unsafe { system.pin_mut_unchecked() })
}
}
impl std::fmt::Debug for TextureSystem {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("TextureSystem")
.finish_non_exhaustive()
}
}
enum_names!("wrap mode", WrapMode {
Default => "default",
Black => "black",
Clamp => "clamp",
Periodic => "periodic",
Mirror => "mirror",
});
enum_names!("mip mode", MipMode {
Default => "default",
None => "none",
OneLevel => "one_level",
Trilinear => "trilinear",
Anisotropic => "anisotropic",
});
enum_names!("interpolation mode", InterpolationMode {
Closest => "closest",
Bilinear => "bilinear",
Bicubic => "bicubic",
SmartBicubic => "smart_bicubic",
});
enum_names!("texture mode", TextureMode {
Texture => "texture",
Shadow => "shadow",
LatLongEnvironment => "latlong_environment",
LightProbe => "light_probe",
BumpWithSlopes => "bump_with_slopes",
});
impl TextureOptions {
#[must_use]
pub fn with_first_channel(mut self, first_channel: u32) -> Self {
self.first_channel = first_channel;
self
}
#[must_use]
pub fn with_subimage(mut self, subimage: u32) -> Self {
self.subimage = subimage;
self
}
#[must_use]
pub fn with_s_wrap(mut self, s_wrap: WrapMode) -> Self {
self.s_wrap = s_wrap;
self
}
#[must_use]
pub fn with_t_wrap(mut self, t_wrap: WrapMode) -> Self {
self.t_wrap = t_wrap;
self
}
#[must_use]
pub fn with_mip_mode(mut self, mip_mode: MipMode) -> Self {
self.mip_mode = mip_mode;
self
}
#[must_use]
pub fn with_interpolation(mut self, interpolation: InterpolationMode) -> Self {
self.interpolation = interpolation;
self
}
#[must_use]
pub fn with_s_blur(mut self, s_blur: f32) -> Self {
self.s_blur = s_blur;
self
}
#[must_use]
pub fn with_t_blur(mut self, t_blur: f32) -> Self {
self.t_blur = t_blur;
self
}
#[must_use]
pub fn with_s_width(mut self, s_width: f32) -> Self {
self.s_width = s_width;
self
}
#[must_use]
pub fn with_t_width(mut self, t_width: f32) -> Self {
self.t_width = t_width;
self
}
#[must_use]
pub fn with_fill(mut self, fill: f32) -> Self {
self.fill = fill;
self
}
#[must_use]
pub fn with_conservative_filter(mut self, conservative_filter: bool) -> Self {
self.conservative_filter = conservative_filter;
self
}
#[must_use]
pub fn with_anisotropic(mut self, anisotropic: u16) -> Self {
self.anisotropic = anisotropic;
self
}
#[must_use]
pub fn with_missing_color(mut self, missing_color: Option<Vec<f32>>) -> Self {
self.missing_color = missing_color;
self
}
}