1pub use ::wgpu;
11
12mod atlas;
13mod canvas_pipeline;
14#[cfg(feature = "custom-shader")]
15pub mod custom_shader;
16mod effects_pass;
17pub mod interop;
18mod layer_pool;
19mod offscreen;
20mod pipeline;
21mod pso_cache;
22mod ramp;
23mod shared_exporter;
24mod slug_glyph;
25mod window;
26
27#[cfg(feature = "custom-shader")]
28pub use custom_shader::{
29 register_custom_shader, unregister_custom_shader, CustomShaderPrimitive, CustomShaderViewport,
30};
31pub use interop::{ExportedHandle, ExternalSyncHandle};
32pub use offscreen::WgpuOffscreenRenderer;
33pub use pipeline::{WgpuMemoryStats, WgpuRenderer};
34pub use shared_exporter::{SharedFrameLease, SharedSlot, WgpuSharedExportRenderer};
35pub use window::{PreparedWgpuContext, SurfacePresentOutcome, WgpuWindowRenderer};
36
37use core::future::Future;
38use core::pin::pin;
39use core::task::{Context, Poll, Waker};
40use std::sync::{Arc, Condvar, Mutex};
41use std::task::Wake;
42use std::vec::Vec;
43
44use crate::motion::{DrawOp, DrawPayload};
45use crate::renderers::software::{SpatialOcclusionGrid, compute_unoccluded_clip, with_spatial_occlusion};
46use crate::solver::Region;
47use crate::style::Color;
48
49#[repr(C)]
51#[derive(Copy, Clone, Debug, Default, PartialEq)]
52pub struct GpuPrimitive {
53 pub bounds: [f32; 4],
55 pub clip: [f32; 4],
57 pub uv: [f32; 4],
59 pub color0: [f32; 4],
61 pub color1: [f32; 4],
63 pub border_color: [f32; 4],
65 pub params: [f32; 4],
69 pub extra: [f32; 4],
71 pub radii: [f32; 4],
73 pub grad_a: [f32; 4],
75 pub grad_b: [f32; 4],
77 pub xform: [f32; 4],
79}
80
81pub(crate) const KIND_QUAD: f32 = 0.0;
82pub(crate) const KIND_SHADOW: f32 = 1.0;
83pub(crate) const KIND_GLYPH: f32 = 2.0;
84pub(crate) const KIND_SPRITE: f32 = 3.0;
85pub(crate) const KIND_ARC: f32 = 4.0;
86pub(crate) const IDENTITY_XFORM: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
87
88#[repr(C)]
89#[derive(Copy, Clone, Debug, Default)]
90pub(crate) struct ViewportUniform {
91 pub(crate) size: [f32; 2],
92 pub(crate) is_srgb: f32,
93 pub(crate) _pad: f32,
94}
95
96#[inline]
97pub(crate) fn pod_as_bytes<T: Copy>(slice: &[T]) -> &[u8] {
98 unsafe {
99 core::slice::from_raw_parts(
100 slice.as_ptr() as *const u8,
101 core::mem::size_of_val(slice),
102 )
103 }
104}
105
106#[inline(always)]
107pub(crate) fn color_to_f32(c: Color) -> [f32; 4] {
108 const INV: f32 = 1.0 / 255.0;
109 [
110 (c.r() as f32) * INV,
111 (c.g() as f32) * INV,
112 (c.b() as f32) * INV,
113 (c.a() as f32) * INV,
114 ]
115}
116
117#[inline]
118#[allow(clippy::too_many_arguments)]
119pub(crate) fn make_quad_primitive(
120 bounds: [f32; 4],
121 clip: [f32; 4],
122 clip_radius: f32,
123 corner_radius: f32,
124 border_width: f32,
125 horiz_grad: bool,
126 bg: Color,
127 bg_grad: Color,
128 border_color: Color,
129) -> GpuPrimitive {
130 GpuPrimitive {
131 bounds,
132 clip,
133 uv: [0.0; 4],
134 color0: color_to_f32(bg),
135 color1: color_to_f32(bg_grad),
136 border_color: color_to_f32(border_color),
137 params: [
138 corner_radius,
139 border_width,
140 KIND_QUAD,
141 if horiz_grad { 1.0 } else { 0.0 },
142 ],
143 extra: [clip_radius, 0.0, 0.0, 0.0],
144 radii: [corner_radius; 4],
145 grad_a: [0.0; 4],
146 grad_b: [0.0; 4],
147 xform: IDENTITY_XFORM,
148 }
149}
150
151#[inline]
152pub(crate) fn make_shadow_primitive(
153 bounds: [f32; 4],
154 clip: [f32; 4],
155 clip_radius: f32,
156 corner_radius: f32,
157 blur_radius: f32,
158 color: Color,
159) -> GpuPrimitive {
160 GpuPrimitive {
161 bounds,
162 clip,
163 uv: [0.0; 4],
164 color0: color_to_f32(color),
165 color1: [0.0; 4],
166 border_color: [0.0; 4],
167 params: [corner_radius, blur_radius, KIND_SHADOW, 0.0],
168 extra: [clip_radius, 0.0, 0.0, 0.0],
169 radii: [corner_radius; 4],
170 grad_a: [0.0; 4],
171 grad_b: [0.0; 4],
172 xform: IDENTITY_XFORM,
173 }
174}
175
176#[inline]
177#[allow(clippy::too_many_arguments)]
178pub(crate) fn make_arc_primitive(
179 bounds: [f32; 4],
180 clip: [f32; 4],
181 clip_radius: f32,
182 thickness_px: f32,
183 start_deg10: u16,
184 sweep_deg10: u16,
185 fill_sweep_deg10: u16,
186 track_color: Color,
187 fill_color: Color,
188) -> GpuPrimitive {
189 const DEG10_TO_RAD: f32 = core::f32::consts::PI / 1800.0;
190 let start_rad = ((start_deg10 % 3600) as f32) * DEG10_TO_RAD;
191 let sweep_rad = (sweep_deg10.clamp(20, 3590) as f32) * DEG10_TO_RAD;
192 let fill_rad = (fill_sweep_deg10.min(sweep_deg10) as f32) * DEG10_TO_RAD;
193 GpuPrimitive {
194 bounds,
195 clip,
196 uv: [start_rad, sweep_rad, fill_rad, thickness_px],
197 color0: color_to_f32(track_color),
198 color1: color_to_f32(fill_color),
199 border_color: [0.0; 4],
200 params: [0.0, 0.0, KIND_ARC, 0.0],
201 extra: [clip_radius, 0.0, 0.0, 0.0],
202 radii: [0.0; 4],
203 grad_a: [0.0; 4],
204 grad_b: [0.0; 4],
205 xform: IDENTITY_XFORM,
206 }
207}
208
209#[inline]
211#[allow(clippy::too_many_arguments)]
212pub(crate) fn make_styled_quad_primitive(
213 bounds: [f32; 4],
214 clip: [f32; 4],
215 clip_radius: f32,
216 sq: &crate::paint::StyledQuad<'_>,
217 scale: f32,
218 ramp_v: Option<f32>,
219) -> Option<GpuPrimitive> {
220 let radii = [
221 (sq.radii.tl as f32) * scale,
222 (sq.radii.tr as f32) * scale,
223 (sq.radii.br as f32) * scale,
224 (sq.radii.bl as f32) * scale,
225 ];
226 let bw = if sq.border_width == 0 {
227 0.0
228 } else {
229 ((sq.border_width as f32) * scale).round().max(1.0)
230 };
231 let (xform, tx, ty) = if let Some(t) = sq.transform {
232 if !t.is_identity() {
233 let linear_only = crate::paint::Transform2D::new(t.a, t.b, t.c, t.d, 0.0, 0.0);
234 let inv = linear_only.invert()?;
235 ([inv.a, inv.b, inv.c, inv.d], t.e * scale, t.f * scale)
236 } else {
237 (IDENTITY_XFORM, 0.0, 0.0)
238 }
239 } else {
240 (IDENTITY_XFORM, 0.0, 0.0)
241 };
242
243 let (color0, color1, grad_kind, grad_a, grad_b, extend_f) = match sq.paint {
244 crate::paint::Paint::Solid(c) => {
245 let cf = color_to_f32(c.scale_alpha(sq.opacity));
246 (cf, cf, 0.0, [0.0; 4], [0.0, 0.0, tx, ty], 0.0)
247 }
248 crate::paint::Paint::LinearGradient {
249 start, end, extend, ..
250 } => (
251 [0.0; 4],
252 [0.0; 4],
253 1.0,
254 [start[0], start[1], end[0], end[1]],
255 [0.0, 0.0, tx, ty],
256 extend as u8 as f32,
257 ),
258 crate::paint::Paint::RadialGradient {
259 center,
260 radius,
261 focal,
262 focal_radius,
263 extend,
264 ..
265 } => (
266 [0.0; 4],
267 [0.0; 4],
268 2.0,
269 [center[0], center[1], radius, focal[0]],
270 [focal[1], focal_radius, tx, ty],
271 extend as u8 as f32,
272 ),
273 crate::paint::Paint::ConicGradient {
274 center,
275 start_angle_deg,
276 sweep_deg,
277 extend,
278 ..
279 } => {
280 let start_rad = (start_angle_deg * (core::f32::consts::PI / 180.0))
281 .rem_euclid(core::f32::consts::TAU);
282 let sweep_rad = (sweep_deg.abs().max(1e-3) * (core::f32::consts::PI / 180.0))
283 .min(core::f32::consts::TAU);
284 (
285 [0.0; 4],
286 [0.0; 4],
287 3.0,
288 [center[0], center[1], start_rad, sweep_rad],
289 [0.0, 0.0, tx, ty],
290 extend as u8 as f32,
291 )
292 }
293 };
294
295 Some(GpuPrimitive {
296 bounds,
297 clip,
298 uv: [0.0; 4],
299 color0,
300 color1,
301 border_color: color_to_f32(sq.border_color),
302 params: [sq.radii.max_radius() as f32 * scale, bw, KIND_QUAD, 0.0],
303 extra: [clip_radius, grad_kind, ramp_v.unwrap_or(0.0), extend_f],
304 radii,
305 grad_a,
306 grad_b,
307 xform,
308 })
309}
310
311#[inline(always)]
316pub(crate) fn snap_bounds(r: Region, scale: f32) -> [f32; 4] {
317 let x0 = ((r.x as f32) * scale).round();
318 let y0 = ((r.y as f32) * scale).round();
319 let w = if r.w == 1 {
320 scale.round().max(1.0)
321 } else {
322 (((r.right() as f32) * scale).round() - x0).max(0.0)
323 };
324 let h = if r.h == 1 {
325 scale.round().max(1.0)
326 } else {
327 (((r.bottom() as f32) * scale).round() - y0).max(0.0)
328 };
329 [x0, y0, w, h]
330}
331
332#[inline(always)]
334pub(crate) fn snap_clip(r: Region, scale: f32) -> [f32; 4] {
335 [
336 ((r.x as f32) * scale).round(),
337 ((r.y as f32) * scale).round(),
338 ((r.right() as f32) * scale).round(),
339 ((r.bottom() as f32) * scale).round(),
340 ]
341}
342
343pub(crate) fn create_wgpu_instance(backends: ::wgpu::Backends) -> ::wgpu::Instance {
346 let mut backend_options = ::wgpu::BackendOptions::from_env_or_default();
347 #[cfg(target_os = "windows")]
348 if ::wgpu::Dx12Compiler::from_env().is_none() {
349 backend_options.dx12.shader_compiler = ::wgpu::Dx12Compiler::Fxc;
350 }
351 ::wgpu::Instance::new(::wgpu::InstanceDescriptor {
352 backends,
353 flags: ::wgpu::InstanceFlags::empty().with_env(),
354 backend_options,
355 memory_budget_thresholds: ::wgpu::MemoryBudgetThresholds::default(),
356 display: None,
357 })
358}
359
360pub(crate) fn block_on<F: Future>(fut: F) -> F::Output {
362 struct ThreadSignal {
363 ready: Mutex<bool>,
364 cv: Condvar,
365 }
366 impl Wake for ThreadSignal {
367 fn wake(self: Arc<Self>) {
368 self.wake_by_ref();
369 }
370 fn wake_by_ref(self: &Arc<Self>) {
371 if let Ok(mut guard) = self.ready.lock() {
372 *guard = true;
373 self.cv.notify_one();
374 }
375 }
376 }
377
378 let signal = Arc::new(ThreadSignal {
379 ready: Mutex::new(false),
380 cv: Condvar::new(),
381 });
382 let waker = Waker::from(signal.clone());
383 let mut cx = Context::from_waker(&waker);
384 let mut fut = pin!(fut);
385 loop {
386 match fut.as_mut().poll(&mut cx) {
387 Poll::Ready(out) => return out,
388 Poll::Pending => {
389 if let Ok(mut guard) = signal.ready.lock() {
390 while !*guard {
391 guard = match signal.cv.wait(guard) {
392 Ok(g) => g,
393 Err(poisoned) => poisoned.into_inner(),
394 };
395 }
396 *guard = false;
397 }
398 }
399 }
400 }
401}
402
403#[derive(Clone, Debug, Default)]
405pub struct WgpuScene {
406 pub primitives: Vec<GpuPrimitive>,
407 pub quad_count: usize,
408 pub shadow_count: usize,
409 pub text_run_count: usize,
410 pub sprite_count: usize,
411 pub arc_count: usize,
412}
413
414impl WgpuScene {
415 pub fn new() -> Self {
416 Self::default()
417 }
418
419 pub fn clear(&mut self) {
420 self.primitives.clear();
421 self.quad_count = 0;
422 self.shadow_count = 0;
423 self.text_run_count = 0;
424 self.sprite_count = 0;
425 self.arc_count = 0;
426 }
427
428 pub fn record_draw_ops(
430 &mut self,
431 ops: &[DrawOp<'_>],
432 dpi_scale: i16,
433 dirty_regions: &[Region],
434 ) -> usize {
435 self.clear();
436 if dirty_regions.is_empty() {
437 return 0;
438 }
439 with_spatial_occlusion(ops, |occlusion| {
440 self.record_visible_ops(ops, dpi_scale, dirty_regions, occlusion)
441 })
442 }
443
444 fn record_visible_ops(
445 &mut self,
446 ops: &[DrawOp<'_>],
447 dpi_scale: i16,
448 dirty_regions: &[Region],
449 occlusion: Option<&SpatialOcclusionGrid>,
450 ) -> usize {
451 let s = (dpi_scale.max(1)) as f32;
452 for &dirty in dirty_regions {
453 if dirty.is_empty() {
454 continue;
455 }
456 for (idx, op) in ops.iter().enumerate() {
457 let raw_clip = dirty.intersect(op.clip).intersect(op.bounds);
458 if raw_clip.is_empty() {
459 continue;
460 }
461 let eff_clip = match occlusion {
462 Some(grid) => grid.clip_region(raw_clip, idx),
463 None => compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]),
464 };
465 if eff_clip.is_empty() {
466 continue;
467 }
468 let sb = snap_bounds(op.bounds, s);
469 let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
470 let sc = snap_clip(clip_region, s);
471 let cr = (op.clip_radius as f32) * s;
472 match op.payload {
473 DrawPayload::Quad {
474 bg,
475 bg_grad,
476 border_color,
477 rounded,
478 border_width,
479 } => {
480 let bw = ((border_width & 0x7F) as f32) * s;
481 let horiz = (border_width & 0x80) != 0;
482 let r = (rounded as f32) * s;
483 let is_shadow = border_color.a() == 0 && (border_width & 0x7F) > 0;
484 if is_shadow {
485 if bg.a() > 0 {
486 self.shadow_count += 1;
487 self.primitives
488 .push(make_shadow_primitive(sb, sc, cr, r, bw, bg));
489 }
490 } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0)
491 {
492 self.quad_count += 1;
493 self.primitives.push(make_quad_primitive(
494 sb,
495 sc,
496 cr,
497 r,
498 bw,
499 horiz,
500 bg,
501 bg_grad,
502 border_color,
503 ));
504 }
505 }
506 DrawPayload::TextRun { text, color, .. } => {
507 if !text.is_empty() && color.a() > 0 {
508 self.text_run_count += 1;
509 }
510 }
511 DrawPayload::Sprite(crate::element::SpriteSource::Arc {
512 thickness,
513 start_deg10,
514 sweep_deg10,
515 fill_sweep_deg10,
516 track_color,
517 fill_color,
518 }) => {
519 self.arc_count += 1;
520 self.primitives.push(make_arc_primitive(
521 sb,
522 sc,
523 cr,
524 (thickness as f32) * s,
525 start_deg10,
526 sweep_deg10,
527 fill_sweep_deg10,
528 track_color,
529 fill_color,
530 ));
531 }
532 DrawPayload::Sprite(_) => {
533 self.sprite_count += 1;
534 }
535 DrawPayload::StyledQuad(sq) => {
536 if let Some(prim) = make_styled_quad_primitive(sb, sc, cr, sq, s, None) {
537 self.quad_count += 1;
538 self.primitives.push(prim);
539 }
540 }
541 DrawPayload::PushLayer(_) | DrawPayload::PopLayer => {}
542 DrawPayload::ExternalTexture(_)
543 | DrawPayload::RichText(_)
544 | DrawPayload::DecodedImage(_)
545 | DrawPayload::Vector(_)
546 | DrawPayload::SceneCanvas(_) => {
547 self.sprite_count += 1;
548 }
549 }
550 }
551 }
552 self.primitives.len() + self.text_run_count + self.sprite_count
553 }
554}