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
use std::collections::{LinkedList, VecDeque};

use crate::core::{
    BufferMut, BufferRef, CreateFrom, Metadata, ReadFrom, Reader, RuntimeSizedArray, ShaderSize,
    WriteInto, Writer,
};
use crate::ShaderType;

/// Helper type meant to be used together with the [`derive@ShaderType`] derive macro
///
/// This type should be interpreted as an [`u32`] in the shader
///
/// # Problem
///
/// There are cases where the use of the WGSL function [`arrayLength()`](https://gpuweb.github.io/gpuweb/wgsl/#array-builtin-functions)
/// might be inadequate because of its return value
///
/// - being a minimum of 1 due to how [`minBindingSize` is calculated](https://gpuweb.github.io/gpuweb/#ref-for-dom-gpubufferbindinglayout-minbindingsize%E2%91%A7)
///
/// - possibly being higher than expected due to padding at the end of a struct or buffer being interpreted as array elements
///
/// - representing the capacity of the array for usecaseses that require oversized buffers
///
/// # Solution
///
/// Using this type on a field of a struct with the [`derive@ShaderType`] derive macro will automatically:
///
/// - on write, write the length of the contained runtime-sized array as an [`u32`] to the buffer
///
/// - on read, read the value as an [`u32`] from the buffer (rep as `LEN`) and when reading the elements of the contained runtime-sized array a max of `LEN` elements will be read
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArrayLength;

impl ShaderType for ArrayLength {
    type ExtraMetadata = ();
    const METADATA: Metadata<Self::ExtraMetadata> = Metadata::from_alignment_and_size(4, 4);
}

impl ShaderSize for ArrayLength {}

impl WriteInto for ArrayLength {
    fn write_into<B: BufferMut>(&self, writer: &mut Writer<B>) {
        let length = writer.ctx.rts_array_length.unwrap();
        WriteInto::write_into(&length, writer);
    }
}

impl ReadFrom for ArrayLength {
    fn read_from<B: BufferRef>(&mut self, reader: &mut Reader<B>) {
        let length = CreateFrom::create_from(reader);
        reader.ctx.rts_array_max_el_to_read = Some(length);
    }
}

impl CreateFrom for ArrayLength {
    fn create_from<B: BufferRef>(reader: &mut Reader<B>) -> Self {
        let length = CreateFrom::create_from(reader);
        reader.ctx.rts_array_max_el_to_read = Some(length);
        ArrayLength
    }
}

pub trait Length {
    fn length(&self) -> usize;
}

pub trait Truncate {
    fn truncate(&mut self, _len: usize);
}

/// Used to implement `ShaderType` for the given runtime-sized array type
///
/// The given runtime-sized array type should implement [`Length`] and optionally [`Truncate`]
/// depending on needed capability (they can also be derived via `$using`)
///
/// # Args
///
/// - `$type` the type (representing a runtime-sized array) for which `ShaderType` will be imeplemented for
///
/// - `$generics` \[optional\] generics that will be passed into the `impl< >`
///
/// - `$using` \[optional\] can be any combination of `len truncate`
#[macro_export]
macro_rules! impl_rts_array {
    ($type:ty $( ; using $($using:tt)* )?) => {
        $crate::impl_rts_array_inner!(__inner, ($type, T); $( $($using)* )?);
    };
    ($type:ty; ($($generics:tt)*) $( ; using $($using:tt)* )?) => {
        $crate::impl_rts_array_inner!(__inner, ($type, $($generics)*); $( $($using)* )?);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_rts_array_inner {
    (__inner, ($($other:tt)*); len $($using:tt)*) => {
        $crate::impl_rts_array_inner!(__len, $($other)*);
        $crate::impl_rts_array_inner!(__inner, ($($other)*); $($using)*);
    };
    (__inner, ($($other:tt)*); truncate $($using:tt)*) => {
        $crate::impl_rts_array_inner!(__truncate, $($other)*);
        $crate::impl_rts_array_inner!(__inner, ($($other)*); $($using)*);
    };
    (__inner, ($type:ty, $($generics:tt)*); ) => {
        $crate::impl_rts_array_inner!(__main, $type, $($generics)*);
    };

    (__len, $type:ty, $($generics:tt)*) => {
        impl<$($generics)*> $crate::private::Length for $type {
            fn length(&self) -> ::core::primitive::usize {
                self.len()
            }
        }
    };
    (__truncate, $type:ty, $($generics:tt)*) => {
        impl<$($generics)*> $crate::private::Truncate for $type {
            fn truncate(&mut self, len: ::core::primitive::usize) {
                self.truncate(len)
            }
        }
    };
    (__main, $type:ty, $($generics:tt)*) => {
        impl<$($generics)*> $crate::private::ShaderType for $type
        where
            T: $crate::private::ShaderType + $crate::private::ShaderSize,
            Self: $crate::private::Length,
        {
            type ExtraMetadata = $crate::private::ArrayMetadata;
            const METADATA: $crate::private::Metadata<Self::ExtraMetadata> = {
                let alignment = T::METADATA.alignment();
                let el_size = $crate::private::SizeValue::from(T::SHADER_SIZE);

                let stride = alignment.round_up_size(el_size);
                let el_padding = alignment.padding_needed_for(el_size.get());

                $crate::private::Metadata {
                    alignment,
                    has_uniform_min_alignment: true,
                    min_size: el_size,
                    extra: $crate::private::ArrayMetadata { stride, el_padding },
                }
            };

            const UNIFORM_COMPAT_ASSERT: fn() = ||
                ::core::panic!("runtime-sized array can't be used in uniform buffers");

            fn size(&self) -> ::core::num::NonZeroU64 {
                use ::core::cmp::Ord;

                Self::METADATA.stride()
                    .mul($crate::private::Length::length(self).max(1) as ::core::primitive::u64)
                    .0
            }
        }

        impl<$($generics)*> $crate::private::RuntimeSizedArray for $type
        where
            Self: $crate::private::Length,
        {
            fn len(&self) -> ::core::primitive::usize {
                $crate::private::Length::length(self)
            }
        }

        impl<$($generics)*> $crate::private::CalculateSizeFor for $type
        where
            Self: $crate::private::ShaderType<ExtraMetadata = $crate::private::ArrayMetadata>,
        {
            fn calculate_size_for(nr_of_el: ::core::primitive::u64) -> ::core::num::NonZeroU64 {
                use ::core::cmp::Ord;

                <Self as $crate::private::ShaderType>::METADATA.stride().mul(nr_of_el.max(1)).0
            }
        }

        impl<$($generics)*> $crate::private::WriteInto for $type
        where
            T: $crate::private::WriteInto,
            Self: $crate::private::ShaderType<ExtraMetadata = $crate::private::ArrayMetadata>,
            for<'a> &'a Self: ::core::iter::IntoIterator<Item = &'a T>,
        {
            fn write_into<B: $crate::private::BufferMut>(&self, writer: &mut $crate::private::Writer<B>) {
                use ::core::iter::IntoIterator;

                for item in self.into_iter() {
                    $crate::private::WriteInto::write_into(item, writer);
                    writer.advance(<Self as $crate::private::ShaderType>::METADATA.el_padding() as ::core::primitive::usize);
                }
            }
        }

        impl<$($generics)*> $crate::private::ReadFrom for $type
        where
            T: $crate::private::ReadFrom + $crate::private::CreateFrom,
            Self: $crate::private::Truncate + $crate::private::Length + ::core::iter::Extend<T> + $crate::private::ShaderType<ExtraMetadata = $crate::private::ArrayMetadata>,
            for<'a> &'a mut Self: ::core::iter::IntoIterator<Item = &'a mut T>,
        {
            fn read_from<B: $crate::private::BufferRef>(&mut self, reader: &mut $crate::private::Reader<B>) {
                use ::core::cmp::Ord;
                use ::core::iter::{IntoIterator, Extend, Iterator};

                let max = reader.ctx.rts_array_max_el_to_read.unwrap_or(::core::primitive::u32::MAX) as ::core::primitive::usize;
                let count = max.min(reader.remaining() / <Self as $crate::private::ShaderType>::METADATA.stride().get() as ::core::primitive::usize);
                $crate::private::Truncate::truncate(self, count);

                for item in self.into_iter() {
                    $crate::private::ReadFrom::read_from(item, reader);
                    reader.advance(<Self as $crate::private::ShaderType>::METADATA.el_padding() as ::core::primitive::usize);
                }

                let remaining = count - $crate::private::Length::length(self);
                self.extend(
                    ::core::iter::repeat_with(|| {
                        let el = $crate::private::CreateFrom::create_from(reader);
                        reader.advance(<Self as $crate::private::ShaderType>::METADATA.el_padding() as ::core::primitive::usize);
                        el
                    })
                    .take(remaining),
                );
            }
        }

        impl<$($generics)*> $crate::private::CreateFrom for $type
        where
            T: $crate::private::CreateFrom,
            Self: ::core::iter::FromIterator<T> + $crate::private::ShaderType<ExtraMetadata = $crate::private::ArrayMetadata>,
        {
            fn create_from<B: $crate::private::BufferRef>(reader: &mut $crate::private::Reader<B>) -> Self {
                use ::core::cmp::Ord;
                use ::core::iter::Iterator;

                let max = reader.ctx.rts_array_max_el_to_read.unwrap_or(::core::primitive::u32::MAX) as ::core::primitive::usize;
                let count = max.min(reader.remaining() / <Self as $crate::private::ShaderType>::METADATA.stride().get() as ::core::primitive::usize);

                ::core::iter::FromIterator::from_iter(
                    ::core::iter::repeat_with(|| {
                        let el = $crate::private::CreateFrom::create_from(reader);
                        reader.advance(<Self as $crate::private::ShaderType>::METADATA.el_padding() as ::core::primitive::usize);
                        el
                    })
                    .take(count),
                )
            }
        }
    };
}

impl_rts_array!([T]; using len);
impl_rts_array!(Vec<T>; using len truncate);
impl_rts_array!(VecDeque<T>; using len truncate);
impl_rts_array!(LinkedList<T>; using len);

impl<T> Truncate for LinkedList<T> {
    fn truncate(&mut self, len: usize) {
        if len < self.len() {
            self.split_off(len);
        }
    }
}

#[cfg(test)]
mod array_length {
    use super::ArrayLength;

    #[test]
    fn derived_traits() {
        assert_eq!(ArrayLength, ArrayLength.clone());

        assert_eq!(format!("{ArrayLength:?}"), "ArrayLength");
    }
}