tirbofish/dropbear
main / crates / dropbear-engine / src / pipelines / mod.rs · 6773 bytes
crates/dropbear-engine/src/pipelines/mod.rs
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
use std::path::PathBuf;
use crate::graphics::SharedGraphicsContext;
use crate::shader::Shader;
use std::sync::Arc;
use arc_swap::ArcSwap;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
pub mod globals;
pub mod hdr;
pub mod light_cube;
pub mod shader;
pub mod animation;
pub mod builder;
pub use globals::{Globals, GlobalsUniform};
/// A render pipeline that hot-swaps itself when shader source files change.
pub struct HotPipeline {
pipeline: Arc<ArcSwap<wgpu::RenderPipeline>>,
}
impl HotPipeline {
pub fn new<F>(
device: Arc<wgpu::Device>,
watch_dir: PathBuf,
factory: F,
) -> anyhow::Result<Self>
where
F: Fn(&wgpu::Device) -> anyhow::Result<wgpu::RenderPipeline> + Send + Sync + 'static,
{
let factory = Arc::new(factory);
let initial = factory(&device)?;
let pipeline = Arc::new(ArcSwap::from_pointee(initial));
if !watch_dir.exists() {
log::warn!("HotPipeline: watch directory does not exist: {watch_dir:?}");
return Ok(Self { pipeline });
}
let (tx, rx) = std::sync::mpsc::channel::<notify::Result<notify::Event>>();
let mut watcher = RecommendedWatcher::new(tx, notify::Config::default())?;
watcher.watch(&watch_dir, RecursiveMode::Recursive)?;
let pipeline_ref = pipeline.clone();
std::thread::spawn(move || {
let _watcher = watcher; // keep the watcher alive inside the thread
for event in rx {
match event {
Ok(ev) => {
use notify::EventKind::*;
match ev.kind {
Modify(_) | Create(_) => {
log::info!("Shader change detected: {:?}", ev.paths);
let result = std::panic::catch_unwind(
std::panic::AssertUnwindSafe(|| factory(&device)),
);
match result {
Ok(Ok(new_pipeline)) => {
pipeline_ref.store(Arc::new(new_pipeline));
log::info!("Pipeline hot-reloaded successfully");
}
Ok(Err(e)) => {
log::error!(
"Shader compile error, keeping old pipeline: {e}"
);
}
Err(_) => {
log::error!(
"Shader factory panicked during hot reload, keeping old pipeline"
);
}
}
}
_ => {}
}
}
Err(e) => log::error!("Shader watcher error: {e}"),
}
}
});
Ok(Self { pipeline })
}
pub fn get(&self) -> arc_swap::Guard<Arc<wgpu::RenderPipeline>> {
self.pipeline.load()
}
}
/// A helper in defining a pipelines required information, as well as getters.
///
/// This contains the bare minimum for any pipeline.
pub trait DropbearShaderPipeline {
/// Creates a new instance of a pipeline.
fn new(graphics: Arc<SharedGraphicsContext>) -> Self;
/// Fetches the shader property
fn shader(&self) -> &Shader;
/// Fetches the pipeline layout
fn pipeline_layout(&self) -> &wgpu::PipelineLayout;
/// Fetches the pipeline
fn pipeline(&self) -> &wgpu::RenderPipeline;
}
pub fn create_render_pipeline(
label: Option<&str>,
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
color_format: wgpu::TextureFormat,
depth_format: Option<wgpu::TextureFormat>,
vertex_layouts: &[wgpu::VertexBufferLayout],
topology: wgpu::PrimitiveTopology,
shader: wgpu::ShaderModuleDescriptor,
sample_count: u32,
) -> wgpu::RenderPipeline {
create_render_pipeline_ex(
label,
device,
layout,
color_format,
depth_format,
vertex_layouts,
topology,
shader,
true, // depth_write_enabled
wgpu::CompareFunction::LessEqual,
sample_count,
)
}
pub fn create_render_pipeline_ex(
label: Option<&str>,
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
color_format: wgpu::TextureFormat,
depth_format: Option<wgpu::TextureFormat>,
vertex_layouts: &[wgpu::VertexBufferLayout],
topology: wgpu::PrimitiveTopology,
shader: wgpu::ShaderModuleDescriptor,
depth_write_enabled: bool,
depth_compare: wgpu::CompareFunction,
sample_count: u32,
) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(shader);
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label,
layout: Some(layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: vertex_layouts,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology, // NEW!
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: depth_format.map(|format| wgpu::DepthStencilState {
format,
depth_write_enabled: Some(depth_write_enabled),
depth_compare: Some(depth_compare),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
cache: None,
multiview_mask: None,
})
}