1pub use ::wgpu;
11
12mod atlas;
13mod offscreen;
14mod pipeline;
15mod window;
16
17pub use offscreen::WgpuOffscreenRenderer;
18pub use pipeline::WgpuRenderer;
19pub use window::{PreparedWgpuContext, WgpuWindowRenderer};
20
21use core::future::Future;
22use core::pin::pin;
23use core::task::{Context, Poll, Waker};
24use std::sync::{Arc, Condvar, Mutex};
25use std::task::Wake;
26use std::vec::Vec;
27
28use crate::motion::{DrawOp, DrawPayload};
29use crate::renderers::software::compute_unoccluded_clip;
30use crate::solver::Region;
31use crate::style::Color;
32
33#[repr(C)]
35#[derive(Copy, Clone, Debug, Default, PartialEq)]
36pub struct GpuPrimitive {
37 pub bounds: [f32; 4],
39 pub clip: [f32; 4],
41 pub uv: [f32; 4],
43 pub color0: [f32; 4],
45 pub color1: [f32; 4],
47 pub border_color: [f32; 4],
49 pub params: [f32; 4],
53 pub extra: [f32; 4],
55}
56
57pub(crate) const KIND_QUAD: f32 = 0.0;
58pub(crate) const KIND_SHADOW: f32 = 1.0;
59pub(crate) const KIND_GLYPH: f32 = 2.0;
60pub(crate) const KIND_SPRITE: f32 = 3.0;
61pub(crate) const KIND_ARC: f32 = 4.0;
62
63#[repr(C)]
64#[derive(Copy, Clone, Debug, Default)]
65pub(crate) struct ViewportUniform {
66 pub(crate) size: [f32; 2],
67 pub(crate) is_srgb: f32,
68 pub(crate) _pad: f32,
69}
70
71#[inline]
72pub(crate) fn pod_as_bytes<T: Copy>(slice: &[T]) -> &[u8] {
73 unsafe {
74 core::slice::from_raw_parts(
75 slice.as_ptr() as *const u8,
76 core::mem::size_of_val(slice),
77 )
78 }
79}
80
81#[inline(always)]
82pub(crate) fn color_to_f32(c: Color) -> [f32; 4] {
83 const INV: f32 = 1.0 / 255.0;
84 [
85 (c.r() as f32) * INV,
86 (c.g() as f32) * INV,
87 (c.b() as f32) * INV,
88 (c.a() as f32) * INV,
89 ]
90}
91
92#[inline]
93#[allow(clippy::too_many_arguments)]
94pub(crate) fn make_quad_primitive(
95 bounds: [f32; 4],
96 clip: [f32; 4],
97 clip_radius: f32,
98 corner_radius: f32,
99 border_width: f32,
100 horiz_grad: bool,
101 bg: Color,
102 bg_grad: Color,
103 border_color: Color,
104) -> GpuPrimitive {
105 GpuPrimitive {
106 bounds,
107 clip,
108 uv: [0.0; 4],
109 color0: color_to_f32(bg),
110 color1: color_to_f32(bg_grad),
111 border_color: color_to_f32(border_color),
112 params: [
113 corner_radius,
114 border_width,
115 KIND_QUAD,
116 if horiz_grad { 1.0 } else { 0.0 },
117 ],
118 extra: [clip_radius, 0.0, 0.0, 0.0],
119 }
120}
121
122#[inline]
123pub(crate) fn make_shadow_primitive(
124 bounds: [f32; 4],
125 clip: [f32; 4],
126 clip_radius: f32,
127 corner_radius: f32,
128 blur_radius: f32,
129 color: Color,
130) -> GpuPrimitive {
131 GpuPrimitive {
132 bounds,
133 clip,
134 uv: [0.0; 4],
135 color0: color_to_f32(color),
136 color1: [0.0; 4],
137 border_color: [0.0; 4],
138 params: [corner_radius, blur_radius, KIND_SHADOW, 0.0],
139 extra: [clip_radius, 0.0, 0.0, 0.0],
140 }
141}
142
143#[inline]
144#[allow(clippy::too_many_arguments)]
145pub(crate) fn make_arc_primitive(
146 bounds: [f32; 4],
147 clip: [f32; 4],
148 clip_radius: f32,
149 thickness_px: f32,
150 start_deg10: u16,
151 sweep_deg10: u16,
152 fill_sweep_deg10: u16,
153 track_color: Color,
154 fill_color: Color,
155) -> GpuPrimitive {
156 const DEG10_TO_RAD: f32 = core::f32::consts::PI / 1800.0;
157 let start_rad = ((start_deg10 % 3600) as f32) * DEG10_TO_RAD;
158 let sweep_rad = (sweep_deg10.clamp(20, 3590) as f32) * DEG10_TO_RAD;
159 let fill_rad = (fill_sweep_deg10.min(sweep_deg10) as f32) * DEG10_TO_RAD;
160 GpuPrimitive {
161 bounds,
162 clip,
163 uv: [start_rad, sweep_rad, fill_rad, thickness_px],
164 color0: color_to_f32(track_color),
165 color1: color_to_f32(fill_color),
166 border_color: [0.0; 4],
167 params: [0.0, 0.0, KIND_ARC, 0.0],
168 extra: [clip_radius, 0.0, 0.0, 0.0],
169 }
170}
171
172#[inline(always)]
177pub(crate) fn snap_bounds(r: Region, scale: f32) -> [f32; 4] {
178 let x0 = ((r.x as f32) * scale).round();
179 let y0 = ((r.y as f32) * scale).round();
180 let w = if r.w == 1 {
181 scale.round().max(1.0)
182 } else {
183 (((r.right() as f32) * scale).round() - x0).max(0.0)
184 };
185 let h = if r.h == 1 {
186 scale.round().max(1.0)
187 } else {
188 (((r.bottom() as f32) * scale).round() - y0).max(0.0)
189 };
190 [x0, y0, w, h]
191}
192
193#[inline(always)]
195pub(crate) fn snap_clip(r: Region, scale: f32) -> [f32; 4] {
196 [
197 ((r.x as f32) * scale).round(),
198 ((r.y as f32) * scale).round(),
199 ((r.right() as f32) * scale).round(),
200 ((r.bottom() as f32) * scale).round(),
201 ]
202}
203
204pub(crate) fn create_wgpu_instance(backends: ::wgpu::Backends) -> ::wgpu::Instance {
207 let mut backend_options = ::wgpu::BackendOptions::from_env_or_default();
208 #[cfg(target_os = "windows")]
209 if ::wgpu::Dx12Compiler::from_env().is_none() {
210 backend_options.dx12.shader_compiler = ::wgpu::Dx12Compiler::Fxc;
211 }
212 ::wgpu::Instance::new(::wgpu::InstanceDescriptor {
213 backends,
214 flags: ::wgpu::InstanceFlags::empty().with_env(),
215 backend_options,
216 memory_budget_thresholds: ::wgpu::MemoryBudgetThresholds::default(),
217 display: None,
218 })
219}
220
221pub(crate) fn block_on<F: Future>(fut: F) -> F::Output {
223 struct ThreadSignal {
224 ready: Mutex<bool>,
225 cv: Condvar,
226 }
227 impl Wake for ThreadSignal {
228 fn wake(self: Arc<Self>) {
229 self.wake_by_ref();
230 }
231 fn wake_by_ref(self: &Arc<Self>) {
232 if let Ok(mut guard) = self.ready.lock() {
233 *guard = true;
234 self.cv.notify_one();
235 }
236 }
237 }
238
239 let signal = Arc::new(ThreadSignal {
240 ready: Mutex::new(false),
241 cv: Condvar::new(),
242 });
243 let waker = Waker::from(signal.clone());
244 let mut cx = Context::from_waker(&waker);
245 let mut fut = pin!(fut);
246 loop {
247 match fut.as_mut().poll(&mut cx) {
248 Poll::Ready(out) => return out,
249 Poll::Pending => {
250 if let Ok(mut guard) = signal.ready.lock() {
251 while !*guard {
252 guard = match signal.cv.wait(guard) {
253 Ok(g) => g,
254 Err(poisoned) => poisoned.into_inner(),
255 };
256 }
257 *guard = false;
258 }
259 }
260 }
261 }
262}
263
264#[derive(Clone, Debug, Default)]
266pub struct WgpuScene {
267 pub primitives: Vec<GpuPrimitive>,
268 pub quad_count: usize,
269 pub shadow_count: usize,
270 pub text_run_count: usize,
271 pub sprite_count: usize,
272 pub arc_count: usize,
273}
274
275impl WgpuScene {
276 pub fn new() -> Self {
277 Self::default()
278 }
279
280 pub fn clear(&mut self) {
281 self.primitives.clear();
282 self.quad_count = 0;
283 self.shadow_count = 0;
284 self.text_run_count = 0;
285 self.sprite_count = 0;
286 self.arc_count = 0;
287 }
288
289 pub fn record_draw_ops(
291 &mut self,
292 ops: &[DrawOp<'_>],
293 dpi_scale: i16,
294 dirty_regions: &[Region],
295 ) -> usize {
296 self.clear();
297 if dirty_regions.is_empty() {
298 return 0;
299 }
300 let s = (dpi_scale.max(1)) as f32;
301 for &dirty in dirty_regions {
302 if dirty.is_empty() {
303 continue;
304 }
305 for (idx, op) in ops.iter().enumerate() {
306 let raw_clip = dirty.intersect(op.clip).intersect(op.bounds);
307 if raw_clip.is_empty() {
308 continue;
309 }
310 let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
311 if eff_clip.is_empty() {
312 continue;
313 }
314 let sb = snap_bounds(op.bounds, s);
315 let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
316 let sc = snap_clip(clip_region, s);
317 let cr = (op.clip_radius as f32) * s;
318 match op.payload {
319 DrawPayload::Quad {
320 bg,
321 bg_grad,
322 border_color,
323 rounded,
324 border_width,
325 } => {
326 let bw = ((border_width & 0x7F) as f32) * s;
327 let horiz = (border_width & 0x80) != 0;
328 let r = (rounded as f32) * s;
329 let is_shadow = border_color.a() == 0 && (border_width & 0x7F) > 0;
330 if is_shadow {
331 if bg.a() > 0 {
332 self.shadow_count += 1;
333 self.primitives
334 .push(make_shadow_primitive(sb, sc, cr, r, bw, bg));
335 }
336 } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0)
337 {
338 self.quad_count += 1;
339 self.primitives.push(make_quad_primitive(
340 sb,
341 sc,
342 cr,
343 r,
344 bw,
345 horiz,
346 bg,
347 bg_grad,
348 border_color,
349 ));
350 }
351 }
352 DrawPayload::TextRun { text, color, .. } => {
353 if !text.is_empty() && color.a() > 0 {
354 self.text_run_count += 1;
355 }
356 }
357 DrawPayload::Sprite(crate::element::SpriteSource::Arc {
358 thickness,
359 start_deg10,
360 sweep_deg10,
361 fill_sweep_deg10,
362 track_color,
363 fill_color,
364 }) => {
365 self.arc_count += 1;
366 self.primitives.push(make_arc_primitive(
367 sb,
368 sc,
369 cr,
370 (thickness as f32) * s,
371 start_deg10,
372 sweep_deg10,
373 fill_sweep_deg10,
374 track_color,
375 fill_color,
376 ));
377 }
378 DrawPayload::Sprite(_) => {
379 self.sprite_count += 1;
380 }
381 }
382 }
383 }
384 self.primitives.len() + self.text_run_count + self.sprite_count
385 }
386}