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
mod key;
mod pipeline;
mod plugin;

use std::sync::Arc;

use bevy::{
    prelude::{Commands, Entity},
    reflect::{FromReflect, Reflect, TypeUuid},
    render::render_resource::{AsBindGroup, RenderPipelineDescriptor, ShaderRef},
};

pub use key::*;
pub use pipeline::*;
pub use plugin::*;

pub trait MaterialUI: AsBindGroup + Send + Sync + Clone + TypeUuid + Sized + 'static {
    /// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader
    /// will be used.
    fn vertex_shader() -> ShaderRef {
        ShaderRef::Default
    }

    /// Returns this material's fragment shader. If [`ShaderRef::Default`] is returned, the default mesh fragment shader
    /// will be used.
    fn fragment_shader() -> ShaderRef {
        ShaderRef::Default
    }

    /// Customizes the default [`RenderPipelineDescriptor`].
    #[allow(unused_variables)]
    #[inline]
    fn specialize(descriptor: &mut RenderPipelineDescriptor, key: MaterialUIKey<Self>) {}
}

#[derive(Default, Clone, Reflect, FromReflect)]
pub struct MaterialHandle {
    uuid: String,
    #[reflect(ignore)]
    closure: HandleClosure,
}

#[derive(Clone)]
pub struct HandleClosure {
    pub(crate) c: Arc<dyn Fn(&mut Commands, Entity)>,
}

unsafe impl Send for HandleClosure {}
unsafe impl Sync for HandleClosure {}

impl Default for HandleClosure {
    fn default() -> Self {
        Self {
            c: Arc::new(|_, _| {}),
        }
    }
}

impl core::fmt::Debug for MaterialHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MaterialHandle")
            .field("uuid", &self.uuid)
            .finish()
    }
}

impl PartialEq for MaterialHandle {
    fn eq(&self, other: &Self) -> bool {
        self.uuid == other.uuid
    }
}

impl MaterialHandle {
    pub fn new<F>(closure: F) -> Self
    where
        F: Fn(&mut Commands, Entity) + 'static,
    {
        Self {
            uuid: uuid::Uuid::new_v4().to_string(),
            closure: HandleClosure {
                c: Arc::new(closure),
            },
        }
    }

    pub fn run(&self, commands: &mut Commands, id: Entity) {
        self.closure.c.as_ref()(commands, id);
    }
}