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
use std::fmt;
use std::path;
use std::collections::BTreeMap;
use std::io::Read;
use sdl2::pixels;
use sdl2::render;
use sdl2::surface;
use sdl2::image::ImageRWops;
use rusttype;
use context::Context;
use GameError;
use GameResult;
use util;
pub use sdl2::rect::Rect;
pub use sdl2::rect::Point;
pub use sdl2::pixels::Color;
pub use sdl2::render::BlendMode;
#[derive(Debug)]
pub enum DrawMode {
Line,
Fill,
}
#[derive(Debug)]
pub struct GraphicsContext {
background: pixels::Color,
foreground: pixels::Color,
}
impl GraphicsContext {
pub fn new() -> GraphicsContext {
GraphicsContext {
background: pixels::Color::RGB(0u8, 0u8, 255u8),
foreground: pixels::Color::RGB(255, 255, 255),
}
}
}
impl Default for GraphicsContext {
fn default() -> Self {
Self::new()
}
}
pub fn set_background_color(ctx: &mut Context, color: Color) {
ctx.gfx_context.background = color;
}
pub fn set_color(ctx: &mut Context, color: Color) {
let r = &mut ctx.renderer;
ctx.gfx_context.foreground = color;
r.set_draw_color(ctx.gfx_context.foreground);
}
pub fn clear(ctx: &mut Context) {
let r = &mut ctx.renderer;
r.set_draw_color(ctx.gfx_context.background);
r.clear();
r.set_draw_color(ctx.gfx_context.foreground);
}
pub fn draw(ctx: &mut Context,
drawable: &mut Drawable,
src: Option<Rect>,
dst: Option<Rect>)
-> GameResult<()> {
drawable.draw(ctx, src, dst)
}
pub fn draw_ex(ctx: &mut Context,
drawable: &mut Drawable,
src: Option<Rect>,
dst: Option<Rect>,
angle: f64,
center: Option<Point>,
flip_horizontal: bool,
flip_vertical: bool)
-> GameResult<()> {
drawable.draw_ex(ctx, src, dst, angle, center, flip_horizontal, flip_vertical)
}
pub fn present(ctx: &mut Context) {
let r = &mut ctx.renderer;
r.present()
}
pub fn print(_ctx: &mut Context) {
unimplemented!();
}
pub fn printf(_ctx: &mut Context) {
unimplemented!();
}
pub fn rectangle(ctx: &mut Context, mode: DrawMode, rect: Rect) -> GameResult<()> {
let r = &mut ctx.renderer;
match mode {
DrawMode::Line => {
let res = r.draw_rect(rect);
res.map_err(GameError::from)
}
DrawMode::Fill => {
let res = r.fill_rect(rect);
res.map_err(GameError::from)
}
}
}
pub fn rectangles(ctx: &mut Context, mode: DrawMode, rect: &[Rect]) -> GameResult<()> {
let r = &mut ctx.renderer;
match mode {
DrawMode::Line => {
let res = r.draw_rects(rect);
res.map_err(GameError::from)
}
DrawMode::Fill => {
let res = r.fill_rects(rect);
res.map_err(GameError::from)
}
}
}
pub fn line(ctx: &mut Context, start: Point, end: Point) -> GameResult<()> {
let r = &mut ctx.renderer;
let res = r.draw_line(start, end);
res.map_err(GameError::from)
}
pub fn lines(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let r = &mut ctx.renderer;
let res = r.draw_lines(points);
res.map_err(GameError::from)
}
pub fn point(ctx: &mut Context, point: Point) -> GameResult<()> {
let r = &mut ctx.renderer;
let res = r.draw_point(point);
res.map_err(GameError::from)
}
pub fn points(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let r = &mut ctx.renderer;
let res = r.draw_points(points);
res.map_err(GameError::from)
}
pub trait Drawable {
fn draw_ex(&mut self,
context: &mut Context,
src: Option<Rect>,
dst: Option<Rect>,
angle: f64,
center: Option<Point>,
flip_horizontal: bool,
flip_vertical: bool)
-> GameResult<()>;
fn draw(&mut self,
context: &mut Context,
src: Option<Rect>,
dst: Option<Rect>)
-> GameResult<()> {
self.draw_ex(context, src, dst, 0.0, None, false, false)
}
}
pub struct Image {
texture: render::Texture,
texture_query: render::TextureQuery,
}
impl Image {
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Image> {
let mut buffer: Vec<u8> = Vec::new();
let rwops = try!(util::rwops_from_path(context, path.as_ref(), &mut buffer));
let surf = try!(rwops.load());
let renderer = &context.renderer;
let tex = try!(renderer.create_texture_from_surface(surf));
let tq = tex.query();
Ok(Image {
texture: tex,
texture_query: tq,
})
}
pub fn solid(context: &mut Context, size: u32, color: Color) -> GameResult<Image> {
let mut surf = try!(surface::Surface::new(size, size, pixels::PixelFormatEnum::RGBA8888));
try!(surf.fill_rect(None, color));
Image::from_surface(context, surf)
}
fn from_surface(context: &Context, surface: surface::Surface) -> GameResult<Image> {
let renderer = &context.renderer;
let tex = try!(renderer.create_texture_from_surface(surface));
let tq = tex.query();
Ok(Image {
texture: tex,
texture_query: tq,
})
}
pub fn rect(&self) -> Rect {
Rect::new(0, 0, self.width(), self.height())
}
pub fn blend_mode(&self) -> BlendMode {
self.texture.blend_mode()
}
pub fn set_blend_mode(&mut self, blend: BlendMode) {
self.texture.set_blend_mode(blend)
}
pub fn color_mod(&self) -> Color {
let (r, g, b) = self.texture.color_mod();
pixels::Color::RGB(r, g, b)
}
pub fn set_color_mod(&mut self, color: Color) {
match color {
pixels::Color::RGB(r, g, b) |
pixels::Color::RGBA(r, g, b, _) => self.texture.set_color_mod(r, g, b),
}
}
pub fn alpha_mod(&self) -> u8 {
self.texture.alpha_mod()
}
pub fn set_alpha_mod(&mut self, alpha: u8) {
self.texture.set_alpha_mod(alpha)
}
pub fn width(&self) -> u32 {
self.texture_query.width
}
pub fn height(&self) -> u32 {
self.texture_query.height
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"<Image: {}x{}, {:p}, texture address {:p}>",
self.width(),
self.height(),
self,
&self.texture)
}
}
impl Drawable for Image {
fn draw_ex(&mut self,
context: &mut Context,
src: Option<Rect>,
dst: Option<Rect>,
angle: f64,
center: Option<Point>,
flip_horizontal: bool,
flip_vertical: bool)
-> GameResult<()> {
let renderer = &mut context.renderer;
renderer.copy_ex(&self.texture,
src,
dst,
angle,
center,
flip_horizontal,
flip_vertical)
.map_err(GameError::RenderError)
}
}
pub enum Font {
TTFFont {
font: rusttype::Font<'static>,
points: u32,
},
BitmapFont {
surface: surface::Surface<'static>,
glyphs: BTreeMap<char, u32>,
glyph_width: u32,
},
}
impl Font {
pub fn new<P>(context: &mut Context, path: P, size: u32) -> GameResult<Font>
where P: AsRef<path::Path> + fmt::Debug
{
let mut stream = try!(context.filesystem.open(path.as_ref()));
let mut buf = Vec::new();
try!(stream.read_to_end(&mut buf));
let name = format!("{:?}", path);
Font::font_from_bytes(&name, buf, size)
}
fn font_from_bytes<B>(name: &str, bytes: B, size: u32) -> GameResult<Font>
where B: Into<rusttype::SharedBytes<'static>>
{
let collection = rusttype::FontCollection::from_bytes(bytes);
let font_err = GameError::ResourceLoadError(format!("Could not load font collection for \
font {:?}",
name));
let font = collection.into_font().ok_or(font_err)?;
Ok(Font::TTFFont {
font: font,
points: size,
})
}
pub fn new_bitmap<P: AsRef<path::Path>>(context: &mut Context,
path: P,
glyphs: &str)
-> GameResult<Font> {
let s2 = try!(util::load_surface(context, path.as_ref()));
let image_width = s2.width();
let glyph_width = image_width / (glyphs.len() as u32);
let mut glyphs_map: BTreeMap<char, u32> = BTreeMap::new();
for (i, c) in glyphs.chars().enumerate() {
let small_i = i as u32;
glyphs_map.insert(c, small_i * glyph_width);
}
Ok(Font::BitmapFont {
surface: s2,
glyphs: glyphs_map,
glyph_width: glyph_width,
})
}
pub fn default_font() -> GameResult<Self> {
let size = 16;
let buf = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/DejaVuSerif.ttf"));
Font::font_from_bytes("default", &buf[..], size)
}
}
impl fmt::Debug for Font {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Font::TTFFont { .. } => write!(f, "<TTFFont: {:p}>", &self),
Font::BitmapFont { .. } => write!(f, "<BitmapFont: {:p}>", &self),
}
}
}
pub struct Text {
texture: render::Texture,
texture_query: render::TextureQuery,
contents: String,
}
fn display_independent_scale(points: u32, dpi_w: f32, dpi_h: f32) -> rusttype::Scale {
let points = points as f32;
let points_per_inch = 72.0;
let pixels_per_point_w = dpi_w * (1.0 / points_per_inch);
let pixels_per_point_h = dpi_h * (1.0 / points_per_inch);
let scale = rusttype::Scale {
x: pixels_per_point_w * points,
y: pixels_per_point_h * points,
};
scale
}
fn render_ttf(context: &Context,
text: &str,
font: &rusttype::Font<'static>,
size: u32)
-> GameResult<Text> {
let (_diag_dpi, x_dpi, y_dpi) = context.dpi;
let scale = display_independent_scale(size, x_dpi, y_dpi);
let pixel_height = scale.y.ceil() as usize;
let v_metrics = font.v_metrics(scale);
let offset = rusttype::point(0.0, v_metrics.ascent);
let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect();
let width = glyphs.iter()
.rev()
.filter_map(|g| {
g.pixel_bounding_box()
.map(|b| b.min.x as f32 + g.unpositioned().h_metrics().advance_width)
})
.next()
.unwrap_or(0.0)
.ceil() as usize;
let bytes_per_pixel = 4;
let mut pixel_data = vec![0; width * pixel_height * bytes_per_pixel];
let pitch = width * bytes_per_pixel;
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
if x >= 0 && x < width as i32 && y >= 0 && y < pixel_height as i32 {
let x = x as usize * bytes_per_pixel;
let y = y as usize;
pixel_data[(x + y * pitch + 0)] = c;
pixel_data[(x + y * pitch + 1)] = c;
pixel_data[(x + y * pitch + 2)] = c;
pixel_data[(x + y * pitch + 3)] = c;
}
})
}
}
let format = pixels::PixelFormatEnum::RGBA8888;
let surface = try!(surface::Surface::from_data(&mut pixel_data,
width as u32,
pixel_height as u32,
pitch as u32,
format));
let image = try!(Image::from_surface(context, surface));
let text_string = text.to_string();
let tq = image.texture.query();
Ok(Text {
texture: image.texture,
texture_query: tq,
contents: text_string,
})
}
fn render_bitmap(context: &Context,
text: &str,
surface: &surface::Surface,
glyphs_map: &BTreeMap<char, u32>,
glyph_width: u32)
-> GameResult<Text> {
let text_length = text.len() as u32;
let glyph_height = surface.height();
let format = pixels::PixelFormatEnum::RGBA8888;
let mut dest_surface =
try!(surface::Surface::new(text_length * glyph_width, glyph_height, format));
for (i, c) in text.chars().enumerate() {
let small_i = i as u32;
let error_message = format!("Character '{}' not in bitmap font!", c);
let source_offset = try!(glyphs_map.get(&c)
.ok_or(GameError::FontError(String::from(error_message))));
let dest_offset = glyph_width * small_i;
let source_rect = Rect::new(*source_offset as i32, 0, glyph_width, glyph_height);
let dest_rect = Rect::new(dest_offset as i32, 0, glyph_width, glyph_height);
try!(surface.blit(Some(source_rect), &mut dest_surface, Some(dest_rect)));
}
let image = try!(Image::from_surface(context, dest_surface));
let text_string = text.to_string();
let tq = image.texture.query();
Ok(Text {
texture: image.texture,
texture_query: tq,
contents: text_string,
})
}
impl Text {
pub fn new(context: &Context, text: &str, font: &Font) -> GameResult<Text> {
match *font {
Font::TTFFont { font: ref f, points } => render_ttf(context, text, f, points),
Font::BitmapFont { ref surface, glyph_width, glyphs: ref glyphs_map, .. } => {
render_bitmap(context, text, surface, glyphs_map, glyph_width)
}
}
}
pub fn width(&self) -> u32 {
self.texture_query.width
}
pub fn height(&self) -> u32 {
self.texture_query.height
}
pub fn contents(&self) -> &str {
&self.contents
}
pub fn set_color_mod(&mut self, color: Color) {
match color {
pixels::Color::RGB(r, g, b) |
pixels::Color::RGBA(r, g, b, _) => self.texture.set_color_mod(r, g, b),
}
}
pub fn set_alpha_mod(&mut self, alpha: u8) {
self.texture.set_alpha_mod(alpha)
}
}
impl Drawable for Text {
fn draw_ex(&mut self,
context: &mut Context,
src: Option<Rect>,
dst: Option<Rect>,
angle: f64,
center: Option<Point>,
flip_horizontal: bool,
flip_vertical: bool)
-> GameResult<()> {
let renderer = &mut context.renderer;
renderer.copy_ex(&self.texture,
src,
dst,
angle,
center,
flip_horizontal,
flip_vertical)
.map_err(GameError::RenderError)
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let tq = self.texture.query();
write!(f,
"<Text: {}x{}, {:p}, texture address {:p}>",
tq.width,
tq.height,
&self,
&self.texture)
}
}