summaryrefslogtreecommitdiff
path: root/src/texture.rs
diff options
context:
space:
mode:
authorMicha White <botahamec@outlook.com>2022-10-05 11:00:01 -0400
committerMicha White <botahamec@outlook.com>2022-10-05 11:00:01 -0400
commited5b952b313275e58102770e9dda29a7274c363c (patch)
treee4212570a01d3cba217d0dd7bf0328f80c276cfb /src/texture.rs
parent1169cf72ec435a495e1449bdf222bc0ccfd6f62a (diff)
Moved around some logic
Diffstat (limited to 'src/texture.rs')
-rw-r--r--src/texture.rs208
1 files changed, 194 insertions, 14 deletions
diff --git a/src/texture.rs b/src/texture.rs
index f5d1c34..4ba460d 100644
--- a/src/texture.rs
+++ b/src/texture.rs
@@ -1,8 +1,9 @@
use std::error::Error;
+use std::num::NonZeroU32;
use std::sync::atomic::{AtomicUsize, Ordering};
use image::error::DecodingError;
-use image::{DynamicImage, ImageError};
+use image::{DynamicImage, EncodableLayout, GenericImage, ImageError, RgbaImage};
use texture_packer::{
exporter::{ExportResult, ImageExporter},
MultiTexturePacker, TexturePackerConfig,
@@ -60,11 +61,12 @@ impl From<ImageError> for TextureError {
}
// TODO make this Debug
+// TODO make these resizable
pub struct TextureAtlases<'a> {
packer: MultiTexturePacker<'a, image::RgbaImage, TextureId>,
+ images: Vec<RgbaImage>,
width: u32,
height: u32,
- changed: bool,
}
impl<'a> Default for TextureAtlases<'a> {
@@ -86,7 +88,7 @@ impl<'a> TextureAtlases<'a> {
}),
width,
height,
- changed: false,
+ images: Vec::with_capacity(1),
}
}
@@ -101,7 +103,6 @@ impl<'a> TextureAtlases<'a> {
self.packer
.pack_own(id, img)
.map_err(TextureError::TextureTooLarge)?;
- self.changed = true;
Ok(id)
}
@@ -134,15 +135,7 @@ impl<'a> TextureAtlases<'a> {
Some(frame.frame.y)
}
- pub(crate) const fn bytes_per_row(&self) -> u32 {
- self.width * 4
- }
-
- pub(crate) const fn height(&self) -> u32 {
- self.height
- }
-
- pub(crate) const fn extent_3d(&self) -> wgpu::Extent3d {
+ const fn extent_3d(&self) -> wgpu::Extent3d {
wgpu::Extent3d {
width: self.width,
height: self.height,
@@ -150,7 +143,7 @@ impl<'a> TextureAtlases<'a> {
}
}
- pub(crate) fn atlases(&self) -> ExportResult<Box<[DynamicImage]>> {
+ fn atlases(&self) -> ExportResult<Box<[DynamicImage]>> {
self.packer
.get_pages()
.iter()
@@ -158,4 +151,191 @@ impl<'a> TextureAtlases<'a> {
.collect::<ExportResult<Vec<DynamicImage>>>()
.map(Vec::into_boxed_slice)
}
+
+ fn push_image(&mut self) -> &mut RgbaImage {
+ self.images.push(
+ RgbaImage::from_raw(
+ self.width,
+ self.height,
+ vec![0; 4 * self.width as usize * self.height as usize],
+ )
+ .expect("the image was the wrong size"),
+ );
+
+ self.images
+ .last_mut()
+ .expect("we just added an image to the list")
+ }
+
+ fn fill_images(&mut self) -> ExportResult<()> {
+ for (i, atlas) in self.atlases()?.iter().enumerate() {
+ #[allow(clippy::option_if_let_else)]
+ if let Some(image) = self.images.get_mut(i) {
+ image
+ .copy_from(atlas, 0, 0)
+ .expect("atlases shouldn't be too large");
+ } else {
+ let image = self.push_image();
+ image
+ .copy_from(atlas, 0, 0)
+ .expect("atlases shouldn't be too large");
+ }
+ }
+
+ Ok(())
+ }
+
+ fn images(&mut self) -> ExportResult<&[RgbaImage]> {
+ self.fill_images()?;
+ Ok(&self.images)
+ }
+}
+
+pub struct WgpuTextures {
+ atlases: TextureAtlases<'static>,
+ diffuse_texture: wgpu::Texture,
+ diffuse_bind_group: wgpu::BindGroup,
+}
+
+impl WgpuTextures {
+ // TODO this is still too large
+ pub fn new(device: &wgpu::Device, width: u32, height: u32) -> (Self, wgpu::BindGroupLayout) {
+ let atlases = TextureAtlases::new(width, height);
+ let atlas_size = atlases.extent_3d();
+
+ let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Diffuse Texture"),
+ size: atlas_size,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ });
+
+ // TODO I don't think this refreshes anything
+ let diffuse_texture_view =
+ diffuse_texture.create_view(&wgpu::TextureViewDescriptor::default());
+
+ let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor::default());
+
+ let texture_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Texture Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+
+ let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Diffuse Bind Group"),
+ layout: &texture_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
+ },
+ ],
+ });
+
+ (
+ Self {
+ atlases,
+ diffuse_texture,
+ diffuse_bind_group,
+ },
+ texture_bind_group_layout,
+ )
+ }
+
+ /// Loads a texture from memory, in the given file format
+ ///
+ /// # Errors
+ ///
+ /// This returns an error if the texture is not in the given format, or if
+ /// the texture is so large that it cannot fit in the texture atlas.
+ pub fn texture_from_memory(
+ &mut self,
+ texture: &[u8],
+ format: ImageFormat,
+ ) -> Result<TextureId, TextureError> {
+ self.atlases.load_from_memory(texture, format)
+ }
+
+ // TODO try to remove this
+ #[allow(clippy::cast_precision_loss)]
+ pub fn texture_width(&self, id: TextureId) -> Option<f32> {
+ self.atlases
+ .texture_width(id)
+ .map(|u| u as f32 / self.atlases.extent_3d().width as f32)
+ }
+
+ #[allow(clippy::cast_precision_loss)]
+ pub fn texture_height(&self, id: TextureId) -> Option<f32> {
+ self.atlases
+ .texture_height(id)
+ .map(|u| u as f32 / self.atlases.extent_3d().height as f32)
+ }
+
+ #[allow(clippy::cast_precision_loss)]
+ pub fn texture_x(&self, id: TextureId) -> Option<f32> {
+ self.atlases
+ .texture_x(id)
+ .map(|u| u as f32 / self.atlases.extent_3d().width as f32)
+ }
+
+ #[allow(clippy::cast_precision_loss)]
+ pub fn texture_y(&self, id: TextureId) -> Option<f32> {
+ self.atlases
+ .texture_y(id)
+ .map(|u| u as f32 / self.atlases.extent_3d().height as f32)
+ }
+
+ pub const fn bind_group(&self) -> &wgpu::BindGroup {
+ &self.diffuse_bind_group
+ }
+
+ pub fn fill_textures(&mut self, queue: &wgpu::Queue) {
+ let atlas_size = self.atlases.extent_3d();
+
+ // put the packed texture into the base image
+ let Ok(atlases) = self.atlases.images() else { return };
+ let Some(atlas) = atlases.first() else { return };
+
+ // copy that to the gpu
+ queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &self.diffuse_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ atlas.as_bytes(),
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: NonZeroU32::new(atlas_size.width * 4),
+ rows_per_image: NonZeroU32::new(atlas_size.height),
+ },
+ atlas_size,
+ );
+ }
}