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
use std::path::Path;
use glium::{ Texture2d };
use glium::texture::{ RawImage2d, TextureCreationError };
use glium::backend::Facade;
use image::{ self, DynamicImage, RgbaImage };
use texture::{ self, ImageSize, TextureSettings, Rgba8Texture };
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Flip {
None,
Vertical,
}
pub struct Texture(pub Texture2d);
impl Texture {
pub fn new(texture: Texture2d) -> Texture {
Texture(texture)
}
pub fn empty<F>(factory: &mut F) -> Result<Self, TextureCreationError>
where F: Facade
{
Rgba8Texture::create(factory, &[0u8; 4], [1, 1], &TextureSettings::new())
}
pub fn from_path<F, P>(
factory: &mut F,
path: P,
flip: Flip,
settings: &TextureSettings
) -> Result<Self, String>
where F: Facade,
P: AsRef<Path>
{
let img = try!(image::open(path).map_err(|e| e.to_string()));
let img = match img {
DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
};
let img = if flip == Flip::Vertical {
image::imageops::flip_vertical(&img)
} else {
img
};
Texture::from_image(factory, &img, settings).map_err(
|e| format!("{:?}", e))
}
pub fn from_image<F>(
factory: &mut F,
img: &RgbaImage,
settings: &TextureSettings
) -> Result<Self, TextureCreationError>
where F: Facade
{
let (width, height) = img.dimensions();
Rgba8Texture::create(factory, img, [width, height], settings)
}
pub fn from_memory_alpha<F>(
factory: &mut F,
buffer: &[u8],
width: u32,
height: u32,
settings: &TextureSettings
) -> Result<Self, TextureCreationError>
where F: Facade
{
if width == 0 || height == 0 {
return Texture::empty(factory);
}
let size = [width, height];
let buffer = texture::ops::alpha_to_rgba8(buffer, size);
Rgba8Texture::create(factory, &buffer, size, settings)
}
pub fn update<F>(&mut self, factory: &mut F, img: &RgbaImage)
-> Result<(), TextureCreationError>
where F: Facade
{
let (width, height) = img.dimensions();
Rgba8Texture::update(self, factory, img, [width, height])
}
}
impl ImageSize for Texture {
fn get_size(&self) -> (u32, u32) {
let ref tex = self.0;
(tex.get_width(), tex.get_height().unwrap())
}
}
impl<F> Rgba8Texture<F> for Texture
where F: Facade
{
type Error = TextureCreationError;
fn create<S: Into<[u32; 2]>>(
factory: &mut F,
memory: &[u8],
size: S,
_settings: &TextureSettings
) -> Result<Self, Self::Error> {
let size = size.into();
Ok(Texture(try!(Texture2d::new(factory,
RawImage2d::from_raw_rgba_reversed(memory.to_owned(),
(size[0], size[1]))))))
}
#[allow(unused_variables)]
fn update<S: Into<[u32; 2]>>(
&mut self,
factory: &mut F,
memory: &[u8],
size: S
) -> Result<(), Self::Error> {
unimplemented!()
}
}