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
use std::str;
use owning_ref;
use Matrix4;
use gl;
use glium;
use glium::backend::Facade;
use glium::{glutin, Surface, GlObject};
use glium::glutin::GlContext;
use {GLmatStruct, FBtexs, Screen, DFBFDVertex};
use ScreenType;
use errors::ProcessingErr;
#[cfg(target_os = "macos")]
use mac_priority;
impl<'a> Screen<'a> {
/// Create a new Screen struct with a given width and height. Also, specify if
/// the Screen should be fullscreen, if it should preserve aspect ratio on wide
/// monitors, and if it should be synchronize to the refresh rate of the monitor
/// (this should always be true, except in rare circumstances when you need really
/// high draw rates, such as when doing intense raymarching in a fragment shader).
///
/// It is necessary to call this function before everything else. It's what gets
/// the whole show going. Once you have a Screen, you can then create shapes,
/// load textures, draw, check for user input, etc.
///
/// Screen setup tries to choose a number of glutin and glium defaults that will
/// satisfy most users, especially those that want speed but still have a
/// visually pleasing display of shapes with good color fidelity, if possible.
pub fn new(
width: u32,
height: u32,
fullscreen: bool,
preserve_aspect_ratio: bool,
vsync: bool,
) -> Result<Screen<'a>, ProcessingErr> {
#[cfg(target_os = "macos")] mac_priority();
let mut w = width;
let mut h = height;
let events_loop = glutin::EventsLoop::new();
let window;
if fullscreen {
let m = events_loop.get_primary_monitor();
let wh = m.get_dimensions();
w = wh.0;
h = wh.1;
window = glutin::WindowBuilder::new()
.with_title("Processing-rs")
.with_visibility(true)
.with_fullscreen(Some(m))
.with_decorations(false)
.with_dimensions(w, h);
} else {
window = glutin::WindowBuilder::new()
.with_title("Processing-rs")
.with_visibility(true)
.with_dimensions(w, h);
}
let context = glutin::ContextBuilder::new()
.with_vsync(vsync)
//.with_pixel_format(30, 2)
//.with_depth_buffer(32)
.with_gl_profile(glutin::GlProfile::Core)
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 3)));
let display = glium::Display::new(window, context, &events_loop).map_err(|e| ProcessingErr::DisplayNoCreate(e))?;
// Load the OpenGL function pointers
// TODO: `as *const _` will not be needed once glutin is updated to the latest gl version
gl::load_with(|symbol| {
(*display.gl_window()).get_proc_address(symbol) as *const _
});
let mut glsl_version;
{
let glt = display.get_context().get_opengl_version();
glsl_version = format!("{}{:0<2}", glt.1, glt.2).to_owned();
println!("OpenGL version {}", glsl_version);
}
// if frame_rate == 0 {
// glfw.window_hint(glfw::WindowHint::RefreshRate(Some(60)));
// } else if frame_rate == -1 {
// let system determine frame rate
// } else {
// glfw.window_hint(glfw::WindowHint::RefreshRate(
// Some(frame_rate as u32),
// ));
// }
display.gl_window().show();
display.gl_window().set_inner_size(w, h);
if let Some(fb) = display.gl_window().get_inner_size_pixels() {
w = fb.0;
h = fb.1;
}
let aspect_ratio = w as f32 / h as f32;
let fb_size = vec![w, h];
unsafe {
gl::Viewport(
0,
0,
fb_size[0] as gl::types::GLsizei,
fb_size[1] as gl::types::GLsizei,
);
}
let fbtexture = glium::texture::Texture2d::empty_with_format(
&display,
glium::texture::UncompressedFloatFormat::F32F32F32F32,
glium::texture::MipmapsOption::NoMipmap,
w,
h,
).map_err(|e| ProcessingErr::TextureNoCreate(e))?;
let fbid = fbtexture.get_id();
let depthtexture = glium::texture::DepthTexture2d::empty_with_format(
&display,
glium::texture::DepthFormat::F32,
glium::texture::MipmapsOption::NoMipmap,
w,
h,
).map_err(|e| ProcessingErr::TextureNoCreate(e))?;
let oh = owning_ref::OwningHandle::new_with_fn(
Box::new(FBtexs {
fbtex: fbtexture,
depthtexture: depthtexture,
}),
|v| unsafe {
Box::new(
glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(
&display,
&(*v).fbtex,
&(*v).depthtexture,
).expect("Could not create a SimpleFrameBuffer with attached DepthBuffer. Please check your graphics card, drivers, and OS."),
)
},
);
let fbtexture = unsafe {
glium::texture::Texture2d::from_id(
&display,
glium::texture::UncompressedFloatFormat::F32F32F32F32,
fbid,
true,
glium::texture::MipmapsOption::NoMipmap,
glium::texture::Dimensions::Texture2d {
width: w,
height: h,
},
)
};
let draw_params = glium::draw_parameters::DrawParameters {
point_size: Some(2f32),
line_width: Some(2f32),
depth: glium::Depth {
write: true,
test: glium::DepthTest::Overwrite,
..Default::default()
},
blend: glium::Blend {
color: glium::BlendingFunction::Addition {
source: glium::LinearBlendingFactor::SourceAlpha,
destination: glium::LinearBlendingFactor::OneMinusSourceAlpha,
},
alpha: glium::BlendingFunction::Addition {
source: glium::LinearBlendingFactor::One,
destination: glium::LinearBlendingFactor::One,
},
constant_value: (1.0, 1.0, 1.0, 1.0),
},
multisampling: false,
// smooth: Some(glium::draw_parameters::Smooth::Nicest),
smooth: None,
..Default::default()
};
display.gl_window().set_cursor(
glium::glutin::MouseCursor::Default,
);
// if !fonts_initialized {
// setupFontCharacters()
// }
// fonts_initialized = true
// glCheckError("Screen initilization.");
// by default, use system fonts that are known to basically always be available
let mut font_face = "".to_owned();
if cfg!(target_os = "windows") {
font_face = "C:/Windows/Fonts/arial.ttf".to_owned();
} else if cfg!(target_os = "linux") {
font_face = "/usr/share/fonts/ttf-dejavu-ib/DejaVuSansMono.ttf".to_owned();
} else if cfg!(target_os = "macos") {
font_face = "/Users/rje/Library/Fonts/Go-Regular.ttf".to_owned();
}
let shader_bank = init_shaders(&display, &glsl_version)?;
let vertex1 = DFBFDVertex {
position: [-1.0, -1.0],
texcoord: [0.0, 0.0],
};
let vertex2 = DFBFDVertex {
position: [1.0, -1.0],
texcoord: [1.0, 0.0],
};
let vertex3 = DFBFDVertex {
position: [1.0, 1.0],
texcoord: [1.0, 1.0],
};
let vertex4 = DFBFDVertex {
position: [-1.0, 1.0],
texcoord: [0.0, 1.0],
};
let shape = vec![vertex1, vertex2, vertex3, vertex4];
let fb_shape_buffer = glium::VertexBuffer::new(&display, &shape)
.map_err(|e| ProcessingErr::VBNoCreate(e))?;
let fb_index_buffer = glium::IndexBuffer::new(
&display,
glium::index::PrimitiveType::TrianglesList,
&[0u16, 1, 2, 0, 2, 3],
).map_err(|e| ProcessingErr::IBNoCreate(e))?;
Ok(Screen {
// start with default identity matrix, as expected.
matrices: GLmatStruct {
curr_matrix: Matrix4::new(
1.0f32,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
),
matrix_stack: vec![
Matrix4::new(
1.0f32,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0
);
1
],
},
fbo: oh,
fbtexture: fbtexture,
fb_shape_buffer: fb_shape_buffer,
fb_index_buffer: fb_index_buffer,
display: ScreenType::Window(display),
events_loop: events_loop,
draw_params: draw_params,
bg_col: vec![0.8f32, 0.8, 0.8, 0.8],
fill_stuff: true,
fill_col: vec![1.0f32, 1.0, 1.0, 1.0],
stroke_stuff: true,
stroke_col: vec![0.0f32, 0.0, 0.0, 1.0],
tint_stuff: false,
tint_col: vec![1.0f32, 1.0, 1.0, 1.0],
shader_bank: shader_bank,
draw_texture: false,
aspect_ratio: aspect_ratio,
preserve_aspect_ratio: preserve_aspect_ratio,
fb_size: fb_size,
stroke_weight: 1.0,
font_face: font_face,
text_size: 0.4,
height: height,
width: width,
left: -1f32,
right: 1f32,
top: 1f32,
bottom: -1f32,
c_mode: "RGB".to_owned(),
title: "processing-rs".to_owned(),
ellipse_mode: "CENTER".to_owned(),
rect_mode: "CORNER".to_owned(),
shape_mode: "CORNER".to_owned(),
image_mode: "CORNER".to_owned(),
frame_rate: 60,
frame_count: 0,
fonts_initialized: false,
curr_shader: 0,
curr_cursor: glium::glutin::MouseCursor::Default,
wrap: glium::uniforms::SamplerWrapFunction::Repeat,
curr_texture: None,
alternate_shader: 1 << 20,
using_alternate_shader: false,
glsl_version: glsl_version,
drew_points: false,
keypressed: None,
mousepressed: None,
mousereleased: None,
mousepos: (-100., -100.),
headless: false,
})
}
/// This creates a "headless" rendering screen. It's basically the same as a screen
/// except that you won't see a window. This is useful when you need to quickly
/// render some kind of image, but you don't want to user to see all of the
/// drawing that leads up to the final image. In other words, you could draw in the
/// headless window, save the result, and load it as a texture to be displayed in
/// a main display window. One circumstance where I used this was to have a GLSL
/// fragment shader pathtrace a scene and then have the result displayed in another
/// window. For various reasons, I couldn't have users see the scene being
/// progressively created, so the "headless" rendering screen effectively hid it.
///
/// This takes width and height as parameters, as well as whether or not aspect
/// ratio should be preserved. Fullscreen makes no sense for a "headless"
/// rendering window, and neither does frame synchronization, since it never
/// displays anything on the monitor. Otherwise, you should also see the
/// documentation for the main Screen struct.
pub fn new_headless(
width: u32,
height: u32,
//fullscreen: bool,
preserve_aspect_ratio: bool,
//vsync: bool,
) -> Result<Screen<'a>, ProcessingErr> {
#[cfg(target_os = "macos")] mac_priority();
let w = width;
let h = height;
let events_loop = glutin::EventsLoop::new();
let context = glutin::HeadlessRendererBuilder::new(w, h).build().map_err(|e| ProcessingErr::HeadlessRendererNoBuild(e))?;
unsafe { context.make_current().map_err(|e| ProcessingErr::HeadlessContextError(e))? };
// Load the OpenGL function pointers
// TODO: `as *const _` will not be needed once glutin is updated to the latest gl version
gl::load_with(|symbol| context.get_proc_address(symbol) as *const _);
let display = glium::HeadlessRenderer::new(context).map_err(|e| ProcessingErr::HeadlessNoCreate(e))?;
let mut glsl_version;
{
let glt = display.get_context().get_opengl_version();
glsl_version = format!("{}{:0<2}", glt.1, glt.2).to_owned();
println!("OpenGL version {}", glsl_version);
}
// if frame_rate == 0 {
// glfw.window_hint(glfw::WindowHint::RefreshRate(Some(60)));
// } else if frame_rate == -1 {
// let system determine frame rate
// } else {
// glfw.window_hint(glfw::WindowHint::RefreshRate(
// Some(frame_rate as u32),
// ));
// }
let (w, h) = display.get_framebuffer_dimensions();
let aspect_ratio = w as f32 / h as f32;
let fb_size = vec![w, h];
unsafe {
gl::Viewport(
0,
0,
fb_size[0] as gl::types::GLsizei,
fb_size[1] as gl::types::GLsizei,
);
}
let fbtexture = glium::texture::Texture2d::empty_with_format(
&display,
glium::texture::UncompressedFloatFormat::F32F32F32F32,
glium::texture::MipmapsOption::NoMipmap,
w,
h,
).map_err(|e| ProcessingErr::TextureNoCreate(e))?;
let fbid = fbtexture.get_id();
let depthtexture = glium::texture::DepthTexture2d::empty_with_format(
&display,
glium::texture::DepthFormat::F32,
glium::texture::MipmapsOption::NoMipmap,
w,
h,
).map_err(|e| ProcessingErr::TextureNoCreate(e))?;
let oh = owning_ref::OwningHandle::new_with_fn(
Box::new(FBtexs {
fbtex: fbtexture,
depthtexture: depthtexture,
}),
|v| unsafe {
Box::new(glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(
&display,
&(*v).fbtex,
&(*v).depthtexture,
).expect("Could not create a SimpleFrameBuffer with attached DepthBuffer. Please check your graphics card, drivers, and OS."),
)
},
);
let fbtexture = unsafe {
glium::texture::Texture2d::from_id(
&display,
glium::texture::UncompressedFloatFormat::F32F32F32F32,
fbid,
true,
glium::texture::MipmapsOption::NoMipmap,
glium::texture::Dimensions::Texture2d {
width: w,
height: h,
},
)
};
let draw_params = glium::draw_parameters::DrawParameters {
point_size: Some(2f32),
line_width: Some(2f32),
depth: glium::Depth {
write: true,
test: glium::DepthTest::Overwrite,
..Default::default()
},
blend: glium::Blend {
color: glium::BlendingFunction::Addition {
source: glium::LinearBlendingFactor::SourceAlpha,
destination: glium::LinearBlendingFactor::OneMinusSourceAlpha,
},
alpha: glium::BlendingFunction::Addition {
source: glium::LinearBlendingFactor::One,
destination: glium::LinearBlendingFactor::One,
},
constant_value: (1.0, 1.0, 1.0, 1.0),
},
multisampling: false,
// smooth: Some(glium::draw_parameters::Smooth::Nicest),
smooth: None,
..Default::default()
};
// if !fonts_initialized {
// setupFontCharacters()
// }
// fonts_initialized = true
// by default, use system fonts that are known to basically always be available
let mut font_face = "".to_owned();
if cfg!(target_os = "windows") {
font_face = "C:/Windows/Fonts/arial.ttf".to_owned();
} else if cfg!(target_os = "linux") {
font_face = "/usr/share/fonts/ttf-dejavu-ib/DejaVuSansMono.ttf".to_owned();
} else if cfg!(target_os = "macos") {
font_face = "/Users/rje/Library/Fonts/Go-Regular.ttf".to_owned();
}
// glCheckError("Screen initilization.");
let shader_bank = init_shaders(&display, &glsl_version)?;
let vertex1 = DFBFDVertex {
position: [-1.0, -1.0],
texcoord: [0.0, 0.0],
};
let vertex2 = DFBFDVertex {
position: [1.0, -1.0],
texcoord: [1.0, 0.0],
};
let vertex3 = DFBFDVertex {
position: [1.0, 1.0],
texcoord: [1.0, 1.0],
};
let vertex4 = DFBFDVertex {
position: [-1.0, 1.0],
texcoord: [0.0, 1.0],
};
let shape = vec![vertex1, vertex2, vertex3, vertex4];
let fb_shape_buffer = glium::VertexBuffer::new(&display, &shape)
.map_err(|e| ProcessingErr::VBNoCreate(e))?;
let fb_index_buffer = glium::IndexBuffer::new(
&display,
glium::index::PrimitiveType::TrianglesList,
&[0u16, 1, 2, 0, 2, 3],
).map_err(|e| ProcessingErr::IBNoCreate(e))?;
Ok(Screen {
// start with default identity matrix, as expected.
matrices: GLmatStruct {
curr_matrix: Matrix4::new(
1.0f32,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
),
matrix_stack: vec![
Matrix4::new(
1.0f32,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0
);
1
],
},
fbo: oh,
fbtexture: fbtexture,
fb_shape_buffer: fb_shape_buffer,
fb_index_buffer: fb_index_buffer,
display: ScreenType::Headless(display),
events_loop: events_loop,
draw_params: draw_params,
bg_col: vec![0.8f32, 0.8, 0.8, 0.8],
fill_stuff: true,
fill_col: vec![1.0f32, 1.0, 1.0, 1.0],
stroke_stuff: true,
stroke_col: vec![0.0f32, 0.0, 0.0, 1.0],
tint_stuff: false,
tint_col: vec![1.0f32, 1.0, 1.0, 1.0],
shader_bank: shader_bank,
draw_texture: false,
aspect_ratio: aspect_ratio,
preserve_aspect_ratio: preserve_aspect_ratio,
fb_size: fb_size,
stroke_weight: 1.0,
font_face: font_face,
text_size: 0.4,
height: height,
width: width,
left: -1f32,
right: 1f32,
top: 1f32,
bottom: -1f32,
c_mode: "RGB".to_owned(),
title: "processing-rs".to_owned(),
ellipse_mode: "CENTER".to_owned(),
rect_mode: "CORNER".to_owned(),
shape_mode: "CORNER".to_owned(),
image_mode: "CORNER".to_owned(),
frame_rate: 60,
frame_count: 0,
fonts_initialized: false,
curr_shader: 0,
curr_cursor: glium::glutin::MouseCursor::Default,
wrap: glium::uniforms::SamplerWrapFunction::Repeat,
curr_texture: None,
alternate_shader: 1 << 20,
using_alternate_shader: false,
glsl_version: glsl_version,
drew_points: false,
keypressed: None,
mousepressed: None,
mousereleased: None,
mousepos: (-100., -100.),
headless: true,
})
}
/// Once you have finished drawing a number of shapes to the screen, you will need
/// to call screen.reveal() for the result to be viewable on the monitor. This is
/// because `processing-rs` uses double-buffering, whereby all of the drawing
/// happens on a separate, hidden buffer and once that is done, it is transferred
/// to a viewable, monitor buffer. This is standard practice in graphics programming,
/// since it makes drawing faster and reduces screen tearing.
#[inline]
pub fn reveal(&mut self) -> Result<(), ProcessingErr> {
let mut target = match self.display {
ScreenType::Window(ref d) => d.draw(),
ScreenType::Headless(ref d) => d.draw(),
};
{
let uniforms = uniform! { texFramebuffer: &self.fbtexture };
let p = &self.shader_bank[3];
target
.draw(
&self.fb_shape_buffer,
&self.fb_index_buffer,
p,
&uniforms,
&Default::default(),
)
.map_err(|e| ProcessingErr::DrawFailed(e))?;
target.finish().map_err(|e| ProcessingErr::SwapFailed(e))?;
}
let mut kp = None;
let mut mp = None;
let mut mr = None;
let mut mpos = (-100., -100.);
self.events_loop.poll_events(|event| match event {
glutin::Event::WindowEvent { event, .. } => {
match event {
glutin::WindowEvent::Closed => panic!("need a smoother way to quit..."),
glutin::WindowEvent::KeyboardInput { input, .. }
if glutin::ElementState::Pressed == input.state => {
match input.virtual_keycode {
Some(b) => {
kp = Some(b);
}
_ => (),
}
}
glutin::WindowEvent::MouseInput {
state: s,
button: b,
..
} if glutin::ElementState::Pressed == s => {
mp = Some(b);
}
glutin::WindowEvent::MouseInput {
state: s,
button: b,
..
} if glutin::ElementState::Released == s => {
mr = Some(b);
}
glutin::WindowEvent::CursorMoved { position, .. } => {
mpos = position;
}
_ => (),
}
}
_ => (),
});
self.keypressed = kp;
self.mousepressed = mp;
self.mousereleased = mr;
self.mousepos = mpos;
self.frame_count += 1;
Ok(())
}
/// This function works exactly the same as screen.reveal(), except that it also
/// outputs a Vector of raw glutin events, if you need that for any reason. I needed
/// it once, so I leave it here.
#[inline]
pub fn reveal_with_events(&mut self) -> Result<Vec<glium::glutin::Event>, ProcessingErr> {
let mut target = match self.display {
ScreenType::Window(ref d) => d.draw(),
ScreenType::Headless(ref d) => d.draw(),
};
{
let uniforms = uniform! { texFramebuffer: &self.fbtexture };
let p = &self.shader_bank[3];
target
.draw(
&self.fb_shape_buffer,
&self.fb_index_buffer,
p,
&uniforms,
&Default::default(),
)
.map_err(|e| ProcessingErr::DrawFailed(e))?;
target.finish().map_err(|e| ProcessingErr::SwapFailed(e))?;
}
let mut kp = None;
let mut mp = None;
let mut mr = None;
let mut mpos = (-100., -100.);
let mut events = Vec::new();
self.events_loop.poll_events(|event| {
events.push(event.clone());
match event {
glutin::Event::WindowEvent { event, .. } => {
match event {
glutin::WindowEvent::Closed => panic!("need a smoother way to quit..."),
glutin::WindowEvent::KeyboardInput { input, .. }
if glutin::ElementState::Pressed == input.state => {
match input.virtual_keycode {
Some(b) => {
kp = Some(b);
}
_ => (),
}
}
glutin::WindowEvent::MouseInput {
state: s,
button: b,
..
} if glutin::ElementState::Pressed == s => {
mp = Some(b);
}
glutin::WindowEvent::MouseInput {
state: s,
button: b,
..
} if glutin::ElementState::Released == s => {
mr = Some(b);
}
glutin::WindowEvent::CursorMoved { position, .. } => {
mpos = position;
}
_ => (),
}
}
_ => (),
}
});
self.keypressed = kp;
self.mousepressed = mp;
self.mousereleased = mr;
self.mousepos = mpos;
self.frame_count += 1;
Ok(events)
}
// #[inline]
// pub fn clone_display(&self) -> ScreenType {
// self.display.clone()
// }
/// This will safely close a window and drop the Screen struct associated with it.
/// Currently unimplemented, so for now, to close a window, you have to quit the
/// running program.
pub fn end_drawing(self) { unimplemented!() }
}
//
// pub fn drawing_window(glfw: &mut glfw::Glfw, window: &mut glfw::Window) {
// glfw.make_context_current(Some(window));
// window.show();
// }
pub fn init_shaders(
display: &glium::backend::Facade,
glsl_version: &str,
) -> Result<Vec<glium::program::Program>, ProcessingErr> {
let mut shader_bank = Vec::new();
// basicShapes
let vsh_bs = "
#version "
.to_owned() + &glsl_version +
"
in vec3 position;
in vec4 color;
out vec4 vColor;
uniform \
mat4 MVP;
void main() {
vColor = color;
gl_Position = MVP * \
vec4(position, 1.0);
}
";
let fsh_bs = "
#version "
.to_owned() + &glsl_version +
"
in vec4 vColor;
out vec4 outColor;
void main() {
\
outColor = vColor;
}
";
let bs_program = glium::Program::new(
display,
glium::program::ProgramCreationInput::SourceCode {
vertex_shader: &vsh_bs,
tessellation_control_shader: None,
tessellation_evaluation_shader: None,
geometry_shader: None,
fragment_shader: &fsh_bs,
transform_feedback_varyings: None,
outputs_srgb: true,
uses_point_size: true,
},
).map_err(|e| ProcessingErr::ShaderCompileFail(e))?;
shader_bank.push(bs_program);
// texturedShapes
let vsh_ts = "
#version "
.to_owned() + &glsl_version +
"
in vec3 position;
in vec4 color;
in vec2 texcoord;
out vec4 \
vColor;
out vec2 Texcoord;
uniform mat4 MVP;
void main() {
\
vColor = color;
Texcoord = texcoord;
gl_Position = MVP * \
vec4(position, 1.0);
}
";
let fsh_ts = "
#version "
.to_owned() + &glsl_version +
"
in vec4 vColor;
in vec2 Texcoord;
out vec4 outColor;
uniform \
sampler2D tex;
void main() {
outColor = texture(tex, Texcoord) * \
vColor;
}
";
let ts_program = glium::Program::new(
display,
glium::program::ProgramCreationInput::SourceCode {
vertex_shader: &vsh_ts,
tessellation_control_shader: None,
tessellation_evaluation_shader: None,
geometry_shader: None,
fragment_shader: &fsh_ts,
transform_feedback_varyings: None,
outputs_srgb: true,
uses_point_size: true,
},
).map_err(|e| ProcessingErr::ShaderCompileFail(e))?;
shader_bank.push(ts_program);
// fontDrawing
let vsh_fd = "
#version "
.to_owned() + &glsl_version +
"
in vec2 position;
in vec2 texcoord;
out vec2 TexCoord;
\
uniform mat4 proj;
void main()
{
gl_Position = proj * \
vec4(position, 0.0, 1.0);
TexCoord = texcoord;
}
";
let fsh_fd = "
#version "
.to_owned() + &glsl_version +
"
in vec2 TexCoord;
out vec4 color;
uniform sampler2D text;
\
uniform vec3 textColor;
void main()
{
vec4 sampled = vec4(1.0, \
1.0, 1.0, texture(text, TexCoord).r);
color = vec4(textColor, 1.0) * \
sampled;
}
";
let fd_program = glium::Program::new(
display,
glium::program::ProgramCreationInput::SourceCode {
vertex_shader: &vsh_fd,
tessellation_control_shader: None,
tessellation_evaluation_shader: None,
geometry_shader: None,
fragment_shader: &fsh_fd,
transform_feedback_varyings: None,
outputs_srgb: true,
uses_point_size: true,
},
).map_err(|e| ProcessingErr::ShaderCompileFail(e))?;
shader_bank.push(fd_program);
// text is rendered with an orthographic projection
// let projection = vec![
// 2.0f32 / width as f32,
// 0.,
// 0.,
// -1.,
// 0.,
// 2.0 / height as f32,
// 0.,
// -1.,
// 0.,
// 0.,
// -1.,
// 0.,
// 0.,
// 0.,
// 0.,
// 1.,
// ];
// unsafe {
// gl::UniformMatrix4fv(
// gl::GetUniformLocation(
// *shader_bank.get("fontDrawing").unwrap(),
// CString::new("proj").unwrap().as_ptr(),
// ),
// 1,
// gl::FALSE as GLboolean,
// mem::transmute(&projection[0]),
// );
// }
// framebuffer
let vsh_dfb = "
#version "
.to_owned() + &glsl_version +
"
in vec2 position;
in vec2 texcoord;
out vec2 Texcoord;
void \
main() {
Texcoord = texcoord;
gl_Position = vec4(position, 0.0, \
1.0);
}
";
let fsh_dfb = "
#version "
.to_owned() + &glsl_version +
"
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D \
texFramebuffer;
void main() {
outColor = texture(texFramebuffer, \
Texcoord);
}
";
let dfb_program = glium::Program::new(
display,
glium::program::ProgramCreationInput::SourceCode {
vertex_shader: &vsh_dfb,
tessellation_control_shader: None,
tessellation_evaluation_shader: None,
geometry_shader: None,
fragment_shader: &fsh_dfb,
transform_feedback_varyings: None,
outputs_srgb: true,
uses_point_size: true,
},
).map_err(|e| ProcessingErr::ShaderCompileFail(e))?;
shader_bank.push(dfb_program);
Ok(shader_bank)
}