sketch_2d/
store.rs

1/*
2 * Created on Thu Jul 06 2023
3 *
4 * Copyright (c) storycraft. Licensed under the MIT Licence.
5 */
6
7use fn_store::{AtomicFnStore, LocalFnStore};
8use wgpu::{Device, Queue};
9
10use crate::pipeline::RenderPipelineData;
11
12#[derive(Debug, Default)]
13pub struct BackendData(AtomicFnStore<'static>);
14
15impl BackendData {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    pub const fn as_ref<'a>(
21        &'a self,
22        device: &'a Device,
23        queue: &'a Queue,
24    ) -> BackendFnStore<'a> {
25        BackendFnStore {
26            device,
27            queue,
28            store: &self.0,
29        }
30    }
31}
32
33#[derive(Debug, Default)]
34pub struct RenderData(LocalFnStore<'static>);
35
36impl RenderData {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    pub const fn as_ref<'a>(
42        &'a self,
43        backend: BackendFnStore<'a>,
44        pipeline: &'a RenderPipelineData,
45    ) -> RenderFnStore<'a> {
46        RenderFnStore {
47            backend,
48            pipeline,
49            store: &self.0,
50        }
51    }
52}
53
54#[derive(Debug, Clone)]
55pub struct BackendFnStore<'a> {
56    device: &'a Device,
57    queue: &'a Queue,
58    store: &'a AtomicFnStore<'static>,
59}
60
61impl<'a> BackendFnStore<'a> {
62    pub const fn device(&self) -> &'a Device {
63        self.device
64    }
65
66    pub const fn queue(&self) -> &'a Queue {
67        self.queue
68    }
69
70    pub fn get<T: Sync + Send + 'static>(&self, func: impl FnOnce(&Self) -> T) -> &'a T {
71        self.store.get(|| func(self))
72    }
73}
74
75#[derive(Debug, Clone)]
76pub struct RenderFnStore<'a> {
77    backend: BackendFnStore<'a>,
78    pipeline: &'a RenderPipelineData,
79    store: &'a LocalFnStore<'static>,
80}
81
82impl<'a> RenderFnStore<'a> {
83    pub const fn backend(&self) -> &BackendFnStore<'a> {
84        &self.backend
85    }
86
87    pub const fn pipeline(&self) -> &'a RenderPipelineData {
88        self.pipeline
89    }
90
91    pub fn get<T: Send + 'static>(&self, func: impl FnOnce(&Self) -> T) -> &'a T {
92        self.store.get(|| func(self))
93    }
94}