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
use std::convert::TryFrom;
use crate::context::Context;
use crate::error;
use crate::error::GameResult;
use crate::graphics::shader::BlendMode;
use crate::graphics::types::FilterMode;
use crate::graphics::{self, transform_rect, BackendSpec, DrawParam, Matrix4, Rect, Transform};
use gfx::Factory;
#[derive(Debug, Clone, PartialEq)]
pub struct SpriteBatch {
image: graphics::Image,
sprites: Vec<graphics::DrawParam>,
blend_mode: Option<BlendMode>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SpriteIdx(pub usize);
impl SpriteBatch {
pub fn new(image: graphics::Image) -> Self {
Self {
image,
sprites: vec![],
blend_mode: None,
}
}
pub fn add<P>(&mut self, param: P) -> SpriteIdx
where
P: Into<graphics::DrawParam>,
{
self.sprites.push(param.into());
SpriteIdx(self.sprites.len() - 1)
}
pub fn set<P>(&mut self, handle: SpriteIdx, param: P) -> GameResult
where
P: Into<graphics::DrawParam>,
{
if handle.0 < self.sprites.len() {
self.sprites[handle.0] = param.into();
Ok(())
} else {
Err(error::GameError::RenderError(String::from(
"Provided index is out of bounds.",
)))
}
}
fn flush(&self, ctx: &mut Context, image: &graphics::Image) -> GameResult {
let new_sprites = self
.sprites
.iter()
.map(|param| {
let src_width = param.src.w;
let src_height = param.src.h;
let new_param = match param.trans {
Transform::Values { scale, .. } => {
let new_scale = mint::Vector2 {
x: scale.x * src_width * f32::from(image.width),
y: scale.y * src_height * f32::from(image.height),
};
param.scale(new_scale)
}
Transform::Matrix(_) => *param,
};
let primitive_param = new_param;
primitive_param.to_instance_properties(ctx.gfx_context.is_srgb())
})
.collect::<Vec<_>>();
let gfx = &mut ctx.gfx_context;
if gfx.data.rect_instance_properties.len() < self.sprites.len() {
gfx.data.rect_instance_properties = gfx.factory.create_buffer(
self.sprites.len(),
gfx::buffer::Role::Vertex,
gfx::memory::Usage::Dynamic,
gfx::memory::Bind::TRANSFER_DST,
)?;
}
gfx.encoder
.update_buffer(&gfx.data.rect_instance_properties, &new_sprites[..], 0)?;
Ok(())
}
pub fn clear(&mut self) {
self.sprites.clear();
}
pub fn into_inner(self) -> graphics::Image {
self.image
}
pub fn set_image(&mut self, image: graphics::Image) -> graphics::Image {
use std::mem;
mem::replace(&mut self.image, image)
}
pub fn filter(&self) -> FilterMode {
self.image.filter()
}
pub fn set_filter(&mut self, mode: FilterMode) {
self.image.set_filter(mode);
}
}
impl graphics::Drawable for SpriteBatch {
fn draw(&self, ctx: &mut Context, param: DrawParam) -> GameResult {
let mut new_param = param;
if let Transform::Values { offset, .. } = param.trans {
if offset != [0.0, 0.0].into() {
if let Some(dim) = self.dimensions(ctx) {
let new_offset = mint::Vector2 {
x: offset.x * dim.w + dim.x,
y: offset.y * dim.h + dim.y,
};
new_param = param.offset(new_offset);
}
}
}
self.flush(ctx, &self.image)?;
let gfx = &mut ctx.gfx_context;
let sampler = gfx
.samplers
.get_or_insert(self.image.sampler_info, gfx.factory.as_mut());
gfx.data.vbuf = gfx.quad_vertex_buffer.clone();
let typed_thingy = gfx
.backend_spec
.raw_to_typed_shader_resource(self.image.texture.clone());
gfx.data.tex = (typed_thingy, sampler);
let mut slice = gfx.quad_slice.clone();
slice.instances = Some((u32::try_from(self.sprites.len()).unwrap(), 0));
let m = Matrix4::from(new_param.trans.to_bare_matrix());
gfx.set_global_mvp(m)?;
let previous_mode: Option<BlendMode> = if let Some(mode) = self.blend_mode {
let current_mode = gfx.blend_mode();
if current_mode != mode {
gfx.set_blend_mode(mode)?;
Some(current_mode)
} else {
None
}
} else {
None
};
gfx.draw(Some(&slice))?;
if let Some(mode) = previous_mode {
gfx.set_blend_mode(mode)?;
}
gfx.set_global_mvp(graphics::Matrix4::IDENTITY)?;
Ok(())
}
fn dimensions(&self, _ctx: &mut Context) -> Option<Rect> {
if self.sprites.is_empty() {
return None;
}
let dimensions = self.image.dimensions();
self.sprites
.iter()
.map(|¶m| transform_rect(dimensions, param))
.fold(None, |acc: Option<Rect>, rect| {
Some(if let Some(acc) = acc {
acc.combine_with(rect)
} else {
rect
})
})
}
fn set_blend_mode(&mut self, mode: Option<BlendMode>) {
self.blend_mode = mode;
}
fn blend_mode(&self) -> Option<BlendMode> {
self.blend_mode
}
}