@@ -11,31 +11,67 @@ use winit::window::Window;
11
11
12
12
#[ cfg( not( any( target_os = "android" , target_os = "ios" ) ) ) ]
13
13
pub ( super ) fn fill_window ( window : & Window ) {
14
- use softbuffer:: GraphicsContext ;
14
+ use softbuffer:: { Context , Surface } ;
15
15
use std:: cell:: RefCell ;
16
16
use std:: collections:: HashMap ;
17
+ use std:: num:: NonZeroU32 ;
17
18
use winit:: window:: WindowId ;
18
19
20
+ /// The graphics context used to draw to a window.
21
+ struct GraphicsContext {
22
+ /// The global softbuffer context.
23
+ context : Context ,
24
+
25
+ /// The hash map of window IDs to surfaces.
26
+ surfaces : HashMap < WindowId , Surface > ,
27
+ }
28
+
29
+ impl GraphicsContext {
30
+ fn new ( w : & Window ) -> Self {
31
+ Self {
32
+ context : unsafe { Context :: new ( w) } . expect ( "Failed to create a softbuffer context" ) ,
33
+ surfaces : HashMap :: new ( ) ,
34
+ }
35
+ }
36
+
37
+ fn surface ( & mut self , w : & Window ) -> & mut Surface {
38
+ self . surfaces . entry ( w. id ( ) ) . or_insert_with ( || {
39
+ unsafe { Surface :: new ( & self . context , w) }
40
+ . expect ( "Failed to create a softbuffer surface" )
41
+ } )
42
+ }
43
+ }
44
+
19
45
thread_local ! {
20
46
/// A static, thread-local map of graphics contexts to open windows.
21
- static GC : RefCell <HashMap < WindowId , GraphicsContext >> = RefCell :: new( HashMap :: new ( ) ) ;
47
+ static GC : RefCell <Option < GraphicsContext >> = RefCell :: new( None ) ;
22
48
}
23
49
24
50
GC . with ( |gc| {
25
51
// Either get the last context used or create a new one.
26
52
let mut gc = gc. borrow_mut ( ) ;
27
- let context = gc. entry ( window. id ( ) ) . or_insert_with ( || unsafe {
28
- GraphicsContext :: new ( window, window)
29
- . expect ( "Failed to create a softbuffer graphics context" )
30
- } ) ;
53
+ let surface = gc
54
+ . get_or_insert_with ( || GraphicsContext :: new ( window) )
55
+ . surface ( window) ;
31
56
32
57
// Fill a buffer with a solid color.
33
- const LIGHT_GRAY : u32 = 0xFFD3D3D3 ;
58
+ const DARK_GRAY : u32 = 0xFF181818 ;
34
59
let size = window. inner_size ( ) ;
35
- let buffer = vec ! [ LIGHT_GRAY ; size. width as usize * size. height as usize ] ;
36
60
37
- // Draw the buffer to the window.
38
- context. set_buffer ( & buffer, size. width as u16 , size. height as u16 ) ;
61
+ surface
62
+ . resize (
63
+ NonZeroU32 :: new ( size. width ) . expect ( "Width must be greater than zero" ) ,
64
+ NonZeroU32 :: new ( size. height ) . expect ( "Height must be greater than zero" ) ,
65
+ )
66
+ . expect ( "Failed to resize the softbuffer surface" ) ;
67
+
68
+ let mut buffer = surface
69
+ . buffer_mut ( )
70
+ . expect ( "Failed to get the softbuffer buffer" ) ;
71
+ buffer. fill ( DARK_GRAY ) ;
72
+ buffer
73
+ . present ( )
74
+ . expect ( "Failed to present the softbuffer buffer" ) ;
39
75
} )
40
76
}
41
77
0 commit comments