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
//! Texture resource.

pub use gfx::texture::{FilterMethod, WrapMode};

use amethyst_assets::{Asset, Handle};
use amethyst_core::specs::prelude::DenseVecStorage;

use std::marker::PhantomData;

use error::Result;
use gfx::format::{ChannelType, SurfaceType};
use gfx::texture::{Info, Mipmap, SamplerInfo};
use gfx::traits::Pod;

use formats::TextureData;
use types::{ChannelFormat, Factory, RawShaderResourceView, RawTexture, Sampler, SurfaceFormat};

/// A handle to a `Texture` asset.
pub type TextureHandle = Handle<Texture>;

/// Handle to a GPU texture resource.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Texture {
    sampler: Sampler,
    texture: RawTexture,
    view: RawShaderResourceView,
}

impl Texture {
    /// Builds a new texture with the given raw texture data.
    pub fn from_data<T: Pod + Copy, D: AsRef<[T]>>(data: D) -> TextureBuilder<D, T> {
        TextureBuilder::new(data)
    }

    /// Builds a new texture with the given raw texture data.
    pub fn from_color_val<C: Into<[f32; 4]>>(rgba: C) -> TextureBuilder<[u8; 4], u8> {
        TextureBuilder::from_color_val(rgba)
    }

    /// Returns the sampler for the texture.
    pub fn sampler(&self) -> &Sampler {
        &self.sampler
    }

    /// Returns the texture's raw shader resource view.
    pub fn view(&self) -> &RawShaderResourceView {
        &self.view
    }

    /// Returns the texture's dimensions ``(width, height)``
    pub fn size(&self) -> (usize, usize) {
        let (w, h, _, _) = self.texture.get_info().kind.get_dimensions();
        (w as usize, h as usize)
    }
}

impl Asset for Texture {
    const NAME: &'static str = "renderer::Texture";
    type Data = TextureData;
    type HandleStorage = DenseVecStorage<TextureHandle>;
}

/// Builds new textures.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct TextureBuilder<D, T> {
    data: D,
    info: Info,
    channel_type: ChannelType,
    sampler: SamplerInfo,
    pd: PhantomData<T>,
}

impl TextureBuilder<[u8; 4], u8> {
    /// Creates a new `TextureBuilder` from the given RGBA color value.
    pub fn from_color_val<C: Into<[f32; 4]>>(rgba: C) -> Self {
        let color = rgba.into();
        let data: [u8; 4] = [
            (color[0] * 255.0) as u8,
            (color[1] * 255.0) as u8,
            (color[2] * 255.0) as u8,
            (color[3] * 255.0) as u8,
        ];

        TextureBuilder::new(data)
    }
}

impl<D, T> TextureBuilder<D, T>
where
    D: AsRef<[T]>,
    T: Pod + Copy,
{
    /// Creates a new `TextureBuilder` with the given raw texture data.
    pub fn new(data: D) -> Self {
        use gfx::format::{ChannelTyped, SurfaceTyped};
        use gfx::memory::Bind;
        use gfx::memory::Usage;
        use gfx::texture::{AaMode, Kind};

        TextureBuilder {
            data: data,
            info: Info {
                kind: Kind::D2(1, 1, AaMode::Single),
                levels: 1,
                format: SurfaceFormat::get_surface_type(),
                bind: Bind::SHADER_RESOURCE,
                usage: Usage::Dynamic,
            },
            channel_type: ChannelFormat::get_channel_type(),
            sampler: SamplerInfo::new(FilterMethod::Scale, WrapMode::Clamp),
            pd: PhantomData,
        }
    }

    /// Sets the `SamplerInfo` for the texture
    pub fn with_sampler(mut self, sampler: SamplerInfo) -> Self {
        self.sampler = sampler;
        self
    }

    /// Sets the number of mipmap levels to generate.
    ///
    /// FIXME: Only encoders can generate mipmap levels.
    pub fn mip_levels(mut self, val: u8) -> Self {
        self.info.levels = val;
        self
    }

    /// Sets the texture width and height in pixels.
    pub fn with_size(mut self, w: u16, h: u16) -> Self {
        use gfx::texture::{AaMode, Kind};
        self.info.kind = Kind::D2(w, h, AaMode::Single);
        self
    }

    /// Sets whether the texture is mutable or not.
    pub fn dynamic(mut self, mutable: bool) -> Self {
        use gfx::memory::Usage;
        self.info.usage = if mutable { Usage::Dynamic } else { Usage::Data };
        self
    }

    /// Sets the texture format
    pub fn with_format(mut self, format: SurfaceType) -> Self {
        self.info.format = format;
        self
    }

    /// Sets the texture channel type
    pub fn with_channel_type(mut self, channel_type: ChannelType) -> Self {
        self.channel_type = channel_type;
        self
    }

    /// Builds and returns the new texture.
    pub fn build(self, fac: &mut Factory) -> Result<Texture> {
        use gfx::format::Swizzle;
        use gfx::memory::cast_slice;
        use gfx::texture::ResourceDesc;
        use gfx::Factory;
        use std::mem::size_of;

        // This variable has to live here to make sure the flipped
        // buffer lives long enough. (If one exists)
        let mut v_flip_buffer;
        let mut data = self.data.as_ref();

        if cfg!(feature = "opengl") {
            let pixel_width = (self.info.format.get_total_bits() / 8) as usize / size_of::<T>();
            v_flip_buffer = Vec::with_capacity(data.len());
            let (w, h, _, _) = self.info.kind.get_dimensions();
            let w = w as usize;
            let h = h as usize;
            for y in 0..h {
                for x in 0..(w * pixel_width) {
                    v_flip_buffer.push(data[x + (h - y - 1) * w * pixel_width]);
                    // Uncomment this if you need to debug this.
                    //println!("x: {}, y: {}, w: {}, h: {}, pw: {}", x, y, w, h, pixel_width);
                }
            }
            data = &v_flip_buffer;
        }

        let tex = fac.create_texture_raw(
            self.info,
            Some(self.channel_type),
            Some((&[cast_slice(data)], Mipmap::Provided)),
        )?;

        let desc = ResourceDesc {
            channel: self.channel_type,
            layer: None,
            min: 1,
            max: self.info.levels,
            swizzle: Swizzle::new(),
        };

        let view = fac.view_texture_as_shader_resource_raw(&tex, desc)?;
        let sampler = fac.create_sampler(self.sampler);

        Ok(Texture {
            sampler: sampler,
            texture: tex,
            view: view,
        })
    }
}