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
use {
    crate::{
        bind::{self, Binder, ForeignShader, GroupHandler, UniqueBinding, Visit},
        draw::Draw,
        instance::Row,
        layer::{Config, Layer},
        mesh::{self, Mesh},
        shader::Shader,
        sl::IntoModule,
        state::{AsTarget, State},
        texture::{self, CopyBuffer, CopyBufferView, Filter, Make, MapResult, Mapped, Sampler},
        uniform::{IntoValue, Uniform, Value},
        Vertex,
    },
    std::{error, fmt, future::IntoFuture, sync::Arc},
};

/// Creates the context instance.
///
/// If you need a window call the [`window`] function.
///
/// # Errors
/// Returns an error when the context could not be created.
/// See [`FailedMakeContext`] for details.
pub async fn context() -> Result<Context, FailedMakeContext> {
    Context::new().await
}

/// The main dunge context.
///
/// It can be created via the [`context`](fn@crate::context) function
/// or the [`window`](fn@crate::window) function if you need a window
/// and the `winit` feature is enabled.
#[derive(Clone)]
pub struct Context(Arc<State>);

impl Context {
    pub(crate) async fn new() -> Result<Self, FailedMakeContext> {
        use wgpu::{Backends, Instance, InstanceDescriptor, InstanceFlags};

        let backends;

        #[cfg(any(target_family = "unix", target_family = "windows"))]
        {
            backends = Backends::VULKAN;
        }

        #[cfg(target_family = "wasm")]
        {
            backends = Backends::BROWSER_WEBGPU;
        }

        let instance = {
            let desc = InstanceDescriptor {
                backends,
                flags: InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER,
                ..Default::default()
            };

            Instance::new(desc)
        };

        let state = State::new(instance).await?;
        Ok(Self(Arc::new(state)))
    }

    pub(crate) fn state(&self) -> &State {
        &self.0
    }

    pub fn make_shader<M, A>(&self, module: M) -> Shader<M::Vertex, M::Instance>
    where
        M: IntoModule<A>,
    {
        Shader::new(&self.0, module)
    }

    pub fn make_binder<'a, V, I>(&'a self, shader: &'a Shader<V, I>) -> Binder<'a> {
        Binder::new(&self.0, shader)
    }

    pub fn make_uniform<U>(&self, val: U) -> Uniform<U::Value>
    where
        U: IntoValue,
    {
        let val = val.into_value();
        Uniform::new(&self.0, val.value().as_ref())
    }

    pub fn make_layer<V, I, O>(&self, shader: &Shader<V, I>, opts: O) -> Layer<V, I>
    where
        O: Into<Config>,
    {
        let opts = opts.into();
        Layer::new(&self.0, shader, &opts)
    }

    pub fn make_mesh<V>(&self, data: &mesh::MeshData<V>) -> Mesh<V>
    where
        V: Vertex,
    {
        Mesh::new(&self.0, data)
    }

    pub fn make_row<U>(&self, data: &[U]) -> Row<U>
    where
        U: Value,
    {
        Row::new(&self.0, data)
    }

    pub fn make_texture<M>(&self, data: M) -> M::Out
    where
        M: Make,
    {
        texture::make(&self.0, data)
    }

    pub fn make_sampler(&self, filter: Filter) -> Sampler {
        Sampler::new(&self.0, filter)
    }

    pub fn make_copy_buffer(&self, size: (u32, u32)) -> CopyBuffer {
        CopyBuffer::new(&self.0, size)
    }

    pub async fn map_view<'a, S, R, F>(&self, view: CopyBufferView<'a>, tx: S, rx: R) -> Mapped<'a>
    where
        S: FnOnce(MapResult) + wgpu::WasmNotSend + 'static,
        R: FnOnce() -> F,
        F: IntoFuture<Output = MapResult>,
    {
        view.map(&self.0, tx, rx).await
    }

    pub fn update_group<G>(
        &self,
        uni: &mut UniqueBinding,
        handler: &GroupHandler<G::Projection>,
        group: &G,
    ) -> Result<(), ForeignShader>
    where
        G: Visit,
    {
        bind::update(&self.0, uni, handler, group)
    }

    pub fn draw_to<T, D>(&self, target: &T, draw: D)
    where
        T: AsTarget,
        D: Draw,
    {
        let target = target.as_target();
        self.0.draw(target, draw);
    }
}

/// An error returned from the [context](Context) constructor.
#[derive(Debug)]
pub enum FailedMakeContext {
    BackendSelection,
    RequestDevice(wgpu::RequestDeviceError),
}

impl fmt::Display for FailedMakeContext {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::BackendSelection => write!(f, "failed to select backend"),
            Self::RequestDevice(err) => write!(f, "failed to get device: {err}"),
        }
    }
}

impl error::Error for FailedMakeContext {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::BackendSelection => None,
            Self::RequestDevice(err) => Some(err),
        }
    }
}