Struct ResMut

Source
pub struct ResMut<'w, T>
where T: Resource + ?Sized,
{ /* private fields */ }
Expand description

Unique mutable borrow of a Resource.

See the Resource documentation for usage.

If you need a shared borrow, use Res instead.

This SystemParam fails validation if resource doesn’t exist. This will cause a panic, but can be configured to do nothing or warn once.

Use Option<ResMut<T>> instead if the resource might not always exist.

Implementations§

Source§

impl<'w, T> ResMut<'w, T>
where T: Resource + ?Sized,

Source

pub fn into_inner(self) -> &'w mut T

Consume self and return a mutable reference to the contained value while marking self as “changed”.

Examples found in repository?
examples/stress_tests/bevymark.rs (line 189)
180fn scheduled_spawner(
181    mut commands: Commands,
182    args: Res<Args>,
183    window: Single<&Window>,
184    mut scheduled: ResMut<BirdScheduled>,
185    mut counter: ResMut<BevyCounter>,
186    bird_resources: ResMut<BirdResources>,
187) {
188    if scheduled.waves > 0 {
189        let bird_resources = bird_resources.into_inner();
190        spawn_birds(
191            &mut commands,
192            args.into_inner(),
193            &window.resolution,
194            &mut counter,
195            scheduled.per_wave,
196            bird_resources,
197            None,
198            scheduled.waves - 1,
199        );
200
201        scheduled.waves -= 1;
202    }
203}
204
205#[derive(Resource)]
206struct BirdResources {
207    textures: Vec<Handle<Image>>,
208    materials: Vec<Handle<ColorMaterial>>,
209    quad: Handle<Mesh>,
210    color_rng: ChaCha8Rng,
211    material_rng: ChaCha8Rng,
212    velocity_rng: ChaCha8Rng,
213    transform_rng: ChaCha8Rng,
214}
215
216#[derive(Component)]
217struct StatsText;
218
219fn setup(
220    mut commands: Commands,
221    args: Res<Args>,
222    asset_server: Res<AssetServer>,
223    mut meshes: ResMut<Assets<Mesh>>,
224    material_assets: ResMut<Assets<ColorMaterial>>,
225    images: ResMut<Assets<Image>>,
226    window: Single<&Window>,
227    counter: ResMut<BevyCounter>,
228) {
229    warn!(include_str!("warning_string.txt"));
230
231    let args = args.into_inner();
232    let images = images.into_inner();
233
234    let mut textures = Vec::with_capacity(args.material_texture_count.max(1));
235    if matches!(args.mode, Mode::Sprite) || args.material_texture_count > 0 {
236        textures.push(asset_server.load("branding/icon.png"));
237    }
238    init_textures(&mut textures, args, images);
239
240    let material_assets = material_assets.into_inner();
241    let materials = init_materials(args, &textures, material_assets);
242
243    let mut bird_resources = BirdResources {
244        textures,
245        materials,
246        quad: meshes.add(Rectangle::from_size(Vec2::splat(BIRD_TEXTURE_SIZE as f32))),
247        // We're seeding the PRNG here to make this example deterministic for testing purposes.
248        // This isn't strictly required in practical use unless you need your app to be deterministic.
249        color_rng: ChaCha8Rng::seed_from_u64(42),
250        material_rng: ChaCha8Rng::seed_from_u64(42),
251        velocity_rng: ChaCha8Rng::seed_from_u64(42),
252        transform_rng: ChaCha8Rng::seed_from_u64(42),
253    };
254
255    let font = TextFont {
256        font_size: 40.0,
257        ..Default::default()
258    };
259
260    commands.spawn(Camera2d);
261    commands
262        .spawn((
263            Node {
264                position_type: PositionType::Absolute,
265                padding: UiRect::all(Val::Px(5.0)),
266                ..default()
267            },
268            BackgroundColor(Color::BLACK.with_alpha(0.75)),
269            GlobalZIndex(i32::MAX),
270        ))
271        .with_children(|p| {
272            p.spawn((Text::default(), StatsText)).with_children(|p| {
273                p.spawn((
274                    TextSpan::new("Bird Count: "),
275                    font.clone(),
276                    TextColor(LIME.into()),
277                ));
278                p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into())));
279                p.spawn((
280                    TextSpan::new("\nFPS (raw): "),
281                    font.clone(),
282                    TextColor(LIME.into()),
283                ));
284                p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into())));
285                p.spawn((
286                    TextSpan::new("\nFPS (SMA): "),
287                    font.clone(),
288                    TextColor(LIME.into()),
289                ));
290                p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into())));
291                p.spawn((
292                    TextSpan::new("\nFPS (EMA): "),
293                    font.clone(),
294                    TextColor(LIME.into()),
295                ));
296                p.spawn((TextSpan::new(""), font.clone(), TextColor(AQUA.into())));
297            });
298        });
299
300    let mut scheduled = BirdScheduled {
301        per_wave: args.per_wave,
302        waves: args.waves,
303    };
304
305    if args.benchmark {
306        let counter = counter.into_inner();
307        for wave in (0..scheduled.waves).rev() {
308            spawn_birds(
309                &mut commands,
310                args,
311                &window.resolution,
312                counter,
313                scheduled.per_wave,
314                &mut bird_resources,
315                Some(wave),
316                wave,
317            );
318        }
319        scheduled.waves = 0;
320    }
321    commands.insert_resource(bird_resources);
322    commands.insert_resource(scheduled);
323}
324
325fn mouse_handler(
326    mut commands: Commands,
327    args: Res<Args>,
328    time: Res<Time>,
329    mouse_button_input: Res<ButtonInput<MouseButton>>,
330    window: Query<&Window>,
331    bird_resources: ResMut<BirdResources>,
332    mut counter: ResMut<BevyCounter>,
333    mut rng: Local<Option<ChaCha8Rng>>,
334    mut wave: Local<usize>,
335) {
336    let Ok(window) = window.single() else {
337        return;
338    };
339
340    if rng.is_none() {
341        // We're seeding the PRNG here to make this example deterministic for testing purposes.
342        // This isn't strictly required in practical use unless you need your app to be deterministic.
343        *rng = Some(ChaCha8Rng::seed_from_u64(42));
344    }
345    let rng = rng.as_mut().unwrap();
346
347    if mouse_button_input.just_released(MouseButton::Left) {
348        counter.color = Color::linear_rgb(rng.r#gen(), rng.r#gen(), rng.r#gen());
349    }
350
351    if mouse_button_input.pressed(MouseButton::Left) {
352        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
353        spawn_birds(
354            &mut commands,
355            args.into_inner(),
356            &window.resolution,
357            &mut counter,
358            spawn_count,
359            bird_resources.into_inner(),
360            None,
361            *wave,
362        );
363        *wave += 1;
364    }
365}
More examples
Hide additional examples
examples/stress_tests/many_materials.rs (line 53)
46fn setup(
47    mut commands: Commands,
48    args: Res<Args>,
49    mesh_assets: ResMut<Assets<Mesh>>,
50    material_assets: ResMut<Assets<StandardMaterial>>,
51) {
52    let args = args.into_inner();
53    let material_assets = material_assets.into_inner();
54    let mesh_assets = mesh_assets.into_inner();
55    let n = args.grid_size;
56
57    // Camera
58    let w = n as f32;
59    commands.spawn((
60        Camera3d::default(),
61        Transform::from_xyz(w * 1.25, w + 1.0, w * 1.25)
62            .looking_at(Vec3::new(0.0, (w * -1.1) + 1.0, 0.0), Vec3::Y),
63    ));
64
65    // Light
66    commands.spawn((
67        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
68        DirectionalLight {
69            illuminance: 3000.0,
70            shadows_enabled: true,
71            ..default()
72        },
73    ));
74
75    // Cubes
76    let mesh_handle = mesh_assets.add(Cuboid::from_size(Vec3::ONE));
77    for x in 0..n {
78        for z in 0..n {
79            commands.spawn((
80                Mesh3d(mesh_handle.clone()),
81                MeshMaterial3d(material_assets.add(Color::WHITE)),
82                Transform::from_translation(Vec3::new(x as f32, 0.0, z as f32)),
83            ));
84        }
85    }
86}
examples/stress_tests/many_cubes.rs (line 147)
137fn setup(
138    mut commands: Commands,
139    args: Res<Args>,
140    mesh_assets: ResMut<Assets<Mesh>>,
141    material_assets: ResMut<Assets<StandardMaterial>>,
142    images: ResMut<Assets<Image>>,
143) {
144    warn!(include_str!("warning_string.txt"));
145
146    let args = args.into_inner();
147    let images = images.into_inner();
148    let material_assets = material_assets.into_inner();
149    let mesh_assets = mesh_assets.into_inner();
150
151    let meshes = init_meshes(args, mesh_assets);
152
153    let material_textures = init_textures(args, images);
154    let materials = init_materials(args, &material_textures, material_assets);
155
156    // We're seeding the PRNG here to make this example deterministic for testing purposes.
157    // This isn't strictly required in practical use unless you need your app to be deterministic.
158    let mut material_rng = ChaCha8Rng::seed_from_u64(42);
159    match args.layout {
160        Layout::Sphere => {
161            // NOTE: This pattern is good for testing performance of culling as it provides roughly
162            // the same number of visible meshes regardless of the viewing angle.
163            const N_POINTS: usize = WIDTH * HEIGHT * 4;
164            // NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
165            let radius = WIDTH as f64 * 2.5;
166            let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());
167            for i in 0..N_POINTS {
168                let spherical_polar_theta_phi =
169                    fibonacci_spiral_on_sphere(golden_ratio, i, N_POINTS);
170                let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);
171                let (mesh, transform) = meshes.choose(&mut material_rng).unwrap();
172                commands
173                    .spawn((
174                        Mesh3d(mesh.clone()),
175                        MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
176                        Transform::from_translation((radius * unit_sphere_p).as_vec3())
177                            .looking_at(Vec3::ZERO, Vec3::Y)
178                            .mul_transform(*transform),
179                    ))
180                    .insert_if(NoFrustumCulling, || args.no_frustum_culling)
181                    .insert_if(NoAutomaticBatching, || args.no_automatic_batching);
182            }
183
184            // camera
185            let mut camera = commands.spawn(Camera3d::default());
186            if args.no_indirect_drawing {
187                camera.insert(NoIndirectDrawing);
188            }
189            if args.no_cpu_culling {
190                camera.insert(NoCpuCulling);
191            }
192
193            // Inside-out box around the meshes onto which shadows are cast (though you cannot see them...)
194            commands.spawn((
195                Mesh3d(mesh_assets.add(Cuboid::from_size(Vec3::splat(radius as f32 * 2.2)))),
196                MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))),
197                Transform::from_scale(-Vec3::ONE),
198                NotShadowCaster,
199            ));
200        }
201        _ => {
202            // NOTE: This pattern is good for demonstrating that frustum culling is working correctly
203            // as the number of visible meshes rises and falls depending on the viewing angle.
204            let scale = 2.5;
205            for x in 0..WIDTH {
206                for y in 0..HEIGHT {
207                    // introduce spaces to break any kind of moiré pattern
208                    if x % 10 == 0 || y % 10 == 0 {
209                        continue;
210                    }
211                    // cube
212                    commands.spawn((
213                        Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
214                        MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
215                        Transform::from_xyz((x as f32) * scale, (y as f32) * scale, 0.0),
216                    ));
217                    commands.spawn((
218                        Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
219                        MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
220                        Transform::from_xyz(
221                            (x as f32) * scale,
222                            HEIGHT as f32 * scale,
223                            (y as f32) * scale,
224                        ),
225                    ));
226                    commands.spawn((
227                        Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
228                        MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
229                        Transform::from_xyz((x as f32) * scale, 0.0, (y as f32) * scale),
230                    ));
231                    commands.spawn((
232                        Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
233                        MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
234                        Transform::from_xyz(0.0, (x as f32) * scale, (y as f32) * scale),
235                    ));
236                }
237            }
238            // camera
239            let center = 0.5 * scale * Vec3::new(WIDTH as f32, HEIGHT as f32, WIDTH as f32);
240            commands.spawn((Camera3d::default(), Transform::from_translation(center)));
241            // Inside-out box around the meshes onto which shadows are cast (though you cannot see them...)
242            commands.spawn((
243                Mesh3d(mesh_assets.add(Cuboid::from_size(2.0 * 1.1 * center))),
244                MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))),
245                Transform::from_scale(-Vec3::ONE).with_translation(center),
246                NotShadowCaster,
247            ));
248        }
249    }
250
251    commands.spawn((
252        DirectionalLight {
253            shadows_enabled: args.shadows,
254            ..default()
255        },
256        Transform::IDENTITY.looking_at(Vec3::new(0.0, -1.0, -1.0), Vec3::Y),
257    ));
258}
Source

pub fn reborrow(&mut self) -> Mut<'_, T>

Returns a Mut<> with a smaller lifetime. This is useful if you have &mut ResMut <T>, but you need a Mut<T>.

Source

pub fn map_unchanged<U>(self, f: impl FnOnce(&mut T) -> &mut U) -> Mut<'w, U>
where U: ?Sized,

Maps to an inner value by applying a function to the contained reference, without flagging a change.

You should never modify the argument passed to the closure – if you want to modify the data without flagging a change, consider using DetectChangesMut::bypass_change_detection to make your intent explicit.

// When run, zeroes the translation of every entity.
fn reset_positions(mut transforms: Query<&mut Transform>) {
    for transform in &mut transforms {
        // We pinky promise not to modify `t` within the closure.
        // Breaking this promise will result in logic errors, but will never cause undefined behavior.
        let mut translation = transform.map_unchanged(|t| &mut t.translation);
        // Only reset the translation if it isn't already zero;
        translation.set_if_neq(Vec2::ZERO);
    }
}
Source

pub fn filter_map_unchanged<U>( self, f: impl FnOnce(&mut T) -> Option<&mut U>, ) -> Option<Mut<'w, U>>
where U: ?Sized,

Optionally maps to an inner value by applying a function to the contained reference. This is useful in a situation where you need to convert a Mut<T> to a Mut<U>, but only if T contains U.

As with map_unchanged, you should never modify the argument passed to the closure.

Source

pub fn try_map_unchanged<U, E>( self, f: impl FnOnce(&mut T) -> Result<&mut U, E>, ) -> Result<Mut<'w, U>, E>
where U: ?Sized,

Optionally maps to an inner value by applying a function to the contained reference, returns an error on failure. This is useful in a situation where you need to convert a Mut<T> to a Mut<U>, but only if T contains U.

As with map_unchanged, you should never modify the argument passed to the closure.

Source

pub fn as_deref_mut(&mut self) -> Mut<'_, <T as Deref>::Target>
where T: DerefMut,

Allows you access to the dereferenced value of this pointer without immediately triggering change detection.

Trait Implementations§

Source§

impl<'w, T> AsMut<T> for ResMut<'w, T>
where T: Resource,

Source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<'w, T> AsRef<T> for ResMut<'w, T>
where T: Resource,

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<'w, T> Debug for ResMut<'w, T>
where T: Resource + Debug + ?Sized,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'w, T> Deref for ResMut<'w, T>
where T: Resource + ?Sized,

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<ResMut<'w, T> as Deref>::Target

Dereferences the value.
Source§

impl<'w, T> DerefMut for ResMut<'w, T>
where T: Resource + ?Sized,

Source§

fn deref_mut(&mut self) -> &mut <ResMut<'w, T> as Deref>::Target

Mutably dereferences the value.
Source§

impl<'w, T> DetectChanges for ResMut<'w, T>
where T: Resource + ?Sized,

Source§

fn is_added(&self) -> bool

Returns true if this value was added after the system last ran.
Source§

fn is_changed(&self) -> bool

Returns true if this value was added or mutably dereferenced either since the last time the system ran or, if the system never ran, since the beginning of the program. Read more
Source§

fn last_changed(&self) -> Tick

Returns the change tick recording the time this data was most recently changed. Read more
Source§

fn added(&self) -> Tick

Returns the change tick recording the time this data was added.
Source§

fn changed_by(&self) -> MaybeLocation

The location that last caused this to change.
Source§

impl<'w, T> DetectChangesMut for ResMut<'w, T>
where T: Resource + ?Sized,

Source§

type Inner = T

The type contained within this smart pointer Read more
Source§

fn set_changed(&mut self)

Flags this value as having been changed. Read more
Source§

fn set_added(&mut self)

Flags this value as having been added. Read more
Source§

fn set_last_changed(&mut self, last_changed: Tick)

Manually sets the change tick recording the time when this data was last mutated. Read more
Source§

fn set_last_added(&mut self, last_added: Tick)

Manually sets the added tick recording the time when this data was last added. Read more
Source§

fn bypass_change_detection( &mut self, ) -> &mut <ResMut<'w, T> as DetectChangesMut>::Inner

Manually bypasses change detection, allowing you to mutate the underlying value without updating the change tick. Read more
Source§

fn set_if_neq(&mut self, value: Self::Inner) -> bool
where Self::Inner: Sized + PartialEq,

Overwrites this smart pointer with the given value, if and only if *self != value. Returns true if the value was overwritten, and returns false if it was not. Read more
Source§

fn replace_if_neq(&mut self, value: Self::Inner) -> Option<Self::Inner>
where Self::Inner: Sized + PartialEq,

Overwrites this smart pointer with the given value, if and only if *self != value, returning the previous value if this occurs. Read more
Source§

fn clone_from_if_neq<T>(&mut self, value: &T) -> bool
where T: ToOwned<Owned = Self::Inner> + ?Sized, Self::Inner: PartialEq<T>,

Overwrites this smart pointer with a clone of the given value, if and only if *self != value. Returns true if the value was overwritten, and returns false if it was not. Read more
Source§

impl<'w, T> From<ResMut<'w, T>> for Mut<'w, T>
where T: Resource,

Source§

fn from(other: ResMut<'w, T>) -> Mut<'w, T>

Convert this ResMut into a Mut. This allows keeping the change-detection feature of Mut while losing the specificity of ResMut for resources.

Source§

impl<'w, T> From<ResMut<'w, T>> for Res<'w, T>
where T: Resource,

Source§

fn from(res: ResMut<'w, T>) -> Res<'w, T>

Converts to this type from the input type.
Source§

impl<'w, 'a, T> IntoIterator for &'a ResMut<'w, T>

Source§

type Item = <&'a T as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <&'a T as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <&'a ResMut<'w, T> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'w, 'a, T> IntoIterator for &'a mut ResMut<'w, T>

Source§

type Item = <&'a mut T as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <&'a mut T as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <&'a mut ResMut<'w, T> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T> SystemParam for ResMut<'a, T>
where T: Resource,

Source§

type State = ComponentId

Used to store data which persists across invocations of a system.
Source§

type Item<'w, 's> = ResMut<'w, T>

The item type returned when constructing this system param. The value of this associated type should be Self, instantiated with new lifetimes. Read more
Source§

fn init_state( world: &mut World, system_meta: &mut SystemMeta, ) -> <ResMut<'a, T> as SystemParam>::State

Registers any World access used by this SystemParam and creates a new instance of this param’s State.
Source§

unsafe fn validate_param( _: &<ResMut<'a, T> as SystemParam>::State, _system_meta: &SystemMeta, world: UnsafeWorldCell<'_>, ) -> Result<(), SystemParamValidationError>

Validates that the param can be acquired by the get_param. Read more
Source§

unsafe fn get_param<'w, 's>( _: &'s mut <ResMut<'a, T> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> <ResMut<'a, T> as SystemParam>::Item<'w, 's>

Creates a parameter to be passed into a SystemParamFunction. Read more
Source§

unsafe fn new_archetype( state: &mut Self::State, archetype: &Archetype, system_meta: &mut SystemMeta, )

For the specified Archetype, registers the components accessed by this SystemParam (if applicable).a Read more
Source§

fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)

Applies any deferred mutations stored in this SystemParam’s state. This is used to apply Commands during ApplyDeferred.
Source§

fn queue( state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld<'_>, )

Queues any deferred mutations to be applied at the next ApplyDeferred.

Auto Trait Implementations§

§

impl<'w, T> Freeze for ResMut<'w, T>
where T: ?Sized,

§

impl<'w, T> RefUnwindSafe for ResMut<'w, T>
where T: RefUnwindSafe + ?Sized,

§

impl<'w, T> Send for ResMut<'w, T>
where T: ?Sized,

§

impl<'w, T> Sync for ResMut<'w, T>
where T: ?Sized,

§

impl<'w, T> Unpin for ResMut<'w, T>
where T: ?Sized,

§

impl<'w, T> !UnwindSafe for ResMut<'w, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T, C, D> Curve<T> for D
where C: Curve<T> + ?Sized, D: Deref<Target = C>,

Source§

fn domain(&self) -> Interval

The interval over which this curve is parametrized. Read more
Source§

fn sample_unchecked(&self, t: f32) -> T

Sample a point on this curve at the parameter value t, extracting the associated value. This is the unchecked version of sampling, which should only be used if the sample time t is already known to lie within the curve’s domain. Read more
Source§

fn sample(&self, t: f32) -> Option<T>

Sample a point on this curve at the parameter value t, returning None if the point is outside of the curve’s domain.
Source§

fn sample_clamped(&self, t: f32) -> T

Sample a point on this curve at the parameter value t, clamping t to lie inside the domain of the curve.
Source§

impl<C, T> CurveExt<T> for C
where C: Curve<T>,

Source§

fn sample_iter( &self, iter: impl IntoIterator<Item = f32>, ) -> impl Iterator<Item = Option<T>>

Sample a collection of n >= 0 points on this curve at the parameter values t_n, returning None if the point is outside of the curve’s domain. Read more
Source§

fn sample_iter_unchecked( &self, iter: impl IntoIterator<Item = f32>, ) -> impl Iterator<Item = T>

Sample a collection of n >= 0 points on this curve at the parameter values t_n, extracting the associated values. This is the unchecked version of sampling, which should only be used if the sample times t_n are already known to lie within the curve’s domain. Read more
Source§

fn sample_iter_clamped( &self, iter: impl IntoIterator<Item = f32>, ) -> impl Iterator<Item = T>

Sample a collection of n >= 0 points on this curve at the parameter values t_n, clamping t_n to lie inside the domain of the curve. Read more
Source§

fn map<S, F>(self, f: F) -> MapCurve<T, S, Self, F>
where F: Fn(T) -> S,

Create a new curve by mapping the values of this curve via a function f; i.e., if the sample at time t for this curve is x, the value at time t on the new curve will be f(x).
Source§

fn reparametrize<F>(self, domain: Interval, f: F) -> ReparamCurve<T, Self, F>
where F: Fn(f32) -> f32,

Create a new Curve whose parameter space is related to the parameter space of this curve by f. For each time t, the sample from the new curve at time t is the sample from this curve at time f(t). The given domain will be the domain of the new curve. The function f is expected to take domain into self.domain(). Read more
Source§

fn reparametrize_linear( self, domain: Interval, ) -> Result<LinearReparamCurve<T, Self>, LinearReparamError>

Linearly reparametrize this Curve, producing a new curve whose domain is the given domain instead of the current one. This operation is only valid for curves with bounded domains. Read more
Source§

fn reparametrize_by_curve<C>(self, other: C) -> CurveReparamCurve<T, Self, C>
where C: Curve<f32>,

Reparametrize this Curve by sampling from another curve. Read more
Source§

fn graph(self) -> GraphCurve<T, Self>

Create a new Curve which is the graph of this one; that is, its output echoes the sample time as part of a tuple. Read more
Source§

fn zip<S, C>( self, other: C, ) -> Result<ZipCurve<T, S, Self, C>, InvalidIntervalError>
where C: Curve<S>,

Create a new Curve by zipping this curve together with another. Read more
Source§

fn chain<C>(self, other: C) -> Result<ChainCurve<T, Self, C>, ChainError>
where C: Curve<T>,

Create a new Curve by composing this curve end-to-start with another, producing another curve with outputs of the same type. The domain of the other curve is translated so that its start coincides with where this curve ends. Read more
Source§

fn reverse(self) -> Result<ReverseCurve<T, Self>, ReverseError>

Create a new Curve inverting this curve on the x-axis, producing another curve with outputs of the same type, effectively playing backwards starting at self.domain().end() and transitioning over to self.domain().start(). The domain of the new curve is still the same. Read more
Source§

fn repeat(self, count: usize) -> Result<RepeatCurve<T, Self>, RepeatError>

Create a new Curve repeating this curve N times, producing another curve with outputs of the same type. The domain of the new curve will be bigger by a factor of n + 1. Read more
Source§

fn forever(self) -> Result<ForeverCurve<T, Self>, RepeatError>

Create a new Curve repeating this curve forever, producing another curve with outputs of the same type. The domain of the new curve will be unbounded. Read more
Source§

fn ping_pong(self) -> Result<PingPongCurve<T, Self>, PingPongError>

Create a new Curve chaining the original curve with its inverse, producing another curve with outputs of the same type. The domain of the new curve will be twice as long. The transition point is guaranteed to not make any jumps. Read more
Source§

fn chain_continue<C>( self, other: C, ) -> Result<ContinuationCurve<T, Self, C>, ChainError>
where T: VectorSpace, C: Curve<T>,

Create a new Curve by composing this curve end-to-start with another, producing another curve with outputs of the same type. The domain of the other curve is translated so that its start coincides with where this curve ends. Read more
Source§

fn samples( &self, samples: usize, ) -> Result<impl Iterator<Item = T>, ResamplingError>

Extract an iterator over evenly-spaced samples from this curve. Read more
Source§

fn by_ref(&self) -> &Self

Borrow this curve rather than taking ownership of it. This is essentially an alias for a prefix &; the point is that intermediate operations can be performed while retaining access to the original curve. Read more
Source§

fn flip<U, V>(self) -> impl Curve<(V, U)>
where Self: CurveExt<(U, V)>,

Flip this curve so that its tuple output is arranged the other way.
Source§

impl<C, T> CurveResampleExt<T> for C
where C: Curve<T> + ?Sized,

Source§

fn resample<I>( &self, segments: usize, interpolation: I, ) -> Result<SampleCurve<T, I>, ResamplingError>
where I: Fn(&T, &T, f32) -> T,

Resample this Curve to produce a new one that is defined by interpolation over equally spaced sample values, using the provided interpolation to interpolate between adjacent samples. The curve is interpolated on segments segments between samples. For example, if segments is 1, only the start and end points of the curve are used as samples; if segments is 2, a sample at the midpoint is taken as well, and so on. Read more
Source§

fn resample_auto( &self, segments: usize, ) -> Result<SampleAutoCurve<T>, ResamplingError>

Resample this Curve to produce a new one that is defined by interpolation over equally spaced sample values, using automatic interpolation to interpolate between adjacent samples. The curve is interpolated on segments segments between samples. For example, if segments is 1, only the start and end points of the curve are used as samples; if segments is 2, a sample at the midpoint is taken as well, and so on. Read more
Source§

fn resample_uneven<I>( &self, sample_times: impl IntoIterator<Item = f32>, interpolation: I, ) -> Result<UnevenSampleCurve<T, I>, ResamplingError>
where I: Fn(&T, &T, f32) -> T,

Resample this Curve to produce a new one that is defined by interpolation over samples taken at a given set of times. The given interpolation is used to interpolate adjacent samples, and the sample_times are expected to contain at least two valid times within the curve’s domain interval. Read more
Source§

fn resample_uneven_auto( &self, sample_times: impl IntoIterator<Item = f32>, ) -> Result<UnevenSampleAutoCurve<T>, ResamplingError>

Resample this Curve to produce a new one that is defined by automatic interpolation over samples taken at the given set of times. The given sample_times are expected to contain at least two valid times within the curve’s domain interval. Read more
Source§

impl<T, C> CurveWithDerivative<T> for C
where T: HasTangent, C: SampleDerivative<T>,

Source§

fn with_derivative(self) -> SampleDerivativeWrapper<C>

This curve, but with its first derivative included in sampling. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, C, D> SampleDerivative<T> for D
where T: HasTangent, C: SampleDerivative<T> + ?Sized, D: Deref<Target = C>,

Source§

fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T>

Sample this curve at the parameter value t, extracting the associated value in addition to its derivative. This is the unchecked version of sampling, which should only be used if the sample time t is already known to lie within the curve’s domain. Read more
Source§

fn sample_with_derivative(&self, t: f32) -> Option<WithDerivative<T>>

Sample this curve’s value and derivative at the parameter value t, returning None if the point is outside of the curve’s domain.
Source§

fn sample_with_derivative_clamped(&self, t: f32) -> WithDerivative<T>

Sample this curve’s value and derivative at the parameter value t, clamping t to lie inside the domain of the curve.
Source§

impl<T> Source for T
where T: Deref, <T as Deref>::Target: Source,

Source§

type Slice<'a> = <<T as Deref>::Target as Source>::Slice<'a> where T: 'a

A type this Source can be sliced into.
Source§

fn len(&self) -> usize

Length of the source
Source§

fn read<'a, Chunk>(&'a self, offset: usize) -> Option<Chunk>
where Chunk: Chunk<'a>,

Read a chunk of bytes into an array. Returns None when reading out of bounds would occur. Read more
Source§

unsafe fn read_byte_unchecked(&self, offset: usize) -> u8

Read a byte without doing bounds checks. Read more
Source§

fn slice(&self, range: Range<usize>) -> Option<<T as Source>::Slice<'_>>

Get a slice of the source at given range. This is analogous to slice::get(range). Read more
Source§

unsafe fn slice_unchecked( &self, range: Range<usize>, ) -> <T as Source>::Slice<'_>

Get a slice of the source at given range. This is analogous to slice::get_unchecked(range). Read more
Source§

fn is_boundary(&self, index: usize) -> bool

Check if index is valid for this Source, that is: Read more
Source§

fn find_boundary(&self, index: usize) -> usize

For &str sources attempts to find the closest char boundary at which source can be sliced, starting from index. Read more
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,