Skip to main content

clat_gui/
lib.rs

1use anyhow::{Result, anyhow};
2use futures;
3use std::sync::Arc;
4use winit::event::{Event, WindowEvent};
5use winit::event_loop::{ControlFlow, EventLoop};
6use winit::window::{Window as WinitWindow, WindowBuilder};
7use wgpu::Instance;
8
9// 定义窗口类型
10pub struct Window {
11    window: Arc<WinitWindow>,
12    surface: wgpu::Surface<'static>,
13    device: wgpu::Device,
14    queue: wgpu::Queue,
15    config: Option<wgpu::SurfaceConfiguration>,
16    surface_format: wgpu::TextureFormat,
17    surface_caps: wgpu::SurfaceCapabilities,
18}
19
20// 定义应用程序类型
21pub struct Application {
22    event_loop: Option<EventLoop<()>>,
23    windows: Vec<Window>,
24}
25
26// 应用程序实现
27impl Application {
28    // 创建新的应用程序实例
29    pub fn new() -> Result<Self> {
30        Ok(Self {
31            event_loop: Some(EventLoop::new()?),
32            windows: Vec::new(),
33        })
34    }
35    
36    // 创建新窗口
37    pub fn create_window(&mut self, title: &str, width: u32, height: u32) -> Result<()> {
38        if let Some(event_loop) = self.event_loop.as_ref() {
39            let window = WindowBuilder::new()
40                .with_title(title)
41                .with_inner_size(winit::dpi::LogicalSize::new(width, height))
42                .build(event_loop)?;
43            
44            // 包装为Arc以便共享
45            let window_arc = Arc::new(window);
46            
47            // 初始化wgpu相关资源
48            let instance = Instance::default();
49            // 创建surface,使用unsafe块将引用转换为'static
50            // 这是安全的,因为window_arc将被保存在Window结构体中
51            // 只要Window存在,window_arc就会存在
52            let surface = unsafe {
53                // 创建一个具有'static生命周期的引用
54                let static_ref: &Arc<WinitWindow> = &window_arc;
55                let static_ref_ptr = static_ref as *const Arc<WinitWindow>;
56                &*static_ref_ptr
57            };
58            let surface = instance.create_surface(surface)?;
59            let adapter = futures::executor::block_on(instance.request_adapter(
60                &wgpu::RequestAdapterOptions {
61                    power_preference: wgpu::PowerPreference::default(),
62                    compatible_surface: Some(&surface),
63                    force_fallback_adapter: false,
64                },
65            )).ok_or_else(|| anyhow::anyhow!("Failed to find an appropriate adapter"))?;
66            
67            let (device, queue) = futures::executor::block_on(adapter.request_device(
68                &wgpu::DeviceDescriptor {
69                    required_features: wgpu::Features::empty(),
70                    required_limits: wgpu::Limits::default(),
71                    label: Some("Device"),
72                },
73                None,
74            ))?;
75            
76            let surface_caps = surface.get_capabilities(&adapter);
77            let surface_format = surface_caps.formats.iter()
78                .copied()
79                .find(|f| f.is_srgb())
80                .unwrap_or(surface_caps.formats[0]);
81            
82            // 不在创建窗口时立即配置surface,而是存储必要的配置信息
83            // 将窗口添加到应用程序,暂时不配置surface
84            self.windows.push(Window {
85                window: window_arc,
86                surface,
87                device,
88                queue,
89                config: None,
90                surface_format,
91                surface_caps,
92            });
93        }
94        
95        Ok(())
96    }
97    
98    // 运行应用程序
99    pub fn run(mut self) -> Result<()> {
100        let event_loop = self.event_loop.take().expect("Event loop already taken");
101        
102        event_loop.run(move |event, target| {
103            target.set_control_flow(ControlFlow::Wait);
104            
105            match event {
106                Event::WindowEvent { event, window_id } => {
107                    match event {
108                        WindowEvent::CloseRequested => {
109                            // 正确的控制流变体
110                            target.set_control_flow(ControlFlow::WaitUntil(std::time::Instant::now()));
111                        },
112                        WindowEvent::Resized(new_size) => {
113            // 更新窗口大小
114            for window in &mut self.windows {
115                if window.window.id() == window_id {
116                    // 检查窗口大小是否有效
117                    if new_size.width > 0 && new_size.height > 0 {
118                        // 创建或更新surface配置
119                        let config = wgpu::SurfaceConfiguration {
120                            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
121                            format: window.surface_format,
122                            width: new_size.width,
123                            height: new_size.height,
124                            present_mode: window.surface_caps.present_modes[0],
125                            alpha_mode: window.surface_caps.alpha_modes[0],
126                            view_formats: vec![],
127                            desired_maximum_frame_latency: 2,
128                        };
129                        
130                        // 先配置surface,再保存config
131                        window.surface.configure(&window.device, &config);
132                        window.config = Some(config);
133                        window.window.request_redraw();
134                    }
135                }
136            }
137        },
138                        WindowEvent::RedrawRequested => {
139                            // 渲染窗口内容
140                            for window in &mut self.windows {
141                                if window.window.id() == window_id {
142                                    if let Err(err) = window.render() {
143                                        eprintln!("Error during rendering: {:?}", err);
144                                    }
145                                }
146                            }
147                        },
148                        _ => {},
149                    }
150                },
151                // 在新版本winit中,RedrawRequested是通过不同方式处理的
152                Event::AboutToWait => {
153                    // 为所有窗口请求重绘
154                    for window in &self.windows {
155                        window.window.request_redraw();
156                    }
157                },
158                _ => {},
159            }        }).map_err(|e| anyhow!("Event loop error: {:?}", e))
160    }
161}
162
163// 窗口实现
164impl Window {
165    // 渲染窗口内容
166    pub fn render(&mut self) -> Result<()> {
167        // 检查是否需要配置surface
168        if self.config.is_none() {
169            let window_size = self.window.inner_size();
170            
171            // 只有当窗口大小有效时才配置surface
172            if window_size.width > 0 && window_size.height > 0 {
173                let config = wgpu::SurfaceConfiguration {
174                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
175                    format: self.surface_format,
176                    width: window_size.width,
177                    height: window_size.height,
178                    present_mode: self.surface_caps.present_modes[0],
179                    alpha_mode: self.surface_caps.alpha_modes[0],
180                    view_formats: vec![],
181                    desired_maximum_frame_latency: 2,
182                };
183                
184                // 先配置surface,再保存config
185                self.surface.configure(&self.device, &config);
186                self.config = Some(config);
187            } else {
188                // 窗口大小无效,跳过渲染
189                return Ok(());
190            }
191        }
192        
193        // 尝试获取当前纹理
194        let output = match self.surface.get_current_texture() {
195            Ok(output) => output,
196            Err(wgpu::SurfaceError::Outdated) | Err(wgpu::SurfaceError::Lost) => {
197                // 如果surface过期或丢失,尝试重新配置
198                if let Some(config) = &self.config {
199                    self.surface.configure(&self.device, config);
200                }
201                return Ok(());
202            },
203            Err(err) => return Err(err.into()),
204        };
205        
206        let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
207        
208        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
209            label: Some("Render Encoder"),
210        });
211        
212        // 清除屏幕(这里使用简单的背景色)
213        {
214            let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
215                label: Some("Render Pass"),
216                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
217                    view: &view,
218                    resolve_target: None,
219                    ops: wgpu::Operations {
220                        load: wgpu::LoadOp::Clear(wgpu::Color {
221                            r: 0.1,
222                            g: 0.2,
223                            b: 0.3,
224                            a: 1.0,
225                        }),
226                        store: wgpu::StoreOp::Store,
227                    },
228                })],
229                depth_stencil_attachment: None,
230                timestamp_writes: None,
231                occlusion_query_set: None,
232            });
233            // 这里可以添加更多渲染代码
234            drop(render_pass);
235        }
236        
237        self.queue.submit(std::iter::once(encoder.finish()));
238        output.present();
239        
240        Ok(())
241    }
242}