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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use std::fmt;
use std::path;
use std::convert::From;
use std::collections::HashMap;
use std::io::Read;
use std::u16;
use sdl2;
use image;
use gfx;
use gfx::texture;
use gfx::traits::Device;
use gfx::traits::FactoryExt;
use gfx_device_gl;
use gfx_window_sdl;
use gfx::Factory;
use context::Context;
use GameError;
use GameResult;
mod tessellation;
mod text;
mod types;
pub use self::text::*;
pub use self::types::*;
const GL_MAJOR_VERSION: u8 = 3;
const GL_MINOR_VERSION: u8 = 2;
const QUAD_VERTS: [Vertex; 4] = [Vertex {
pos: [-0.5, -0.5],
uv: [0.0, 0.0],
},
Vertex {
pos: [0.5, -0.5],
uv: [1.0, 0.0],
},
Vertex {
pos: [0.5, 0.5],
uv: [1.0, 1.0],
},
Vertex {
pos: [-0.5, 0.5],
uv: [0.0, 1.0],
}];
const QUAD_INDICES: [u16; 6] = [0, 1, 2, 0, 2, 3];
type ColorFormat = gfx::format::Srgba8;
type DepthFormat = gfx::format::DepthStencil;
gfx_defines!{
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
}
constant Globals {
transform: [[f32; 4];4] = "u_Transform",
color: [f32; 4] = "u_Color",
}
constant RectProperties {
src: [f32; 4] = "u_Src",
dest: [f32; 2] = "u_Dest",
scale: [f32;2] = "u_Scale",
offset: [f32;2] = "u_Offset",
shear: [f32;2] = "u_Shear",
rotation: f32 = "u_Rotation",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
tex: gfx::TextureSampler<[f32; 4]> = "t_Texture",
globals: gfx::ConstantBuffer<Globals> = "Globals",
rect_properties: gfx::ConstantBuffer<RectProperties> = "RectProperties",
out: gfx::BlendTarget<ColorFormat> =
("Target0", gfx::state::MASK_ALL, gfx::preset::blend::ALPHA),
}
}
impl Default for RectProperties {
fn default() -> Self {
RectProperties {
src: [0.0, 0.0, 1.0, 1.0],
dest: [0.0, 0.0],
scale: [1.0, 1.0],
offset: [0.0, 0.0],
shear: [0.0, 0.0],
rotation: 0.0,
}
}
}
impl From<DrawParam> for RectProperties {
fn from(p: DrawParam) -> Self {
RectProperties {
src: p.src.into(),
dest: p.dest.into(),
scale: [p.scale.x, p.scale.y],
offset: p.offset.into(),
shear: p.shear.into(),
rotation: p.rotation,
}
}
}
struct SamplerCache<R>
where R: gfx::Resources
{
samplers: HashMap<texture::SamplerInfo, gfx::handle::Sampler<R>>,
}
impl<R> SamplerCache<R>
where R: gfx::Resources
{
fn new() -> Self {
SamplerCache { samplers: HashMap::new() }
}
fn get_or_insert<F>(&mut self,
info: texture::SamplerInfo,
factory: &mut F)
-> gfx::handle::Sampler<R>
where F: gfx::Factory<R>
{
let sampler = self.samplers
.entry(info)
.or_insert_with(|| factory.create_sampler(info));
sampler.clone()
}
}
pub struct GraphicsContextGeneric<R, F, C, D>
where R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>
{
background_color: Color,
shader_globals: Globals,
white_image: Image,
line_width: f32,
point_size: f32,
screen_rect: Rect,
dpi: (f32, f32, f32),
window: sdl2::video::Window,
#[allow(dead_code)]
gl_context: sdl2::video::GLContext,
device: Box<D>,
factory: Box<F>,
encoder: gfx::Encoder<R, C>,
#[allow(dead_code)]
depth_view: gfx::handle::DepthStencilView<R, gfx::format::DepthStencil>,
pso: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
quad_slice: gfx::Slice<R>,
quad_vertex_buffer: gfx::handle::Buffer<R, Vertex>,
default_sampler_info: texture::SamplerInfo,
samplers: SamplerCache<R>,
}
impl<R, F, C, D> fmt::Debug for GraphicsContextGeneric<R, F, C, D>
where R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "<GraphicsContext: {:p}>", self)
}
}
pub type GraphicsContext = GraphicsContextGeneric<gfx_device_gl::Resources,
gfx_device_gl::Factory,
gfx_device_gl::CommandBuffer,
gfx_device_gl::Device>;
#[allow(unused)]
fn test_opengl_versions(video: &sdl2::VideoSubsystem) {
let mut major_versions = [4u8, 3u8, 2u8, 1u8];
let minor_versions = [5u8, 4u8, 3u8, 2u8, 1u8, 0u8];
major_versions.reverse();
for major in &major_versions {
for minor in &minor_versions {
let gl = video.gl_attr();
gl.set_context_version(*major, *minor);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
print!("Requesting GL {}.{}... ", major, minor);
let window_builder = video.window("so full of hate", 640, 480);
let result = gfx_window_sdl::init::<ColorFormat, DepthFormat>(window_builder);
match result {
Ok(_) => {
println!("Ok, got GL {}.{}.",
gl.context_major_version(),
gl.context_minor_version())
}
Err(res) => println!("Request failed: {:?}", res),
}
}
}
}
impl GraphicsContext {
pub fn new(video: sdl2::VideoSubsystem,
window_title: &str,
screen_width: u32,
screen_height: u32,
vsync: bool)
-> GameResult<GraphicsContext> {
let gl = video.gl_attr();
gl.set_context_version(GL_MAJOR_VERSION, GL_MINOR_VERSION);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
let window_builder = video.window(window_title, screen_width, screen_height);
let (window, gl_context, device, mut factory, color_view, depth_view) =
gfx_window_sdl::init(window_builder)?;
let vsync_int = if vsync { 1 } else { 0 };
video.gl_set_swap_interval(vsync_int);
let display_index = window.display_index()?;
let dpi = window.subsystem().display_dpi(display_index)?;
let encoder: gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> =
factory.create_command_buffer().into();
let pso = factory
.create_pipeline_simple(include_bytes!("shader/basic_150.glslv"),
include_bytes!("shader/basic_150.glslf"),
pipe::new())?;
let (quad_vertex_buffer, quad_slice) =
factory.create_vertex_buffer_with_slice(&QUAD_VERTS, &QUAD_INDICES[..]);
let rect_props = factory.create_constant_buffer(1);
let globals_buffer = factory.create_constant_buffer(1);
let mut samplers: SamplerCache<gfx_device_gl::Resources> = SamplerCache::new();
let sampler_info = texture::SamplerInfo::new(texture::FilterMethod::Bilinear,
texture::WrapMode::Clamp);
let sampler = samplers.get_or_insert(sampler_info, &mut factory);
let white_image =
Image::make_raw(&mut factory, &sampler_info, 1, 1, &[255, 255, 255, 255])?;
let texture = white_image.texture.clone();
let data = pipe::Data {
vbuf: quad_vertex_buffer.clone(),
tex: (texture, sampler),
rect_properties: rect_props,
globals: globals_buffer,
out: color_view,
};
let left = 0.0;
let right = screen_width as f32;
let top = 0.0;
let bottom = screen_height as f32;
let globals = Globals {
transform: ortho(left, right, top, bottom, 1.0, -1.0),
color: types::WHITE.into(),
};
let mut gfx = GraphicsContext {
background_color: Color::new(0.1, 0.2, 0.3, 1.0),
shader_globals: globals,
line_width: 1.0,
point_size: 1.0,
white_image: white_image,
screen_rect: Rect::new(left, bottom, (right - left), (top - bottom)),
dpi: dpi,
window: window,
gl_context: gl_context,
device: Box::new(device),
factory: Box::new(factory),
encoder: encoder,
depth_view: depth_view,
pso: pso,
data: data,
quad_slice: quad_slice,
quad_vertex_buffer: quad_vertex_buffer,
default_sampler_info: sampler_info,
samplers: samplers,
};
gfx.update_globals()?;
Ok(gfx)
}
fn update_globals(&mut self) -> GameResult<()> {
self.encoder
.update_buffer(&self.data.globals, &[self.shader_globals], 0)?;
Ok(())
}
fn update_rect_properties(&mut self, draw_params: DrawParam) -> GameResult<()> {
let properties = draw_params.into();
self.encoder
.update_buffer(&self.data.rect_properties, &[properties], 0)?;
Ok(())
}
pub fn get_window(&mut self) -> &mut sdl2::video::Window {
&mut self.window
}
pub fn get_factory(&mut self) -> &mut gfx_device_gl::Factory {
&mut self.factory
}
pub fn get_device(&mut self) -> &mut gfx_device_gl::Device {
self.device.as_mut()
}
pub fn get_encoder(&mut self) -> &mut gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> {
&mut self.encoder
}
pub fn get_depth_view(&self) -> gfx::handle::DepthStencilView<gfx_device_gl::Resources, gfx::format::DepthStencil> {
self.depth_view.clone()
}
pub fn get_color_view(&self) -> gfx::handle::RenderTargetView<gfx_device_gl::Resources, (gfx::format::R8_G8_B8_A8, gfx::format::Srgb)> {
self.data.out.clone()
}
}
fn ortho(left: f32, right: f32, top: f32, bottom: f32, far: f32, near: f32) -> [[f32; 4]; 4] {
let c0r0 = 2.0 / (right - left);
let c0r1 = 0.0;
let c0r2 = 0.0;
let c0r3 = 0.0;
let c1r0 = 0.0;
let c1r1 = 2.0 / (top - bottom);
let c1r2 = 0.0;
let c1r3 = 0.0;
let c2r0 = 0.0;
let c2r1 = 0.0;
let c2r2 = -2.0 / (far - near);
let c2r3 = 0.0;
let c3r0 = -(right + left) / (right - left);
let c3r1 = -(top + bottom) / (top - bottom);
let c3r2 = -(far + near) / (far - near);
let c3r3 = 1.0;
[[c0r0, c1r0, c2r0, c3r0],
[c0r1, c1r1, c2r1, c3r1],
[c0r2, c1r2, c2r2, c3r2],
[c0r3, c1r3, c2r3, c3r3]]
}
pub fn clear(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
gfx.encoder
.clear(&gfx.data.out, gfx.background_color.into());
}
pub fn draw(ctx: &mut Context, drawable: &Drawable, dest: Point, rotation: f32) -> GameResult<()> {
drawable.draw(ctx, dest, rotation)
}
pub fn draw_ex(ctx: &mut Context, drawable: &Drawable, params: DrawParam) -> GameResult<()> {
drawable.draw_ex(ctx, params)
}
pub fn present(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
gfx.encoder.flush(&mut *gfx.device);
gfx.window.gl_swap_window();
gfx.device.cleanup();
}
pub fn circle(ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
segments: u32)
-> GameResult<()> {
let m = Mesh::new_circle(ctx, mode, point, radius, segments)?;
m.draw(ctx, Point::default(), 0.0)
}
pub fn ellipse(ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
segments: u32)
-> GameResult<()> {
let m = Mesh::new_ellipse(ctx, mode, point, radius1, radius2, segments)?;
m.draw(ctx, Point::default(), 0.0)
}
pub fn line(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_line(ctx, points, w)?;
m.draw(ctx, Point::default(), 0.0)
}
pub fn points(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let size = ctx.gfx_context.point_size;
for p in points {
let r = Rect::new(p.x, p.y, size, size);
rectangle(ctx, DrawMode::Fill, r)?;
}
Ok(())
}
pub fn polygon(ctx: &mut Context, mode: DrawMode, vertices: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_polygon(ctx, mode, vertices, w)?;
m.draw(ctx, Point::default(), 0.0)
}
pub fn rectangle(ctx: &mut Context, mode: DrawMode, rect: Rect) -> GameResult<()> {
let x = rect.x;
let y = rect.y;
let w = rect.w;
let h = rect.h;
let x1 = x - (w / 2.0);
let x2 = x + (w / 2.0);
let y1 = y - (h / 2.0);
let y2 = y + (h / 2.0);
let pts = [[x1, y1].into(),
[x2, y1].into(),
[x2, y2].into(),
[x1, y2].into()];
polygon(ctx, mode, &pts)
}
pub fn get_background_color(ctx: &Context) -> Color {
ctx.gfx_context.background_color
}
pub fn get_color(ctx: &Context) -> Color {
ctx.gfx_context.shader_globals.color.into()
}
pub fn get_default_filter(ctx: &Context) -> FilterMode {
let gfx = &ctx.gfx_context;
gfx.default_sampler_info.filter.into()
}
pub fn get_line_width(ctx: &Context) -> f32 {
ctx.gfx_context.line_width
}
pub fn get_point_size(ctx: &Context) -> f32 {
ctx.gfx_context.point_size
}
pub fn get_renderer_info(ctx: &Context) -> GameResult<String> {
let video = ctx.sdl_context.video()?;
let gl = video.gl_attr();
Ok(format!("Requested GL {}.{} Core profile, actually got GL {}.{} {:?} profile.",
GL_MAJOR_VERSION,
GL_MINOR_VERSION,
gl.context_major_version(),
gl.context_minor_version(),
gl.context_profile()))
}
pub fn get_screen_coordinates(ctx: &Context) -> Rect {
ctx.gfx_context.screen_rect
}
pub fn set_background_color(ctx: &mut Context, color: Color) {
ctx.gfx_context.background_color = color;
}
pub fn set_color(ctx: &mut Context, color: Color) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.shader_globals.color = color.into();
gfx.update_globals()
}
pub fn set_default_filter(ctx: &mut Context, mode: FilterMode) {
let gfx = &mut ctx.gfx_context;
let new_mode = mode.into();
let sampler_info = texture::SamplerInfo::new(new_mode, texture::WrapMode::Clamp);
let _sampler = gfx.samplers.get_or_insert(sampler_info, &mut *gfx.factory);
gfx.default_sampler_info = sampler_info;
}
pub fn set_line_width(ctx: &mut Context, width: f32) {
ctx.gfx_context.line_width = width;
}
pub fn set_point_size(ctx: &mut Context, size: f32) {
ctx.gfx_context.point_size = size;
}
pub fn set_screen_coordinates(context: &mut Context,
left: f32,
right: f32,
top: f32,
bottom: f32)
-> GameResult<()> {
let gfx = &mut context.gfx_context;
gfx.screen_rect = Rect::new(left, bottom, (right - left), (top - bottom));
gfx.shader_globals.transform = ortho(left, right, top, bottom, 1.0, -1.0);
gfx.update_globals()
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct DrawParam {
pub src: Rect,
pub dest: Point,
pub rotation: f32,
pub scale: Point,
pub offset: Point,
pub shear: Point,
}
impl Default for DrawParam {
fn default() -> Self {
DrawParam {
src: Rect::one(),
dest: Point::zero(),
rotation: 0.0,
scale: Point::new(1.0, 1.0),
offset: Point::new(0.0, 0.0),
shear: Point::new(0.0, 0.0),
}
}
}
pub trait Drawable {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()>;
fn draw(&self, ctx: &mut Context, dest: Point, rotation: f32) -> GameResult<()> {
self.draw_ex(ctx,
DrawParam {
dest: dest,
rotation: rotation,
..Default::default()
})
}
}
#[derive(Clone)]
pub struct ImageGeneric<R>
where R: gfx::Resources
{
texture: gfx::handle::ShaderResourceView<R, [f32; 4]>,
sampler_info: gfx::texture::SamplerInfo,
width: u32,
height: u32,
}
pub type Image = ImageGeneric<gfx_device_gl::Resources>;
fn scale_rgba_up_to_power_of_2(width: u16, height: u16, rgba: &[u8]) -> (u16, u16, Vec<u8>) {
let width = width as usize;
let height = height as usize;
let w2 = width.next_power_of_two();
let h2 = height.next_power_of_two();
let num_vals = w2 * h2 * 4;
let mut v: Vec<u8> = Vec::with_capacity(num_vals);
v.resize(num_vals, 0);
for i in 0..h2 {
if i < height {
let src_start = i * width * 4;
let src_end = src_start + width * 4;
let dest_start = i * w2 * 4;
let dest_end = dest_start + width * 4;
let slice = &mut v[dest_start..dest_end];
slice.copy_from_slice(&rgba[src_start..src_end]);
}
}
(w2 as u16, h2 as u16, v)
}
impl Image {
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Image> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (width, height) = img.dimensions();
Image::from_rgba8(context, width as u16, height as u16, &img)
}
pub fn from_rgba8(context: &mut Context,
width: u16,
height: u16,
rgba: &[u8])
-> GameResult<Image> {
Image::make_raw(&mut context.gfx_context.factory,
&context.gfx_context.default_sampler_info,
width,
height,
rgba)
}
fn make_raw(factory: &mut gfx_device_gl::Factory,
sampler_info: &texture::SamplerInfo,
width: u16,
height: u16,
rgba: &[u8])
-> GameResult<Image> {
let view = if false {
let (width, height, rgba) = scale_rgba_up_to_power_of_2(width, height, rgba);
let rgba = &rgba;
assert_eq!((width as usize) * (height as usize) * 4, rgba.len());
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
} else {
if width == 0 || height == 0 {
let msg = format!("Tried to create a texture of size {}x{}, each dimension must be >0", width, height);
return Err(GameError::ResourceLoadError(msg));
}
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
};
Ok(Image {
texture: view,
sampler_info: *sampler_info,
width: width as u32,
height: height as u32,
})
}
pub fn solid(context: &mut Context, size: u16, color: Color) -> GameResult<Image> {
let pixel_array: [u8; 4] = color.into();
let size_squared = size as usize * size as usize;
let mut buffer = Vec::with_capacity(size_squared);
for _i in 0..size_squared {
buffer.extend(&pixel_array[..]);
}
Image::from_rgba8(context, size, size, &buffer)
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn get_filter(&self) -> FilterMode {
self.sampler_info.filter.into()
}
pub fn set_filter(&mut self, mode: FilterMode) {
self.sampler_info.filter = mode.into();
}
pub fn get_dimensions(&self) -> Rect {
Rect::new(0.0, 0.0, self.width() as f32, self.height() as f32)
}
pub fn get_wrap(&self) -> (WrapMode, WrapMode) {
(self.sampler_info.wrap_mode.0, self.sampler_info.wrap_mode.1)
}
pub fn set_wrap(&mut self, wrap_x: WrapMode, wrap_y: WrapMode) {
self.sampler_info.wrap_mode.0 = wrap_x;
self.sampler_info.wrap_mode.1 = wrap_y;
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"<Image: {}x{}, {:p}, texture address {:p}, sampler: {:?}>",
self.width(),
self.height(),
self,
&self.texture,
&self.sampler_info)
}
}
impl Drawable for Image {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
let src_width = param.src.w;
let src_height = param.src.h;
let invert_y = if gfx.screen_rect.h < 0.0 { 1.0 } else { -1.0 };
let real_scale = Point {
x: src_width * param.scale.x * self.width as f32,
y: src_height * param.scale.y * self.height as f32 * invert_y,
};
let mut new_param = param;
new_param.scale = real_scale;
new_param.offset.x *= -1.0 * param.scale.x;
new_param.offset.y *= param.scale.y;
gfx.update_rect_properties(new_param)?;
let sampler = gfx.samplers
.get_or_insert(self.sampler_info, gfx.factory.as_mut());
gfx.data.vbuf = gfx.quad_vertex_buffer.clone();
gfx.data.tex = (self.texture.clone(), sampler);
gfx.encoder.draw(&gfx.quad_slice, &gfx.pso, &gfx.data);
Ok(())
}
}
pub struct Mesh {
buffer: gfx::handle::Buffer<gfx_device_gl::Resources, Vertex>,
slice: gfx::Slice<gfx_device_gl::Resources>,
}
impl Mesh {
fn from_tessellation(ctx: &mut Context, buffer: tessellation::Buffer) -> GameResult<Mesh> {
let (vbuf, slice) =
ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&buffer.vertices[..], &buffer.indices[..]);
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
pub fn new_line(ctx: &mut Context, points: &[Point], width: f32) -> GameResult<Mesh> {
Mesh::from_tessellation(ctx, tessellation::build_line(points, width)?)
}
pub fn new_circle(ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
segments: u32)
-> GameResult<Mesh> {
let buf = match mode {
DrawMode::Fill => tessellation::build_ellipse_fill(point, radius, radius, segments),
DrawMode::Line => unimplemented!(),
}?;
Mesh::from_tessellation(ctx, buf)
}
pub fn new_ellipse(ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
segments: u32)
-> GameResult<Mesh> {
let buf = match mode {
DrawMode::Fill => tessellation::build_ellipse_fill(point, radius1, radius2, segments),
DrawMode::Line => unimplemented!(),
}?;
Mesh::from_tessellation(ctx, buf)
}
pub fn new_polygon(ctx: &mut Context,
mode: DrawMode,
points: &[Point],
width: f32)
-> GameResult<Mesh> {
let buf = match mode {
DrawMode::Fill => tessellation::build_polygon_fill(points),
DrawMode::Line => tessellation::build_polygon(points, width),
}?;
Mesh::from_tessellation(ctx, buf)
}
pub fn from_triangles(ctx: &mut Context, triangles: &[Point]) -> GameResult<Mesh> {
let points: Vec<Vertex> = triangles.into_iter()
.map(|p| Vertex{
pos: (*p).into(),
uv: (*p).into(),
}).collect();
let (vbuf, slice) =
ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&points[..], ());
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
}
impl Drawable for Mesh {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.update_rect_properties(param)?;
gfx.data.vbuf = self.buffer.clone();
gfx.data.tex.0 = gfx.white_image.texture.clone();
gfx.encoder.draw(&self.slice, &gfx.pso, &gfx.data);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_scaling_up() {
let mut from: Vec<u8> = Vec::new();
const WIDTH: u16 = 5;
const HEIGHT: u16 = 11;
for i in 0..HEIGHT {
let v = vec![i as u8;WIDTH as usize * 4];
from.extend(v.iter());
}
assert_eq!(from.len(), WIDTH as usize * HEIGHT as usize * 4);
let (width, height, res) = scale_rgba_up_to_power_of_2(WIDTH, HEIGHT, &from);
assert_eq!(width, WIDTH.next_power_of_two());
assert_eq!(height, HEIGHT.next_power_of_two());
for i in 0..HEIGHT.next_power_of_two() {
for j in 0..WIDTH.next_power_of_two() {
let offset_within_row = (j * 4) as usize;
let src_row_offset = (i * WIDTH * 4) as usize;
let dst_row_offset = (i * width * 4) as usize;
println!("{} {}", i, j);
if i < HEIGHT && j < WIDTH {
assert_eq!(res[dst_row_offset + offset_within_row],
from[src_row_offset + offset_within_row]);
} else {
assert_eq!(res[dst_row_offset + offset_within_row], 0);
}
}
}
}
}