Skip to main content

gpui_wgpu/
custom_draw.rs

1//! Backend-owned preparation and composition of independent custom paint sources.
2mod coverage_cache;
3#[cfg(all(unix, feature = "dma-buf"))]
4pub mod dma_buf;
5use anyhow::{Result, ensure};
6pub(crate) use coverage_cache::{CoverageCache, CoverageKey};
7use gpui::{CustomDraw, DevicePixels, Size, size};
8use std::sync::{
9    Arc, Mutex,
10    atomic::{AtomicU8, Ordering},
11};
12#[cfg(test)]
13use wgpu::util::DeviceExt;
14
15const PENDING: u8 = 0;
16const SUBMITTED: u8 = 1;
17const ABANDONED: u8 = 2;
18const STAGED: u8 = 3;
19
20struct Recording {
21    guards: Mutex<Vec<ImageCopyCompletion>>,
22    state: AtomicU8,
23    batch: Option<Arc<()>>,
24    /// GPU-side waits staged with this recording's host submission.
25    #[cfg(all(target_os = "linux", feature = "external-memory"))]
26    waits: Mutex<Vec<(ash::vk::Semaphore, u64)>>,
27}
28impl Recording {
29    fn new(batch: Option<Arc<()>>) -> Self {
30        Self {
31            guards: Mutex::new(Vec::new()),
32            state: AtomicU8::new(PENDING),
33            batch,
34            #[cfg(all(target_os = "linux", feature = "external-memory"))]
35            waits: Mutex::new(Vec::new()),
36        }
37    }
38    fn can_reuse(self: &Arc<Self>, output: &Arc<Self>) -> bool {
39        match output.state.load(Ordering::Acquire) {
40            SUBMITTED => true,
41            PENDING => Arc::ptr_eq(output, self),
42            STAGED => self
43                .batch
44                .as_ref()
45                .zip(output.batch.as_ref())
46                .is_some_and(|(a, b)| Arc::ptr_eq(a, b)),
47            _ => false,
48        }
49    }
50    fn abandon(&self, from: u8) {
51        if self
52            .state
53            .compare_exchange(from, ABANDONED, Ordering::AcqRel, Ordering::Acquire)
54            .is_ok()
55        {
56            self.guards.lock().unwrap().clear();
57        }
58    }
59}
60
61impl std::fmt::Debug for Recording {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("Recording")
64            .field("state", &self.state)
65            .finish()
66    }
67}
68fn release_after_completion(queue: &wgpu::Queue, recording: &Recording) {
69    let guards = std::mem::take(&mut *recording.guards.lock().unwrap());
70    if !guards.is_empty() {
71        #[cfg(not(target_family = "wasm"))]
72        queue.on_submitted_work_done(move || drop(guards));
73        #[cfg(target_family = "wasm")]
74        browser_completions::retain(queue, guards);
75    }
76}
77
78// Browser GPU handles are thread-affine, including in atomic WASM builds.
79// The queue callback accepts Send closures, so only a completion signal crosses
80// that boundary. Retained uploads are destroyed on the thread that adopted them.
81#[cfg(any(target_family = "wasm", test))]
82mod browser_completions {
83    use std::sync::{
84        Arc,
85        atomic::{AtomicBool, Ordering},
86    };
87
88    pub(super) struct Pending<T> {
89        pub(super) done: Arc<AtomicBool>,
90        pub(super) value: T,
91    }
92
93    pub(super) fn take_completed<T>(pending: &mut Vec<Pending<T>>) -> Vec<T> {
94        let mut completed = Vec::new();
95        let mut i = 0;
96        while i < pending.len() {
97            if pending[i].done.load(Ordering::Acquire) {
98                completed.push(pending.swap_remove(i).value);
99            } else {
100                i += 1;
101            }
102        }
103        completed
104    }
105
106    #[cfg(target_family = "wasm")]
107    thread_local! {
108        static PENDING: std::cell::RefCell<Vec<Pending<Vec<super::ImageCopyCompletion>>>> =
109            const { std::cell::RefCell::new(Vec::new()) };
110    }
111
112    #[cfg(target_family = "wasm")]
113    pub(super) fn collect() {
114        // Drop outside the RefCell borrow: admission guards may run user code.
115        let completed = PENDING.with(|pending| take_completed(&mut pending.borrow_mut()));
116        drop(completed);
117    }
118
119    #[cfg(target_family = "wasm")]
120    pub(super) fn retain(queue: &wgpu::Queue, guards: Vec<super::ImageCopyCompletion>) {
121        let done = Arc::new(AtomicBool::new(false));
122        PENDING.with(|pending| {
123            pending.borrow_mut().push(Pending {
124                done: done.clone(),
125                value: guards,
126            })
127        });
128        queue.on_submitted_work_done(move || {
129            done.store(true, Ordering::Release);
130            // Browser callbacks normally run on the submitting thread. If a
131            // backend calls elsewhere, the owner's next preparation collects.
132            collect();
133        });
134    }
135}
136
137struct EncoderState {
138    encoder: Option<wgpu::CommandEncoder>,
139    finished: bool,
140    failed: bool,
141}
142
143/// A batch owns accepted recordings until all paint preparation succeeds.
144/// Dropping an unfinished batch invalidates its staged outputs without submitting.
145pub(crate) struct PreparationBatch {
146    device: Arc<wgpu::Device>,
147    queue: Arc<wgpu::Queue>,
148    id: Arc<()>,
149    pending: Vec<(Option<wgpu::CommandBuffer>, Arc<Recording>)>,
150}
151impl PreparationBatch {
152    pub fn new(device: Arc<wgpu::Device>, queue: &Arc<wgpu::Queue>) -> Self {
153        Self {
154            device,
155            queue: queue.clone(),
156            id: Arc::new(()),
157            pending: Vec::new(),
158        }
159    }
160    /// Run producer preparation and host output validation before staging its work.
161    pub fn prepare<T>(
162        &mut self,
163        prepare: impl FnOnce(&WgpuCustomContext) -> Result<T>,
164    ) -> Result<T> {
165        let context =
166            WgpuCustomContext::with_batch(self.device.clone(), &self.queue, Some(self.id.clone()));
167        let output = prepare(&context)?;
168        let command = context.finish()?;
169        context.recording.state.store(STAGED, Ordering::Release);
170        self.pending.push((command, context.recording.clone()));
171        Ok(output)
172    }
173    pub fn submit(mut self) -> Result<()> {
174        // Staged waits apply to the next queue submission, so stage them here,
175        // immediately before this batch's submit, never during preparation
176        // (preparation may submit native/coverage subframes in between).
177        #[cfg(all(target_os = "linux", feature = "external-memory"))]
178        let waits: Vec<_> = self
179            .pending
180            .iter()
181            .flat_map(|(_, recording)| std::mem::take(&mut *recording.waits.lock().unwrap()))
182            .collect();
183        #[cfg(all(target_os = "linux", feature = "external-memory"))]
184        let has_waits = !waits.is_empty();
185        #[cfg(not(all(target_os = "linux", feature = "external-memory")))]
186        let has_waits = false;
187        #[cfg(all(target_os = "linux", feature = "external-memory"))]
188        if has_waits {
189            let queue = unsafe { self.queue.as_hal::<wgpu::hal::api::Vulkan>() }
190                .ok_or_else(|| anyhow::anyhow!("semaphore waits require the Vulkan backend"))?;
191            for (semaphore, value) in waits {
192                queue.add_wait_semaphore(
193                    semaphore,
194                    Some(value),
195                    ash::vk::PipelineStageFlags::ALL_COMMANDS,
196                );
197            }
198        }
199        if has_waits || self.pending.iter().any(|(command, _)| command.is_some()) {
200            self.queue.submit(
201                self.pending
202                    .iter_mut()
203                    .filter_map(|(command, _)| command.take()),
204            );
205        }
206        for (_, recording) in &self.pending {
207            recording.state.store(SUBMITTED, Ordering::Release);
208            release_after_completion(&self.queue, recording);
209        }
210        Ok(())
211    }
212}
213impl Drop for PreparationBatch {
214    fn drop(&mut self) {
215        for (_, recording) in &self.pending {
216            recording.abandon(STAGED);
217        }
218    }
219}
220
221/// Host-owned recording context. Producers record work; only the renderer submits.
222pub struct WgpuCustomContext {
223    /// Device on which producer pipelines and buffers must be created.
224    pub device: Arc<wgpu::Device>,
225    key: usize,
226    queue: Arc<wgpu::Queue>,
227    encoder: Mutex<EncoderState>,
228    recording: Arc<Recording>,
229}
230
231impl WgpuCustomContext {
232    #[cfg(test)]
233    pub(crate) fn new(device: Arc<wgpu::Device>, queue: &Arc<wgpu::Queue>) -> Self {
234        Self::with_batch(device, queue, None)
235    }
236    fn with_batch(
237        device: Arc<wgpu::Device>,
238        queue: &Arc<wgpu::Queue>,
239        batch: Option<Arc<()>>,
240    ) -> Self {
241        #[cfg(target_family = "wasm")]
242        browser_completions::collect();
243        Self {
244            device,
245            key: Arc::as_ptr(queue) as usize,
246            queue: queue.clone(),
247            encoder: Mutex::new(EncoderState {
248                encoder: None,
249                finished: false,
250                failed: false,
251            }),
252            recording: Arc::new(Recording::new(batch)),
253        }
254    }
255    /// Queue-scoped cache identity; cached output retains the device and queue.
256    pub fn cache_key(&self) -> usize {
257        self.key
258    }
259    /// Allocate a host-device output with straight-alpha encoded-sRGB RGBA8 channels.
260    pub fn create_output(&self, extent: Size<DevicePixels>) -> Result<WgpuCustomOutput> {
261        ensure!(
262            self.recording.state.load(Ordering::Acquire) == PENDING,
263            "custom preparation is no longer writable"
264        );
265        let texture = new_texture(&self.device, extent, wgpu::TextureFormat::Rgba8Unorm)?;
266        Ok(WgpuCustomOutput {
267            texture,
268            source_sized: false,
269            key: self.key,
270            _queue: self.queue.clone(),
271            recording: self.recording.clone(),
272        })
273    }
274    /// Owned worker-safe handles for allocating and filling image staging data.
275    /// The worker cannot submit work on the renderer queue.
276    pub fn image_upload_context(&self) -> WgpuImageUploadContext {
277        WgpuImageUploadContext {
278            device: self.device.clone(),
279            queue: self.queue.clone(),
280        }
281    }
282    /// Synchronous convenience route. Media workers normally stage first and
283    /// call `adopt_image_upload` during host preparation instead.
284    pub fn create_image_output(&self, data: &gpui::ImageTextureData) -> Result<WgpuCustomOutput> {
285        ensure!(
286            self.recording.state.load(Ordering::Acquire) == PENDING,
287            "image preparation is no longer writable"
288        );
289        let staged = self.image_upload_context().stage(data)?;
290        self.adopt_image_upload(&staged)
291    }
292    /// Record copies of already-filled buffers. No texture allocation or pixel
293    /// copying occurs here. A staged image may be adopted again after abandonment.
294    pub fn adopt_image_upload(&self, staged: &WgpuStagedImage) -> Result<WgpuCustomOutput> {
295        self.adopt_image_upload_with_guard(staged, None)
296    }
297    /// Retain an admission lease until GPU completion, or release it when this
298    /// recording is abandoned. Staging resources have their own completion guard.
299    pub fn adopt_image_upload_with_guard(
300        &self,
301        staged: &WgpuStagedImage,
302        guard: Option<Arc<dyn Send + Sync>>,
303    ) -> Result<WgpuCustomOutput> {
304        ensure!(
305            Arc::ptr_eq(&staged.queue, &self.queue),
306            "foreign staged image queue"
307        );
308        ensure!(
309            Arc::ptr_eq(&staged.device, &self.device),
310            "foreign staged image device"
311        );
312        self.record(|encoder| {
313            for (level, mip) in staged.mips.iter().enumerate() {
314                encoder.copy_buffer_to_texture(
315                    wgpu::TexelCopyBufferInfo {
316                        buffer: staged.allocation.resource(),
317                        layout: wgpu::TexelCopyBufferLayout {
318                            offset: mip.offset,
319                            bytes_per_row: Some(mip.row),
320                            rows_per_image: None,
321                        },
322                    },
323                    wgpu::TexelCopyTextureInfo {
324                        texture: &staged.texture,
325                        mip_level: level as u32,
326                        origin: wgpu::Origin3d::ZERO,
327                        aspect: wgpu::TextureAspect::All,
328                    },
329                    wgpu::Extent3d {
330                        width: mip.width,
331                        height: mip.height,
332                        depth_or_array_layers: 1,
333                    },
334                );
335            }
336            Ok(())
337        })?;
338        // Struct fields drop in declaration order: return the source buffer
339        // before releasing admission, so the next admitted worker can check it out.
340        self.recording
341            .guards
342            .lock()
343            .unwrap()
344            .push(ImageCopyCompletion {
345                #[cfg(target_family = "wasm")]
346                _resource: OwnerThread(staged.allocation.clone()),
347                #[cfg(not(target_family = "wasm"))]
348                _resource: staged.allocation.clone(),
349                _admission: guard,
350            });
351        Ok(WgpuCustomOutput {
352            texture: staged.texture.clone(),
353            source_sized: true,
354            key: self.key,
355            _queue: self.queue.clone(),
356            recording: self.recording.clone(),
357        })
358    }
359    /// Adopt a texture created on this context's `device` (for example from
360    /// imported external memory) as a source-sized output.
361    ///
362    /// Accepted: 2D, one mip level/sample/layer, `TEXTURE_BINDING`, and
363    /// `Rgba8Unorm`/`Bgra8Unorm` (straight-alpha encoded sRGB) or `Rgba16Float`
364    /// (associated linear content per the producer's `ImageColorMode`).
365    ///
366    /// # Safety
367    /// `texture` must belong to `self.device`. Its contents must be complete and
368    /// visible to this queue before any command that samples them executes; record
369    /// any required ownership acquire or barrier on this context. The contents must
370    /// not change while this output, a cached copy of it, or a retained scene
371    /// referencing its content can still be sampled.
372    pub unsafe fn adopt_texture(&self, texture: wgpu::Texture) -> Result<WgpuCustomOutput> {
373        ensure!(
374            self.recording.state.load(Ordering::Acquire) == PENDING,
375            "custom preparation is no longer writable"
376        );
377        ensure!(
378            texture.dimension() == wgpu::TextureDimension::D2
379                && texture.mip_level_count() == 1
380                && texture.sample_count() == 1
381                && texture.depth_or_array_layers() == 1
382                && texture.usage().contains(wgpu::TextureUsages::TEXTURE_BINDING),
383            "adopted texture must be a sampleable single-level 2D texture"
384        );
385        ensure!(
386            matches!(
387                texture.format(),
388                wgpu::TextureFormat::Rgba8Unorm
389                    | wgpu::TextureFormat::Bgra8Unorm
390                    | wgpu::TextureFormat::Rgba16Float
391            ),
392            "adopted texture format must be Rgba8Unorm, Bgra8Unorm or Rgba16Float"
393        );
394        ensure!(
395            (1..=16384).contains(&texture.width()) && (1..=16384).contains(&texture.height()),
396            "adopted texture extent must be 1..=16384"
397        );
398        Ok(WgpuCustomOutput {
399            texture,
400            source_sized: true,
401            key: self.key,
402            _queue: self.queue.clone(),
403            recording: self.recording.clone(),
404        })
405    }
406    /// Make the host wait on the GPU, before this preparation's commands and the
407    /// composition that follows, until `semaphore` reaches `value`.
408    ///
409    /// The wait is staged together with the host batch submission, so no other
410    /// submission can consume it. Record an ownership acquire or barrier whose
411    /// first scope includes `ALL_COMMANDS` to order later sampling after it.
412    ///
413    /// # Safety
414    /// `semaphore` must be a timeline semaphore valid on this host device (for
415    /// example imported from another device) that outlives the host submission,
416    /// and work that signals it to at least `value` must already be submitted;
417    /// otherwise host submissions can stall on the CPU or the GPU.
418    #[cfg(all(target_os = "linux", feature = "external-memory"))]
419    pub unsafe fn wait_vulkan_semaphore(
420        &self,
421        semaphore: ash::vk::Semaphore,
422        value: u64,
423    ) -> Result<()> {
424        ensure!(
425            self.recording.state.load(Ordering::Acquire) == PENDING,
426            "custom preparation is no longer writable"
427        );
428        self.recording.waits.lock().unwrap().push((semaphore, value));
429        Ok(())
430    }
431    /// Record preparation commands. Do not submit work or wait on the GPU here.
432    /// An encoding error invalidates this transaction, including commands recorded earlier.
433    pub fn record<T>(
434        &self,
435        encode: impl FnOnce(&mut wgpu::CommandEncoder) -> Result<T>,
436    ) -> Result<T> {
437        let mut state = self
438            .encoder
439            .lock()
440            .map_err(|_| anyhow::anyhow!("custom encoder poisoned"))?;
441        ensure!(
442            !state.finished && !state.failed,
443            "custom preparation already finished or failed"
444        );
445        let encoder = state.encoder.get_or_insert_with(|| {
446            self.device
447                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
448                    label: Some("custom_preparation"),
449                })
450        });
451        let result = encode(encoder);
452        if result.is_err() {
453            state.failed = true;
454            state.encoder.take();
455            self.recording.abandon(PENDING);
456        }
457        result
458    }
459    /// Whether output is submitted, local to this recording, or staged earlier in this host batch.
460    pub fn can_reuse(&self, output: &WgpuCustomOutput) -> bool {
461        output.key == self.key && self.recording.can_reuse(&output.recording)
462    }
463    fn finish(&self) -> Result<Option<wgpu::CommandBuffer>> {
464        let mut state = self
465            .encoder
466            .lock()
467            .map_err(|_| anyhow::anyhow!("custom encoder poisoned"))?;
468        ensure!(
469            !state.finished && !state.failed,
470            "custom preparation already finished or failed"
471        );
472        state.finished = true;
473        Ok(state.encoder.take().map(|encoder| encoder.finish()))
474    }
475    #[cfg(test)]
476    pub(crate) fn submit(&self) -> Result<()> {
477        if let Some(command) = self.finish()? {
478            self.queue.submit([command]);
479        }
480        self.recording.state.store(SUBMITTED, Ordering::Release);
481        release_after_completion(&self.queue, &self.recording);
482        Ok(())
483    }
484}
485
486impl Drop for WgpuCustomContext {
487    fn drop(&mut self) {
488        self.recording.abandon(PENDING);
489    }
490}
491
492/// Worker-owned image allocation context; it exposes no queue submission API.
493#[derive(Clone)]
494pub struct WgpuImageUploadContext {
495    device: Arc<wgpu::Device>,
496    queue: Arc<wgpu::Queue>,
497}
498struct ImageCopyCompletion {
499    // Browser resources stay on their owner thread in browser_completions.
500    // Native queue callbacks move these guards and require Send + Sync.
501    #[cfg(target_family = "wasm")]
502    _resource: OwnerThread,
503    #[cfg(not(target_family = "wasm"))]
504    _resource: Arc<dyn Send + Sync>,
505    _admission: Option<Arc<dyn Send + Sync>>,
506}
507
508/// A browser upload resource (a thread-affine `wgpu::Buffer` allocation) held
509/// until its copy completes; `browser_completions` drops it on the owner thread.
510#[cfg(target_family = "wasm")]
511struct OwnerThread(#[allow(dead_code)] Arc<dyn std::any::Any>);
512
513// SAFETY: wasm32 without the `atomics` target feature has no shared-memory
514// threads, so the resource can never be observed or dropped off its owner
515// thread. This is the condition under which wgpu's own
516// `fragile-send-sync-non-atomic-wasm` treats browser handles as Send + Sync; it
517// keeps `Recording` (and `WgpuCustomOutput`, held by `CustomContent` producers)
518// no less thread-safe than wgpu's own types. Atomic builds get no such impls.
519#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
520unsafe impl Send for OwnerThread {}
521#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
522unsafe impl Sync for OwnerThread {}
523
524// `Recording` must add no thread-affinity of its own wherever wgpu's handles can
525// be Send + Sync: native, and wasm without atomics (#166 regressed this).
526#[cfg(any(not(target_family = "wasm"), not(target_feature = "atomics")))]
527const _: () = {
528    const fn assert_send_sync<T: Send + Sync>() {}
529    assert_send_sync::<ImageCopyCompletion>();
530    assert_send_sync::<Recording>();
531};
532struct StagedMip {
533    offset: u64,
534    row: u32,
535    width: u32,
536    height: u32,
537}
538/// Device-bound cache of exclusive staging buffers. Completion guards prevent
539/// a buffer from returning to the cache while GPU commands still reference it.
540#[derive(Clone)]
541pub struct WgpuImageStagingPool {
542    device: Arc<wgpu::Device>,
543    queue: Arc<wgpu::Queue>,
544    buffers: Arc<gpui::ImageStagingPool<wgpu::Buffer>>,
545}
546impl WgpuImageStagingPool {
547    pub fn stats(&self) -> gpui::ImageStagingPoolStats {
548        self.buffers.stats()
549    }
550}
551/// Immutable worker-filled staging plus a sampleable destination texture.
552pub struct WgpuStagedImage {
553    device: Arc<wgpu::Device>,
554    queue: Arc<wgpu::Queue>,
555    texture: wgpu::Texture,
556    allocation: Arc<gpui::ImageStagingLease<wgpu::Buffer>>,
557    mips: Vec<StagedMip>,
558}
559impl WgpuImageUploadContext {
560    pub fn staging_pool(&self, capacity: usize) -> WgpuImageStagingPool {
561        WgpuImageStagingPool {
562            device: self.device.clone(),
563            queue: self.queue.clone(),
564            buffers: gpui::ImageStagingPool::new(capacity),
565        }
566    }
567    /// Unpooled convenience path; full media images use `stage_with_pool`.
568    pub fn stage(&self, data: &gpui::ImageTextureData) -> Result<WgpuStagedImage> {
569        self.stage_with_pool(data, &self.staging_pool(data.staging_byte_len()))
570    }
571    /// Worker-only pooled staging. Mapping a reused buffer can wait on this
572    /// worker for driver progress; this method must not run on the UI thread.
573    pub fn stage_with_pool(
574        &self,
575        data: &gpui::ImageTextureData,
576        pool: &WgpuImageStagingPool,
577    ) -> Result<WgpuStagedImage> {
578        ensure!(
579            Arc::ptr_eq(&self.device, &pool.device) && Arc::ptr_eq(&self.queue, &pool.queue),
580            "foreign staging pool"
581        );
582        ensure!(
583            data.width().max(data.height()) <= self.device.limits().max_texture_dimension_2d,
584            "image exceeds device texture limits"
585        );
586        #[cfg(target_family = "wasm")]
587        browser_completions::collect();
588        let bytes = data.staging_byte_len();
589        ensure!(
590            bytes as u64 <= self.device.limits().max_buffer_size,
591            "image staging exceeds device buffer limit"
592        );
593        let allocation = pool.buffers.checkout(bytes as u64, bytes, || {
594            Ok(self.device.create_buffer(&wgpu::BufferDescriptor {
595                label: Some("media_staging_pool"),
596                size: bytes as u64,
597                usage: wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC,
598                mapped_at_creation: true,
599            }))
600        })?;
601        let fill = (|| -> Result<Vec<StagedMip>> {
602            let buffer = allocation.resource();
603            if allocation.was_reused() {
604                let (sender, receiver) = std::sync::mpsc::channel();
605                buffer
606                    .slice(..)
607                    .map_async(wgpu::MapMode::Write, move |result| {
608                        let _ = sender.send(result);
609                    });
610                self.device.poll(wgpu::PollType::Wait {
611                    submission_index: None,
612                    timeout: Some(std::time::Duration::from_secs(5)),
613                })?;
614                receiver.recv_timeout(std::time::Duration::from_secs(5))??;
615            }
616            let mut mapped = buffer.slice(..).get_mapped_range_mut()?;
617            let mut mips = Vec::new();
618            let mut offset = 0usize;
619            for (level, pixels) in data.levels().iter().enumerate() {
620                let width = (data.width() >> level).max(1);
621                let height = (data.height() >> level).max(1);
622                let bpp = data.bytes_per_pixel();
623                let row = (width * bpp as u32).div_ceil(256) * 256;
624                for y in 0..height as usize {
625                    mapped
626                        .slice(
627                            offset + y * row as usize
628                                ..offset + y * row as usize + width as usize * bpp,
629                        )
630                        .copy_from_slice(
631                            &pixels[y * width as usize * bpp..(y + 1) * width as usize * bpp],
632                        );
633                }
634                mips.push(StagedMip {
635                    offset: offset as u64,
636                    row,
637                    width,
638                    height,
639                });
640                offset += row as usize * height as usize;
641            }
642            drop(mapped);
643            buffer.unmap();
644            Ok(mips)
645        })();
646        let mips = match fill {
647            Ok(mips) => mips,
648            Err(error) => {
649                allocation.resource().unmap();
650                allocation.discard();
651                return Err(error);
652            }
653        };
654        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
655            label: Some("media_image"),
656            size: wgpu::Extent3d {
657                width: data.width(),
658                height: data.height(),
659                depth_or_array_layers: 1,
660            },
661            mip_level_count: data.levels().len() as u32,
662            sample_count: 1,
663            dimension: wgpu::TextureDimension::D2,
664            format: match data.format() {
665                gpui::ImageTextureFormat::Rgba8Srgb => wgpu::TextureFormat::Rgba8Unorm,
666                gpui::ImageTextureFormat::LinearP3Rgba16Float
667                | gpui::ImageTextureFormat::LinearRec2020Rgba16Float => {
668                    wgpu::TextureFormat::Rgba16Float
669                }
670            },
671            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
672            view_formats: &[],
673        });
674        Ok(WgpuStagedImage {
675            device: self.device.clone(),
676            queue: self.queue.clone(),
677            texture,
678            allocation: Arc::new(allocation),
679            mips,
680        })
681    }
682}
683
684/// Cacheable immutable producer output. Construct through the host context.
685#[derive(Clone, Debug)]
686pub struct WgpuCustomOutput {
687    texture: wgpu::Texture,
688    source_sized: bool,
689    key: usize,
690    _queue: Arc<wgpu::Queue>,
691    recording: Arc<Recording>,
692}
693impl WgpuCustomOutput {
694    /// Host submission has accepted this recording (GPU completion is separate).
695    pub fn is_submitted(&self) -> bool {
696        self.recording.state.load(Ordering::Acquire) == SUBMITTED
697    }
698
699    /// Texture to render into during preparation; immutable after host submission.
700    pub fn texture(&self) -> &wgpu::Texture {
701        &self.texture
702    }
703    pub(crate) fn validate(
704        self,
705        context: &WgpuCustomContext,
706        extent: Size<DevicePixels>,
707    ) -> Result<Self> {
708        ensure!(
709            context.can_reuse(&self),
710            "custom output belongs to another queue or abandoned recording"
711        );
712        ensure!(
713            self.source_sized
714                || (self.texture.width() == extent.width.0 as u32
715                    && self.texture.height() == extent.height.0 as u32),
716            "invalid custom texture extent"
717        );
718        Ok(self)
719    }
720}
721
722pub(crate) fn new_texture(
723    device: &wgpu::Device,
724    extent: Size<DevicePixels>,
725    format: wgpu::TextureFormat,
726) -> Result<wgpu::Texture> {
727    ensure!(
728        extent.width.0 > 0
729            && extent.height.0 > 0
730            && extent.width.0 as u32 <= device.limits().max_texture_dimension_2d
731            && extent.height.0 as u32 <= device.limits().max_texture_dimension_2d
732            && extent.width.0 as u64 * extent.height.0 as u64 * 4 <= 64 * 1024 * 1024,
733        "invalid custom texture extent"
734    );
735    Ok(device.create_texture(&wgpu::TextureDescriptor {
736        label: Some("custom_paint"),
737        size: wgpu::Extent3d {
738            width: extent.width.0 as u32,
739            height: extent.height.0 as u32,
740            depth_or_array_layers: 1,
741        },
742        mip_level_count: 1,
743        sample_count: 1,
744        dimension: wgpu::TextureDimension::D2,
745        format,
746        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
747        view_formats: &[],
748    }))
749}
750
751pub(crate) fn extent(draw: &CustomDraw) -> Result<Size<DevicePixels>> {
752    ensure!(
753        draw.opacity.is_finite() && (0.0..=1.0).contains(&draw.opacity),
754        "invalid custom opacity"
755    );
756    ensure!(
757        [
758            draw.bounds.origin.x.0,
759            draw.bounds.origin.y.0,
760            draw.bounds.size.width.0,
761            draw.bounds.size.height.0,
762            draw.content_mask.bounds.origin.x.0,
763            draw.content_mask.bounds.origin.y.0,
764            draw.content_mask.bounds.size.width.0,
765            draw.content_mask.bounds.size.height.0,
766            draw.corner_radii.top_left.0,
767            draw.corner_radii.top_right.0,
768            draw.corner_radii.bottom_right.0,
769            draw.corner_radii.bottom_left.0
770        ]
771        .iter()
772        .all(|v| v.is_finite()),
773        "non-finite custom geometry"
774    );
775    if let Some(source) = draw.content.image_source_size() {
776        ensure!(
777            draw.coverage.is_none()
778                && draw.bounds.size.width.0.is_finite()
779                && draw.bounds.size.height.0.is_finite()
780                && draw.bounds.size.width.0 > 0.
781                && draw.bounds.size.height.0 > 0.
782                && source.width.0 > 0
783                && source.height.0 > 0
784                && source.width.0 <= 16384
785                && source.height.0 <= 16384,
786            "invalid source-sized image preparation"
787        );
788        return Ok(source);
789    }
790    ensure!(
791        draw.bounds.size.width.0 > 0.
792            && draw.bounds.size.height.0 > 0.
793            && draw.bounds.size.width.0 <= 16384.
794            && draw.bounds.size.height.0 <= 16384.,
795        "invalid custom extent"
796    );
797    Ok(size(
798        DevicePixels(draw.bounds.size.width.0.ceil() as i32),
799        DevicePixels(draw.bounds.size.height.0.ceil() as i32),
800    ))
801}
802
803pub(crate) struct PreparedDraw {
804    pub bind_group: wgpu::BindGroup,
805    pub uniform_offset: u32,
806}
807
808const UNIFORM_BYTES: u64 = 144;
809/// Renderer-private arena. Reuse only after previous render commands are submitted;
810/// queue-ordered uploads then preserve reads by still-running previous frames.
811struct UniformArena {
812    buffer: Option<wgpu::Buffer>,
813    bytes: Vec<u8>,
814    stride: u64,
815    capacity: u64,
816    cursor: usize,
817    #[cfg(test)]
818    creations: usize,
819}
820impl UniformArena {
821    fn new(device: &wgpu::Device) -> Self {
822        Self {
823            buffer: None,
824            bytes: Vec::new(),
825            stride: UNIFORM_BYTES
826                .next_multiple_of(device.limits().min_uniform_buffer_offset_alignment as u64),
827            capacity: 0,
828            cursor: 0,
829            #[cfg(test)]
830            creations: 0,
831        }
832    }
833    fn begin(&mut self, device: &wgpu::Device, count: usize) -> Result<()> {
834        let required = (count as u64)
835            .checked_mul(self.stride)
836            .ok_or_else(|| anyhow::anyhow!("custom uniform size overflow"))?;
837        let limit = device.limits().max_buffer_size.min(u32::MAX as u64);
838        ensure!(
839            required <= limit,
840            "custom uniforms exceed buffer/offset limits"
841        );
842        if required > self.capacity {
843            let capacity = required
844                .checked_next_power_of_two()
845                .unwrap_or(required)
846                .min(limit);
847            self.buffer = Some(device.create_buffer(&wgpu::BufferDescriptor {
848                label: Some("custom_params_arena"),
849                size: capacity,
850                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
851                mapped_at_creation: false,
852            }));
853            self.capacity = capacity;
854            #[cfg(test)]
855            {
856                self.creations += 1;
857            }
858        }
859        self.bytes.resize(required as usize, 0);
860        self.cursor = 0;
861        Ok(())
862    }
863    fn write(&mut self, params: &[[f32; 4]; 9]) -> u32 {
864        let offset = self.cursor * self.stride as usize;
865        self.cursor += 1;
866        self.bytes[offset..offset + UNIFORM_BYTES as usize]
867            .copy_from_slice(bytemuck::cast_slice(params));
868        offset as u32
869    }
870    fn upload(&self, queue: &wgpu::Queue) {
871        debug_assert_eq!(self.cursor as u64 * self.stride, self.bytes.len() as u64);
872        if !self.bytes.is_empty() {
873            queue.write_buffer(self.buffer.as_ref().expect("uniform arena"), 0, &self.bytes);
874        }
875    }
876}
877pub(crate) struct CustomCompositor {
878    pub pipeline: wgpu::RenderPipeline,
879    layout: wgpu::BindGroupLayout,
880    sampler: wgpu::Sampler,
881    uniforms: UniformArena,
882    pub masks: CoverageCache<wgpu::Texture>,
883    pub mask_bytes: usize,
884}
885impl CustomCompositor {
886    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
887        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
888            label: Some("custom_compositor"),
889            source: wgpu::ShaderSource::Wgsl(include_str!("custom_draw.wgsl").into()),
890        });
891        let entries = [
892            wgpu::BindGroupLayoutEntry {
893                binding: 0,
894                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
895                ty: wgpu::BindingType::Buffer {
896                    ty: wgpu::BufferBindingType::Uniform,
897                    has_dynamic_offset: true,
898                    min_binding_size: wgpu::BufferSize::new(UNIFORM_BYTES),
899                },
900                count: None,
901            },
902            wgpu::BindGroupLayoutEntry {
903                binding: 1,
904                visibility: wgpu::ShaderStages::FRAGMENT,
905                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
906                count: None,
907            },
908            wgpu::BindGroupLayoutEntry {
909                binding: 2,
910                visibility: wgpu::ShaderStages::FRAGMENT,
911                ty: wgpu::BindingType::Texture {
912                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
913                    view_dimension: wgpu::TextureViewDimension::D2,
914                    multisampled: false,
915                },
916                count: None,
917            },
918            wgpu::BindGroupLayoutEntry {
919                binding: 3,
920                visibility: wgpu::ShaderStages::FRAGMENT,
921                ty: wgpu::BindingType::Texture {
922                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
923                    view_dimension: wgpu::TextureViewDimension::D2,
924                    multisampled: false,
925                },
926                count: None,
927            },
928        ];
929        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
930            label: Some("custom_paint"),
931            entries: &entries,
932        });
933        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
934            label: Some("custom_paint"),
935            bind_group_layouts: &[Some(&layout)],
936            immediate_size: 0,
937        });
938        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
939            label: Some("custom_paint"),
940            layout: Some(&pipeline_layout),
941            vertex: wgpu::VertexState {
942                module: &shader,
943                entry_point: Some("custom_vertex"),
944                buffers: &[],
945                compilation_options: Default::default(),
946            },
947            fragment: Some(wgpu::FragmentState {
948                module: &shader,
949                entry_point: Some("custom_fragment"),
950                targets: &[Some(wgpu::ColorTargetState {
951                    format,
952                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
953                    write_mask: wgpu::ColorWrites::ALL,
954                })],
955                compilation_options: Default::default(),
956            }),
957            primitive: Default::default(),
958            depth_stencil: None,
959            multisample: Default::default(),
960            multiview_mask: None,
961            cache: None,
962        });
963        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
964            label: Some("custom_paint"),
965            mag_filter: wgpu::FilterMode::Linear,
966            min_filter: wgpu::FilterMode::Linear,
967            mipmap_filter: wgpu::MipmapFilterMode::Linear,
968            ..Default::default()
969        });
970        Self {
971            pipeline,
972            layout,
973            sampler,
974            uniforms: UniformArena::new(device),
975            masks: Default::default(),
976            mask_bytes: 0,
977        }
978    }
979    pub(crate) fn begin_uniforms(&mut self, device: &wgpu::Device, count: usize) -> Result<()> {
980        self.uniforms.begin(device, count)
981    }
982    pub(crate) fn upload_uniforms(&self, queue: &wgpu::Queue) {
983        self.uniforms.upload(queue);
984    }
985    pub fn prepare(
986        &mut self,
987        device: &wgpu::Device,
988        draw: &CustomDraw,
989        source: &wgpu::Texture,
990        mask: Option<&wgpu::Texture>,
991        native: bool,
992        viewport: Size<DevicePixels>,
993    ) -> PreparedDraw {
994        let adjustments = draw.content.image_linear_adjustments();
995        let transform = adjustments
996            .map(|v| v.rows())
997            .unwrap_or_else(|| draw.content.image_color_transform());
998        let vignette = adjustments
999            .map(|v| v.vignette())
1000            .unwrap_or([0., 0., 1., 1.]);
1001        let linear = [
1002            if adjustments.is_some() { 1. } else { 0. },
1003            draw.content.image_color_mode().shader_value(),
1004            if adjustments.is_some_and(|v| v.is_p3()) {
1005                1.
1006            } else {
1007                0.
1008            },
1009            0.,
1010        ];
1011        let params: [[f32; 4]; 9] = [
1012            [
1013                draw.bounds.origin.x.0,
1014                draw.bounds.origin.y.0,
1015                draw.bounds.size.width.0,
1016                draw.bounds.size.height.0,
1017            ],
1018            [
1019                draw.content_mask.bounds.origin.x.0,
1020                draw.content_mask.bounds.origin.y.0,
1021                draw.content_mask.bounds.size.width.0,
1022                draw.content_mask.bounds.size.height.0,
1023            ],
1024            [
1025                draw.corner_radii.top_left.0,
1026                draw.corner_radii.top_right.0,
1027                draw.corner_radii.bottom_right.0,
1028                draw.corner_radii.bottom_left.0,
1029            ],
1030            [
1031                viewport.width.0 as f32,
1032                viewport.height.0 as f32,
1033                draw.opacity * draw.content.image_sample_opacity().clamp(0., 1.),
1034                u32::from(mask.is_some()) as f32 + if native { 2. } else { 0. },
1035            ],
1036            transform[0],
1037            transform[1],
1038            transform[2],
1039            vignette,
1040            linear,
1041        ];
1042        let uniform_offset = self.uniforms.write(&params);
1043        let uniform = self.uniforms.buffer.as_ref().expect("uniform arena");
1044        let source = source.create_view(&Default::default());
1045        let mask = mask
1046            .map(|t| t.create_view(&Default::default()))
1047            .unwrap_or_else(|| source.clone());
1048        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
1049            label: Some("custom_paint"),
1050            layout: &self.layout,
1051            entries: &[
1052                wgpu::BindGroupEntry {
1053                    binding: 0,
1054                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1055                        buffer: uniform,
1056                        offset: 0,
1057                        size: wgpu::BufferSize::new(UNIFORM_BYTES),
1058                    }),
1059                },
1060                wgpu::BindGroupEntry {
1061                    binding: 1,
1062                    resource: wgpu::BindingResource::Sampler(&self.sampler),
1063                },
1064                wgpu::BindGroupEntry {
1065                    binding: 2,
1066                    resource: wgpu::BindingResource::TextureView(&source),
1067                },
1068                wgpu::BindGroupEntry {
1069                    binding: 3,
1070                    resource: wgpu::BindingResource::TextureView(&mask),
1071                },
1072            ],
1073        });
1074        PreparedDraw {
1075            bind_group,
1076            uniform_offset,
1077        }
1078    }
1079}
1080
1081pub(crate) fn coverage_scene(draw: &CustomDraw, extent: Size<DevicePixels>) -> Result<gpui::Scene> {
1082    use gpui::*;
1083    let mut scene = Scene::default();
1084    let bounds = Bounds::new(
1085        point(ScaledPixels(0.), ScaledPixels(0.)),
1086        size(
1087            ScaledPixels(extent.width.0 as f32),
1088            ScaledPixels(extent.height.0 as f32),
1089        ),
1090    );
1091    let mask = ContentMask { bounds };
1092    match draw.coverage.as_ref().expect("coverage") {
1093        CustomCoverage::Border { widths, style } => {
1094            ensure!(
1095                [widths.top.0, widths.right.0, widths.bottom.0, widths.left.0]
1096                    .iter()
1097                    .all(|v| v.is_finite() && *v >= 0.),
1098                "invalid border widths"
1099            );
1100            scene.insert_primitive(Quad {
1101                bounds,
1102                content_mask: mask,
1103                background: transparent_black().into(),
1104                border_color: white(),
1105                border_widths: *widths,
1106                corner_radii: draw.corner_radii,
1107                border_style: *style,
1108                ..Default::default()
1109            });
1110        }
1111        CustomCoverage::Path(path) => {
1112            ensure!(path.vertices.len() <= 1_000_000, "coverage path too large");
1113            let mut path = path.as_ref().clone();
1114            let sx = bounds.size.width.0 / draw.bounds.size.width.0;
1115            let sy = bounds.size.height.0 / draw.bounds.size.height.0;
1116            for vertex in &mut path.vertices {
1117                vertex.xy_position.x =
1118                    ScaledPixels((vertex.xy_position.x.0 - draw.bounds.origin.x.0) * sx);
1119                vertex.xy_position.y =
1120                    ScaledPixels((vertex.xy_position.y.0 - draw.bounds.origin.y.0) * sy);
1121                ensure!(
1122                    [
1123                        vertex.xy_position.x.0,
1124                        vertex.xy_position.y.0,
1125                        vertex.st_position.x,
1126                        vertex.st_position.y
1127                    ]
1128                    .iter()
1129                    .all(|v| v.is_finite()),
1130                    "non-finite coverage path"
1131                );
1132                vertex.content_mask = mask;
1133            }
1134            path.bounds = bounds;
1135            path.content_mask = mask;
1136            path.color = white().into();
1137            scene.insert_primitive(path);
1138        }
1139    }
1140    scene.finish();
1141    Ok(scene)
1142}
1143
1144#[cfg(test)]
1145mod tests;