1use super::composition::LayerComposition;
5use super::*;
6use mgui_core::paint::BlendMode;
7
8const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;
9
10pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
12
13pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
15pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);
17
18fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
20 let (w, h) = match logical {
21 Some(s) => (s.width, s.height),
22 None => screen,
23 };
24 let w = (w * dpr).ceil() as u32;
26 let h = (h * dpr).ceil() as u32;
27 (w.max(1).min(max_dim), h.max(1).min(max_dim))
28}
29
30fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
31 sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
32}
33
34pub(crate) fn layer_texture_targets(
44 layer_paints: &[LayerPaint],
45 dpr: f32,
46 screen_size: (f32, f32),
47 max_dim: u32,
48 budget: u64,
49) -> LayerTextureTargets {
50 let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
51 let max_dim = max_dim.max(1);
52 let compute = |scale: f32| -> Vec<LayerTextureSize> {
53 layer_paints
54 .iter()
55 .map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
56 .collect()
57 };
58
59 let mut scale = 1.0f32;
60 let mut sizes = compute(scale);
61 let mut total = layer_tex_total_bytes(&sizes);
62 if total > budget {
63 for _ in 0..8 {
65 if total <= budget {
66 break;
67 }
68 let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
69 let next = (scale as f64 * factor) as f32;
70 if next >= scale || next <= 0.01 {
71 break;
72 }
73 scale = next;
74 sizes = compute(scale);
75 total = layer_tex_total_bytes(&sizes);
76 }
77 let quantized = (scale * 8.0).floor() / 8.0;
80 if quantized > 0.0 && quantized < scale {
81 scale = quantized;
82 sizes = compute(scale);
83 }
84 }
85 (sizes, scale)
86}
87
88fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
90 use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
91 let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
92 match mode {
93 BlendMode::Normal => BlendState::ALPHA_BLENDING,
94 BlendMode::Multiply => BlendState {
95 color: comp(BlendFactor::Dst, BlendFactor::Zero),
96 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
97 },
98 BlendMode::Screen => BlendState {
99 color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
100 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
101 },
102 BlendMode::Add => BlendState {
103 color: comp(BlendFactor::One, BlendFactor::One),
104 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
105 },
106 }
107}
108
109fn stencil_equal_state() -> wgpu::DepthStencilState {
111 let face = wgpu::StencilFaceState {
112 compare: wgpu::CompareFunction::Equal,
113 fail_op: wgpu::StencilOperation::Keep,
114 depth_fail_op: wgpu::StencilOperation::Keep,
115 pass_op: wgpu::StencilOperation::Keep,
116 };
117 wgpu::DepthStencilState {
118 format: STENCIL_FMT,
119 depth_write_enabled: None,
120 depth_compare: None,
121 stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
122 bias: wgpu::DepthBiasState::default(),
123 }
124}
125
126impl Renderer {
127 pub fn shared_resources(&self) -> RendererShared {
129 self.image_cache.borrow_mut().evict_enabled = false;
131 RendererShared {
132 atlas_cache: Rc::clone(&self.atlas_cache),
133 image_cache: Rc::clone(&self.image_cache),
134 rect_pipelines: self.rect_pipelines.clone(),
135 rect_bgl: self.rect_bgl.clone(),
136 text_pipeline: self.text_pipeline.clone(),
137 text_bgl: self.text_bgl.clone(),
138 text_pipeline_mask: self.text_pipeline_mask.clone(),
139 text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
140 tri_pipeline: self.tri_pipeline.clone(),
141 tri_bgl: self.tri_bgl.clone(),
142 tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
143 tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
144 rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
145 text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
146 tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
147 blit_pipeline: self.blit_pipeline.clone(),
148 blit_bgl: self.blit_bgl.clone(),
149 blit_sampler: self.blit_sampler.clone(),
150 backdrop_pipeline: self.backdrop_pipeline.clone(),
151 backdrop_bgl: self.backdrop_bgl.clone(),
152 format: self.format,
153 }
154 }
155
156 pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
158 Self {
159 rect_pipelines: shared.rect_pipelines.clone(),
160 rect_bgl: shared.rect_bgl.clone(),
161 text_pipeline: shared.text_pipeline.clone(),
162 text_bgl: shared.text_bgl.clone(),
163 text_pipeline_mask: shared.text_pipeline_mask.clone(),
164 text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
165 tri_pipeline: shared.tri_pipeline.clone(),
166 tri_bgl: shared.tri_bgl.clone(),
167 tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
168 tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
169 rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
170 text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
171 tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
172 atlas_cache: Rc::clone(&shared.atlas_cache),
173 layer_cache: HashMap::new(),
174 active_layer_ids: std::collections::HashSet::new(),
175 frame_layer_sizes: HashMap::new(),
176 composition_scratch: mgui_core::CompositionScratch::default(),
177 blit_pipeline: shared.blit_pipeline.clone(),
178 blit_bgl: shared.blit_bgl.clone(),
179 blit_sampler: shared.blit_sampler.clone(),
180 backdrop_pipeline: shared.backdrop_pipeline.clone(),
181 backdrop_bgl: shared.backdrop_bgl.clone(),
182 format: shared.format,
183 gpu_profiler: crate::gpu_profiler::mount(device),
184 batch_pools: HashMap::new(),
185 image_cache: Rc::clone(&shared.image_cache),
186 msaa_scratch: HashMap::new(),
187 stencil_scratch: HashMap::new(),
188 snapshot_scratch: HashMap::new(),
189 last_stats: RenderStats::default(),
190 pending_upload: None,
191 }
192 }
193
194 pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
195 let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
201 let text_msaa = pass1_msaa;
205
206 let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
208 label: Some("rect-shader"),
209 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
210 });
211
212 let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
213 label: Some("rect-bgl"),
214 entries: &[
215 wgpu::BindGroupLayoutEntry {
216 binding: 0,
218 visibility: wgpu::ShaderStages::VERTEX,
219 ty: wgpu::BindingType::Buffer {
220 ty: wgpu::BufferBindingType::Uniform,
221 has_dynamic_offset: false,
222 min_binding_size: None,
223 },
224 count: None,
225 },
226 wgpu::BindGroupLayoutEntry {
227 binding: 1,
229 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
230 ty: wgpu::BindingType::Buffer {
231 ty: wgpu::BufferBindingType::Storage { read_only: true },
232 has_dynamic_offset: false,
233 min_binding_size: None,
234 },
235 count: None,
236 },
237 ],
238 });
239
240 let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
241 label: Some("rect-pipeline-layout"),
242 bind_group_layouts: &[Some(&rect_bgl)],
243 immediate_size: 0,
244 });
245
246 const RECT_BLEND_MODES: [BlendMode; 4] =
249 [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
250 let make_rect_pipeline =
251 |label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
252 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
253 label: Some(label),
254 layout: Some(&rect_pipeline_layout),
255 vertex: wgpu::VertexState {
256 module: &rect_shader,
257 entry_point: Some("vs_main"),
258 compilation_options: Default::default(),
259 buffers: &[],
260 },
261 primitive: wgpu::PrimitiveState {
262 topology: wgpu::PrimitiveTopology::TriangleList,
263 ..Default::default()
264 },
265 depth_stencil,
266 multisample: pass1_msaa,
267 fragment: Some(wgpu::FragmentState {
268 module: &rect_shader,
269 entry_point: Some("fs_main"),
270 compilation_options: Default::default(),
271 targets: &[Some(wgpu::ColorTargetState {
272 format,
273 blend: Some(blend),
274 write_mask: wgpu::ColorWrites::ALL,
275 })],
276 }),
277 multiview_mask: None,
278 cache: None,
279 })
280 };
281 let rect_pipelines: [wgpu::RenderPipeline; 4] =
282 std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));
283
284 let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
286 label: Some("text-shader"),
287 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
288 });
289
290 let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
291 label: Some("text-bgl"),
292 entries: &[
293 wgpu::BindGroupLayoutEntry {
294 binding: 0,
296 visibility: wgpu::ShaderStages::VERTEX,
297 ty: wgpu::BindingType::Buffer {
298 ty: wgpu::BufferBindingType::Uniform,
299 has_dynamic_offset: false,
300 min_binding_size: None,
301 },
302 count: None,
303 },
304 wgpu::BindGroupLayoutEntry {
305 binding: 1,
307 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
308 ty: wgpu::BindingType::Buffer {
309 ty: wgpu::BufferBindingType::Storage { read_only: true },
310 has_dynamic_offset: false,
311 min_binding_size: None,
312 },
313 count: None,
314 },
315 wgpu::BindGroupLayoutEntry {
316 binding: 2,
318 visibility: wgpu::ShaderStages::FRAGMENT,
319 ty: wgpu::BindingType::Texture {
320 sample_type: wgpu::TextureSampleType::Float { filterable: true },
321 view_dimension: wgpu::TextureViewDimension::D2,
322 multisampled: false,
323 },
324 count: None,
325 },
326 wgpu::BindGroupLayoutEntry {
327 binding: 3,
329 visibility: wgpu::ShaderStages::FRAGMENT,
330 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
331 count: None,
332 },
333 ],
334 });
335
336 let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
337 label: Some("text-pipeline-layout"),
338 bind_group_layouts: &[Some(&text_bgl)],
339 immediate_size: 0,
340 });
341
342 let mask_blend = wgpu::BlendState {
346 color: wgpu::BlendComponent {
347 src_factor: wgpu::BlendFactor::Zero,
348 dst_factor: wgpu::BlendFactor::One,
349 operation: wgpu::BlendOperation::Add,
350 },
351 alpha: wgpu::BlendComponent {
352 src_factor: wgpu::BlendFactor::Zero,
353 dst_factor: wgpu::BlendFactor::SrcAlpha,
354 operation: wgpu::BlendOperation::Add,
355 },
356 };
357
358 let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
359 label: Some("text-pipeline"),
360 layout: Some(&text_pipeline_layout),
361 vertex: wgpu::VertexState {
362 module: &text_shader,
363 entry_point: Some("vs_main"),
364 compilation_options: Default::default(),
365 buffers: &[],
366 },
367 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
368 depth_stencil: None,
369 multisample: text_msaa,
371 fragment: Some(wgpu::FragmentState {
372 module: &text_shader,
373 entry_point: Some("fs_main"),
374 compilation_options: Default::default(),
375 targets: &[Some(wgpu::ColorTargetState {
376 format,
377 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
378 write_mask: wgpu::ColorWrites::ALL,
379 })],
380 }),
381 multiview_mask: None,
382 cache: None,
383 });
384
385 let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
387 label: Some("text-pipeline-mask"),
388 layout: Some(&text_pipeline_layout),
389 vertex: wgpu::VertexState {
390 module: &text_shader,
391 entry_point: Some("vs_main"),
392 compilation_options: Default::default(),
393 buffers: &[],
394 },
395 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
396 depth_stencil: None,
397 multisample: text_msaa,
398 fragment: Some(wgpu::FragmentState {
399 module: &text_shader,
400 entry_point: Some("fs_main"),
401 compilation_options: Default::default(),
402 targets: &[Some(wgpu::ColorTargetState {
403 format,
404 blend: Some(mask_blend),
405 write_mask: wgpu::ColorWrites::ALL,
406 })],
407 }),
408 multiview_mask: None,
409 cache: None,
410 });
411
412 let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
414 label: Some("tri-shader"),
415 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
416 });
417
418 let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
419 label: Some("tri-bgl"),
420 entries: &[wgpu::BindGroupLayoutEntry {
421 binding: 0,
422 visibility: wgpu::ShaderStages::VERTEX,
423 ty: wgpu::BindingType::Buffer {
424 ty: wgpu::BufferBindingType::Uniform,
425 has_dynamic_offset: false,
426 min_binding_size: None,
427 },
428 count: None,
429 }],
430 });
431
432 let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
433 label: Some("tri-pipeline-layout"),
434 bind_group_layouts: &[Some(&tri_bgl)],
435 immediate_size: 0,
436 });
437
438 let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
439 array_stride: 24,
440 step_mode: wgpu::VertexStepMode::Vertex,
441 attributes: &[
442 wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
443 wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
444 ],
445 })];
446
447 let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
448 label: Some("tri-pipeline"),
449 layout: Some(&tri_pipeline_layout),
450 vertex: wgpu::VertexState {
451 module: &tri_shader,
452 entry_point: Some("vs_main"),
453 compilation_options: Default::default(),
454 buffers: &tri_vb_layouts,
455 },
456 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
457 depth_stencil: None,
458 multisample: pass1_msaa,
459 fragment: Some(wgpu::FragmentState {
460 module: &tri_shader,
461 entry_point: Some("fs_main"),
462 compilation_options: Default::default(),
463 targets: &[Some(wgpu::ColorTargetState {
464 format,
465 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
466 write_mask: wgpu::ColorWrites::ALL,
467 })],
468 }),
469 multiview_mask: None,
470 cache: None,
471 });
472
473 let keep_op = wgpu::StencilOperation::Keep;
477
478 let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
480 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
481 label: Some(label),
482 layout: Some(&tri_pipeline_layout),
483 vertex: wgpu::VertexState {
484 module: &tri_shader,
485 entry_point: Some("vs_main"),
486 compilation_options: Default::default(),
487 buffers: &tri_vb_layouts,
488 },
489 primitive: wgpu::PrimitiveState {
490 topology: wgpu::PrimitiveTopology::TriangleList,
491 ..Default::default()
492 },
493 depth_stencil: Some(wgpu::DepthStencilState {
494 format: STENCIL_FMT,
495 depth_write_enabled: None,
496 depth_compare: None,
497 stencil: wgpu::StencilState {
498 front: wgpu::StencilFaceState {
499 compare: wgpu::CompareFunction::Always,
500 fail_op: keep_op,
501 depth_fail_op: keep_op,
502 pass_op: op,
503 },
504 back: wgpu::StencilFaceState {
505 compare: wgpu::CompareFunction::Always,
506 fail_op: keep_op,
507 depth_fail_op: keep_op,
508 pass_op: op,
509 },
510 read_mask: 0xFF,
511 write_mask: 0xFF,
512 },
513 bias: wgpu::DepthBiasState::default(),
514 }),
515 multisample: pass1_msaa,
516 fragment: Some(wgpu::FragmentState {
517 module: &tri_shader,
518 entry_point: Some("fs_main"),
519 compilation_options: Default::default(),
520 targets: &[Some(wgpu::ColorTargetState {
521 format,
522 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
523 write_mask: wgpu::ColorWrites::empty(), })],
525 }),
526 multiview_mask: None,
527 cache: None,
528 })
529 };
530 let tri_pipeline_stencil_inc =
531 stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
532 let tri_pipeline_stencil_dec =
533 stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);
534
535 let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
537 make_rect_pipeline(
538 "rect-pipeline-stencil-test",
539 blend_state_for(RECT_BLEND_MODES[i]),
540 Some(stencil_equal_state()),
541 )
542 });
543
544 let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
546 label: Some("text-pipeline-stencil-test"),
547 layout: Some(&text_pipeline_layout),
548 vertex: wgpu::VertexState {
549 module: &text_shader,
550 entry_point: Some("vs_main"),
551 compilation_options: Default::default(),
552 buffers: &[],
553 },
554 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
555 depth_stencil: Some(wgpu::DepthStencilState {
556 format: STENCIL_FMT,
557 depth_write_enabled: None,
558 depth_compare: None,
559 stencil: wgpu::StencilState {
560 front: wgpu::StencilFaceState {
561 compare: wgpu::CompareFunction::Equal,
562 fail_op: keep_op,
563 depth_fail_op: keep_op,
564 pass_op: keep_op,
565 },
566 back: wgpu::StencilFaceState {
567 compare: wgpu::CompareFunction::Equal,
568 fail_op: keep_op,
569 depth_fail_op: keep_op,
570 pass_op: keep_op,
571 },
572 read_mask: 0xFF,
573 write_mask: 0,
574 },
575 bias: wgpu::DepthBiasState::default(),
576 }),
577 multisample: text_msaa,
578 fragment: Some(wgpu::FragmentState {
579 module: &text_shader,
580 entry_point: Some("fs_main"),
581 compilation_options: Default::default(),
582 targets: &[Some(wgpu::ColorTargetState {
583 format,
584 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
585 write_mask: wgpu::ColorWrites::ALL,
586 })],
587 }),
588 multiview_mask: None,
589 cache: None,
590 });
591
592 let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
594 label: Some("text-pipeline-mask-stencil-test"),
595 layout: Some(&text_pipeline_layout),
596 vertex: wgpu::VertexState {
597 module: &text_shader,
598 entry_point: Some("vs_main"),
599 compilation_options: Default::default(),
600 buffers: &[],
601 },
602 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
603 depth_stencil: Some(wgpu::DepthStencilState {
604 format: STENCIL_FMT,
605 depth_write_enabled: None,
606 depth_compare: None,
607 stencil: wgpu::StencilState {
608 front: wgpu::StencilFaceState {
609 compare: wgpu::CompareFunction::Equal,
610 fail_op: keep_op,
611 depth_fail_op: keep_op,
612 pass_op: keep_op,
613 },
614 back: wgpu::StencilFaceState {
615 compare: wgpu::CompareFunction::Equal,
616 fail_op: keep_op,
617 depth_fail_op: keep_op,
618 pass_op: keep_op,
619 },
620 read_mask: 0xFF,
621 write_mask: 0,
622 },
623 bias: wgpu::DepthBiasState::default(),
624 }),
625 multisample: text_msaa,
626 fragment: Some(wgpu::FragmentState {
627 module: &text_shader,
628 entry_point: Some("fs_main"),
629 compilation_options: Default::default(),
630 targets: &[Some(wgpu::ColorTargetState {
631 format,
632 blend: Some(mask_blend),
633 write_mask: wgpu::ColorWrites::ALL,
634 })],
635 }),
636 multiview_mask: None,
637 cache: None,
638 });
639
640 let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
642 label: Some("tri-pipeline-stencil-test"),
643 layout: Some(&tri_pipeline_layout),
644 vertex: wgpu::VertexState {
645 module: &tri_shader,
646 entry_point: Some("vs_main"),
647 compilation_options: Default::default(),
648 buffers: &tri_vb_layouts,
649 },
650 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
651 depth_stencil: Some(wgpu::DepthStencilState {
652 format: STENCIL_FMT,
653 depth_write_enabled: None,
654 depth_compare: None,
655 stencil: wgpu::StencilState {
656 front: wgpu::StencilFaceState {
657 compare: wgpu::CompareFunction::Equal,
658 fail_op: keep_op,
659 depth_fail_op: keep_op,
660 pass_op: keep_op,
661 },
662 back: wgpu::StencilFaceState {
663 compare: wgpu::CompareFunction::Equal,
664 fail_op: keep_op,
665 depth_fail_op: keep_op,
666 pass_op: keep_op,
667 },
668 read_mask: 0xFF,
669 write_mask: 0,
670 },
671 bias: wgpu::DepthBiasState::default(),
672 }),
673 multisample: pass1_msaa,
674 fragment: Some(wgpu::FragmentState {
675 module: &tri_shader,
676 entry_point: Some("fs_main"),
677 compilation_options: Default::default(),
678 targets: &[Some(wgpu::ColorTargetState {
679 format,
680 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
681 write_mask: wgpu::ColorWrites::ALL,
682 })],
683 }),
684 multiview_mask: None,
685 cache: None,
686 });
687
688 let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
690 label: Some("blit-shader"),
691 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
692 });
693 let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
694 label: Some("blit-bgl"),
695 entries: &[
696 wgpu::BindGroupLayoutEntry {
697 binding: 0,
698 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
699 ty: wgpu::BindingType::Buffer {
700 ty: wgpu::BufferBindingType::Uniform,
701 has_dynamic_offset: false,
702 min_binding_size: None,
703 },
704 count: None,
705 },
706 wgpu::BindGroupLayoutEntry {
707 binding: 1,
708 visibility: wgpu::ShaderStages::FRAGMENT,
709 ty: wgpu::BindingType::Texture {
710 sample_type: wgpu::TextureSampleType::Float { filterable: true },
711 view_dimension: wgpu::TextureViewDimension::D2,
712 multisampled: false,
713 },
714 count: None,
715 },
716 wgpu::BindGroupLayoutEntry {
717 binding: 2,
718 visibility: wgpu::ShaderStages::FRAGMENT,
719 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
720 count: None,
721 },
722 ],
723 });
724 let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
725 label: Some("blit-pipeline-layout"),
726 bind_group_layouts: &[Some(&blit_bgl)],
727 immediate_size: 0,
728 });
729 let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
730 label: Some("blit-pipeline"),
731 layout: Some(&blit_pipeline_layout),
732 vertex: wgpu::VertexState {
733 module: &blit_shader,
734 entry_point: Some("vs_main"),
735 compilation_options: Default::default(),
736 buffers: &[],
737 },
738 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
739 depth_stencil: None,
740 multisample: wgpu::MultisampleState::default(),
742 fragment: Some(wgpu::FragmentState {
743 module: &blit_shader,
744 entry_point: Some("fs_main"),
745 compilation_options: Default::default(),
746 targets: &[Some(wgpu::ColorTargetState {
747 format,
748 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
749 write_mask: wgpu::ColorWrites::ALL,
750 })],
751 }),
752 multiview_mask: None,
753 cache: None,
754 });
755 let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
757 label: Some("backdrop-shader"),
758 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
759 });
760 let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
761 label: Some("backdrop-bgl"),
762 entries: &[
763 wgpu::BindGroupLayoutEntry {
764 binding: 0,
765 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
766 ty: wgpu::BindingType::Buffer {
767 ty: wgpu::BufferBindingType::Uniform,
768 has_dynamic_offset: false,
769 min_binding_size: None,
770 },
771 count: None,
772 },
773 wgpu::BindGroupLayoutEntry {
774 binding: 1,
775 visibility: wgpu::ShaderStages::FRAGMENT,
776 ty: wgpu::BindingType::Texture {
777 sample_type: wgpu::TextureSampleType::Float { filterable: true },
778 view_dimension: wgpu::TextureViewDimension::D2,
779 multisampled: false,
780 },
781 count: None,
782 },
783 wgpu::BindGroupLayoutEntry {
784 binding: 2,
785 visibility: wgpu::ShaderStages::FRAGMENT,
786 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
787 count: None,
788 },
789 ],
790 });
791 let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
792 label: Some("backdrop-pipeline-layout"),
793 bind_group_layouts: &[Some(&backdrop_bgl)],
794 immediate_size: 0,
795 });
796 let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
797 label: Some("backdrop-pipeline"),
798 layout: Some(&backdrop_pipeline_layout),
799 vertex: wgpu::VertexState {
800 module: &backdrop_shader,
801 entry_point: Some("vs_main"),
802 compilation_options: Default::default(),
803 buffers: &[],
804 },
805 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
806 depth_stencil: Some(stencil_equal_state()),
808 multisample: pass1_msaa,
809 fragment: Some(wgpu::FragmentState {
810 module: &backdrop_shader,
811 entry_point: Some("fs_main"),
812 compilation_options: Default::default(),
813 targets: &[Some(wgpu::ColorTargetState {
814 format,
815 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
816 write_mask: wgpu::ColorWrites::ALL,
817 })],
818 }),
819 multiview_mask: None,
820 cache: None,
821 });
822
823 let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
824 address_mode_u: wgpu::AddressMode::ClampToEdge,
825 address_mode_v: wgpu::AddressMode::ClampToEdge,
826 address_mode_w: wgpu::AddressMode::ClampToEdge,
827 mag_filter: wgpu::FilterMode::Linear,
828 min_filter: wgpu::FilterMode::Linear,
829 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
830 ..Default::default()
831 });
832
833 Self {
834 rect_pipelines,
835 rect_bgl,
836 text_pipeline,
837 text_bgl,
838 text_pipeline_mask,
839 text_pipeline_mask_stencil_test,
840 tri_pipeline,
841 tri_bgl,
842 tri_pipeline_stencil_inc,
843 tri_pipeline_stencil_dec,
844 rect_pipelines_stencil_test,
845 text_pipeline_stencil_test,
846 tri_pipeline_stencil_test,
847 atlas_cache: Rc::new(RefCell::new(None)),
848 layer_cache: HashMap::new(),
849 blit_pipeline,
850 blit_bgl,
851 blit_sampler,
852 backdrop_pipeline,
853 backdrop_bgl,
854 format,
858 active_layer_ids: std::collections::HashSet::new(),
860 frame_layer_sizes: HashMap::new(),
861 composition_scratch: mgui_core::CompositionScratch::default(),
862 gpu_profiler: crate::gpu_profiler::mount(device),
865 batch_pools: HashMap::new(),
867 image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
868 msaa_scratch: HashMap::new(),
869 stencil_scratch: HashMap::new(),
870 snapshot_scratch: HashMap::new(),
871 last_stats: RenderStats::default(),
872 pending_upload: None,
873 }
874 }
875
876 pub(crate) fn ensure_atlas(
882 &mut self,
883 device: &wgpu::Device,
884 queue: &wgpu::Queue,
885 ) -> (wgpu::TextureView, wgpu::Sampler) {
886 let snap = crate::text::atlas_snapshot();
887 let mut atlas_cache = self.atlas_cache.borrow_mut();
888
889 let need_recreate = match atlas_cache.as_ref() {
890 None => true,
891 Some(c) => c.cached_size != (snap.width, snap.height),
892 };
893
894 if need_recreate {
895 log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
896 let (dy0, dy1) = snap.dirty_y;
898 let rows = dy1.saturating_sub(dy0);
899 let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
900 let texture = device.create_texture(&wgpu::TextureDescriptor {
901 label: Some("glyph-atlas"),
902 size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
903 mip_level_count: 1,
904 sample_count: 1,
905 dimension: wgpu::TextureDimension::D2,
906 format: wgpu::TextureFormat::R8Unorm,
907 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
908 view_formats: &[],
909 });
910 if rows > 0 && !pixels.is_empty() {
911 queue.write_texture(
912 wgpu::TexelCopyTextureInfo {
913 texture: &texture,
914 mip_level: 0,
915 origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
916 aspect: wgpu::TextureAspect::All,
917 },
918 pixels,
919 wgpu::TexelCopyBufferLayout {
920 offset: 0,
921 bytes_per_row: Some(snap.width),
922 rows_per_image: Some(rows),
923 },
924 wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
925 );
926 }
927 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
928 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
929 address_mode_u: wgpu::AddressMode::ClampToEdge,
930 address_mode_v: wgpu::AddressMode::ClampToEdge,
931 address_mode_w: wgpu::AddressMode::ClampToEdge,
932 mag_filter: wgpu::FilterMode::Linear,
933 min_filter: wgpu::FilterMode::Linear,
934 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
935 ..Default::default()
936 });
937 *atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
938 } else if snap.dirty {
939 let (dy0, dy1) = snap.dirty_y;
940 let rows = dy1.saturating_sub(dy0);
941 log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
942 if rows > 0 {
944 if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
945 queue.write_texture(
946 wgpu::TexelCopyTextureInfo {
947 texture: &cache.texture,
948 mip_level: 0,
949 origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
950 aspect: wgpu::TextureAspect::All,
951 },
952 pixels,
953 wgpu::TexelCopyBufferLayout {
954 offset: 0,
955 bytes_per_row: Some(snap.width),
956 rows_per_image: Some(rows),
957 },
958 wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
959 );
960 }
961 }
962 }
963
964 if snap.dirty {
966 crate::text::atlas_clear_dirty();
967 }
968
969 let atlas = atlas_cache.as_ref().expect("atlas cache populated");
970 (atlas.view.clone(), atlas.sampler.clone())
971 }
972
973 pub(crate) fn ensure_all_layer_caches(
1006 &mut self,
1007 device: &wgpu::Device,
1008 layer_paints: &[LayerPaint],
1009 dpr: f32,
1010 screen_size: (f32, f32),
1011 ) {
1012 let max_dim = device.limits().max_texture_dimension_2d.max(1);
1013 let (targets, scale) =
1014 layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
1015 if scale < 0.999 {
1016 log::debug!(
1017 target: "mgui_profile",
1018 "layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
1019 targets.len(),
1020 scale * 100.0
1021 );
1022 }
1023
1024 for (layer_id, tex_size) in targets {
1025 let need_create = match self.layer_cache.get(&layer_id) {
1028 None => true,
1029 Some(c) => c.cached_size != tex_size,
1030 };
1031 if need_create {
1032 let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
1033 label: Some("layer-resolve"),
1034 size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
1035 mip_level_count: 1,
1036 sample_count: 1,
1037 dimension: wgpu::TextureDimension::D2,
1038 format: self.format,
1039 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
1041 | wgpu::TextureUsages::TEXTURE_BINDING
1042 | wgpu::TextureUsages::COPY_SRC,
1043 view_formats: &[],
1044 });
1045 let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
1046 self.layer_cache.insert(
1047 layer_id,
1048 LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size },
1049 );
1050 }
1051 }
1052 }
1053
1054 pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1056 if let Some(v) = self.msaa_scratch.get(&size) {
1057 return v.clone();
1058 }
1059 let tex = device.create_texture(&wgpu::TextureDescriptor {
1060 label: Some("scratch-msaa"),
1061 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1062 mip_level_count: 1,
1063 sample_count: 4,
1064 dimension: wgpu::TextureDimension::D2,
1065 format: self.format,
1066 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1067 view_formats: &[],
1068 });
1069 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1070 self.msaa_scratch.insert(size, view.clone());
1071 view
1072 }
1073
1074 pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1076 if let Some(v) = self.stencil_scratch.get(&size) {
1077 return v.clone();
1078 }
1079 let tex = device.create_texture(&wgpu::TextureDescriptor {
1080 label: Some("scratch-stencil"),
1081 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1082 mip_level_count: 1,
1083 sample_count: 4,
1084 dimension: wgpu::TextureDimension::D2,
1085 format: wgpu::TextureFormat::Stencil8,
1086 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1087 view_formats: &[],
1088 });
1089 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1090 self.stencil_scratch.insert(size, view.clone());
1091 view
1092 }
1093
1094 pub(super) fn snapshot_scratch(
1096 &mut self,
1097 device: &wgpu::Device,
1098 size: (u32, u32),
1099 ) -> (wgpu::Texture, wgpu::TextureView) {
1100 if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
1101 return (tex.clone(), view.clone());
1102 }
1103 let tex = device.create_texture(&wgpu::TextureDescriptor {
1104 label: Some("scratch-snapshot"),
1105 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1106 mip_level_count: 1,
1107 sample_count: 1,
1108 dimension: wgpu::TextureDimension::D2,
1109 format: self.format,
1110 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1111 view_formats: &[],
1112 });
1113 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1114 self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
1115 (tex, view)
1116 }
1117
1118 }
1122
1123#[cfg(test)]
1129pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
1130 let comp = LayerComposition::single(lp, *layer_logical_size);
1131 build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
1132}
1133
1134pub(crate) fn build_blit_uniform_composed(
1139 lp: &LayerPaint,
1140 comp: &LayerComposition,
1141 layer_logical_size: &Size,
1142 screen_size: (f32, f32),
1143) -> BlitUniform {
1144 let mut flags: u32 = 0;
1145 let mut rotation = 0.0_f32;
1146 let mut scale_x = 1.0_f32;
1147 let mut scale_y = 1.0_f32;
1148 let mut translate_x = 0.0_f32;
1149 let mut translate_y = 0.0_f32;
1150 let mut clip_radius = 0.0_f32;
1151
1152 match lp.effect {
1153 LayerEffect::None => {}
1154 LayerEffect::Transform(t) => {
1155 if !t.is_identity() {
1156 flags |= effect_flags::HAS_TRANSFORM;
1157 }
1158 rotation = t.rotation;
1159 scale_x = t.scale_x;
1160 scale_y = t.scale_y;
1161 translate_x = t.translate.x;
1162 translate_y = t.translate.y;
1163 }
1164 LayerEffect::Opacity(_) => {}
1165 LayerEffect::ClipRRect(RRectDef { radius }) => {
1166 clip_radius = radius;
1167 }
1168 }
1169 if comp.opacity < 1.0 {
1170 flags |= effect_flags::HAS_OPACITY;
1171 }
1172 if !comp.clips.is_empty() {
1173 flags |= effect_flags::HAS_CLIP;
1174 }
1175
1176 let w = layer_logical_size.width;
1177 let h = layer_logical_size.height;
1178 let mut clip_rect0 = [0.0; 4];
1179 let mut clip_rect1 = [0.0; 4];
1180 let mut clip_params = [0.0; 4];
1181 if let Some(c) = comp.clips.first() {
1182 clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1183 clip_params[0] = c.radius;
1184 }
1185 if let Some(c) = comp.clips.get(1) {
1186 clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1187 clip_params[1] = c.radius;
1188 }
1189 clip_params[2] = comp.clips.len().min(2) as f32;
1190
1191 BlitUniform {
1192 offset: [lp.offset.x, lp.offset.y],
1193 size: [w, h],
1194 screen: [screen_size.0, screen_size.1],
1195 effect_flags: flags,
1196 opacity: comp.opacity,
1197 rotation,
1198 scale_x,
1199 translate_x,
1200 translate_y,
1201 clip_radius,
1202 scale_y,
1203 quad_offset: [lp.offset.x, lp.offset.y],
1204 quad_size: [w, h],
1205 phys_screen: [0.0, 0.0],
1207 affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
1208 affine_translate: [comp.affine.tx, comp.affine.ty],
1209 _affine_pad: [0.0; 2],
1210 clip_rect0,
1211 clip_rect1,
1212 clip_params,
1213 }
1214}