blade_renderer.rs

  1// Doing `if let` gives you nice scoping with passes/encoders
  2#![allow(irrefutable_let_patterns)]
  3
  4use super::{BladeAtlas, BladeBelt, BladeBeltDescriptor, PATH_TEXTURE_FORMAT};
  5use crate::{
  6    AtlasTextureKind, AtlasTile, Bounds, ContentMask, Hsla, MonochromeSprite, Path, PathId,
  7    PathVertex, PolychromeSprite, PrimitiveBatch, Quad, ScaledPixels, Scene, Shadow, Size,
  8    Underline,
  9};
 10use bytemuck::{Pod, Zeroable};
 11use collections::HashMap;
 12#[cfg(target_os = "macos")]
 13use media::core_video::CVMetalTextureCache;
 14#[cfg(target_os = "macos")]
 15use std::{ffi::c_void, ptr::NonNull};
 16
 17use blade_graphics as gpu;
 18use std::{mem, sync::Arc};
 19
 20const MAX_FRAME_TIME_MS: u32 = 1000;
 21
 22pub type Context = ();
 23pub type Renderer = BladeRenderer;
 24
 25#[cfg(target_os = "macos")]
 26pub unsafe fn new_renderer(
 27    _context: self::Context,
 28    _native_window: *mut c_void,
 29    native_view: *mut c_void,
 30    bounds: crate::Size<f32>,
 31    transparent: bool,
 32) -> Renderer {
 33    use raw_window_handle as rwh;
 34    struct RawWindow {
 35        view: *mut c_void,
 36    }
 37
 38    impl rwh::HasWindowHandle for RawWindow {
 39        fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
 40            let view = NonNull::new(self.view).unwrap();
 41            let handle = rwh::AppKitWindowHandle::new(view);
 42            Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
 43        }
 44    }
 45    impl rwh::HasDisplayHandle for RawWindow {
 46        fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
 47            let handle = rwh::AppKitDisplayHandle::new();
 48            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 49        }
 50    }
 51
 52    let gpu = Arc::new(
 53        gpu::Context::init_windowed(
 54            &RawWindow {
 55                view: native_view as *mut _,
 56            },
 57            gpu::ContextDesc {
 58                validation: cfg!(debug_assertions),
 59                capture: false,
 60                overlay: false,
 61            },
 62        )
 63        .unwrap(),
 64    );
 65
 66    BladeRenderer::new(
 67        gpu,
 68        BladeSurfaceConfig {
 69            size: gpu::Extent {
 70                width: bounds.width as u32,
 71                height: bounds.height as u32,
 72                depth: 1,
 73            },
 74            transparent,
 75        },
 76    )
 77}
 78
 79#[repr(C)]
 80#[derive(Clone, Copy, Pod, Zeroable)]
 81struct GlobalParams {
 82    viewport_size: [f32; 2],
 83    premultiplied_alpha: u32,
 84    pad: u32,
 85}
 86
 87//Note: we can't use `Bounds` directly here because
 88// it doesn't implement Pod + Zeroable
 89#[repr(C)]
 90#[derive(Clone, Copy, Pod, Zeroable)]
 91struct PodBounds {
 92    origin: [f32; 2],
 93    size: [f32; 2],
 94}
 95
 96impl From<Bounds<ScaledPixels>> for PodBounds {
 97    fn from(bounds: Bounds<ScaledPixels>) -> Self {
 98        Self {
 99            origin: [bounds.origin.x.0, bounds.origin.y.0],
100            size: [bounds.size.width.0, bounds.size.height.0],
101        }
102    }
103}
104
105#[repr(C)]
106#[derive(Clone, Copy, Pod, Zeroable)]
107struct SurfaceParams {
108    bounds: PodBounds,
109    content_mask: PodBounds,
110}
111
112#[derive(blade_macros::ShaderData)]
113struct ShaderQuadsData {
114    globals: GlobalParams,
115    b_quads: gpu::BufferPiece,
116}
117
118#[derive(blade_macros::ShaderData)]
119struct ShaderShadowsData {
120    globals: GlobalParams,
121    b_shadows: gpu::BufferPiece,
122}
123
124#[derive(blade_macros::ShaderData)]
125struct ShaderPathRasterizationData {
126    globals: GlobalParams,
127    b_path_vertices: gpu::BufferPiece,
128}
129
130#[derive(blade_macros::ShaderData)]
131struct ShaderPathsData {
132    globals: GlobalParams,
133    t_sprite: gpu::TextureView,
134    s_sprite: gpu::Sampler,
135    b_path_sprites: gpu::BufferPiece,
136}
137
138#[derive(blade_macros::ShaderData)]
139struct ShaderUnderlinesData {
140    globals: GlobalParams,
141    b_underlines: gpu::BufferPiece,
142}
143
144#[derive(blade_macros::ShaderData)]
145struct ShaderMonoSpritesData {
146    globals: GlobalParams,
147    t_sprite: gpu::TextureView,
148    s_sprite: gpu::Sampler,
149    b_mono_sprites: gpu::BufferPiece,
150}
151
152#[derive(blade_macros::ShaderData)]
153struct ShaderPolySpritesData {
154    globals: GlobalParams,
155    t_sprite: gpu::TextureView,
156    s_sprite: gpu::Sampler,
157    b_poly_sprites: gpu::BufferPiece,
158}
159
160#[derive(blade_macros::ShaderData)]
161struct ShaderSurfacesData {
162    globals: GlobalParams,
163    surface_locals: SurfaceParams,
164    t_y: gpu::TextureView,
165    t_cb_cr: gpu::TextureView,
166    s_surface: gpu::Sampler,
167}
168
169#[derive(Clone, Debug, Eq, PartialEq)]
170#[repr(C)]
171struct PathSprite {
172    bounds: Bounds<ScaledPixels>,
173    color: Hsla,
174    tile: AtlasTile,
175}
176
177struct BladePipelines {
178    quads: gpu::RenderPipeline,
179    shadows: gpu::RenderPipeline,
180    path_rasterization: gpu::RenderPipeline,
181    paths: gpu::RenderPipeline,
182    underlines: gpu::RenderPipeline,
183    mono_sprites: gpu::RenderPipeline,
184    poly_sprites: gpu::RenderPipeline,
185    surfaces: gpu::RenderPipeline,
186}
187
188impl BladePipelines {
189    fn new(gpu: &gpu::Context, surface_info: gpu::SurfaceInfo) -> Self {
190        use gpu::ShaderData as _;
191
192        log::info!(
193            "Initializing Blade pipelines for surface {:?}",
194            surface_info
195        );
196        let shader = gpu.create_shader(gpu::ShaderDesc {
197            source: include_str!("shaders.wgsl"),
198        });
199        shader.check_struct_size::<GlobalParams>();
200        shader.check_struct_size::<SurfaceParams>();
201        shader.check_struct_size::<Quad>();
202        shader.check_struct_size::<Shadow>();
203        assert_eq!(
204            mem::size_of::<PathVertex<ScaledPixels>>(),
205            shader.get_struct_size("PathVertex") as usize,
206        );
207        shader.check_struct_size::<PathSprite>();
208        shader.check_struct_size::<Underline>();
209        shader.check_struct_size::<MonochromeSprite>();
210        shader.check_struct_size::<PolychromeSprite>();
211
212        // See https://apoorvaj.io/alpha-compositing-opengl-blending-and-premultiplied-alpha/
213        let blend_mode = match surface_info.alpha {
214            gpu::AlphaMode::Ignored => gpu::BlendState::ALPHA_BLENDING,
215            gpu::AlphaMode::PreMultiplied => gpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
216            gpu::AlphaMode::PostMultiplied => gpu::BlendState::ALPHA_BLENDING,
217        };
218        let color_targets = &[gpu::ColorTargetState {
219            format: surface_info.format,
220            blend: Some(blend_mode),
221            write_mask: gpu::ColorWrites::default(),
222        }];
223
224        Self {
225            quads: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
226                name: "quads",
227                data_layouts: &[&ShaderQuadsData::layout()],
228                vertex: shader.at("vs_quad"),
229                vertex_fetches: &[],
230                primitive: gpu::PrimitiveState {
231                    topology: gpu::PrimitiveTopology::TriangleStrip,
232                    ..Default::default()
233                },
234                depth_stencil: None,
235                fragment: shader.at("fs_quad"),
236                color_targets,
237            }),
238            shadows: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
239                name: "shadows",
240                data_layouts: &[&ShaderShadowsData::layout()],
241                vertex: shader.at("vs_shadow"),
242                vertex_fetches: &[],
243                primitive: gpu::PrimitiveState {
244                    topology: gpu::PrimitiveTopology::TriangleStrip,
245                    ..Default::default()
246                },
247                depth_stencil: None,
248                fragment: shader.at("fs_shadow"),
249                color_targets,
250            }),
251            path_rasterization: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
252                name: "path_rasterization",
253                data_layouts: &[&ShaderPathRasterizationData::layout()],
254                vertex: shader.at("vs_path_rasterization"),
255                vertex_fetches: &[],
256                primitive: gpu::PrimitiveState {
257                    topology: gpu::PrimitiveTopology::TriangleList,
258                    ..Default::default()
259                },
260                depth_stencil: None,
261                fragment: shader.at("fs_path_rasterization"),
262                color_targets: &[gpu::ColorTargetState {
263                    format: PATH_TEXTURE_FORMAT,
264                    blend: Some(gpu::BlendState::ADDITIVE),
265                    write_mask: gpu::ColorWrites::default(),
266                }],
267            }),
268            paths: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
269                name: "paths",
270                data_layouts: &[&ShaderPathsData::layout()],
271                vertex: shader.at("vs_path"),
272                vertex_fetches: &[],
273                primitive: gpu::PrimitiveState {
274                    topology: gpu::PrimitiveTopology::TriangleStrip,
275                    ..Default::default()
276                },
277                depth_stencil: None,
278                fragment: shader.at("fs_path"),
279                color_targets,
280            }),
281            underlines: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
282                name: "underlines",
283                data_layouts: &[&ShaderUnderlinesData::layout()],
284                vertex: shader.at("vs_underline"),
285                vertex_fetches: &[],
286                primitive: gpu::PrimitiveState {
287                    topology: gpu::PrimitiveTopology::TriangleStrip,
288                    ..Default::default()
289                },
290                depth_stencil: None,
291                fragment: shader.at("fs_underline"),
292                color_targets,
293            }),
294            mono_sprites: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
295                name: "mono-sprites",
296                data_layouts: &[&ShaderMonoSpritesData::layout()],
297                vertex: shader.at("vs_mono_sprite"),
298                vertex_fetches: &[],
299                primitive: gpu::PrimitiveState {
300                    topology: gpu::PrimitiveTopology::TriangleStrip,
301                    ..Default::default()
302                },
303                depth_stencil: None,
304                fragment: shader.at("fs_mono_sprite"),
305                color_targets,
306            }),
307            poly_sprites: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
308                name: "poly-sprites",
309                data_layouts: &[&ShaderPolySpritesData::layout()],
310                vertex: shader.at("vs_poly_sprite"),
311                vertex_fetches: &[],
312                primitive: gpu::PrimitiveState {
313                    topology: gpu::PrimitiveTopology::TriangleStrip,
314                    ..Default::default()
315                },
316                depth_stencil: None,
317                fragment: shader.at("fs_poly_sprite"),
318                color_targets,
319            }),
320            surfaces: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
321                name: "surfaces",
322                data_layouts: &[&ShaderSurfacesData::layout()],
323                vertex: shader.at("vs_surface"),
324                vertex_fetches: &[],
325                primitive: gpu::PrimitiveState {
326                    topology: gpu::PrimitiveTopology::TriangleStrip,
327                    ..Default::default()
328                },
329                depth_stencil: None,
330                fragment: shader.at("fs_surface"),
331                color_targets,
332            }),
333        }
334    }
335}
336
337pub struct BladeSurfaceConfig {
338    pub size: gpu::Extent,
339    pub transparent: bool,
340}
341
342pub struct BladeRenderer {
343    gpu: Arc<gpu::Context>,
344    surface_config: gpu::SurfaceConfig,
345    alpha_mode: gpu::AlphaMode,
346    command_encoder: gpu::CommandEncoder,
347    last_sync_point: Option<gpu::SyncPoint>,
348    pipelines: BladePipelines,
349    instance_belt: BladeBelt,
350    path_tiles: HashMap<PathId, AtlasTile>,
351    atlas: Arc<BladeAtlas>,
352    atlas_sampler: gpu::Sampler,
353    #[cfg(target_os = "macos")]
354    core_video_texture_cache: CVMetalTextureCache,
355}
356
357impl BladeRenderer {
358    pub fn new(gpu: Arc<gpu::Context>, config: BladeSurfaceConfig) -> Self {
359        let surface_config = gpu::SurfaceConfig {
360            size: config.size,
361            usage: gpu::TextureUsage::TARGET,
362            display_sync: gpu::DisplaySync::Recent,
363            color_space: gpu::ColorSpace::Linear,
364            allow_exclusive_full_screen: false,
365            transparent: config.transparent,
366        };
367        let surface_info = gpu.resize(surface_config);
368
369        let command_encoder = gpu.create_command_encoder(gpu::CommandEncoderDesc {
370            name: "main",
371            buffer_count: 2,
372        });
373        let pipelines = BladePipelines::new(&gpu, surface_info);
374        let instance_belt = BladeBelt::new(BladeBeltDescriptor {
375            memory: gpu::Memory::Shared,
376            min_chunk_size: 0x1000,
377            alignment: 0x40, // Vulkan `minStorageBufferOffsetAlignment` on Intel Xe
378        });
379        let atlas = Arc::new(BladeAtlas::new(&gpu));
380        let atlas_sampler = gpu.create_sampler(gpu::SamplerDesc {
381            name: "atlas",
382            mag_filter: gpu::FilterMode::Linear,
383            min_filter: gpu::FilterMode::Linear,
384            ..Default::default()
385        });
386
387        #[cfg(target_os = "macos")]
388        let core_video_texture_cache = unsafe {
389            use foreign_types::ForeignType as _;
390            CVMetalTextureCache::new(gpu.metal_device().as_ptr()).unwrap()
391        };
392
393        Self {
394            gpu,
395            surface_config,
396            alpha_mode: surface_info.alpha,
397            command_encoder,
398            last_sync_point: None,
399            pipelines,
400            instance_belt,
401            path_tiles: HashMap::default(),
402            atlas,
403            atlas_sampler,
404            #[cfg(target_os = "macos")]
405            core_video_texture_cache,
406        }
407    }
408
409    fn wait_for_gpu(&mut self) {
410        if let Some(last_sp) = self.last_sync_point.take() {
411            if !self.gpu.wait_for(&last_sp, MAX_FRAME_TIME_MS) {
412                panic!("GPU hung");
413            }
414        }
415    }
416
417    pub fn update_drawable_size(&mut self, size: Size<f64>) {
418        let gpu_size = gpu::Extent {
419            width: size.width as u32,
420            height: size.height as u32,
421            depth: 1,
422        };
423
424        if gpu_size != self.surface_config.size {
425            self.wait_for_gpu();
426            self.surface_config.size = gpu_size;
427            self.gpu.resize(self.surface_config);
428        }
429    }
430
431    pub fn update_transparency(&mut self, transparent: bool) {
432        if transparent != self.surface_config.transparent {
433            self.wait_for_gpu();
434            self.surface_config.transparent = transparent;
435            let surface_info = self.gpu.resize(self.surface_config);
436            self.pipelines = BladePipelines::new(&self.gpu, surface_info);
437            self.alpha_mode = surface_info.alpha;
438        }
439    }
440
441    #[cfg_attr(target_os = "macos", allow(dead_code))]
442    pub fn viewport_size(&self) -> gpu::Extent {
443        self.surface_config.size
444    }
445
446    pub fn sprite_atlas(&self) -> &Arc<BladeAtlas> {
447        &self.atlas
448    }
449
450    #[cfg(target_os = "macos")]
451    pub fn layer(&self) -> metal::MetalLayer {
452        self.gpu.metal_layer().unwrap()
453    }
454
455    #[cfg(target_os = "macos")]
456    pub fn layer_ptr(&self) -> *mut metal::CAMetalLayer {
457        use metal::foreign_types::ForeignType as _;
458        self.gpu.metal_layer().unwrap().as_ptr()
459    }
460
461    #[profiling::function]
462    fn rasterize_paths(&mut self, paths: &[Path<ScaledPixels>]) {
463        self.path_tiles.clear();
464        let mut vertices_by_texture_id = HashMap::default();
465
466        for path in paths {
467            let clipped_bounds = path.bounds.intersect(&path.content_mask.bounds);
468            let tile = self.atlas.allocate_for_rendering(
469                clipped_bounds.size.map(Into::into),
470                AtlasTextureKind::Path,
471                &mut self.command_encoder,
472            );
473            vertices_by_texture_id
474                .entry(tile.texture_id)
475                .or_insert(Vec::new())
476                .extend(path.vertices.iter().map(|vertex| PathVertex {
477                    xy_position: vertex.xy_position - clipped_bounds.origin
478                        + tile.bounds.origin.map(Into::into),
479                    st_position: vertex.st_position,
480                    content_mask: ContentMask {
481                        bounds: tile.bounds.map(Into::into),
482                    },
483                }));
484            self.path_tiles.insert(path.id, tile);
485        }
486
487        for (texture_id, vertices) in vertices_by_texture_id {
488            let tex_info = self.atlas.get_texture_info(texture_id);
489            let globals = GlobalParams {
490                viewport_size: [tex_info.size.width as f32, tex_info.size.height as f32],
491                premultiplied_alpha: 0,
492                pad: 0,
493            };
494
495            let vertex_buf = unsafe { self.instance_belt.alloc_data(&vertices, &self.gpu) };
496            let mut pass = self.command_encoder.render(gpu::RenderTargetSet {
497                colors: &[gpu::RenderTarget {
498                    view: tex_info.raw_view,
499                    init_op: gpu::InitOp::Clear(gpu::TextureColor::OpaqueBlack),
500                    finish_op: gpu::FinishOp::Store,
501                }],
502                depth_stencil: None,
503            });
504
505            let mut encoder = pass.with(&self.pipelines.path_rasterization);
506            encoder.bind(
507                0,
508                &ShaderPathRasterizationData {
509                    globals,
510                    b_path_vertices: vertex_buf,
511                },
512            );
513            encoder.draw(0, vertices.len() as u32, 0, 1);
514        }
515    }
516
517    pub fn destroy(&mut self) {
518        self.wait_for_gpu();
519        self.atlas.destroy();
520        self.instance_belt.destroy(&self.gpu);
521        self.gpu.destroy_command_encoder(&mut self.command_encoder);
522    }
523
524    pub fn draw(&mut self, scene: &Scene) {
525        self.command_encoder.start();
526        self.atlas.before_frame(&mut self.command_encoder);
527        self.rasterize_paths(scene.paths());
528
529        let frame = {
530            profiling::scope!("acquire frame");
531            self.gpu.acquire_frame()
532        };
533        self.command_encoder.init_texture(frame.texture());
534
535        let globals = GlobalParams {
536            viewport_size: [
537                self.surface_config.size.width as f32,
538                self.surface_config.size.height as f32,
539            ],
540            premultiplied_alpha: match self.alpha_mode {
541                gpu::AlphaMode::Ignored | gpu::AlphaMode::PostMultiplied => 0,
542                gpu::AlphaMode::PreMultiplied => 1,
543            },
544            pad: 0,
545        };
546
547        if let mut pass = self.command_encoder.render(gpu::RenderTargetSet {
548            colors: &[gpu::RenderTarget {
549                view: frame.texture_view(),
550                init_op: gpu::InitOp::Clear(gpu::TextureColor::TransparentBlack),
551                finish_op: gpu::FinishOp::Store,
552            }],
553            depth_stencil: None,
554        }) {
555            profiling::scope!("render pass");
556            for batch in scene.batches() {
557                match batch {
558                    PrimitiveBatch::Quads(quads) => {
559                        let instance_buf =
560                            unsafe { self.instance_belt.alloc_data(quads, &self.gpu) };
561                        let mut encoder = pass.with(&self.pipelines.quads);
562                        encoder.bind(
563                            0,
564                            &ShaderQuadsData {
565                                globals,
566                                b_quads: instance_buf,
567                            },
568                        );
569                        encoder.draw(0, 4, 0, quads.len() as u32);
570                    }
571                    PrimitiveBatch::Shadows(shadows) => {
572                        let instance_buf =
573                            unsafe { self.instance_belt.alloc_data(shadows, &self.gpu) };
574                        let mut encoder = pass.with(&self.pipelines.shadows);
575                        encoder.bind(
576                            0,
577                            &ShaderShadowsData {
578                                globals,
579                                b_shadows: instance_buf,
580                            },
581                        );
582                        encoder.draw(0, 4, 0, shadows.len() as u32);
583                    }
584                    PrimitiveBatch::Paths(paths) => {
585                        let mut encoder = pass.with(&self.pipelines.paths);
586                        // todo(linux): group by texture ID
587                        for path in paths {
588                            let tile = &self.path_tiles[&path.id];
589                            let tex_info = self.atlas.get_texture_info(tile.texture_id);
590                            let origin = path.bounds.intersect(&path.content_mask.bounds).origin;
591                            let sprites = [PathSprite {
592                                bounds: Bounds {
593                                    origin: origin.map(|p| p.floor()),
594                                    size: tile.bounds.size.map(Into::into),
595                                },
596                                color: path.color,
597                                tile: (*tile).clone(),
598                            }];
599
600                            let instance_buf =
601                                unsafe { self.instance_belt.alloc_data(&sprites, &self.gpu) };
602                            encoder.bind(
603                                0,
604                                &ShaderPathsData {
605                                    globals,
606                                    t_sprite: tex_info.raw_view,
607                                    s_sprite: self.atlas_sampler,
608                                    b_path_sprites: instance_buf,
609                                },
610                            );
611                            encoder.draw(0, 4, 0, sprites.len() as u32);
612                        }
613                    }
614                    PrimitiveBatch::Underlines(underlines) => {
615                        let instance_buf =
616                            unsafe { self.instance_belt.alloc_data(underlines, &self.gpu) };
617                        let mut encoder = pass.with(&self.pipelines.underlines);
618                        encoder.bind(
619                            0,
620                            &ShaderUnderlinesData {
621                                globals,
622                                b_underlines: instance_buf,
623                            },
624                        );
625                        encoder.draw(0, 4, 0, underlines.len() as u32);
626                    }
627                    PrimitiveBatch::MonochromeSprites {
628                        texture_id,
629                        sprites,
630                    } => {
631                        let tex_info = self.atlas.get_texture_info(texture_id);
632                        let instance_buf =
633                            unsafe { self.instance_belt.alloc_data(sprites, &self.gpu) };
634                        let mut encoder = pass.with(&self.pipelines.mono_sprites);
635                        encoder.bind(
636                            0,
637                            &ShaderMonoSpritesData {
638                                globals,
639                                t_sprite: tex_info.raw_view,
640                                s_sprite: self.atlas_sampler,
641                                b_mono_sprites: instance_buf,
642                            },
643                        );
644                        encoder.draw(0, 4, 0, sprites.len() as u32);
645                    }
646                    PrimitiveBatch::PolychromeSprites {
647                        texture_id,
648                        sprites,
649                    } => {
650                        let tex_info = self.atlas.get_texture_info(texture_id);
651                        let instance_buf =
652                            unsafe { self.instance_belt.alloc_data(sprites, &self.gpu) };
653                        let mut encoder = pass.with(&self.pipelines.poly_sprites);
654                        encoder.bind(
655                            0,
656                            &ShaderPolySpritesData {
657                                globals,
658                                t_sprite: tex_info.raw_view,
659                                s_sprite: self.atlas_sampler,
660                                b_poly_sprites: instance_buf,
661                            },
662                        );
663                        encoder.draw(0, 4, 0, sprites.len() as u32);
664                    }
665                    PrimitiveBatch::Surfaces(surfaces) => {
666                        let mut _encoder = pass.with(&self.pipelines.surfaces);
667
668                        for surface in surfaces {
669                            #[cfg(not(target_os = "macos"))]
670                            {
671                                let _ = surface;
672                                continue;
673                            };
674
675                            #[cfg(target_os = "macos")]
676                            {
677                                let (t_y, t_cb_cr) = {
678                                    use core_foundation::base::TCFType as _;
679                                    use std::ptr;
680
681                                    assert_eq!(
682                                    surface.image_buffer.pixel_format_type(),
683                                    media::core_video::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
684                                );
685
686                                    let y_texture = unsafe {
687                                        self.core_video_texture_cache
688                                            .create_texture_from_image(
689                                                surface.image_buffer.as_concrete_TypeRef(),
690                                                ptr::null(),
691                                                metal::MTLPixelFormat::R8Unorm,
692                                                surface.image_buffer.plane_width(0),
693                                                surface.image_buffer.plane_height(0),
694                                                0,
695                                            )
696                                            .unwrap()
697                                    };
698                                    let cb_cr_texture = unsafe {
699                                        self.core_video_texture_cache
700                                            .create_texture_from_image(
701                                                surface.image_buffer.as_concrete_TypeRef(),
702                                                ptr::null(),
703                                                metal::MTLPixelFormat::RG8Unorm,
704                                                surface.image_buffer.plane_width(1),
705                                                surface.image_buffer.plane_height(1),
706                                                1,
707                                            )
708                                            .unwrap()
709                                    };
710                                    (
711                                        gpu::TextureView::from_metal_texture(
712                                            y_texture.as_texture_ref(),
713                                        ),
714                                        gpu::TextureView::from_metal_texture(
715                                            cb_cr_texture.as_texture_ref(),
716                                        ),
717                                    )
718                                };
719
720                                _encoder.bind(
721                                    0,
722                                    &ShaderSurfacesData {
723                                        globals,
724                                        surface_locals: SurfaceParams {
725                                            bounds: surface.bounds.into(),
726                                            content_mask: surface.content_mask.bounds.into(),
727                                        },
728                                        t_y,
729                                        t_cb_cr,
730                                        s_surface: self.atlas_sampler,
731                                    },
732                                );
733
734                                _encoder.draw(0, 4, 0, 1);
735                            }
736                        }
737                    }
738                }
739            }
740        }
741
742        self.command_encoder.present(frame);
743        let sync_point = self.gpu.submit(&mut self.command_encoder);
744
745        profiling::scope!("finish");
746        self.instance_belt.flush(&sync_point);
747        self.atlas.after_frame(&sync_point);
748        self.atlas.clear_textures(AtlasTextureKind::Path);
749
750        self.wait_for_gpu();
751        self.last_sync_point = Some(sync_point);
752    }
753}