Skip to content
Snippets Groups Projects
pipeline.rs 53 KiB
Newer Older
Louis's avatar
Louis committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
use bevy::ecs::query::ROQueryItem;
use bevy::ecs::system::{SystemParam, SystemParamItem};
use bevy::prelude::{Commands, Rect, Resource, With};
#[cfg(feature = "svg")]
use bevy::prelude::{Mesh, Vec3};
use bevy::render::globals::{GlobalsBuffer, GlobalsUniform};
#[cfg(feature = "svg")]
use bevy::render::mesh::VertexAttributeValues;
use bevy::render::render_phase::{
    DrawFunctionId, PhaseItem, RenderCommand, RenderCommandResult, SetItemPipeline,
};
use bevy::render::render_resource::{
    CachedRenderPipelineId, DynamicUniformBuffer, ShaderType, SpecializedRenderPipeline,
    SpecializedRenderPipelines,
};
use bevy::render::view::ViewTarget;
use bevy::utils::FloatOrd;
use bevy::{
    ecs::system::lifetimeless::{Read, SRes},
    math::{Mat4, Quat, Vec2, Vec4},
    prelude::{Component, Entity, FromWorld, Handle, Query, Res, ResMut, World},
    render::{
        color::Color,
        render_asset::RenderAssets,
        render_phase::{DrawFunctions, TrackedRenderPass},
        render_resource::{
            BindGroup, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry, BindingResource,
            BindingType, BlendState, BufferBindingType, BufferSize, BufferUsages, BufferVec,
            ColorTargetState, ColorWrites, Extent3d, FragmentState, FrontFace, MultisampleState,
            PipelineCache, PolygonMode, PrimitiveState, PrimitiveTopology,
            RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor, ShaderStages,
            TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages,
            TextureViewDescriptor, TextureViewDimension, VertexAttribute, VertexBufferLayout,
            VertexFormat, VertexState, VertexStepMode,
        },
        renderer::{RenderDevice, RenderQueue},
        texture::{BevyDefault, GpuImage, Image},
    },
    utils::HashMap,
};
#[cfg(feature = "svg")]
use bevy_svg::prelude::Svg;
use bytemuck::{Pod, Zeroable};
use kayak_font::{bevy::FontTextureCache, KayakFont};
use std::marker::PhantomData;

use super::UNIFIED_SHADER_HANDLE;
use crate::layout::LayoutCache;
use crate::prelude::Corner;
use crate::render::extract::{UIExtractedView, UIViewUniform, UIViewUniformOffset, UIViewUniforms};
use crate::render::opacity_layer::OpacityLayerManager;
#[cfg(feature = "svg")]
use crate::render::svg::RenderSvgs;
use crate::render::ui_pass::{
    TransparentOpacityUI, TransparentUI, TransparentUIGeneric, UIRenderPhase,
};

#[derive(Resource, Clone)]
pub struct UnifiedPipeline {
    pub view_layout: BindGroupLayout,
    pub types_layout: BindGroupLayout,
    pub image_layout: BindGroupLayout,
    empty_font_texture: GpuImage,
    default_image: (GpuImage, BindGroup),
}

// const QUAD_VERTEX_POSITIONS: &[Vec3] = &[
//     Vec3::from_array([0.0, 1.0, 0.0]),
//     Vec3::from_array([1.0, 0.0, 0.0]),
//     Vec3::from_array([0.0, 0.0, 0.0]),
//     Vec3::from_array([0.0, 1.0, 0.0]),
//     Vec3::from_array([1.0, 1.0, 0.0]),
//     Vec3::from_array([1.0, 0.0, 0.0]),
// ];

const QUAD_INDICES: [usize; 6] = [0, 2, 3, 0, 1, 2];

const QUAD_VERTEX_POSITIONS: [Vec2; 4] = [
    Vec2::new(0.0, 0.0),
    Vec2::new(1.0, 0.0),
    Vec2::new(1.0, 1.0),
    Vec2::new(0.0, 1.0),
];

#[derive(Debug, Component, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnifiedPipelineKey {
    pub msaa: u32,
    pub hdr: bool,
}

impl FromWorld for UnifiedPipeline {
    fn from_world(world: &mut World) -> Self {
        let world = world.cell();
        let render_device = world.resource::<RenderDevice>();

        let view_layout = render_device.create_bind_group_layout(
            "ui_view_layout",
            &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: Some(UIViewUniform::min_size()),
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::VERTEX_FRAGMENT,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: Some(GlobalsUniform::min_size()),
                    },
                    count: None,
                },
            ],
        );

        let types_layout = render_device.create_bind_group_layout(
            "ui_types_layout",
            &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    has_dynamic_offset: true,
                    // TODO: change this to ViewUniform::std140_size_static once crevice fixes this!
                    // Context: https://github.com/LPGhatguy/crevice/issues/29
                    min_binding_size: BufferSize::new(16),
                },
                count: None,
            }],
        );

        let image_layout = render_device.create_bind_group_layout(
            "image_layout",
            &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        multisampled: false,
                        sample_type: TextureSampleType::Float { filterable: true },
                        view_dimension: TextureViewDimension::D2,
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::Filtering),
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        multisampled: false,
                        sample_type: TextureSampleType::Float { filterable: true },
                        view_dimension: TextureViewDimension::D2Array,
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 3,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        );

        let empty_font_texture = FontTextureCache::get_empty(&render_device);

        let texture_descriptor = TextureDescriptor {
            label: Some("empty_texture"),
            size: Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: TextureDimension::D2,
            view_formats: &[TextureFormat::Rgba8UnormSrgb],
            format: TextureFormat::Rgba8UnormSrgb,
            usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
        };

        let sampler_descriptor = SamplerDescriptor::default();

        let texture = render_device.create_texture(&texture_descriptor);
        let sampler = render_device.create_sampler(&sampler_descriptor);

        let texture_view = texture.create_view(&TextureViewDescriptor {
            label: Some("empty_texture_view"),
            format: Some(TextureFormat::Rgba8UnormSrgb),
            dimension: Some(TextureViewDimension::D2),
            aspect: bevy::render::render_resource::TextureAspect::All,
            base_mip_level: 0,
            base_array_layer: 0,
            mip_level_count: None,
            array_layer_count: None,
        });

        let image = GpuImage {
            texture,
            sampler,
            texture_view,
            mip_level_count: 1,
            size: Vec2::new(1.0, 1.0),
            texture_format: TextureFormat::Rgba8UnormSrgb,
        };

        let binding = render_device.create_bind_group(
            Some("default_image_bind_group"),
            &image_layout,
            &[
                BindGroupEntry {
                    binding: 0,
                    resource: BindingResource::TextureView(&image.texture_view),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: BindingResource::Sampler(&image.sampler),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: BindingResource::TextureView(&empty_font_texture.texture_view),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: BindingResource::Sampler(&empty_font_texture.sampler),
                },
            ],
        );

        UnifiedPipeline {
            view_layout,
            empty_font_texture,
            types_layout,
            image_layout,
            default_image: (image, binding),
        }
    }
}

impl SpecializedRenderPipeline for UnifiedPipeline {
    type Key = UnifiedPipelineKey;

    fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
        let vertex_buffer_layout = VertexBufferLayout {
            array_stride: 60,
            step_mode: VertexStepMode::Vertex,
            attributes: vec![
                VertexAttribute {
                    format: VertexFormat::Float32x3,
                    offset: 0,
                    shader_location: 0,
                },
                VertexAttribute {
                    format: VertexFormat::Float32x4,
                    offset: 12,
                    shader_location: 1,
                },
                VertexAttribute {
                    format: VertexFormat::Float32x4,
                    offset: 28,
                    shader_location: 2,
                },
                VertexAttribute {
                    format: VertexFormat::Float32x4,
                    offset: 44,
                    shader_location: 3,
                },
            ],
        };

        RenderPipelineDescriptor {
            vertex: VertexState {
                shader: UNIFIED_SHADER_HANDLE,
                entry_point: "vertex".into(),
                shader_defs: vec![],
                buffers: vec![vertex_buffer_layout],
            },
            fragment: Some(FragmentState {
                shader: UNIFIED_SHADER_HANDLE,
                shader_defs: vec![],
                entry_point: "fragment".into(),
                targets: vec![Some(ColorTargetState {
                    format: if key.hdr {
                        ViewTarget::TEXTURE_FORMAT_HDR
                    } else {
                        TextureFormat::bevy_default()
                    },
                    blend: Some(BlendState::ALPHA_BLENDING),
                    // Some(BlendState {
                    //     color: BlendComponent {
                    //         src_factor: BlendFactor::SrcAlpha,
                    //         dst_factor: BlendFactor::OneMinusSrcAlpha,
                    //         operation: BlendOperation::Add,
                    //     },
                    //     alpha: BlendComponent {
                    //         src_factor: BlendFactor::OneMinusDstAlpha,
                    //         dst_factor: BlendFactor::One,
                    //         operation: BlendOperation::Add,
                    //     },
                    // }),
                    write_mask: ColorWrites::ALL,
                })],
            }),
            layout: vec![
                self.view_layout.clone(),
                self.image_layout.clone(),
                self.types_layout.clone(),
            ],
            primitive: PrimitiveState {
                front_face: FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: PolygonMode::Fill,
                conservative: false,
                topology: PrimitiveTopology::TriangleList,
                strip_index_format: None,
                unclipped_depth: false,
            },
            depth_stencil: None,
            multisample: MultisampleState {
                count: key.msaa,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            label: Some("unified_pipeline".into()),
            push_constant_ranges: vec![],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum UIQuadType {
    Quad,
    BoxShadow,
    Text,
    TextSubpixel,
    Image,
    Clip,
    OpacityLayer,
    DrawOpacityLayer,
    None,
}

impl UIQuadType {
    pub fn get_type_index(&self, quad_type_offsets: &QuadTypeOffsets) -> u32 {
        match self {
            UIQuadType::Quad => quad_type_offsets.quad_type_offset,
            UIQuadType::Text => quad_type_offsets.text_type_offset,
            UIQuadType::TextSubpixel => quad_type_offsets.text_sub_pixel_type_offset,
            UIQuadType::Image => quad_type_offsets.image_type_offset,
            UIQuadType::BoxShadow => quad_type_offsets.box_shadow_type_offset,
            UIQuadType::Clip => 100000,
            UIQuadType::None => 100001,
            UIQuadType::OpacityLayer => 100002,
            UIQuadType::DrawOpacityLayer => quad_type_offsets.image_type_offset,
        }
    }
}

#[derive(Debug, Component, Clone)]
pub struct ExtractedQuad {
    pub org_entity: Entity,
    pub camera_entity: Entity,
    pub rect: Rect,
    pub color: Color,
    pub char_id: u32,
    pub z_index: f32,
    pub font_handle: Option<Handle<KayakFont>>,
    pub quad_type: UIQuadType,
    pub type_index: u32,
    pub border_radius: Corner<f32>,
    pub image: Option<Handle<Image>>,
    pub uv_min: Option<Vec2>,
    pub uv_max: Option<Vec2>,
    #[cfg(feature = "svg")]
    pub svg_handle: (Option<Handle<Svg>>, Option<Color>),
    pub opacity_layer: u32,
    pub c: char,
}

impl Default for ExtractedQuad {
    fn default() -> Self {
        Self {
            org_entity: Entity::PLACEHOLDER,
            camera_entity: Entity::PLACEHOLDER,
            rect: Default::default(),
            color: Default::default(),
            char_id: Default::default(),
            z_index: Default::default(),
            font_handle: Default::default(),
            quad_type: UIQuadType::Quad,
            type_index: Default::default(),
            border_radius: Default::default(),
            image: Default::default(),
            uv_min: Default::default(),
            uv_max: Default::default(),
            #[cfg(feature = "svg")]
            svg_handle: Default::default(),
            opacity_layer: 0,
            c: ' ',
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct QuadVertex {
    pub position: [f32; 3],
    pub color: [f32; 4],
    pub uv: [f32; 4],
    pub pos_size: [f32; 4],
}

unsafe impl Zeroable for QuadVertex {}
unsafe impl Pod for QuadVertex {}

#[repr(C)]
#[derive(Copy, Clone, ShaderType)]
struct QuadType {
    pub t: i32,
    pub _padding_1: i32,
    pub _padding_2: i32,
    pub _padding_3: i32,
}

#[derive(Resource)]
pub struct QuadMeta {
    pub vertices: BufferVec<QuadVertex>,
    types_buffer: DynamicUniformBuffer<QuadType>,
    types_bind_group: Option<BindGroup>,
}

impl Default for QuadMeta {
    fn default() -> Self {
        Self {
            vertices: BufferVec::new(BufferUsages::VERTEX),
            types_buffer: DynamicUniformBuffer::default(),
            types_bind_group: None,
        }
    }
}

#[derive(Debug)]
pub enum QuadOrMaterial {
    Quad(ExtractedQuad),
    Material(Entity),
}

impl QuadOrMaterial {
    pub fn get_entity(&self) -> Entity {
        match self {
            QuadOrMaterial::Material(entity) => *entity,
            QuadOrMaterial::Quad(quad) => quad.org_entity,
        }
    }
}

impl Default for QuadOrMaterial {
    fn default() -> Self {
        Self::Quad(ExtractedQuad::default())
    }
}

#[derive(Resource, Default, Debug)]
pub struct ExtractedQuads {
    layers: Vec<ZLayer>,
    current_layer: usize,
    current_index: usize,
    children: HashMap<usize, Vec<usize>>,
    parents: HashMap<usize, usize>,
}

impl ExtractedQuads {
    pub fn clear(&mut self) {
        self.current_index = 0;
        self.current_layer = 0;
        self.layers.clear();
        self.children.clear();
        self.parents.clear();
    }

    pub fn push(&mut self, quad: QuadOrMaterial) {
        let layer = self.layers.get_mut(self.current_layer).unwrap();
        layer.quads.push(quad);
    }

    pub fn extend(&mut self, quads: Vec<QuadOrMaterial>) {
        let layer = self.layers.get_mut(self.current_layer).unwrap();
        layer.quads.extend(quads);
    }
    pub fn new_layer(&mut self, z_index: Option<f32>) {
        let layer = ZLayer {
            custom_z: z_index.unwrap_or(0.0),
            parent_id: self.current_layer,
            ..Default::default()
        };

        self.current_index = self.layers.len();
        if let Some(c) = self.children.get_mut(&self.current_layer) {
            c.push(self.current_index);
        }
        self.parents.insert(self.current_index, self.current_layer);
        self.layers.push(layer);
        self.current_layer = self.current_index;
        self.children.insert(self.current_index, vec![]);
    }

    pub fn pop_stack(&mut self) {
        let layer = self.layers.get_mut(self.current_layer).unwrap();
        self.current_layer = layer.parent_id;
    }

    pub(crate) fn resolve(&mut self, commands: &mut Commands, layout_cache: &mut LayoutCache) {
        let mut stack = vec![0];

        #[allow(clippy::manual_while_let_some)]
        while !stack.is_empty() {
            let layer_id = stack.pop().unwrap();
            let parent_id = self.layers.get(layer_id).map(|l| l.parent_id).unwrap();
            let parent_z = {
                self.layers
                    .get(parent_id)
                    .map(|l| l.custom_z)
                    .unwrap_or(0.0)
            };
            let children = self.children.get(&layer_id).cloned().unwrap_or_default();
            stack.extend(children);
            let layer = &mut self.layers[layer_id];
            let quad_count = layer.quads.len();
            layer.z = (layer_id.max(parent_id) as f32) + parent_z + layer.custom_z;
            layer.custom_z = if layer.custom_z > 0.0 {
                layer.custom_z
            } else {
                parent_z
            };
            for (i, quad) in layer.quads.iter_mut().enumerate() {
                let current_z = layer.z + (((i + 1) as f32 / quad_count as f32) * 0.999);
                match quad {
                    QuadOrMaterial::Material(entity) => {
                        commands.entity(*entity).insert(MaterialZ(current_z));
                    }
                    QuadOrMaterial::Quad(quad) => {
                        quad.z_index = current_z;
                        if quad.org_entity != Entity::PLACEHOLDER {
                            if let Some(layout) = layout_cache
                                .rect
                                .get_mut(&crate::node::WrappedIndex(quad.org_entity))
                            {
                                layout.z_index = Some(quad.z_index);
                            }
                        }
                    }
                }

                // Propagate z up the tree until we hit a parent with a Z value set.
                // let mut has_z = false;
                // let mut current_node = WrappedIndex(quad.get_entity());
                // while !has_z {
                //     if let Some(parent) = tree.get_parent(current_node) {
                //         if let Some(layout) = layout_cache.rect.get_mut(&parent) {
                //             if layout.z_index.is_none() {
                //                 layout.z_index = Some(current_z);
                //                 current_node = parent;
                //                 continue;
                //             }
                //         }
                //     }
                //     has_z = true;
                // }
            }
        }
    }

    pub fn debug(&self) {
        let mut items = vec![];
        let mut stack = vec![0];
        #[allow(clippy::manual_while_let_some)]
        while !stack.is_empty() {
            let layer_id = stack.pop().unwrap();
            let parent_id = self.layers.get(layer_id).map(|l| l.parent_id).unwrap_or(0);
            // let parent_z = {
            //     self.layers
            //         .get(self.parents.get(&parent_id).map(|id| *id).unwrap_or(0))
            //         .map(|l| l.z)
            //         .unwrap_or(0.0)
            // };
            let children = self.children.get(&layer_id).cloned().unwrap_or_default();
            stack.extend(children);
            let layer = &self.layers[layer_id];

            let qt = layer
                .quads
                .first()
                .map(|q| match q {
                    QuadOrMaterial::Quad(q) => q.quad_type,
                    _ => UIQuadType::None,
                })
                .unwrap_or(UIQuadType::None);
            // let rect = layer
            //     .quads
            //     .first()
            //     .map(|q| match q {
            //         QuadOrMaterial::Quad(q) => q.rect,
            //         _ => Rect::default(),
            //     })
            //     .unwrap_or(Rect::default());
            if qt != UIQuadType::None {
                // items.push((layer.z, format!("{}type: {:?}, layer_id: {}, parent_id: {}, parent_z: {}, z: {}, rect: {:?}", " ".repeat(parent_id + 1), qt, layer_id, parent_id, parent_z, layer.z, rect)));
            }
            if !layer.quads.is_empty() {
                // println!("{}Quads:", " ".repeat(parent_id + 1));
                let mut last_type = UIQuadType::None;
                for quad in layer.quads.iter() {
                    #[allow(clippy::single_match)]
                    match quad {
                        QuadOrMaterial::Quad(q) => {
                            if last_type != q.quad_type {
                                items.push((
                                    q.z_index,
                                    format!(
                                        "{}Q: {:?}, c: {}, rect: {:?}, z: {}",
                                        " ".repeat(parent_id + 1),
                                        q.quad_type,
                                        q.c,
                                        q.rect,
                                        q.z_index
                                    ),
                                ));
                                last_type = q.quad_type;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        items.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        for (_, item) in items.iter() {
            println!("{}", item);
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &ExtractedQuad> + '_ {
        self.layers
            .iter()
            .flat_map(|layer| &layer.quads)
            .filter_map(|quad| match &quad {
                QuadOrMaterial::Material(_) => None,
                QuadOrMaterial::Quad(quad) => match quad.quad_type {
                    UIQuadType::None => None,
                    _ => Some(quad),
                },
            })
    }
}

#[derive(Component)]
pub struct MaterialZ(pub f32);

#[derive(Default, Debug)]
pub struct ZLayer {
    pub z: f32,
    pub custom_z: f32,
    pub parent_id: usize,
    pub quads: Vec<QuadOrMaterial>,
}

#[derive(Debug, Component, PartialEq, Clone)]
pub struct QuadBatch {
    pub image_handle_id: Option<Handle<Image>>,
    pub font_handle_id: Option<Handle<KayakFont>>,
    pub quad_type: UIQuadType,
    pub type_id: u32,
    pub z_index: f32,
}

#[derive(Default, Resource)]
pub struct ImageBindGroups {
    values: HashMap<Handle<Image>, BindGroup>,
    font_values: HashMap<Handle<KayakFont>, BindGroup>,
    previous_sizes: HashMap<Handle<Image>, Vec2>,
}

#[derive(Component, Debug)]
pub struct UIViewBindGroup {
    pub value: BindGroup,
}

pub fn queue_ui_view_bind_groups(
    mut commands: Commands,
    render_device: Res<RenderDevice>,
    unified_pipeline: Res<UnifiedPipeline>,
    view_uniforms: Res<UIViewUniforms>,
    views: Query<Entity, With<UIExtractedView>>,
    globals_buffer: Res<GlobalsBuffer>,
) {
    if let (Some(view_binding), Some(globals)) = (
        view_uniforms.uniforms.binding(),
        globals_buffer.buffer.binding(),
    ) {
        for entity in &views {
            let view_bind_group = render_device.create_bind_group(
                Some("ui_view_bind_group"),
                &unified_pipeline.view_layout,
                &[
                    BindGroupEntry {
                        binding: 0,
                        resource: view_binding.clone(),
                    },
                    BindGroupEntry {
                        binding: 1,
                        resource: globals.clone(),
                    },
                ],
            );
            commands.entity(entity).insert(UIViewBindGroup {
                value: view_bind_group,
            });
        }
    }
}

#[derive(Resource, Default, Debug, Clone, Copy)]
pub struct QuadTypeOffsets {
    pub quad_type_offset: u32,
    pub text_sub_pixel_type_offset: u32,
    pub text_type_offset: u32,
    pub image_type_offset: u32,
    pub box_shadow_type_offset: u32,
}

pub fn queue_quad_types(
    mut commands: Commands,
    quad_pipeline: Res<UnifiedPipeline>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    mut quad_meta: ResMut<QuadMeta>,
) {
    quad_meta.types_buffer.clear();
    // sprite_meta.types_buffer.reserve(2, &render_device);
    let quad_type_offset = quad_meta.types_buffer.push(&QuadType {
        t: 0,
        _padding_1: 0,
        _padding_2: 0,
        _padding_3: 0,
    });
    let text_sub_pixel_type_offset = quad_meta.types_buffer.push(&QuadType {
        t: 1,
        _padding_1: 0,
        _padding_2: 0,
        _padding_3: 0,
    });
    let text_type_offset = quad_meta.types_buffer.push(&QuadType {
        t: 2,
        _padding_1: 0,
        _padding_2: 0,
        _padding_3: 0,
    });
    let image_type_offset = quad_meta.types_buffer.push(&QuadType {
        t: 3,
        _padding_1: 0,
        _padding_2: 0,
        _padding_3: 0,
    });
    let box_shadow_type_offset = quad_meta.types_buffer.push(&QuadType {
        t: 4,
        _padding_1: 0,
        _padding_2: 0,
        _padding_3: 0,
    });
    let quad_type_offsets = QuadTypeOffsets {
        quad_type_offset,
        text_sub_pixel_type_offset,
        text_type_offset,
        image_type_offset,
        box_shadow_type_offset,
    };
    commands.insert_resource(quad_type_offsets);

    quad_meta
        .types_buffer
        .write_buffer(&render_device, &render_queue);

    if let Some(type_binding) = quad_meta.types_buffer.binding() {
        quad_meta.types_bind_group = Some(render_device.create_bind_group(
            Some("quad_type_bind_group"),
            &quad_pipeline.types_layout,
            &[BindGroupEntry {
                binding: 0,
                resource: type_binding,
            }],
        ));
    }
}

#[derive(Resource, Default)]
pub struct PreviousClip {
    pub rect: Rect,
}

#[derive(Resource, Default)]
pub struct PreviousIndex {
    pub index: u32,
    pub last_clip: Rect,
}

#[derive(SystemParam)]
pub struct QueueQuads<'w, 's> {
    #[cfg(feature = "svg")]
    render_svgs: Res<'w, RenderSvgs>,
    opacity_layers: Res<'w, OpacityLayerManager>,
    commands: Commands<'w, 's>,
    draw_functions: Res<'w, DrawFunctions<TransparentUI>>,
    draw_functions_opacity: Res<'w, DrawFunctions<TransparentOpacityUI>>,
    render_device: Res<'w, RenderDevice>,
    render_queue: Res<'w, RenderQueue>,
    quad_meta: ResMut<'w, QuadMeta>,
    quad_pipeline: Res<'w, UnifiedPipeline>,
    pipelines: ResMut<'w, SpecializedRenderPipelines<UnifiedPipeline>>,
    pipeline_cache: Res<'w, PipelineCache>,
    extracted_quads: Res<'w, ExtractedQuads>,
    views: Query<
        'w,
        's,
        (
            Entity,
            &'static mut UIRenderPhase<TransparentUI>,
            &'static mut UIRenderPhase<TransparentOpacityUI>,
            &'static UIExtractedView,
        ),
    >,
    image_bind_groups: ResMut<'w, ImageBindGroups>,
    unified_pipeline: Res<'w, UnifiedPipeline>,
    gpu_images: Res<'w, RenderAssets<Image>>,
    font_texture_cache: Res<'w, FontTextureCache>,
    quad_type_offsets: Res<'w, QuadTypeOffsets>,
    prev_clip: ResMut<'w, PreviousClip>,
    prev_index: ResMut<'w, PreviousIndex>,
    view_uniforms: Res<'w, UIViewUniforms>,
}

pub fn queue_quads(queue_quads: QueueQuads) {
    let QueueQuads {
        #[cfg(feature = "svg")]
        render_svgs,
        opacity_layers,
        mut commands,
        draw_functions,
        draw_functions_opacity,
        render_device,
        render_queue,
        mut quad_meta,
        quad_pipeline,
        mut pipelines,
        pipeline_cache,
        extracted_quads,
        mut views,
        mut image_bind_groups,
        unified_pipeline,
        gpu_images,
        font_texture_cache,
        quad_type_offsets,
        mut prev_clip,
        mut prev_index,
        view_uniforms,
    } = queue_quads;

    if view_uniforms.uniforms.buffer().is_none() {
        return;
    }

    let mut extracted_quads = extracted_quads.iter().collect::<Vec<_>>();

    extracted_quads.sort_unstable_by(|a, b| a.z_index.partial_cmp(&b.z_index).unwrap());

    // let mut last_type = UIQuadType::None;
    // for (t, z, rect) in extracted_quads.iter().map(|q| (q.quad_type, q.z_index, q.rect)) {
    //     if !(t == UIQuadType::Text && last_type == UIQuadType::Text) {
    //         println!("type: {:?}, z: {}, rect: {:?}", t, z, rect);
    //         last_type = t;
    //     }
    // }

    let extracted_sprite_len = extracted_quads.len();
    // don't create buffers when there are no quads
    if extracted_sprite_len == 0 {
        return;
    }

    quad_meta.vertices.clear();
    quad_meta.vertices.reserve(
        extracted_sprite_len * QUAD_VERTEX_POSITIONS.len(),
        &render_device,
    );

    // Sort sprites by z for correct transparency and then by handle to improve batching
    // NOTE: This can be done independent of views by reasonably assuming that all 2D views look along the negative-z axis in world space
    let mut current_batch = QuadBatch {
        image_handle_id: None,
        font_handle_id: None,
        quad_type: UIQuadType::None,
        type_id: quad_type_offsets.quad_type_offset,
        z_index: 0.0,
    };
    let mut current_batch_entity = Entity::PLACEHOLDER;

    // Vertex buffer indices
    let mut index = 0;
    let mut item_start = 0;
    let mut item_end = 0;
    let mut old_item_start = 0;
    let mut current_clip = Rect::default();
    let mut last_clip = Rect::default();

    let draw_quad = draw_functions.read().get_id::<DrawUI>().unwrap();
    let draw_opacity_quad = draw_functions_opacity
        .read()
        .get_id::<DrawUITransparent>()
        .unwrap();
    for (camera_entity, mut transparent_phase, mut opacity_transparent_phase, view) in
        views.iter_mut()
    {
        let key = UnifiedPipelineKey {
            msaa: 1,
            hdr: view.hdr,
        };
        let spec_pipeline = pipelines.specialize(&pipeline_cache, &quad_pipeline, key);

        let mut last_quad = ExtractedQuad::default();

        for quad in extracted_quads.iter() {
            if quad.quad_type == UIQuadType::Clip {
                prev_clip.rect = quad.rect;
            }

            queue_quads_inner(
                &mut commands,
                &render_device,
                &font_texture_cache,
                &opacity_layers,
                &mut image_bind_groups,
                &gpu_images,
                &unified_pipeline,
                #[cfg(feature = "svg")]
                &render_svgs,
                &mut transparent_phase,
                &mut opacity_transparent_phase,
                draw_opacity_quad,
                draw_quad,
                spec_pipeline,
                &mut quad_meta,
                quad,
                camera_entity,
                *quad_type_offsets,
                &mut current_batch,
                &mut current_batch_entity,
                &mut index,
                &mut item_start,
                &mut item_end,
                &last_quad,
                &mut current_clip,
                &mut old_item_start,
                &mut last_clip,
            );

            last_quad = (*quad).clone();
        }

        #[allow(clippy::nonminimal_bool)]
        if last_quad.quad_type != UIQuadType::Clip
            && last_quad.quad_type != UIQuadType::OpacityLayer
            && last_quad.quad_type != UIQuadType::Clip
            && current_batch_entity != Entity::PLACEHOLDER
        {
            commands
                .entity(current_batch_entity)
                .insert(current_batch.clone());

            if last_quad.opacity_layer > 0 && last_quad.quad_type != UIQuadType::DrawOpacityLayer {
                opacity_transparent_phase.add(TransparentOpacityUI {
                    draw_function: draw_opacity_quad,
                    pipeline: spec_pipeline,
                    entity: current_batch_entity,
                    sort_key: FloatOrd(last_quad.z_index),
                    quad_type: last_quad.quad_type,
                    type_index: last_quad.quad_type.get_type_index(&quad_type_offsets),
                    rect: last_clip,
                    batch_range: Some(old_item_start..item_end),