use std::{
error::Error,
fmt,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
use sim_engine::{Color, TextureAddressMode3d, TextureUvTransform3d};
use crate::screen::{ImageFilter, ImageRegion};
static NEXT_TEXTURE_REVISION: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone)]
pub struct TextureAsset3d {
data: Arc<TextureData>,
}
#[derive(Debug)]
struct TextureData {
width: u32,
height: u32,
pixels: Vec<u8>,
revision: u64,
parent: Option<u64>,
region: Option<ImageRegion>,
}
impl TextureAsset3d {
pub fn rgba8(
width: u32,
height: u32,
pixels: Vec<u8>,
max_source_bytes: usize,
) -> Result<Self, TextureVisualError> {
let expected = pixel_bytes(width, height)?;
if pixels.len() != expected {
return Err(TextureVisualError::PixelLength {
expected,
actual: pixels.len(),
});
}
check_bytes(pixels.capacity(), max_source_bytes)?;
let revision = issue_revision()?;
Ok(Self {
data: Arc::new(TextureData {
width,
height,
pixels,
revision,
parent: None,
region: None,
}),
})
}
pub fn width(&self) -> u32 {
self.data.width
}
pub fn height(&self) -> u32 {
self.data.height
}
pub fn pixels(&self) -> &[u8] {
&self.data.pixels
}
pub fn source_bytes(&self) -> usize {
self.data.pixels.capacity()
}
pub fn shares_storage(&self, other: &Self) -> bool {
self.key() == other.key()
}
pub fn is_direct_revision_of(&self, previous: &Self) -> bool {
self.data.parent == Some(previous.key())
}
pub fn with_region_update(
&self,
region: ImageRegion,
row_stride: usize,
pixels: &[u8],
max_source_bytes: usize,
) -> Result<Self, TextureVisualError> {
if region.x() + region.width() > self.width()
|| region.y() + region.height() > self.height()
{
return Err(TextureVisualError::RegionOutOfBounds);
}
let row_bytes = pixel_bytes(region.width(), 1)?;
let required = (region.height() as usize - 1)
.checked_mul(row_stride)
.and_then(|bytes| bytes.checked_add(row_bytes))
.ok_or(TextureVisualError::SizeOverflow)?;
if row_stride < row_bytes || pixels.len() != required {
return Err(TextureVisualError::InvalidPatchLayout);
}
let size = self.pixels().len();
check_bytes(size, max_source_bytes)?;
let mut revised = Vec::new();
revised
.try_reserve_exact(size)
.map_err(|_| TextureVisualError::AllocationFailed {
requested_bytes: size,
})?;
check_bytes(revised.capacity(), max_source_bytes)?;
revised.extend_from_slice(self.pixels());
let destination_stride = pixel_bytes(self.width(), 1)?;
for row in 0..region.height() as usize {
let destination =
(region.y() as usize + row) * destination_stride + region.x() as usize * 4;
let source = row * row_stride;
revised[destination..destination + row_bytes]
.copy_from_slice(&pixels[source..source + row_bytes]);
}
Ok(Self {
data: Arc::new(TextureData {
width: self.width(),
height: self.height(),
pixels: revised,
revision: issue_revision()?,
parent: Some(self.key()),
region: Some(region),
}),
})
}
pub(crate) fn key(&self) -> u64 {
self.data.revision
}
#[cfg(feature = "desktop")]
pub(crate) fn parent_key(&self) -> Option<u64> {
self.data.parent
}
pub fn updated_region(&self) -> Option<ImageRegion> {
self.data.region
}
}
impl PartialEq for TextureAsset3d {
fn eq(&self, other: &Self) -> bool {
self.shares_storage(other)
}
}
impl Eq for TextureAsset3d {}
#[derive(Debug, Clone, PartialEq)]
pub struct TextureVisual3d {
asset: TextureAsset3d,
filter: ImageFilter,
mipmaps: bool,
address: TextureAddressMode3d,
transform: TextureUvTransform3d,
tint: Color,
}
impl TextureVisual3d {
pub fn new(asset: TextureAsset3d) -> Self {
Self {
asset,
filter: ImageFilter::Nearest,
mipmaps: false,
address: TextureAddressMode3d::Clamp,
transform: TextureUvTransform3d::IDENTITY,
tint: Color::WHITE,
}
}
pub const fn asset(&self) -> &TextureAsset3d {
&self.asset
}
pub const fn filter(&self) -> ImageFilter {
self.filter
}
pub const fn mipmaps(&self) -> bool {
self.mipmaps
}
pub const fn address_mode(&self) -> TextureAddressMode3d {
self.address
}
pub const fn uv_transform(&self) -> TextureUvTransform3d {
self.transform
}
pub const fn tint(&self) -> Color {
self.tint
}
pub fn with_filter(mut self, filter: ImageFilter) -> Self {
self.filter = filter;
self
}
pub fn with_mipmaps(mut self, enabled: bool) -> Self {
self.mipmaps = enabled;
self
}
pub fn with_address_mode(mut self, address: TextureAddressMode3d) -> Self {
self.address = address;
self
}
pub fn with_uv_transform(mut self, transform: TextureUvTransform3d) -> Self {
self.transform = transform;
self
}
pub fn with_asset(mut self, asset: TextureAsset3d) -> Self {
self.asset = asset;
self
}
pub fn with_tint(mut self, tint: Color) -> Result<Self, TextureVisualError> {
if !tint.is_normalized() {
return Err(TextureVisualError::InvalidTint);
}
self.tint = tint;
Ok(self)
}
pub fn texel_bytes(&self) -> Result<usize, TextureVisualError> {
let (mut width, mut height) = (self.asset.width(), self.asset.height());
let mut bytes = pixel_bytes(width, height)?;
while self.mipmaps && (width > 1 || height > 1) {
width = (width / 2).max(1);
height = (height / 2).max(1);
bytes = bytes
.checked_add(pixel_bytes(width, height)?)
.ok_or(TextureVisualError::SizeOverflow)?;
}
Ok(bytes)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextureVisualError {
InvalidDimensions,
SizeOverflow,
PixelLength {
expected: usize,
actual: usize,
},
SourceLimit {
requested: usize,
limit: usize,
},
RegionOutOfBounds,
InvalidPatchLayout,
InvalidTint,
AllocationFailed {
requested_bytes: usize,
},
IdentityExhausted,
}
impl fmt::Display for TextureVisualError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidDimensions => {
formatter.write_str("3D texture dimensions must be positive")
}
Self::SizeOverflow => formatter.write_str("3D texture byte count overflows usize"),
Self::PixelLength { expected, actual } => write!(
formatter,
"3D texture needs {expected} bytes, received {actual}"
),
Self::SourceLimit { requested, limit } => write!(
formatter,
"3D texture capacity {requested} exceeds limit {limit}"
),
Self::RegionOutOfBounds => {
formatter.write_str("3D texture patch lies outside source image")
}
Self::InvalidPatchLayout => {
formatter.write_str("3D texture patch stride or byte length is invalid")
}
Self::InvalidTint => formatter.write_str("3D texture tint must be normalized RGBA"),
Self::AllocationFailed { requested_bytes } => {
write!(formatter, "cannot reserve {requested_bytes} texture bytes")
}
Self::IdentityExhausted => {
formatter.write_str("3D texture revision identities exhausted")
}
}
}
}
impl Error for TextureVisualError {}
fn pixel_bytes(width: u32, height: u32) -> Result<usize, TextureVisualError> {
if width == 0 || height == 0 {
return Err(TextureVisualError::InvalidDimensions);
}
(width as usize)
.checked_mul(height as usize)
.and_then(|value| value.checked_mul(4))
.ok_or(TextureVisualError::SizeOverflow)
}
fn check_bytes(requested: usize, limit: usize) -> Result<(), TextureVisualError> {
if requested > limit {
return Err(TextureVisualError::SourceLimit { requested, limit });
}
Ok(())
}
fn issue_revision() -> Result<u64, TextureVisualError> {
NEXT_TEXTURE_REVISION
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
value.checked_add(1)
})
.map_err(|_| TextureVisualError::IdentityExhausted)
}