Skip to main content

wgame_gfx_texture/
lib.rs

1//! CPU texture atlases, GPU render textures, and shared sampling for wgpu.
2//!
3//! [`Texture`] owns CPU-editable pixels through a [`TextureAtlas`], uploading them
4//! on use. [`RenderTexture`] implements [`wgame_gfx::Target`] and owns a dedicated
5//! GPU allocation; its explicit asynchronous readback produces a detached image.
6//! Both implement [`SampledTexture`], accepted by shapes and normal-map materials.
7//! Neither type changes ownership mode, and no CPU mirror is kept for GPU rendering.
8//!
9//! ```no_run
10//! # async fn preview(graphics: &wgame_gfx::Graphics) -> Result<(), Box<dyn std::error::Error>> {
11//! use wgame_gfx::{Target, types::color};
12//! use wgame_gfx_texture::{SampledTexture, TexturingLibrary, TextureSettings};
13//! let textures = TexturingLibrary::new(graphics);
14//! let mut preview = textures.render_texture((256, 256), TextureSettings::linear())?;
15//! preview.clear(color::BLUE);
16//! // Draw through Target::render, Target::scene, or borrowed viewports as usual.
17//! preview.submit(); // Submit drawing before another target samples it.
18//! let sampled = preview.sample(); // Can outlive the drawing target.
19//! let pixels = preview.readback().await?; // Detached snapshot; no automatic downloads.
20//! let frozen = textures.texture(&pixels, TextureSettings::linear());
21//! # Ok(()) }
22//! ```
23//!
24//! See [`Texture`] for atlas updates/relocation, [`RenderTexture`] for submission
25//! and snapshot contracts, and [`TextureSample`] for retained sampling handles.
26
27#![forbid(unsafe_code)]
28
29mod gpu;
30mod readback;
31mod render_texture;
32mod sampling;
33mod state;
34mod texel;
35mod texture;
36
37use glam::{Affine2, Vec2};
38use half::f16;
39use rgb::Rgba;
40use wgame_gfx::{Graphics, types::Color};
41use wgame_image::{Image, ImageBase, ImageWriteMut};
42
43pub use self::{
44    readback::ReadbackError,
45    render_texture::{RenderTexture, RenderTextureError},
46    sampling::{SampledTexture, TextureAttribute, TextureResource, TextureSample},
47    state::TexturingState,
48    texel::Texel,
49    texture::{FilterMode, Texture, TextureAtlas, TextureSettings},
50};
51
52/// A library for managing textures.
53#[derive(Clone)]
54pub struct TexturingLibrary {
55    state: TexturingState,
56    default_atlas: TextureAtlas,
57}
58
59impl TexturingLibrary {
60    /// Creates a new texture library.
61    pub fn new(state: &Graphics) -> Self {
62        let state = TexturingState::new(state);
63        Self {
64            default_atlas: TextureAtlas::new(
65                &state,
66                Default::default(),
67                wgpu::TextureFormat::Rgba16Float,
68            ),
69            state,
70        }
71    }
72
73    /// Returns the texturing state.
74    pub fn state(&self) -> &TexturingState {
75        &self.state
76    }
77
78    /// Create a GPU render target that implements the same sampling trait as images.
79    pub fn render_texture(
80        &self,
81        size: (u32, u32),
82        settings: TextureSettings,
83    ) -> Result<RenderTexture, RenderTextureError> {
84        RenderTexture::new(&self.state, size, settings)
85    }
86
87    /// Creates a texture from an image.
88    pub fn texture(&self, image: &Image<Rgba<f16>>, settings: TextureSettings) -> Texture {
89        let texture = self.default_atlas.allocate(image.size(), settings);
90        texture.update(|mut dst| dst.copy_from(image));
91        texture
92    }
93
94    /// Creates a 1D gradient texture from an array of colors.
95    pub fn gradient<T: Color, const N: usize>(&self, colors: [T; N]) -> Texture {
96        self.gradient2([colors])
97    }
98
99    /// Creates a 2D gradient texture from a 2D array of colors.
100    pub fn gradient2<T: Color, const M: usize, const N: usize>(
101        &self,
102        colors: [[T; M]; N],
103    ) -> Texture {
104        let colors = colors
105            .into_iter()
106            .flatten()
107            .map(|c| c.to_rgba_f16())
108            .collect::<Vec<_>>();
109        let pix_size = Vec2::new(M as f32, N as f32).recip();
110        self.texture(
111            &Image::with_data((M as u32, N as u32), colors),
112            TextureSettings::linear(),
113        )
114        .transform_coord(Affine2::from_scale_angle_translation(
115            1.0 - pix_size,
116            0.0,
117            0.5 * pix_size,
118        ))
119    }
120}