1
2use crate::context::Context;
3
4#[derive(Clone, PartialEq, Eq, Hash, Debug)]
10pub struct Sampler {
11 clamp: bool,
12 linear: bool,
13 mipmap_linear: bool,
14}
15
16impl Sampler {
17 pub(crate) fn sampler_type(&self) -> wgpu::SamplerBindingType {
18 if self.linear || self.mipmap_linear {
19 wgpu::SamplerBindingType::Filtering
20 } else {
21 wgpu::SamplerBindingType::NonFiltering
22 }
23 }
24
25 pub(crate) fn get_or_build(&self, context: &Context) -> wgpu::Sampler {
26 let mut sampler_cache = context.caches.sampler_cache.borrow_mut();
27
28 let address_mode = if self.clamp {
29 wgpu::AddressMode::ClampToEdge
30 } else {
31 wgpu::AddressMode::Repeat
32 };
33
34 let filter = if self.linear {
35 wgpu::FilterMode::Linear
36 } else {
37 wgpu::FilterMode::Nearest
38 };
39
40 let mipmap_filter = if self.mipmap_linear {
41 wgpu::FilterMode::Linear
42 } else {
43 wgpu::FilterMode::Nearest
44 };
45
46 sampler_cache
47 .get_or_insert_with(self.clone(), || {
48 context.device().create_sampler(&wgpu::SamplerDescriptor {
49 label: Some("mip"),
50 address_mode_u: address_mode,
51 address_mode_v: address_mode,
52 address_mode_w: address_mode,
53 mag_filter: filter,
54 min_filter: filter,
55 mipmap_filter,
56 ..Default::default()
57 })
58 })
59 .clone()
60 }
61}
62
63pub struct SamplerBuilder {
65 clamp: bool,
66 linear: bool,
67 mipmap_linear: bool,
68}
69
70impl SamplerBuilder {
71 pub fn new() -> Self {
72 Self {
73 clamp: true,
74 linear: true,
75 mipmap_linear: true,
76 }
77 }
78
79 pub fn clamp(mut self) -> Self {
80 self.clamp = true;
81 self
82 }
83
84 pub fn wrap(mut self) -> Self {
85 self.clamp = false;
86 self
87 }
88
89 pub fn linear(mut self) -> Self {
90 self.linear = true;
91 self
92 }
93 pub fn nearest(mut self) -> Self {
94 self.linear = false;
95 self
96 }
97
98 pub fn mipmap_linear(mut self) -> Self {
99 self.mipmap_linear = true;
100 self
101 }
102 pub fn mipmap_nearest(mut self) -> Self {
103 self.mipmap_linear = false;
104 self
105 }
106
107 pub fn build(self) -> Sampler {
108 Sampler {
109 clamp: self.clamp,
110 linear: self.linear,
111 mipmap_linear: self.mipmap_linear,
112 }
113 }
114}