use super::composition::LayerComposition;
use super::*;
use mgui_core::paint::BlendMode;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;
fn referenced_texture_ids(paint_list: &PaintList) -> Vec<u32> {
let mut ids = Vec::new();
for command in &paint_list.commands {
let id = match command {
PaintCommand::TexturedRect { texture_id, .. } | PaintCommand::MaskRect { texture_id, .. } => *texture_id,
_ => continue,
};
if id != 0 && !ids.contains(&id) {
ids.push(id);
}
}
ids.sort_unstable();
ids
}
pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);
fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
let (w, h) = match logical {
Some(s) => (s.width, s.height),
None => screen,
};
let w = (w * dpr).ceil() as u32;
let h = (h * dpr).ceil() as u32;
(w.max(1).min(max_dim), h.max(1).min(max_dim))
}
fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
}
pub(crate) fn layer_texture_targets(
layer_paints: &[LayerPaint],
dpr: f32,
screen_size: (f32, f32),
max_dim: u32,
budget: u64,
) -> LayerTextureTargets {
let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
let max_dim = max_dim.max(1);
let compute = |scale: f32| -> Vec<LayerTextureSize> {
layer_paints
.iter()
.map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
.collect()
};
let mut scale = 1.0f32;
let mut sizes = compute(scale);
let mut total = layer_tex_total_bytes(&sizes);
if total > budget {
for _ in 0..8 {
if total <= budget {
break;
}
let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
let next = (scale as f64 * factor) as f32;
if next >= scale || next <= 0.01 {
break;
}
scale = next;
sizes = compute(scale);
total = layer_tex_total_bytes(&sizes);
}
let quantized = (scale * 8.0).floor() / 8.0;
if quantized > 0.0 && quantized < scale {
scale = quantized;
sizes = compute(scale);
}
}
(sizes, scale)
}
fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
match mode {
BlendMode::Normal => BlendState::ALPHA_BLENDING,
BlendMode::Multiply => BlendState {
color: comp(BlendFactor::Dst, BlendFactor::Zero),
alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
},
BlendMode::Screen => BlendState {
color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
},
BlendMode::Add => BlendState {
color: comp(BlendFactor::One, BlendFactor::One),
alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
},
}
}
fn stencil_equal_state() -> wgpu::DepthStencilState {
let face = wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: wgpu::StencilOperation::Keep,
depth_fail_op: wgpu::StencilOperation::Keep,
pass_op: wgpu::StencilOperation::Keep,
};
wgpu::DepthStencilState {
format: STENCIL_FMT,
depth_write_enabled: None,
depth_compare: None,
stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
bias: wgpu::DepthBiasState::default(),
}
}
impl Renderer {
pub fn shared_resources(&self) -> RendererShared {
self.image_cache.borrow_mut().evict_enabled = false;
RendererShared {
atlas_cache: Rc::clone(&self.atlas_cache),
image_cache: Rc::clone(&self.image_cache),
rect_pipelines: self.rect_pipelines.clone(),
rect_bgl: self.rect_bgl.clone(),
text_pipeline: self.text_pipeline.clone(),
text_bgl: self.text_bgl.clone(),
text_pipeline_mask: self.text_pipeline_mask.clone(),
text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
tri_pipeline: self.tri_pipeline.clone(),
tri_bgl: self.tri_bgl.clone(),
tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
blit_pipeline: self.blit_pipeline.clone(),
blit_bgl: self.blit_bgl.clone(),
blit_sampler: self.blit_sampler.clone(),
backdrop_pipeline: self.backdrop_pipeline.clone(),
backdrop_bgl: self.backdrop_bgl.clone(),
format: self.format,
}
}
pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
Self {
rect_pipelines: shared.rect_pipelines.clone(),
rect_bgl: shared.rect_bgl.clone(),
text_pipeline: shared.text_pipeline.clone(),
text_bgl: shared.text_bgl.clone(),
text_pipeline_mask: shared.text_pipeline_mask.clone(),
text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
tri_pipeline: shared.tri_pipeline.clone(),
tri_bgl: shared.tri_bgl.clone(),
tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
atlas_cache: Rc::clone(&shared.atlas_cache),
layer_cache: HashMap::new(),
active_layer_ids: std::collections::HashSet::new(),
frame_layer_sizes: HashMap::new(),
composition_scratch: mgui_core::CompositionScratch::default(),
blit_pipeline: shared.blit_pipeline.clone(),
blit_bgl: shared.blit_bgl.clone(),
blit_sampler: shared.blit_sampler.clone(),
backdrop_pipeline: shared.backdrop_pipeline.clone(),
backdrop_bgl: shared.backdrop_bgl.clone(),
format: shared.format,
gpu_profiler: crate::gpu_profiler::mount(device),
batch_pools: HashMap::new(),
image_cache: Rc::clone(&shared.image_cache),
msaa_scratch: HashMap::new(),
stencil_scratch: HashMap::new(),
snapshot_scratch: HashMap::new(),
last_stats: RenderStats::default(),
pending_invalidations: [0; 8],
pending_invalidation_start: None,
cache_high_watermark_bytes: 0,
pending_upload: None,
}
}
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
let text_msaa = pass1_msaa;
let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("rect-shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
});
let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("rect-bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("rect-pipeline-layout"),
bind_group_layouts: &[Some(&rect_bgl)],
immediate_size: 0,
});
const RECT_BLEND_MODES: [BlendMode; 4] =
[BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
let make_rect_pipeline =
|label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&rect_pipeline_layout),
vertex: wgpu::VertexState {
module: &rect_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil,
multisample: pass1_msaa,
fragment: Some(wgpu::FragmentState {
module: &rect_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let rect_pipelines: [wgpu::RenderPipeline; 4] =
std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));
let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("text-shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
});
let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("text-bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("text-pipeline-layout"),
bind_group_layouts: &[Some(&text_bgl)],
immediate_size: 0,
});
let mask_blend = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::SrcAlpha,
operation: wgpu::BlendOperation::Add,
},
};
let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("text-pipeline"),
layout: Some(&text_pipeline_layout),
vertex: wgpu::VertexState {
module: &text_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: None,
multisample: text_msaa,
fragment: Some(wgpu::FragmentState {
module: &text_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("text-pipeline-mask"),
layout: Some(&text_pipeline_layout),
vertex: wgpu::VertexState {
module: &text_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: None,
multisample: text_msaa,
fragment: Some(wgpu::FragmentState {
module: &text_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(mask_blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("tri-shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
});
let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("tri-bgl"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("tri-pipeline-layout"),
bind_group_layouts: &[Some(&tri_bgl)],
immediate_size: 0,
});
let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
array_stride: 24,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
],
})];
let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("tri-pipeline"),
layout: Some(&tri_pipeline_layout),
vertex: wgpu::VertexState {
module: &tri_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &tri_vb_layouts,
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: None,
multisample: pass1_msaa,
fragment: Some(wgpu::FragmentState {
module: &tri_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let keep_op = wgpu::StencilOperation::Keep;
let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&tri_pipeline_layout),
vertex: wgpu::VertexState {
module: &tri_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &tri_vb_layouts,
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: STENCIL_FMT,
depth_write_enabled: None,
depth_compare: None,
stencil: wgpu::StencilState {
front: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Always,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: op,
},
back: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Always,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: op,
},
read_mask: 0xFF,
write_mask: 0xFF,
},
bias: wgpu::DepthBiasState::default(),
}),
multisample: pass1_msaa,
fragment: Some(wgpu::FragmentState {
module: &tri_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::empty(), })],
}),
multiview_mask: None,
cache: None,
})
};
let tri_pipeline_stencil_inc =
stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
let tri_pipeline_stencil_dec =
stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);
let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
make_rect_pipeline(
"rect-pipeline-stencil-test",
blend_state_for(RECT_BLEND_MODES[i]),
Some(stencil_equal_state()),
)
});
let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("text-pipeline-stencil-test"),
layout: Some(&text_pipeline_layout),
vertex: wgpu::VertexState {
module: &text_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: Some(wgpu::DepthStencilState {
format: STENCIL_FMT,
depth_write_enabled: None,
depth_compare: None,
stencil: wgpu::StencilState {
front: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
back: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
read_mask: 0xFF,
write_mask: 0,
},
bias: wgpu::DepthBiasState::default(),
}),
multisample: text_msaa,
fragment: Some(wgpu::FragmentState {
module: &text_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("text-pipeline-mask-stencil-test"),
layout: Some(&text_pipeline_layout),
vertex: wgpu::VertexState {
module: &text_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: Some(wgpu::DepthStencilState {
format: STENCIL_FMT,
depth_write_enabled: None,
depth_compare: None,
stencil: wgpu::StencilState {
front: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
back: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
read_mask: 0xFF,
write_mask: 0,
},
bias: wgpu::DepthBiasState::default(),
}),
multisample: text_msaa,
fragment: Some(wgpu::FragmentState {
module: &text_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(mask_blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("tri-pipeline-stencil-test"),
layout: Some(&tri_pipeline_layout),
vertex: wgpu::VertexState {
module: &tri_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &tri_vb_layouts,
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: Some(wgpu::DepthStencilState {
format: STENCIL_FMT,
depth_write_enabled: None,
depth_compare: None,
stencil: wgpu::StencilState {
front: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
back: wgpu::StencilFaceState {
compare: wgpu::CompareFunction::Equal,
fail_op: keep_op,
depth_fail_op: keep_op,
pass_op: keep_op,
},
read_mask: 0xFF,
write_mask: 0,
},
bias: wgpu::DepthBiasState::default(),
}),
multisample: pass1_msaa,
fragment: Some(wgpu::FragmentState {
module: &tri_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("blit-shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
});
let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("blit-bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("blit-pipeline-layout"),
bind_group_layouts: &[Some(&blit_bgl)],
immediate_size: 0,
});
let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("blit-pipeline"),
layout: Some(&blit_pipeline_layout),
vertex: wgpu::VertexState {
module: &blit_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &blit_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("backdrop-shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
});
let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("backdrop-bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("backdrop-pipeline-layout"),
bind_group_layouts: &[Some(&backdrop_bgl)],
immediate_size: 0,
});
let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("backdrop-pipeline"),
layout: Some(&backdrop_pipeline_layout),
vertex: wgpu::VertexState {
module: &backdrop_shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
depth_stencil: Some(stencil_equal_state()),
multisample: pass1_msaa,
fragment: Some(wgpu::FragmentState {
module: &backdrop_shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
Self {
rect_pipelines,
rect_bgl,
text_pipeline,
text_bgl,
text_pipeline_mask,
text_pipeline_mask_stencil_test,
tri_pipeline,
tri_bgl,
tri_pipeline_stencil_inc,
tri_pipeline_stencil_dec,
rect_pipelines_stencil_test,
text_pipeline_stencil_test,
tri_pipeline_stencil_test,
atlas_cache: Rc::new(RefCell::new(None)),
layer_cache: HashMap::new(),
blit_pipeline,
blit_bgl,
blit_sampler,
backdrop_pipeline,
backdrop_bgl,
format,
active_layer_ids: std::collections::HashSet::new(),
frame_layer_sizes: HashMap::new(),
composition_scratch: mgui_core::CompositionScratch::default(),
gpu_profiler: crate::gpu_profiler::mount(device),
batch_pools: HashMap::new(),
image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
msaa_scratch: HashMap::new(),
stencil_scratch: HashMap::new(),
snapshot_scratch: HashMap::new(),
last_stats: RenderStats::default(),
pending_invalidations: [0; 8],
pending_invalidation_start: None,
cache_high_watermark_bytes: 0,
pending_upload: None,
}
}
pub(crate) fn ensure_atlas(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> (wgpu::TextureView, wgpu::Sampler) {
let snap = crate::text::atlas_snapshot();
let mut atlas_cache = self.atlas_cache.borrow_mut();
let need_recreate = match atlas_cache.as_ref() {
None => true,
Some(c) => c.cached_size != (snap.width, snap.height),
};
if need_recreate {
log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
let (dy0, dy1) = snap.dirty_y;
let rows = dy1.saturating_sub(dy0);
let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("glyph-atlas"),
size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
if rows > 0 && !pixels.is_empty() {
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
aspect: wgpu::TextureAspect::All,
},
pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(snap.width),
rows_per_image: Some(rows),
},
wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
);
}
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
*atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
} else if snap.dirty {
let (dy0, dy1) = snap.dirty_y;
let rows = dy1.saturating_sub(dy0);
log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
if rows > 0 {
if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &cache.texture,
mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
aspect: wgpu::TextureAspect::All,
},
pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(snap.width),
rows_per_image: Some(rows),
},
wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
);
}
}
}
if snap.dirty {
crate::text::atlas_clear_dirty();
}
let atlas = atlas_cache.as_ref().expect("atlas cache populated");
(atlas.view.clone(), atlas.sampler.clone())
}
pub(crate) fn ensure_all_layer_caches(
&mut self,
device: &wgpu::Device,
layer_paints: &[LayerPaint],
dpr: f32,
screen_size: (f32, f32),
) -> (u32, u32, HashMap<LayerId, u64>, HashSet<LayerId>, u64) {
let max_dim = device.limits().max_texture_dimension_2d.max(1);
let (targets, scale) =
layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
if scale < 0.999 {
log::debug!(
target: "mgui_profile",
"layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
targets.len(),
scale * 100.0
);
}
let collecting = mgui_core::frame::cache_stats_collecting();
let incremental = super::incremental_layer_cache_enabled();
let key_start = collecting.then(std::time::Instant::now);
let mut content_keys = HashMap::new();
let mut recreated = HashSet::new();
let image_generations: HashMap<u32, u64> = if incremental {
let mut ids = HashSet::new();
for lp in layer_paints {
ids.extend(referenced_texture_ids(&lp.paint_list));
}
let cache = self.image_cache.borrow();
ids.into_iter().map(|id| (id, cache.generation(id))).collect()
} else {
HashMap::new()
};
let resource_epoch = if incremental { mgui_core::element::resource_epoch() } else { 0 };
let mut created = 0u32;
let mut resized = 0u32;
for (lp, (layer_id, tex_size)) in layer_paints.iter().zip(targets) {
let content_key = if incremental {
let mut hasher = DefaultHasher::new();
lp.paint_list.content_digest().hash(&mut hasher);
tex_size.0.hash(&mut hasher);
tex_size.1.hash(&mut hasher);
resource_epoch.hash(&mut hasher);
for id in referenced_texture_ids(&lp.paint_list) {
id.hash(&mut hasher);
image_generations.get(&id).copied().unwrap_or(0).hash(&mut hasher);
}
hasher.finish()
} else {
0
};
content_keys.insert(layer_id, content_key);
let existed = self.layer_cache.contains_key(&layer_id);
let need_create = match self.layer_cache.get(&layer_id) {
None => true,
Some(c) => c.cached_size != tex_size,
};
if need_create {
if existed {
resized += 1;
self.note_cache_invalidation(CacheInvalidationReason::Layout);
} else {
created += 1;
self.note_cache_invalidation(CacheInvalidationReason::Visibility);
}
let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("layer-resolve"),
size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
self.layer_cache.insert(
layer_id,
LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size, content_key: 0 },
);
recreated.insert(layer_id);
}
}
let key_ns = key_start.map(|start| start.elapsed().as_nanos() as u64).unwrap_or(0);
(created, resized, content_keys, recreated, key_ns)
}
pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
if let Some(v) = self.msaa_scratch.get(&size) {
return v.clone();
}
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("scratch-msaa"),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 4,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
self.msaa_scratch.insert(size, view.clone());
view
}
pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
if let Some(v) = self.stencil_scratch.get(&size) {
return v.clone();
}
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("scratch-stencil"),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 4,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Stencil8,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
self.stencil_scratch.insert(size, view.clone());
view
}
pub(super) fn snapshot_scratch(
&mut self,
device: &wgpu::Device,
size: (u32, u32),
) -> (wgpu::Texture, wgpu::TextureView) {
if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
return (tex.clone(), view.clone());
}
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("scratch-snapshot"),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
(tex, view)
}
}
#[cfg(test)]
pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
let comp = LayerComposition::single(lp, *layer_logical_size);
build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
}
pub(crate) fn build_blit_uniform_composed(
lp: &LayerPaint,
comp: &LayerComposition,
layer_logical_size: &Size,
screen_size: (f32, f32),
) -> BlitUniform {
let mut flags: u32 = 0;
let mut rotation = 0.0_f32;
let mut scale_x = 1.0_f32;
let mut scale_y = 1.0_f32;
let mut translate_x = 0.0_f32;
let mut translate_y = 0.0_f32;
let mut clip_radius = 0.0_f32;
match lp.effect {
LayerEffect::None => {}
LayerEffect::Transform(t) => {
if !t.is_identity() {
flags |= effect_flags::HAS_TRANSFORM;
}
rotation = t.rotation;
scale_x = t.scale_x;
scale_y = t.scale_y;
translate_x = t.translate.x;
translate_y = t.translate.y;
}
LayerEffect::Opacity(_) => {}
LayerEffect::ClipRRect(RRectDef { radius }) => {
clip_radius = radius;
}
}
if comp.opacity < 1.0 {
flags |= effect_flags::HAS_OPACITY;
}
if !comp.clips.is_empty() {
flags |= effect_flags::HAS_CLIP;
}
let w = layer_logical_size.width;
let h = layer_logical_size.height;
let mut clip_rect0 = [0.0; 4];
let mut clip_rect1 = [0.0; 4];
let mut clip_params = [0.0; 4];
if let Some(c) = comp.clips.first() {
clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
clip_params[0] = c.radius;
}
if let Some(c) = comp.clips.get(1) {
clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
clip_params[1] = c.radius;
}
clip_params[2] = comp.clips.len().min(2) as f32;
BlitUniform {
offset: [lp.offset.x, lp.offset.y],
size: [w, h],
screen: [screen_size.0, screen_size.1],
effect_flags: flags,
opacity: comp.opacity,
rotation,
scale_x,
translate_x,
translate_y,
clip_radius,
scale_y,
quad_offset: [lp.offset.x, lp.offset.y],
quad_size: [w, h],
phys_screen: [0.0, 0.0],
affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
affine_translate: [comp.affine.tx, comp.affine.ty],
_affine_pad: [0.0; 2],
clip_rect0,
clip_rect1,
clip_params,
}
}