1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
//! Items related to the inter-operation of the `image` crate (images on disk and in RAM) and //! textures from the wgpu crate (images in GPU memory). use crate::wgpu; use std::path::Path; /// The set of pixel types from the image crate that can be loaded directly into a texture. /// /// The `Rgba8` and `Bgra8` color types are assumed to be non-linear sRGB. /// /// Note that wgpu only supports texture formats whose size are a power of 2. If you notice a /// `image::Pixel` type that does not implement `Pixel`, this is likely why. pub trait Pixel: image::Pixel { /// The wgpu texture format of the pixel type. const TEXTURE_FORMAT: wgpu::TextureFormat; } /// A wrapper around a wgpu buffer that contains an image of a known size and `image::ColorType`. #[derive(Debug)] pub struct BufferImage { color_type: image::ColorType, size: [u32; 2], buffer: wgpu::BufferBytes, } /// A wrapper around a slice of bytes representing an image. /// /// An `ImageReadMapping` may only be created by reading from a `BufferImage` returned by a /// `Texture::to_image` call. pub struct ImageReadMapping { color_type: image::ColorType, size: [u32; 2], mapping: wgpu::BufferReadMapping, } impl wgpu::TextureBuilder { /// The minimum required texture usage when loading from an image. pub const REQUIRED_IMAGE_TEXTURE_USAGE: wgpu::TextureUsage = wgpu::TextureUsage::COPY_DST; /// Produce a texture descriptor from an image. /// /// Specifically, this supports any image type implementing `image::GenericImageView` whose /// `Pixel` type implements `Pixel`. /// /// By default, the produced builder will have the `wgpu::TextureUsage` returned by /// `wgpu::TextureBuilder::default_image_texture_usage()`. This is a general-purpose usage that /// should allow for copying to and from the texture, sampling the texture and rendering to the /// texture. Specifying only the texture usage required may result in better performance. It /// may be necessary to manually specify the the usage if `STORAGE` is required. pub fn from_image_view<T>(image_view: &T) -> Self where T: image::GenericImageView, T::Pixel: Pixel, { builder_from_image_view(image_view) } /// The default texture usage for the case where a user has loaded a texture from an image. pub fn default_image_texture_usage() -> wgpu::TextureUsage { wgpu::TextureUsage::COPY_SRC | wgpu::TextureUsage::COPY_DST | wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::OUTPUT_ATTACHMENT } } /// Types that may provide access to a `wgpu::Device` and an associated `wgpu::Queue` for loading /// a texture from an image. /// /// Notably, implementations exist for `&App`, `&Window`, `&wgpu::DeviceQueuePair` and `(&Device, /// &Queue)`. pub trait WithDeviceQueuePair { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O; } impl wgpu::Texture { /// Load an image from the given path and upload it as a texture. /// /// The device and queue `src` can be either the `App`, a `Window`, a `wgpu::DeviceQueuePair` /// or a tuple `(&wgpu::Device, &mut wgpu::Queue)`. Access to a `Device` is necessary in order /// to create the texture and buffer GPU resources, and access to a `Queue` is necessary for /// submitting the commands responsible for copying the buffer contents to the texture. Note /// that a texture may only be used with the device with which it was created. This is worth /// keeping in mind if you have more than one window and they do not share the same device. /// /// By default, the texture will have the `COPY_SRC`, `COPY_DST`, `SAMPLED` and /// `OUTPUT_ATTACHMENT` usages enabled. If you wish to specify the usage yourself, see the /// `load_from_path` constructor. /// /// If the `&App` is passed as the `src`, the window returned via `app.main_window()` will be /// used as the source of the device and queue. pub fn from_path<'a, T, P>(src: T, path: P) -> image::ImageResult<Self> where T: WithDeviceQueuePair, P: AsRef<Path>, { let path = path.as_ref(); let usage = wgpu::TextureBuilder::default_image_texture_usage(); src.with_device_queue_pair(|device, queue| { wgpu::Texture::load_from_path(device, queue, usage, path) }) } /// Load a texture from the given image. /// /// The device and queue `src` can be either the `App`, a `Window`, a `wgpu::DeviceQueuePair` /// or a tuple `(&wgpu::Device, &mut wgpu::Queue)`. Access to a `Device` is necessary in order /// to create the texture and buffer GPU resources, and access to a `Queue` is necessary for /// submitting the commands responsible for copying the buffer contents to the texture. Note /// that a texture may only be used with the device with which it was created. This is worth /// keeping in mind if you have more than one window and they do not share the same device. /// /// By default, the texture will have the `COPY_SRC`, `COPY_DST`, `SAMPLED` and /// `OUTPUT_ATTACHMENT` usages enabled. If you wish to specify the usage yourself, see the /// `load_from_path` constructor. /// /// If the `&App` is passed as the `src`, the window returned via `app.main_window()` will be /// used as the source of the device and queue. /// /// The `DeviceQueuePairSource` can be either the `App`, a `Window`, a `DeviceQueuePair` or a /// tuple `(&Device, &Queue)`. pub fn from_image<'a, T>(src: T, image: &image::DynamicImage) -> Self where T: WithDeviceQueuePair, { let usage = wgpu::TextureBuilder::default_image_texture_usage(); src.with_device_queue_pair(|device, queue| { wgpu::Texture::load_from_image(device, queue, usage, image) }) } /// Read an image file from the given path and load it directly into a texture. /// /// This is short-hand for calling `image::open` and then `Texture::load_from_image`. pub fn load_from_path<P>( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, path: P, ) -> image::ImageResult<Self> where P: AsRef<Path>, { let path = path.as_ref(); let image = image::open(path)?; Ok(Self::load_from_image(device, queue, usage, &image)) } /// Load a texture directly from a dynamic image. /// /// If the image is already in a format supported by wgpu, no conversions are performed and the /// image is loaded directly as-is with a texture format that matches the original image color /// type. /// /// If the image is of an unsupported format, it will be converted to the closest supported format /// before being uploaded. pub fn load_from_image( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, image: &image::DynamicImage, ) -> Self { load_texture_from_image(device, queue, usage, image) } /// Load a texture directly from an image buffer using the given device queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. pub fn load_from_image_buffer<P, Container>( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, buffer: &image::ImageBuffer<P, Container>, ) -> Self where P: 'static + Pixel, Container: std::ops::Deref<Target = [P::Subpixel]>, { load_texture_from_image_buffer(device, queue, usage, buffer) } /// Load a texture array directly from a sequence of image buffers. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. /// /// Returns `None` if there are no images in the given sequence. pub fn load_array_from_image_buffers<'a, I, P, Container>( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, buffers: I, ) -> Option<Self> where I: IntoIterator<Item = &'a image::ImageBuffer<P, Container>>, I::IntoIter: ExactSizeIterator, P: 'static + Pixel, Container: 'a + std::ops::Deref<Target = [P::Subpixel]>, { load_texture_array_from_image_buffers(device, queue, usage, buffers) } /// Encode the necessary commands to load a texture directly from a dynamic image. /// /// If the image is already in a format supported by wgpu, no conversions are performed and the /// image is loaded directly as-is with a texture format that matches the original image color /// type. /// /// If the image is of an unsupported format, it will be converted to the closest supported format /// before being uploaded. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command buffer /// submitted to the given `device`'s queue. pub fn encode_load_from_image( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, image: &image::DynamicImage, ) -> Self { encode_load_texture_from_image(device, encoder, usage, image) } /// Encode the necessary commands to load a texture from the given image buffer. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command /// buffer submitted to the given `device`'s queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. pub fn encode_load_from_image_buffer<P, Container>( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, buffer: &image::ImageBuffer<P, Container>, ) -> Self where P: 'static + Pixel, Container: std::ops::Deref<Target = [P::Subpixel]>, { encode_load_texture_from_image_buffer(device, encoder, usage, buffer) } /// Encode the necessary commands to load a texture array directly from a sequence of image /// buffers. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command buffer /// submitted to the given `device`'s queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. /// /// Returns `None` if there are no images in the given sequence. pub fn encode_load_array_from_image_buffers<'a, I, P, Container>( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, buffers: I, ) -> Option<Self> where I: IntoIterator<Item = &'a image::ImageBuffer<P, Container>>, I::IntoIter: ExactSizeIterator, P: 'static + Pixel, Container: 'a + std::ops::Deref<Target = [P::Subpixel]>, { encode_load_texture_array_from_image_buffers(device, encoder, usage, buffers) } /// Write the contents of the texture into a new image buffer. /// /// Commands will be added to the given encoder to copy the entire contents of the texture into /// the buffer. /// /// Returns a buffer from which the image can be read asynchronously via `read`. /// /// Returns `None` if there is no directly compatible `image::ColorType` for the texture's format. /// /// NOTE: `read` should not be called on the returned buffer until the encoded commands have /// been submitted to the device queue. pub fn to_image( &self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, ) -> Option<BufferImage> { let color_type = image_color_type_from_format(self.format())?; let size = self.size(); let buffer = self.to_buffer_bytes(device, encoder); Some(BufferImage { color_type, size, buffer, }) } } impl BufferImage { /// The dimensions of the image stored within the buffer. pub fn size(&self) -> [u32; 2] { self.size } /// The color type of the image stored within the buffer. pub fn color_type(&self) -> image::ColorType { self.color_type } /// Asynchronously maps the buffer of bytes from GPU to host memory and, once mapped, calls the /// given user callback with the data represented as an `ImageReadMapping`. /// /// Note: The given callback will not be called until the memory is mapped and the device is /// polled. You should not rely on the callback being called immediately. pub async fn read(&self) -> Result<ImageReadMapping, wgpu::BufferAsyncErr> { let size = self.size; let color_type = self.color_type; let mapping = self.buffer.read().await?; Ok(ImageReadMapping { color_type, size, mapping, }) } } impl ImageReadMapping { /// Produce the color type of an image, compatible with the `image` crate. pub fn color_type(&self) -> image::ColorType { self.color_type } /// The dimensions of the image. pub fn size(&self) -> [u32; 2] { self.size } /// The raw image data as a slice of bytes. pub fn mapping(&self) -> &wgpu::BufferReadMapping { &self.mapping } /// Saves the buffer to a file at the specified path. /// /// The image format is derived from the file extension. pub fn save(&self, path: &Path) -> image::ImageResult<()> { let [width, height] = self.size(); let data = self.mapping.as_slice(); image::save_buffer(path, data, width, height, self.color_type) } /// Saves the buffer to a file at the specified path. pub fn save_with_format( &self, path: &Path, format: image::ImageFormat, ) -> image::ImageResult<()> { let [width, height] = self.size(); image::save_buffer_with_format( path, self.mapping.as_slice(), width, height, self.color_type, format, ) } } impl Pixel for image::Bgra<u8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb; } impl Pixel for image::Luma<u8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm; } impl Pixel for image::Luma<i8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Snorm; } impl Pixel for image::Luma<u16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Uint; } impl Pixel for image::Luma<i16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Sint; } impl Pixel for image::LumaA<u8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg8Unorm; } impl Pixel for image::LumaA<i8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg8Snorm; } impl Pixel for image::LumaA<u16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Uint; } impl Pixel for image::LumaA<i16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Sint; } impl Pixel for image::Rgba<u8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; } impl Pixel for image::Rgba<i8> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Snorm; } impl Pixel for image::Rgba<u16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Uint; } impl Pixel for image::Rgba<i16> { const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Sint; } impl<'a> WithDeviceQueuePair for (&'a wgpu::Device, &'a wgpu::Queue) { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O, { let (device, queue) = self; f(device, queue) } } impl<'a> WithDeviceQueuePair for &'a wgpu::DeviceQueuePair { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O, { let device = self.device(); let queue = self.queue(); f(&*device, &*queue) } } impl<'a> WithDeviceQueuePair for &'a crate::window::Window { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O, { self.swap_chain_device_queue_pair() .with_device_queue_pair(f) } } impl<'a> WithDeviceQueuePair for &'a crate::app::App { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O, { self.main_window().with_device_queue_pair(f) } } impl<'a, 'b> WithDeviceQueuePair for &'a std::cell::Ref<'b, crate::window::Window> { fn with_device_queue_pair<F, O>(self, f: F) -> O where F: FnOnce(&wgpu::Device, &wgpu::Queue) -> O, { (**self).with_device_queue_pair(f) } } /// Convert the given color type from the `image` crate to the corresponding wgpu texture format. /// /// Returns `None` if there is no directly compatible texture format - this is normally the case if /// the `ColorType` would have a bits_per_pixel that is not equal to a power of 2. /// /// The `Rgba8` and `Bgra8` color types are assumed to be non-linear sRGB. pub fn format_from_image_color_type(color_type: image::ColorType) -> Option<wgpu::TextureFormat> { let format = match color_type { image::ColorType::L8 => wgpu::TextureFormat::R8Unorm, image::ColorType::La8 => wgpu::TextureFormat::Rg8Unorm, image::ColorType::Rgba8 => wgpu::TextureFormat::Rgba8UnormSrgb, image::ColorType::L16 => wgpu::TextureFormat::R16Uint, image::ColorType::La16 => wgpu::TextureFormat::Rg16Uint, image::ColorType::Rgba16 => wgpu::TextureFormat::Rgba16Uint, image::ColorType::Bgra8 => wgpu::TextureFormat::Bgra8UnormSrgb, _ => return None, }; Some(format) } /// Convert the given texture format to the corresponding color type from the `image` crate. /// /// Returns `None` if there is no directly compatible color type. /// /// The `Rgba8` and `Bgra8` color types are assumed to be non-linear sRGB. pub fn image_color_type_from_format(format: wgpu::TextureFormat) -> Option<image::ColorType> { let color_type = match format { // TODO: Should we add branches for other same-size formats? e.g. R8Snorm, R8Uint, etc? wgpu::TextureFormat::R8Unorm => image::ColorType::L8, wgpu::TextureFormat::Rg8Unorm => image::ColorType::La8, wgpu::TextureFormat::Rgba8UnormSrgb => image::ColorType::Rgba8, wgpu::TextureFormat::R16Uint => image::ColorType::L16, wgpu::TextureFormat::Rg16Uint => image::ColorType::La16, wgpu::TextureFormat::Rgba16Uint => image::ColorType::Rgba16, wgpu::TextureFormat::Bgra8UnormSrgb => image::ColorType::Bgra8, _ => return None, }; Some(color_type) } /// Produce a texture descriptor from any type implementing `image::GenericImageView` whose `Pixel` /// type implements `Pixel`. /// /// By default, the produced builder will have the `wgpu::TextureUsage` returned by /// `wgpu::TextureBuilder::default_image_texture_usage()`. This is a general-purpose usage that /// should allow for copying to and from the texture, sampling the texture and rendering to the /// texture. Specifying only the texture usage required may result in better performance. It /// may be necessary to manually specify the the usage if `STORAGE` is required. pub fn builder_from_image_view<T>(image: &T) -> wgpu::TextureBuilder where T: image::GenericImageView, T::Pixel: Pixel, { let (width, height) = image.dimensions(); let format = <T::Pixel as Pixel>::TEXTURE_FORMAT; wgpu::TextureBuilder::new() .size([width, height]) .format(format) .usage(wgpu::TextureBuilder::default_image_texture_usage()) } /// Load a texture directly from a dynamic image. /// /// If the image is already in a format supported by wgpu, no conversions are performed and the /// image is loaded directly as-is with a texture format that matches the original image color /// type. /// /// If the image is of an unsupported format, it will be converted to the closest supported format /// before being uploaded. pub fn load_texture_from_image( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, image: &image::DynamicImage, ) -> wgpu::Texture { let cmd_encoder_desc = wgpu::CommandEncoderDescriptor { label: Some("nannou_texture_from_image"), }; let mut encoder = device.create_command_encoder(&cmd_encoder_desc); let texture = encode_load_texture_from_image(device, &mut encoder, usage, image); queue.submit(&[encoder.finish()]); texture } /// Load a texture directly from an image buffer using the given device queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. pub fn load_texture_from_image_buffer<P, Container>( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, buffer: &image::ImageBuffer<P, Container>, ) -> wgpu::Texture where P: 'static + Pixel, Container: std::ops::Deref<Target = [P::Subpixel]>, { let cmd_encoder_desc = wgpu::CommandEncoderDescriptor { label: Some("nannou_texture_from_image_buffer"), }; let mut encoder = device.create_command_encoder(&cmd_encoder_desc); let texture = encode_load_texture_from_image_buffer(device, &mut encoder, usage, buffer); queue.submit(&[encoder.finish()]); texture } /// Load a texture array directly from a sequence of image buffers. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. /// /// Returns `None` if there are no images in the given sequence. pub fn load_texture_array_from_image_buffers<'a, I, P, Container>( device: &wgpu::Device, queue: &wgpu::Queue, usage: wgpu::TextureUsage, buffers: I, ) -> Option<wgpu::Texture> where I: IntoIterator<Item = &'a image::ImageBuffer<P, Container>>, I::IntoIter: ExactSizeIterator, P: 'static + Pixel, Container: 'a + std::ops::Deref<Target = [P::Subpixel]>, { let cmd_encoder_desc = wgpu::CommandEncoderDescriptor { label: Some("nannou_load_texture_array_from_image_buffers"), }; let mut encoder = device.create_command_encoder(&cmd_encoder_desc); let texture = encode_load_texture_array_from_image_buffers(device, &mut encoder, usage, buffers); queue.submit(&[encoder.finish()]); texture } /// Encode the necessary commands to load a texture directly from a dynamic image. /// /// If the image is already in a format supported by wgpu, no conversions are performed and the /// image is loaded directly as-is with a texture format that matches the original image color /// type. /// /// If the image is of an unsupported format, it will be converted to the closest supported format /// before being uploaded. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command buffer /// submitted to the given `device`'s queue. pub fn encode_load_texture_from_image( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, image: &image::DynamicImage, ) -> wgpu::Texture { use image::DynamicImage::*; match image { ImageLuma8(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageLumaA8(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageRgba8(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageBgra8(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageLuma16(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageLumaA16(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageRgba16(img) => encode_load_texture_from_image_buffer(device, encoder, usage, img), ImageRgb8(_img) => { let img = image.to_rgba(); encode_load_texture_from_image_buffer(device, encoder, usage, &img) } ImageBgr8(_img) => { let img = image.to_bgra(); encode_load_texture_from_image_buffer(device, encoder, usage, &img) } ImageRgb16(_img) => { // TODO: I think we lose some quality here - e.g. 16-bit channels down to 8-bit??. let img = image.to_rgba(); encode_load_texture_from_image_buffer(device, encoder, usage, &img) } } } /// Encode the necessary commands to load a texture directly from an image buffer. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command buffer /// submitted to the given `device`'s queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. pub fn encode_load_texture_from_image_buffer<P, Container>( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, buffer: &image::ImageBuffer<P, Container>, ) -> wgpu::Texture where P: 'static + Pixel, Container: std::ops::Deref<Target = [P::Subpixel]>, { // Create the texture. let texture = wgpu::TextureBuilder::from_image_view(buffer) .usage(wgpu::TextureBuilder::REQUIRED_IMAGE_TEXTURE_USAGE | usage) .build(device); // Upload the pixel data. let subpixel_data: &[P::Subpixel] = std::ops::Deref::deref(buffer); // TODO: // This can theoretically be exploited by implementing `image::Primitive` for some type that // has padding. Instead, should make some `Subpixel` trait that we can control and is only // guaranteed to be implemented for safe types. let subpixel_bytes = unsafe { wgpu::bytes::from_slice(subpixel_data) }; let buffer = device.create_buffer_with_data(subpixel_bytes, wgpu::BufferUsage::COPY_SRC); // Submit command for copying pixel data to the texture. let buffer_copy_view = texture.default_buffer_copy_view(&buffer); let texture_copy_view = texture.default_copy_view(); let extent = texture.extent(); encoder.copy_buffer_to_texture(buffer_copy_view, texture_copy_view, extent); texture } /// Encode the necessary commands to load a texture array directly from a sequence of image /// buffers. /// /// NOTE: The returned texture will remain empty until the given `encoder` has its command buffer /// submitted to the given `device`'s queue. /// /// No format or size conversions are performed - the given buffer is loaded directly into GPU /// memory. /// /// Pixel type compatibility is ensured via the `Pixel` trait. /// /// Returns `None` if there are no images in the given sequence. pub fn encode_load_texture_array_from_image_buffers<'a, I, P, Container>( device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, usage: wgpu::TextureUsage, buffers: I, ) -> Option<wgpu::Texture> where I: IntoIterator<Item = &'a image::ImageBuffer<P, Container>>, I::IntoIter: ExactSizeIterator, P: 'static + Pixel, Container: 'a + std::ops::Deref<Target = [P::Subpixel]>, { let mut buffers = buffers.into_iter(); let array_layers = buffers.len() as u32; let first_buffer = buffers.next()?; // Build the texture ready to receive the data. let texture = wgpu::TextureBuilder::from_image_view(first_buffer) .array_layer_count(array_layers) .usage(wgpu::TextureBuilder::REQUIRED_IMAGE_TEXTURE_USAGE | usage) .build(device); // Copy each buffer to the texture, one layer at a time. for (layer, buffer) in Some(first_buffer).into_iter().chain(buffers).enumerate() { // Upload the pixel data. let subpixel_data: &[P::Subpixel] = std::ops::Deref::deref(buffer); // TODO: // This can theoretically be exploited by implementing `image::Primitive` for some type // that has padding. Instead, should make some `Subpixel` trait that we can control and is // only guaranteed to be implemented for safe types. let subpixel_bytes = unsafe { wgpu::bytes::from_slice(subpixel_data) }; let buffer = device.create_buffer_with_data(subpixel_bytes, wgpu::BufferUsage::COPY_SRC); // Submit command for copying pixel data to the texture. let buffer_copy_view = texture.default_buffer_copy_view(&buffer); let mut texture_copy_view = texture.default_copy_view(); texture_copy_view.array_layer = layer as u32; let extent = texture.extent(); encoder.copy_buffer_to_texture(buffer_copy_view, texture_copy_view, extent); } Some(texture) }