Skip to main content

Window

Struct Window 

Source
pub struct Window {
Show 40 fields pub present_mode: PresentMode, pub mode: WindowMode, pub position: WindowPosition, pub resolution: WindowResolution, pub title: String, pub name: Option<String>, pub composite_alpha_mode: CompositeAlphaMode, pub resize_constraints: WindowResizeConstraints, pub resizable: bool, pub enabled_buttons: EnabledButtons, pub decorations: bool, pub transparent: bool, pub focused: bool, pub window_level: WindowLevel, pub canvas: Option<String>, pub fit_canvas_to_parent: bool, pub prevent_default_event_handling: bool, pub internal: InternalWindowState, pub ime_enabled: bool, pub ime_position: Vec2, pub window_theme: Option<WindowTheme>, pub visible: bool, pub skip_taskbar: bool, pub clip_children: bool, pub desired_maximum_frame_latency: Option<NonZero<u32>>, pub recognize_pinch_gesture: bool, pub recognize_rotation_gesture: bool, pub recognize_doubletap_gesture: bool, pub recognize_pan_gesture: Option<(u8, u8)>, pub movable_by_window_background: bool, pub fullsize_content_view: bool, pub has_shadow: bool, pub titlebar_shown: bool, pub titlebar_transparent: bool, pub titlebar_show_title: bool, pub titlebar_show_buttons: bool, pub borderless_game: bool, pub prefers_home_indicator_hidden: bool, pub prefers_status_bar_hidden: bool, pub preferred_screen_edges_deferring_system_gestures: ScreenEdge,
}
Expand description

The defining Component for window entities, storing information about how it should appear and behave.

Each window corresponds to an entity, and is uniquely identified by the value of their Entity. When the Window component is added to an entity, a new window will be opened. When it is removed or the entity is despawned, the window will close.

The primary window entity (and the corresponding window) is spawned by default by WindowPlugin and is marked with the PrimaryWindow component.

This component is synchronized with winit through bevy_winit: it will reflect the current state of the window and can be modified to change this state.

§Example

Because this component is synchronized with winit, it can be used to perform OS-integrated windowing operations. For example, here’s a simple system to change the window mode:

fn change_window_mode(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
    // Query returns one window typically.
    for mut window in windows.iter_mut() {
        window.mode =
            WindowMode::Fullscreen(MonitorSelection::Current, VideoModeSelection::Current);
    }
}

Fields§

§present_mode: PresentMode

What presentation mode to give the window.

§mode: WindowMode

Which fullscreen or windowing mode should be used.

§position: WindowPosition

Where the window should be placed.

§resolution: WindowResolution

What resolution the window should have.

§title: String

Stores the title of the window.

§name: Option<String>

Stores the application ID (on Wayland), WM_CLASS (on X11) or window class name (on Windows) of the window.

For details about application ID conventions, see the Desktop Entry Spec. For details about WM_CLASS, see the X11 Manual Pages. For details about Windows’s window class names, see About Window Classes.

§Platform-specific

  • Windows: Can only be set while building the window, setting the window’s window class name.
  • Wayland: Can only be set while building the window, setting the window’s application ID.
  • X11: Can only be set while building the window, setting the window’s WM_CLASS.
  • macOS, iOS, Android, and Web: not applicable.

Notes: Changing this field during runtime will have no effect for now.

§composite_alpha_mode: CompositeAlphaMode

How the alpha channel of textures should be handled while compositing.

§resize_constraints: WindowResizeConstraints

The limits of the window’s logical size (found in its resolution) when resizing.

§resizable: bool

Should the window be resizable?

Note: This does not stop the program from fullscreening/setting the size programmatically.

§enabled_buttons: EnabledButtons

Specifies which window control buttons should be enabled.

§Platform-specific

iOS, Android, and the Web do not have window control buttons.

On some Linux environments these values have no effect.

§decorations: bool

Should the window have decorations enabled?

(Decorations are the minimize, maximize, and close buttons on desktop apps)

§Platform-specific

iOS, Android, and the Web do not have decorations.

§transparent: bool

Should the window be transparent?

Defines whether the background of the window should be transparent.

§Platform-specific

  • iOS / Android / Web: Unsupported.
  • macOS: Not working as expected.

macOS transparent works with winit out of the box, so this issue might be related to: https://github.com/gfx-rs/wgpu/issues/687. You should also set the window composite_alpha_mode to CompositeAlphaMode::PostMultiplied.

§focused: bool

Get/set whether the window is focused.

It cannot be set unfocused after creation.

§Platform-specific

  • iOS / Android / X11 / Wayland: Spawning unfocused is not supported.
  • iOS / Android / Web / Wayland: Setting focused after creation is not supported.
§window_level: WindowLevel

Where should the window appear relative to other overlapping window.

§Platform-specific

  • iOS / Android / Web / Wayland: Unsupported.
§canvas: Option<String>

The “html canvas” element selector.

If set, this selector will be used to find a matching html canvas element, rather than creating a new one. Uses the CSS selector format.

This value has no effect on non-web platforms.

§fit_canvas_to_parent: bool

Whether or not to fit the canvas element’s size to its parent element’s size.

Warning: this will not behave as expected for parents that set their size according to the size of their children. This creates a “feedback loop” that will result in the canvas growing on each resize. When using this feature, ensure the parent’s size is not affected by its children.

This value has no effect on non-web platforms.

§prevent_default_event_handling: bool

Whether or not to stop events from propagating out of the canvas element

When true, this will prevent common browser hotkeys like F5, F12, Ctrl+R, tab, etc. from performing their default behavior while the bevy app has focus.

This value has no effect on non-web platforms.

§internal: InternalWindowState

Stores internal state that isn’t directly accessible.

§ime_enabled: bool

Should the window use Input Method Editor?

If enabled, the window will receive Ime events instead of KeyboardInput from bevy_input.

IME should be enabled during text input, but not when you expect to get the exact key pressed.

§Platform-specific

  • iOS / Android / Web: Unsupported.
§ime_position: Vec2

Sets location of IME candidate box in client area coordinates relative to the top left.

§Platform-specific

  • iOS / Android / Web: Unsupported.
§window_theme: Option<WindowTheme>

Sets a specific theme for the window.

If None is provided, the window will use the system theme.

§Platform-specific

  • iOS / Android / Web: Unsupported.
§visible: bool

Sets the window’s visibility.

If false, this will hide the window completely, it won’t appear on the screen or in the task bar. If true, this will show the window. Note that this doesn’t change its focused or minimized state.

§Platform-specific

  • Android / Wayland / Web: Unsupported.
§skip_taskbar: bool

Sets whether the window should be shown in the taskbar.

If true, the window will not appear in the taskbar. If false, the window will appear in the taskbar.

Note that this will only take effect on window creation.

§Platform-specific

  • Only supported on Windows.
§clip_children: bool

Sets whether the window should draw over its child windows.

If true, the window excludes drawing over areas obscured by child windows. If false, the window can draw over child windows.

§Platform-specific

  • Only supported on Windows.
§desired_maximum_frame_latency: Option<NonZero<u32>>

Optional hint given to the rendering API regarding the maximum number of queued frames admissible on the GPU.

Given values are usually within the 1-3 range. If not provided, this will default to 2.

See wgpu::SurfaceConfiguration::desired_maximum_frame_latency.

§recognize_pinch_gesture: bool

Sets whether this window recognizes PinchGesture

§Platform-specific

  • Only used on iOS.
  • On macOS, they are recognized by default and can’t be disabled.
§recognize_rotation_gesture: bool

Sets whether this window recognizes RotationGesture

§Platform-specific

  • Only used on iOS.
  • On macOS, they are recognized by default and can’t be disabled.
§recognize_doubletap_gesture: bool

Sets whether this window recognizes DoubleTapGesture

§Platform-specific

  • Only used on iOS.
  • On macOS, they are recognized by default and can’t be disabled.
§recognize_pan_gesture: Option<(u8, u8)>

Sets whether this window recognizes PanGesture, with a number of fingers between the first value and the last.

§Platform-specific

  • Only used on iOS.
§movable_by_window_background: bool

Enables click-and-drag behavior for the entire window, not just the titlebar.

Corresponds to WindowAttributesExtMacOS::with_movable_by_window_background.

§Platform-specific

  • Only used on macOS.
§fullsize_content_view: bool

Makes the window content appear behind the titlebar.

Corresponds to WindowAttributesExtMacOS::with_fullsize_content_view.

For apps which want to render the window buttons on top of the apps itself, this should be enabled along with titlebar_transparent.

§Platform-specific

  • Only used on macOS.
§has_shadow: bool

Toggles drawing the drop shadow behind the window.

Corresponds to WindowAttributesExtMacOS::with_has_shadow.

§Platform-specific

  • Only used on macOS.
§titlebar_shown: bool

Toggles drawing the titlebar.

Corresponds to WindowAttributesExtMacOS::with_titlebar_hidden.

§Platform-specific

  • Only used on macOS.
§titlebar_transparent: bool

Makes the titlebar transparent, allowing the app content to appear behind it.

Corresponds to WindowAttributesExtMacOS::with_titlebar_transparent.

§Platform-specific

  • Only used on macOS.
§titlebar_show_title: bool

Toggles showing the window title.

Corresponds to WindowAttributesExtMacOS::with_title_hidden.

§Platform-specific

  • Only used on macOS.
§titlebar_show_buttons: bool

Toggles showing the traffic light window buttons.

Corresponds to WindowAttributesExtMacOS::with_titlebar_buttons_hidden.

§Platform-specific

  • Only used on macOS.
§borderless_game: bool

Hides the dock and menu bar when a borderless fullscreen window is active.

Corresponds to WindowAttributesExtMacOS::with_borderless_game.

Defaults to true as this is the expected behavior for games.

§Platform-specific

  • Only used on macOS.
§prefers_home_indicator_hidden: bool

Sets whether the Window prefers the home indicator hidden.

Corresponds to WindowAttributesExtIOS::with_prefers_home_indicator_hidden.

§Platform-specific

  • Only used on iOS.
§prefers_status_bar_hidden: bool

Sets whether the Window prefers the status bar hidden.

Corresponds to WindowAttributesExtIOS::with_prefers_status_bar_hidden.

§Platform-specific

  • Only used on iOS.
§preferred_screen_edges_deferring_system_gestures: ScreenEdge

Sets screen edges for which you want your gestures to take precedence over the system gestures.

Corresponds to WindowAttributesExtIOS::with_preferred_screen_edges_deferring_system_gestures.

§Platform-specific

  • Only used on iOS.

Implementations§

Source§

impl Window

Source

pub fn set_maximized(&mut self, maximized: bool)

Setting to true will attempt to maximize the window.

Setting to false will attempt to un-maximize the window.

Source

pub fn set_minimized(&mut self, minimized: bool)

Setting to true will attempt to minimize the window.

Setting to false will attempt to un-minimize the window.

Examples found in repository?
tests/window/minimizing.rs (line 26)
21fn minimize_automatically(mut window: Single<&mut Window>, frames: Res<FrameCount>) {
22    if frames.0 != 60 {
23        return;
24    }
25
26    window.set_minimized(true);
27}
Source

pub fn start_drag_move(&mut self)

Calling this will attempt to start a drag-move of the window.

There is no guarantee that this will work unless the left mouse button was pressed immediately before this function was called.

Examples found in repository?
examples/window/window_drag_move.rs (line 136)
122fn move_or_resize_windows(
123    mut windows: Query<&mut Window>,
124    action: Res<LeftClickAction>,
125    input: Res<ButtonInput<MouseButton>>,
126    dir: Res<ResizeDir>,
127) {
128    // Both `start_drag_move()` and `start_drag_resize()` must be called after a
129    // left mouse button press as done here.
130    //
131    // winit 0.30.5 may panic when initiated without a left mouse button press.
132    if input.just_pressed(MouseButton::Left) {
133        for mut window in windows.iter_mut() {
134            match *action {
135                LeftClickAction::Nothing => (),
136                LeftClickAction::Move => window.start_drag_move(),
137                LeftClickAction::Resize => {
138                    let d = DIRECTIONS[dir.0];
139                    window.start_drag_resize(d);
140                }
141            }
142        }
143    }
144}
Source

pub fn start_drag_resize(&mut self, direction: CompassOctant)

Calling this will attempt to start a drag-resize of the window.

There is no guarantee that this will work unless the left mouse button was pressed immediately before this function was called.

Examples found in repository?
examples/window/window_drag_move.rs (line 139)
122fn move_or_resize_windows(
123    mut windows: Query<&mut Window>,
124    action: Res<LeftClickAction>,
125    input: Res<ButtonInput<MouseButton>>,
126    dir: Res<ResizeDir>,
127) {
128    // Both `start_drag_move()` and `start_drag_resize()` must be called after a
129    // left mouse button press as done here.
130    //
131    // winit 0.30.5 may panic when initiated without a left mouse button press.
132    if input.just_pressed(MouseButton::Left) {
133        for mut window in windows.iter_mut() {
134            match *action {
135                LeftClickAction::Nothing => (),
136                LeftClickAction::Move => window.start_drag_move(),
137                LeftClickAction::Resize => {
138                    let d = DIRECTIONS[dir.0];
139                    window.start_drag_resize(d);
140                }
141            }
142        }
143    }
144}
Source

pub fn width(&self) -> f32

The window’s client area width in logical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/ecs/parallel_query.rs (line 49)
45fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
46    let Ok(window) = window.single() else {
47        return;
48    };
49    let width = window.width();
50    let height = window.height();
51    let left = width / -2.0;
52    let right = width / 2.0;
53    let bottom = height / -2.0;
54    let top = height / 2.0;
55    // The default batch size can also be overridden.
56    // In this case a batch size of 32 is chosen to limit the overhead of
57    // ParallelIterator, since negating a vector is very inexpensive.
58    sprites
59        .par_iter_mut()
60        .batching_strategy(BatchingStrategy::fixed(32))
61        .for_each(|(transform, mut v)| {
62            if !(left < transform.translation.x
63                && transform.translation.x < right
64                && bottom < transform.translation.y
65                && transform.translation.y < top)
66            {
67                // For simplicity, just reverse the velocity; don't use realistic bounces
68                v.0 = -v.0;
69            }
70        });
71}
Source

pub fn height(&self) -> f32

The window’s client area height in logical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/ecs/parallel_query.rs (line 50)
45fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
46    let Ok(window) = window.single() else {
47        return;
48    };
49    let width = window.width();
50    let height = window.height();
51    let left = width / -2.0;
52    let right = width / 2.0;
53    let bottom = height / -2.0;
54    let top = height / 2.0;
55    // The default batch size can also be overridden.
56    // In this case a batch size of 32 is chosen to limit the overhead of
57    // ParallelIterator, since negating a vector is very inexpensive.
58    sprites
59        .par_iter_mut()
60        .batching_strategy(BatchingStrategy::fixed(32))
61        .for_each(|(transform, mut v)| {
62            if !(left < transform.translation.x
63                && transform.translation.x < right
64                && bottom < transform.translation.y
65                && transform.translation.y < top)
66            {
67                // For simplicity, just reverse the velocity; don't use realistic bounces
68                v.0 = -v.0;
69            }
70        });
71}
Source

pub fn size(&self) -> Vec2

The window’s client size in logical pixels

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/stress_tests/bevymark.rs (line 589)
584fn collision_system(window: Query<&Window>, mut bird_query: Query<(&mut Bird, &Transform)>) {
585    let Ok(window) = window.single() else {
586        return;
587    };
588
589    let half_extents = 0.5 * window.size();
590
591    for (mut bird, transform) in &mut bird_query {
592        handle_collision(half_extents, &transform.translation, &mut bird.velocity);
593    }
594}
More examples
Hide additional examples
examples/2d/dynamic_mip_generation.rs (line 433)
427fn animate_image_scale(
428    mut animated_images_query: Query<&mut Transform, With<AnimatedImage>>,
429    windows_query: Query<&Window, With<PrimaryWindow>>,
430    app_status: Res<AppStatus>,
431    time: Res<Time>,
432) {
433    let window_size = windows_query.iter().next().unwrap().size();
434    let animated_mesh_size = app_status.animated_mesh_size(window_size);
435
436    for mut animated_image_transform in &mut animated_images_query {
437        animated_image_transform.scale =
438            animated_mesh_size.extend(1.0) * triangle_wave(time.elapsed_secs(), ANIMATION_PERIOD);
439    }
440}
441
442/// Evaluates a [triangle wave] with the given wavelength.
443///
444/// This is used as part of [`animate_image_scale`], to derive the scale from
445/// the current elapsed time.
446///
447/// [triangle wave]: https://en.wikipedia.org/wiki/Triangle_wave#Definition
448fn triangle_wave(time: f32, wavelength: f32) -> f32 {
449    2.0 * ops::abs(time / wavelength - ops::floor(time / wavelength + 0.5))
450}
451
452/// Adds the top mipmap level of the image to [`MipGenerationJobs`].
453///
454/// Note that this must run in the render world, not the main world, as
455/// [`MipGenerationJobs`] is a resource that exists in the former. Consequently,
456/// it must use [`Extract`] to access main world resources.
457fn extract_mipmap_source_image(
458    mipmap_source_image: Extract<Res<MipmapSourceImage>>,
459    app_status: Extract<Res<AppStatus>>,
460    mut mip_generation_jobs: ResMut<MipGenerationJobs>,
461) {
462    if app_status.enable_mip_generation == EnableMipGeneration::On {
463        mip_generation_jobs.add(MIP_GENERATION_PHASE_ID, mipmap_source_image.id());
464    }
465}
466
467/// Updates the widgets at the bottom of the screen to reflect the settings that
468/// the user has chosen.
469fn update_radio_buttons(
470    mut widgets: Query<
471        (
472            Entity,
473            Option<&mut BackgroundColor>,
474            Has<Text>,
475            &WidgetClickSender<AppSetting>,
476        ),
477        Or<(With<RadioButton>, With<RadioButtonText>)>,
478    >,
479    app_status: Res<AppStatus>,
480    mut writer: TextUiWriter,
481) {
482    for (entity, image, has_text, sender) in widgets.iter_mut() {
483        let selected = match **sender {
484            AppSetting::RegenerateTopMipLevel => continue,
485            AppSetting::EnableMipGeneration(enable_mip_generation) => {
486                enable_mip_generation == app_status.enable_mip_generation
487            }
488            AppSetting::ImageWidth(image_width) => image_width == app_status.image_width,
489            AppSetting::ImageHeight(image_height) => image_height == app_status.image_height,
490        };
491
492        if let Some(mut bg_color) = image {
493            widgets::update_ui_radio_button(&mut bg_color, selected);
494        }
495        if has_text {
496            widgets::update_ui_radio_button_text(entity, &mut writer, selected);
497        }
498    }
499}
500
501/// Handles a request from the user to change application settings via the UI.
502///
503/// This also handles clicks on the "Regenerate Top Mip Level" button.
504fn handle_app_setting_change(
505    mut events: MessageReader<WidgetClickEvent<AppSetting>>,
506    mut app_status: ResMut<AppStatus>,
507    mut regenerate_image_message_writer: MessageWriter<RegenerateImage>,
508) {
509    for event in events.read() {
510        // If this is a setting, update the setting. Fall through if, in
511        // addition to updating the setting, we need to regenerate the image.
512        match **event {
513            AppSetting::EnableMipGeneration(enable_mip_generation) => {
514                app_status.enable_mip_generation = enable_mip_generation;
515                continue;
516            }
517
518            AppSetting::RegenerateTopMipLevel => {}
519            AppSetting::ImageWidth(image_size) => app_status.image_width = image_size,
520            AppSetting::ImageHeight(image_size) => app_status.image_height = image_size,
521        }
522
523        // Schedule the image to be regenerated.
524        regenerate_image_message_writer.write(RegenerateImage);
525    }
526}
527
528/// Handles resize events for the window.
529///
530/// Resizing the window invalidates the image and repositions all image views.
531/// (Regenerating the image isn't strictly necessary, but it's simplest to have
532/// a single function that both regenerates the image and recreates the image
533/// views.)
534fn handle_window_resize_events(
535    mut events: MessageReader<WindowResized>,
536    mut regenerate_image_message_writer: MessageWriter<RegenerateImage>,
537) {
538    for _ in events.read() {
539        regenerate_image_message_writer.write(RegenerateImage);
540    }
541}
542
543/// Recreates the image, as well as all views that show the image, when a
544/// [`RegenerateImage`] message is received.
545///
546/// The views that show the image consist of the animated mesh on the left side
547/// of the window and the column of mipmap level views on the right side of the
548/// window.
549fn regenerate_image_when_requested(
550    mut commands: Commands,
551    image_views_query: Query<Entity, With<ImageView>>,
552    windows_query: Query<&Window, With<PrimaryWindow>>,
553    app_assets: Res<AppAssets>,
554    mut app_status: ResMut<AppStatus>,
555    mut images: ResMut<Assets<Image>>,
556    mut single_mip_level_materials: ResMut<Assets<SingleMipLevelMaterial>>,
557    mut color_materials: ResMut<Assets<ColorMaterial>>,
558    mut message_reader: MessageReader<RegenerateImage>,
559) {
560    // Only do this at most once per frame, or else the despawn logic below will
561    // get confused.
562    if message_reader.read().count() == 0 {
563        return;
564    }
565
566    // Despawn all entities that show the image.
567    for entity in image_views_query.iter() {
568        commands.entity(entity).despawn();
569    }
570
571    // Regenerate the image.
572    let image_handle = app_status.regenerate_mipmap_source_image(&mut commands, &mut images);
573
574    // Respawn the animated image view on the left side of the window.
575    spawn_animated_mesh(
576        &mut commands,
577        &app_status,
578        &app_assets,
579        &windows_query,
580        &mut color_materials,
581        &image_handle,
582    );
583
584    // Respawn the column of mip level views on the right side of the window.
585    spawn_mip_level_views(
586        &mut commands,
587        &app_status,
588        &app_assets,
589        &windows_query,
590        &mut single_mip_level_materials,
591        &image_handle,
592    );
593}
594
595/// Spawns the image on the left that continually changes scale.
596///
597/// Continually changing scale effectively cycles though each mip level,
598/// demonstrating the difference between mip level images being present and mip
599/// level image being absent.
600fn spawn_animated_mesh(
601    commands: &mut Commands,
602    app_status: &AppStatus,
603    app_assets: &AppAssets,
604    windows_query: &Query<&Window, With<PrimaryWindow>>,
605    color_materials: &mut Assets<ColorMaterial>,
606    image_handle: &Handle<Image>,
607) {
608    let window_size = windows_query.iter().next().unwrap().size();
609    let animated_mesh_area_size = app_status.animated_mesh_area_size(window_size);
610    let animated_mesh_size = app_status.animated_mesh_size(window_size);
611
612    commands.spawn((
613        Mesh2d(app_assets.rectangle.clone()),
614        MeshMaterial2d(color_materials.add(ColorMaterial {
615            texture: Some(image_handle.clone()),
616            ..default()
617        })),
618        Transform::from_translation(
619            (animated_mesh_area_size * 0.5 - window_size * 0.5).extend(0.0),
620        )
621        .with_scale(animated_mesh_size.extend(1.0)),
622        AnimatedImage,
623        ImageView,
624    ));
625}
626
627/// Creates the column on the right side of the window that displays each mip
628/// level by itself.
629fn spawn_mip_level_views(
630    commands: &mut Commands,
631    app_status: &AppStatus,
632    app_assets: &AppAssets,
633    windows_query: &Query<&Window, With<PrimaryWindow>>,
634    single_mip_level_materials: &mut Assets<SingleMipLevelMaterial>,
635    image_handle: &Handle<Image>,
636) {
637    let window_size = windows_query.iter().next().unwrap().size();
638
639    // Calculate the placement of the column of mipmap levels.
640    let max_slice_size = app_status.max_mip_slice_size(window_size);
641    let y_origin = app_status.vertical_mip_slice_origin(window_size);
642    let y_spacing = app_status.vertical_mip_slice_spacing(window_size);
643    let x_origin = app_status.horizontal_mip_slice_origin(window_size);
644
645    for (mip_level, mip_size) in MipmapSizeIterator::new(app_status).enumerate() {
646        let y_center = y_origin - y_spacing * mip_level as f32;
647
648        // Size each image to fit its container, preserving aspect ratio.
649        let mut slice_size = mip_size.as_vec2();
650        let ratios = max_slice_size / slice_size;
651        let slice_scale = ratios.x.min(ratios.y).min(1.0);
652        slice_size *= slice_scale;
653
654        // Spawn the image. Use the `SingleMipLevelMaterial` with its custom
655        // shader so that only the mip level in question is displayed.
656        commands.spawn((
657            Mesh2d(app_assets.rectangle.clone()),
658            MeshMaterial2d(single_mip_level_materials.add(SingleMipLevelMaterial {
659                mip_level: mip_level as u32,
660                texture: image_handle.clone(),
661            })),
662            Transform::from_xyz(x_origin, y_center, 0.0).with_scale(slice_size.extend(1.0)),
663            ImageView,
664        ));
665
666        // Display a label to the side.
667        commands.spawn((
668            Text2d::new(format!(
669                "Level {}\n{}×{}",
670                mip_level, mip_size.x, mip_size.y
671            )),
672            app_assets.text_font.clone(),
673            TextLayout::justify(Justify::Center),
674            Text2dShadow::default(),
675            Transform::from_xyz(x_origin - max_slice_size.x * 0.5 - 64.0, y_center, 0.0),
676            ImageView,
677        ));
678    }
679}
examples/showcase/contributors.rs (line 264)
255fn collisions(
256    window: Query<&Window>,
257    mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>,
258    mut rng: ResMut<SharedRng>,
259) {
260    let Ok(window) = window.single() else {
261        return;
262    };
263
264    let window_size = window.size();
265
266    let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.);
267
268    // The maximum height the birbs should try to reach is one birb below the top of the window.
269    let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0);
270    let min_bounce_height = max_bounce_height * 0.4;
271
272    for (mut velocity, mut transform) in &mut query {
273        // Clamp the translation to not go out of the bounds
274        if transform.translation.y < collision_area.min.y {
275            transform.translation.y = collision_area.min.y;
276
277            // How high this birb will bounce.
278            let bounce_height = rng.random_range(min_bounce_height..=max_bounce_height);
279
280            // Apply the velocity that would bounce the birb up to bounce_height.
281            velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt();
282        }
283
284        // Birbs might hit the ceiling if the window is resized.
285        // If they do, bounce them.
286        if transform.translation.y > collision_area.max.y {
287            transform.translation.y = collision_area.max.y;
288            velocity.translation.y *= -1.0;
289        }
290
291        // On side walls flip the horizontal velocity
292        if transform.translation.x < collision_area.min.x {
293            transform.translation.x = collision_area.min.x;
294            velocity.translation.x *= -1.0;
295            velocity.rotation *= -1.0;
296        }
297        if transform.translation.x > collision_area.max.x {
298            transform.translation.x = collision_area.max.x;
299            velocity.translation.x *= -1.0;
300            velocity.rotation *= -1.0;
301        }
302    }
303}
Source

pub fn physical_width(&self) -> u32

The window’s client area width in physical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/3d/mirror.rs (line 241)
235fn create_mirror_texture_resource(
236    commands: &mut Commands,
237    windows_query: &Query<&Window>,
238    images: &mut Assets<Image>,
239) -> Handle<Image> {
240    let window = windows_query.iter().next().expect("No window found");
241    let window_size = uvec2(window.physical_width(), window.physical_height());
242    let image = create_mirror_texture_image(images, window_size);
243    commands.insert_resource(MirrorImage(image.clone()));
244    image
245}
246
247/// Spawns the camera that renders the mirror world.
248fn spawn_mirror_camera(
249    commands: &mut Commands,
250    camera_transform: &Transform,
251    camera_projection: &PerspectiveProjection,
252    mirror_transform: &Transform,
253    mirror_render_target: Handle<Image>,
254) {
255    let (mirror_camera_transform, mirror_camera_projection) =
256        calculate_mirror_camera_transform_and_projection(
257            camera_transform,
258            camera_projection,
259            mirror_transform,
260        );
261
262    commands.spawn((
263        Camera3d::default(),
264        Camera {
265            order: -1,
266            // Reflecting the model across the mirror will flip the winding of
267            // all the polygons. Therefore, in order to properly backface cull,
268            // we need to turn on `invert_culling`.
269            invert_culling: true,
270            ..default()
271        },
272        RenderTarget::Image(mirror_render_target.clone().into()),
273        mirror_camera_transform,
274        Projection::Perspective(mirror_camera_projection),
275        MirrorCamera,
276    ));
277}
278
279/// Spawns the animated fox.
280///
281/// Note that this doesn't play the animation; that's handled in
282/// [`play_fox_animation`].
283fn spawn_fox(commands: &mut Commands, asset_server: &AssetServer) {
284    commands.spawn((
285        WorldAssetRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_ASSET_PATH))),
286        Transform::from_xyz(-50.0, 0.0, -100.0),
287    ));
288}
289
290/// Spawns the mirror plane mesh and returns its transform.
291fn spawn_mirror(
292    commands: &mut Commands,
293    meshes: &mut Assets<Mesh>,
294    screen_space_texture_materials: &mut Assets<
295        ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>,
296    >,
297    mirror_render_target: Handle<Image>,
298) -> Transform {
299    let mirror_transform = Transform::from_scale(vec3(300.0, 1.0, 150.0))
300        .with_rotation(Quat::from_rotation_x(MIRROR_ROTATION_ANGLE))
301        .with_translation(MIRROR_POSITION);
302
303    commands.spawn((
304        Mesh3d(meshes.add(Plane3d::default().mesh().size(1.0, 1.0))),
305        MeshMaterial3d(screen_space_texture_materials.add(ExtendedMaterial {
306            base: StandardMaterial {
307                base_color: Color::BLACK,
308                emissive: Color::WHITE.into(),
309                emissive_texture: Some(mirror_render_target),
310                perceptual_roughness: 0.0,
311                metallic: 1.0,
312                ..default()
313            },
314            extension: ScreenSpaceTextureExtension { dummy: 0.0 },
315        })),
316        mirror_transform,
317        Mirror,
318    ));
319
320    mirror_transform
321}
322
323/// Spawns the buttons at the bottom of the screen.
324fn spawn_buttons(commands: &mut Commands) {
325    // Spawn the radio buttons that allow the user to select an object to
326    // control.
327    commands.spawn((
328        widgets::main_ui_node(),
329        children![widgets::option_buttons(
330            "Drag Action",
331            &[
332                (DragAction::MoveCamera, "Move Camera"),
333                (DragAction::MoveFox, "Move Fox"),
334            ],
335        )],
336    ));
337}
338
339/// Given the transform and projection of the main camera, returns an
340/// appropriate transform and projection for the mirror camera.
341fn calculate_mirror_camera_transform_and_projection(
342    main_camera_transform: &Transform,
343    main_camera_projection: &PerspectiveProjection,
344    mirror_transform: &Transform,
345) -> (Transform, PerspectiveProjection) {
346    // Calculate the reflection matrix (a.k.a. Householder matrix) that will
347    // reflect the scene across the mirror plane.
348    //
349    // Note that you must calculate this in *matrix* form and only *afterward*
350    // convert to a `Transform` instead of composing `Transform`s. This is
351    // because the reflection matrix has non-uniform scale, and composing
352    // transforms can't always handle composition of matrices with non-uniform
353    // scales.
354    let mirror_camera_transform = Transform::from_matrix(
355        Mat4::from_mat3a(reflection_matrix(Vec3::NEG_Z)) * main_camera_transform.to_matrix(),
356    );
357
358    // Compute the distance from the camera to the mirror plane. This will be
359    // used to calculate the distance to the near clip plane for the mirror
360    // world.
361    let distance_from_camera_to_mirror = InfinitePlane3d::new(mirror_transform.rotation * Vec3::Y)
362        .signed_distance(
363            Isometry3d::IDENTITY,
364            mirror_transform.translation - main_camera_transform.translation,
365        );
366
367    // Compute the normal of the mirror plane in view space.
368    let view_from_world = main_camera_transform.compute_affine().matrix3.inverse();
369    let mirror_projection_plane_normal =
370        (view_from_world * (mirror_transform.rotation * Vec3::NEG_Y)).normalize();
371
372    // Compute the final projection. It should match the main camera projection,
373    // except that `near` and `near_normal` should be set to the updated near
374    // plane and near normal plane as above.
375    let mirror_camera_projection = PerspectiveProjection {
376        near_clip_plane: mirror_projection_plane_normal.extend(distance_from_camera_to_mirror),
377        ..*main_camera_projection
378    };
379
380    (mirror_camera_transform, mirror_camera_projection)
381}
382
383/// A system that resizes the render target image when the user resizes the window.
384///
385/// Since the image that stores the rendered mirror world has the same physical
386/// size as the window, we need to reallocate it and reattach it to the mirror
387/// material whenever the window size changes.
388fn handle_window_resize_messages(
389    windows_query: Query<&Window>,
390    mut mirror_cameras_query: Query<&mut RenderTarget, With<MirrorCamera>>,
391    mut images: ResMut<Assets<Image>>,
392    mut mirror_image: ResMut<MirrorImage>,
393    mut screen_space_texture_materials: ResMut<
394        Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>,
395    >,
396    mut resize_messages: MessageReader<WindowResized>,
397) {
398    // We run at most once, regardless of the number of window resize messages
399    // there were this frame.
400    let Some(resize_message) = resize_messages.read().next() else {
401        return;
402    };
403    let Ok(window) = windows_query.get(resize_message.window) else {
404        return;
405    };
406
407    let window_size = uvec2(window.physical_width(), window.physical_height());
408    let image = create_mirror_texture_image(&mut images, window_size);
409    images.remove(mirror_image.0.id());
410
411    mirror_image.0 = image.clone();
412
413    for mut target in mirror_cameras_query.iter_mut() {
414        *target = image.clone().into();
415    }
416
417    for (_, material) in screen_space_texture_materials.iter_mut() {
418        material.base.emissive_texture = Some(image.clone());
419    }
420}
Source

pub fn physical_height(&self) -> u32

The window’s client area height in physical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/3d/mirror.rs (line 241)
235fn create_mirror_texture_resource(
236    commands: &mut Commands,
237    windows_query: &Query<&Window>,
238    images: &mut Assets<Image>,
239) -> Handle<Image> {
240    let window = windows_query.iter().next().expect("No window found");
241    let window_size = uvec2(window.physical_width(), window.physical_height());
242    let image = create_mirror_texture_image(images, window_size);
243    commands.insert_resource(MirrorImage(image.clone()));
244    image
245}
246
247/// Spawns the camera that renders the mirror world.
248fn spawn_mirror_camera(
249    commands: &mut Commands,
250    camera_transform: &Transform,
251    camera_projection: &PerspectiveProjection,
252    mirror_transform: &Transform,
253    mirror_render_target: Handle<Image>,
254) {
255    let (mirror_camera_transform, mirror_camera_projection) =
256        calculate_mirror_camera_transform_and_projection(
257            camera_transform,
258            camera_projection,
259            mirror_transform,
260        );
261
262    commands.spawn((
263        Camera3d::default(),
264        Camera {
265            order: -1,
266            // Reflecting the model across the mirror will flip the winding of
267            // all the polygons. Therefore, in order to properly backface cull,
268            // we need to turn on `invert_culling`.
269            invert_culling: true,
270            ..default()
271        },
272        RenderTarget::Image(mirror_render_target.clone().into()),
273        mirror_camera_transform,
274        Projection::Perspective(mirror_camera_projection),
275        MirrorCamera,
276    ));
277}
278
279/// Spawns the animated fox.
280///
281/// Note that this doesn't play the animation; that's handled in
282/// [`play_fox_animation`].
283fn spawn_fox(commands: &mut Commands, asset_server: &AssetServer) {
284    commands.spawn((
285        WorldAssetRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_ASSET_PATH))),
286        Transform::from_xyz(-50.0, 0.0, -100.0),
287    ));
288}
289
290/// Spawns the mirror plane mesh and returns its transform.
291fn spawn_mirror(
292    commands: &mut Commands,
293    meshes: &mut Assets<Mesh>,
294    screen_space_texture_materials: &mut Assets<
295        ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>,
296    >,
297    mirror_render_target: Handle<Image>,
298) -> Transform {
299    let mirror_transform = Transform::from_scale(vec3(300.0, 1.0, 150.0))
300        .with_rotation(Quat::from_rotation_x(MIRROR_ROTATION_ANGLE))
301        .with_translation(MIRROR_POSITION);
302
303    commands.spawn((
304        Mesh3d(meshes.add(Plane3d::default().mesh().size(1.0, 1.0))),
305        MeshMaterial3d(screen_space_texture_materials.add(ExtendedMaterial {
306            base: StandardMaterial {
307                base_color: Color::BLACK,
308                emissive: Color::WHITE.into(),
309                emissive_texture: Some(mirror_render_target),
310                perceptual_roughness: 0.0,
311                metallic: 1.0,
312                ..default()
313            },
314            extension: ScreenSpaceTextureExtension { dummy: 0.0 },
315        })),
316        mirror_transform,
317        Mirror,
318    ));
319
320    mirror_transform
321}
322
323/// Spawns the buttons at the bottom of the screen.
324fn spawn_buttons(commands: &mut Commands) {
325    // Spawn the radio buttons that allow the user to select an object to
326    // control.
327    commands.spawn((
328        widgets::main_ui_node(),
329        children![widgets::option_buttons(
330            "Drag Action",
331            &[
332                (DragAction::MoveCamera, "Move Camera"),
333                (DragAction::MoveFox, "Move Fox"),
334            ],
335        )],
336    ));
337}
338
339/// Given the transform and projection of the main camera, returns an
340/// appropriate transform and projection for the mirror camera.
341fn calculate_mirror_camera_transform_and_projection(
342    main_camera_transform: &Transform,
343    main_camera_projection: &PerspectiveProjection,
344    mirror_transform: &Transform,
345) -> (Transform, PerspectiveProjection) {
346    // Calculate the reflection matrix (a.k.a. Householder matrix) that will
347    // reflect the scene across the mirror plane.
348    //
349    // Note that you must calculate this in *matrix* form and only *afterward*
350    // convert to a `Transform` instead of composing `Transform`s. This is
351    // because the reflection matrix has non-uniform scale, and composing
352    // transforms can't always handle composition of matrices with non-uniform
353    // scales.
354    let mirror_camera_transform = Transform::from_matrix(
355        Mat4::from_mat3a(reflection_matrix(Vec3::NEG_Z)) * main_camera_transform.to_matrix(),
356    );
357
358    // Compute the distance from the camera to the mirror plane. This will be
359    // used to calculate the distance to the near clip plane for the mirror
360    // world.
361    let distance_from_camera_to_mirror = InfinitePlane3d::new(mirror_transform.rotation * Vec3::Y)
362        .signed_distance(
363            Isometry3d::IDENTITY,
364            mirror_transform.translation - main_camera_transform.translation,
365        );
366
367    // Compute the normal of the mirror plane in view space.
368    let view_from_world = main_camera_transform.compute_affine().matrix3.inverse();
369    let mirror_projection_plane_normal =
370        (view_from_world * (mirror_transform.rotation * Vec3::NEG_Y)).normalize();
371
372    // Compute the final projection. It should match the main camera projection,
373    // except that `near` and `near_normal` should be set to the updated near
374    // plane and near normal plane as above.
375    let mirror_camera_projection = PerspectiveProjection {
376        near_clip_plane: mirror_projection_plane_normal.extend(distance_from_camera_to_mirror),
377        ..*main_camera_projection
378    };
379
380    (mirror_camera_transform, mirror_camera_projection)
381}
382
383/// A system that resizes the render target image when the user resizes the window.
384///
385/// Since the image that stores the rendered mirror world has the same physical
386/// size as the window, we need to reallocate it and reattach it to the mirror
387/// material whenever the window size changes.
388fn handle_window_resize_messages(
389    windows_query: Query<&Window>,
390    mut mirror_cameras_query: Query<&mut RenderTarget, With<MirrorCamera>>,
391    mut images: ResMut<Assets<Image>>,
392    mut mirror_image: ResMut<MirrorImage>,
393    mut screen_space_texture_materials: ResMut<
394        Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>,
395    >,
396    mut resize_messages: MessageReader<WindowResized>,
397) {
398    // We run at most once, regardless of the number of window resize messages
399    // there were this frame.
400    let Some(resize_message) = resize_messages.read().next() else {
401        return;
402    };
403    let Ok(window) = windows_query.get(resize_message.window) else {
404        return;
405    };
406
407    let window_size = uvec2(window.physical_width(), window.physical_height());
408    let image = create_mirror_texture_image(&mut images, window_size);
409    images.remove(mirror_image.0.id());
410
411    mirror_image.0 = image.clone();
412
413    for mut target in mirror_cameras_query.iter_mut() {
414        *target = image.clone().into();
415    }
416
417    for (_, material) in screen_space_texture_materials.iter_mut() {
418        material.base.emissive_texture = Some(image.clone());
419    }
420}
Source

pub fn physical_size(&self) -> UVec2

The window’s client size in physical pixels

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/3d/split_screen.rs (line 169)
159fn set_camera_viewports(
160    windows: Query<&Window>,
161    mut window_resized_reader: MessageReader<WindowResized>,
162    mut query: Query<(&CameraPosition, &mut Camera)>,
163) {
164    // We need to dynamically resize the camera's viewports whenever the window size changes
165    // so then each camera always takes up half the screen.
166    // A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
167    for window_resized in window_resized_reader.read() {
168        let window = windows.get(window_resized.window).unwrap();
169        let size = window.physical_size() / 2;
170
171        for (camera_position, mut camera) in &mut query {
172            camera.viewport = Some(Viewport {
173                physical_position: camera_position.pos * size,
174                physical_size: size,
175                ..default()
176            });
177        }
178    }
179}
More examples
Hide additional examples
examples/3d/camera_sub_view.rs (line 259)
255fn resize_viewports(
256    window: Single<&Window, With<bevy::window::PrimaryWindow>>,
257    mut viewports: Query<(&mut Camera, &ExampleViewports)>,
258) {
259    let window_size = window.physical_size();
260
261    let small_height = window_size.y / 5;
262    let small_width = window_size.x / 8;
263
264    let large_height = small_height * 4;
265    let large_width = small_width * 4;
266
267    let large_size = UVec2::new(large_width, large_height);
268
269    // Enforce the aspect ratio of the small viewports to ensure the images
270    // appear unstretched
271    let small_dim = small_height.min(small_width);
272    let small_size = UVec2::new(small_dim, small_dim);
273
274    let small_wide_size = UVec2::new(small_dim * 2, small_dim);
275
276    for (mut camera, example_viewport) in viewports.iter_mut() {
277        if camera.viewport.is_none() {
278            camera.viewport = Some(Viewport::default());
279        };
280
281        let Some(viewport) = &mut camera.viewport else {
282            continue;
283        };
284
285        let (size, position) = match example_viewport {
286            ExampleViewports::PerspectiveMain => (large_size, UVec2::new(0, small_height)),
287            ExampleViewports::PerspectiveStretched => (small_size, UVec2::ZERO),
288            ExampleViewports::PerspectiveMoving => (small_size, UVec2::new(small_width, 0)),
289            ExampleViewports::PerspectiveControl => {
290                (small_wide_size, UVec2::new(small_width * 2, 0))
291            }
292            ExampleViewports::OrthographicMain => {
293                (large_size, UVec2::new(large_width, small_height))
294            }
295            ExampleViewports::OrthographicStretched => (small_size, UVec2::new(small_width * 4, 0)),
296            ExampleViewports::OrthographicMoving => (small_size, UVec2::new(small_width * 5, 0)),
297            ExampleViewports::OrthographicControl => {
298                (small_wide_size, UVec2::new(small_width * 6, 0))
299            }
300        };
301
302        viewport.physical_size = size;
303        viewport.physical_position = position;
304    }
305}
examples/testbed/3d.rs (line 786)
738    pub fn setup(
739        mut commands: Commands,
740        mut meshes: ResMut<Assets<Mesh>>,
741        mut materials: ResMut<Assets<StandardMaterial>>,
742        window: Single<&Window, With<PrimaryWindow>>,
743    ) {
744        // circular base
745        commands.spawn((
746            Mesh3d(meshes.add(Circle::new(4.0))),
747            MeshMaterial3d(materials.add(Color::WHITE)),
748            Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
749            RenderLayers::layer(0).with(1).with(2),
750            DespawnOnExit(CURRENT_SCENE),
751        ));
752
753        // cubes
754        commands.spawn((
755            Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
756            MeshMaterial3d(materials.add(Color::srgb(1.0, 0.0, 0.0))),
757            Transform::from_xyz(-1.5, 0.5, 0.0),
758            // No render layer for this one to test the default case
759            DespawnOnExit(CURRENT_SCENE),
760        ));
761        commands.spawn((
762            Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
763            MeshMaterial3d(materials.add(Color::srgb(0.0, 1.0, 0.0))),
764            Transform::from_xyz(0.0, 0.5, 0.0),
765            RenderLayers::layer(1),
766            DespawnOnExit(CURRENT_SCENE),
767        ));
768        commands.spawn((
769            Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
770            MeshMaterial3d(materials.add(Color::srgb(0.0, 0.0, 1.0))),
771            Transform::from_xyz(1.5, 0.5, 0.0),
772            RenderLayers::layer(2),
773            DespawnOnExit(CURRENT_SCENE),
774        ));
775
776        // Light
777        commands.spawn((
778            PointLight {
779                shadow_maps_enabled: true,
780                ..default()
781            },
782            Transform::from_xyz(4.0, 8.0, 4.0),
783            DespawnOnExit(CURRENT_SCENE),
784        ));
785
786        let window_half_size = window.physical_size() / 2;
787
788        // Split the screen in 4 different viewports with each of them having a specific render
789        // layer
790        for index in 0..4 {
791            let viewport_pos = UVec2::new((index % 2) as u32, (index / 2) as u32);
792            let mut entity_cmds = commands.spawn((
793                Camera3d::default(),
794                Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
795                Camera {
796                    // Renders cameras with different priorities to prevent ambiguities
797                    order: index as isize,
798                    viewport: Some(Viewport {
799                        physical_position: viewport_pos * window_half_size,
800                        physical_size: window_half_size,
801                        ..default()
802                    }),
803                    ..default()
804                },
805                DespawnOnExit(CURRENT_SCENE),
806            ));
807            match index {
808                0 => {}
809                1 => {
810                    entity_cmds.insert(RenderLayers::layer(1));
811                }
812                2 => {
813                    entity_cmds.insert(RenderLayers::layer(2));
814                }
815                3 => {
816                    entity_cmds.insert(RenderLayers::layer(0).with(1).with(2));
817                }
818                _ => warn!("Unexpected index {index}"),
819            }
820        }
821    }
examples/usage/debug_frustum_culling.rs (line 129)
102fn setup(
103    mut commands: Commands,
104    windows: Query<&Window>,
105    mut config_store: ResMut<GizmoConfigStore>,
106    mut meshes: ResMut<Assets<Mesh>>,
107    mut materials: ResMut<Assets<StandardMaterial>>,
108) -> Result {
109    let window = windows.single()?;
110    // The camera that the user controls to observe the scene.
111    let free_camera = commands
112        .spawn((
113            Camera3d::default(),
114            FREE_CAMERA_START_TRANSFORM.looking_at(FREE_CAMERA_START_TARGET, Vec3::Y),
115            FreeCamera::default(),
116        ))
117        .id();
118
119    // The camera that we want to debug frustum culling for. This will be rendered
120    // as a picture-in-picture in the lower right ninth of the screen.
121    let my_camera = commands
122        .spawn((
123            Camera3d::default(),
124            Transform::from_xyz(0., 1.5, 0.).looking_at(Vec3::new(1.0, 1.5, 0.), Vec3::Y),
125            Camera {
126                order: 1,
127                // The camera-to-debug's view will be in the lower right ninth of the screen.
128                viewport: Some(Viewport {
129                    physical_position: window.physical_size() * 2 / 3,
130                    physical_size: window.physical_size() / 3,
131                    ..default()
132                }),
133                // Do not write the free camera's view rendering back into the P-I-P
134                msaa_writeback: MsaaWriteback::Off,
135                ..default()
136            },
137            MyCamera,
138        ))
139        .id();
140
141    // Instructions placed on top of the free_camera view
142    commands.spawn((
143        UiTargetCamera(free_camera),
144        Node {
145            width: percent(100),
146            height: percent(100),
147            ..default()
148        },
149        children![(
150            Text::new(
151                "This example utilizes free camera controls i.e. move with WASD and mouse grab to change orientation.\n\
152                Press '1' to move the free camera to where MyCamera is, matching its view frustum.\n\
153                Press '2' to move the free camera to its initial position in the example.",
154            ),
155            Node {
156                position_type: PositionType::Absolute,
157                top: px(12),
158                left: px(12),
159                ..default()
160            },
161        )]
162    ));
163    // Label for the picture-in-picture view of MyCamera
164    commands.spawn((
165        UiTargetCamera(my_camera),
166        Node {
167            width: percent(100),
168            height: percent(100),
169            ..default()
170        },
171        children![(
172            Text::new("View of MyCamera"),
173            Node {
174                position_type: PositionType::Absolute,
175                bottom: px(12),
176                right: px(100),
177                ..default()
178            },
179        )],
180    ));
181
182    // Green Floor Plane
183    commands.spawn((
184        Mesh3d(
185            meshes.add(
186                Plane3d::default()
187                    .mesh()
188                    .size(SHAPE_RING_RADIUS * 4., SHAPE_RING_RADIUS * 4.),
189            ),
190        ),
191        MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
192    ));
193    // Blue Wall Plane
194    commands.spawn((
195        Mesh3d(meshes.add(Plane3d::default().mesh().size(5., 5.))),
196        MeshMaterial3d(materials.add(Color::srgb(0.3, 0.3, 0.5))),
197        Transform::from_xyz(20., 2.5, 10.).with_rotation(Quat::from_rotation_z(PI / 2.)),
198    ));
199    // Light
200    commands.spawn((
201        PointLight {
202            shadow_maps_enabled: true,
203            ..default()
204        },
205        Transform::from_xyz(0.0, 10.0, 0.0),
206    ));
207
208    // Configure all AABB's to have a default color of red
209    let (_, aabb_gizmo_config) = config_store.config_mut::<AabbGizmoConfigGroup>();
210    aabb_gizmo_config.default_color = Some(Color::LinearRgba(LinearRgba::RED));
211
212    // Configure the shapes on the ring that will have their AABB's drawn and updated
213    let white_matl = materials.add(Color::WHITE);
214    let shapes = [
215        meshes.add(Cuboid {
216            half_size: Vec3::new(2., 0.5, 1.),
217        }),
218        meshes.add(Tetrahedron {
219            vertices: [
220                Vec3::new(3., 4., 3.),
221                Vec3::new(-0.5, 4., -0.5),
222                Vec3::new(-0.5, -0.5, 3.),
223                Vec3::new(3., -0.5, -0.5),
224            ],
225        }),
226        meshes.add(Cylinder {
227            radius: 0.1,
228            half_height: 1.5,
229        }),
230        meshes.add(Cuboid {
231            half_size: Vec3::new(1., 0.1, 2.),
232        }),
233        meshes.add(Sphere::default().mesh().ico(5).unwrap()),
234    ];
235    let shapes_len = shapes.len() as f32;
236    let mut shape_ring = commands.spawn((Transform::default(), Visibility::default(), ShapeRing));
237    for (i, shape) in shapes.into_iter().enumerate() {
238        // Space the shapes out evenly along the ring
239        let shape_angle = i as f32 * 2. * PI / shapes_len;
240        let (s, c) = ops::sin_cos(shape_angle);
241        let (x, z) = (SHAPE_RING_RADIUS * c, SHAPE_RING_RADIUS * s);
242        shape_ring.with_child((
243            Mesh3d(shape),
244            MeshMaterial3d(white_matl.clone()),
245            Transform::from_xyz(x, 1.5, z).with_rotation(Quat::from_rotation_x(-PI / 4.)),
246            MyShape,
247        ));
248    }
249
250    // Configure the shape that peeks out of the wall plane
251    let wall_shape = meshes.add(Torus::default());
252    commands.spawn((
253        Mesh3d(wall_shape),
254        MeshMaterial3d(white_matl.clone()),
255        Transform::from_xyz(25., 1.5, 12.5).with_rotation(Quat::from_rotation_x(-PI / 4.)),
256        WallShape,
257    ));
258
259    Ok(())
260}
Source

pub fn scale_factor(&self) -> f32

The window’s scale factor.

Ratio of physical size to logical size, see WindowResolution.

Examples found in repository?
examples/window/scale_factor_override.rs (line 68)
62fn display_override(
63    mut window: Single<&mut Window>,
64    mut custom_text: Single<&mut Text, With<CustomText>>,
65) {
66    let text = format!(
67        "Scale factor: {:.1} {}",
68        window.scale_factor(),
69        if window.resolution.scale_factor_override().is_some() {
70            "(overridden)"
71        } else {
72            "(default)"
73        }
74    );
75
76    window.title.clone_from(&text);
77    custom_text.0 = text;
78}
Source

pub fn cursor_position(&self) -> Option<Vec2>

The cursor position in this window in logical pixels.

Returns None if the cursor is outside the window area.

See WindowResolution for an explanation about logical/physical sizes.

Examples found in repository?
examples/showcase/desk_toy.rs (line 212)
205fn get_cursor_world_pos(
206    mut cursor_world_pos: ResMut<CursorWorldPos>,
207    primary_window: Single<&Window, With<PrimaryWindow>>,
208    q_camera: Single<(&Camera, &GlobalTransform)>,
209) {
210    let (main_camera, main_camera_transform) = *q_camera;
211    // Get the cursor position in the world
212    cursor_world_pos.0 = primary_window.cursor_position().and_then(|cursor_pos| {
213        main_camera
214            .viewport_to_world_2d(main_camera_transform, cursor_pos)
215            .ok()
216    });
217}
More examples
Hide additional examples
examples/ecs/observers.rs (line 202)
190fn handle_click(
191    mouse_button_input: Res<ButtonInput<MouseButton>>,
192    camera: Single<(&Camera, &GlobalTransform)>,
193    windows: Query<&Window>,
194    mut commands: Commands,
195) {
196    let Ok(windows) = windows.single() else {
197        return;
198    };
199
200    let (camera, camera_transform) = *camera;
201    if let Some(pos) = windows
202        .cursor_position()
203        .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
204        .map(|ray| ray.origin.truncate())
205        && mouse_button_input.just_pressed(MouseButton::Left)
206    {
207        commands.trigger(ExplodeMines { pos, radius: 1.0 });
208    }
209}
examples/2d/2d_viewport_to_world.rs (line 29)
22fn draw_cursor(
23    camera_query: Single<(&Camera, &GlobalTransform)>,
24    window: Single<&Window>,
25    mut gizmos: Gizmos,
26) {
27    let (camera, camera_transform) = *camera_query;
28
29    if let Some(cursor_position) = window.cursor_position()
30        // Calculate a world position based on the cursor's position.
31        && let Ok(world_pos) = camera.viewport_to_world_2d(camera_transform, cursor_position)
32        // To test Camera::world_to_viewport, convert result back to viewport space and then back to world space.
33        && let Ok(viewport_check) = camera.world_to_viewport(camera_transform, world_pos.extend(0.0))
34        && let Ok(world_check) = camera.viewport_to_world_2d(camera_transform, viewport_check.xy())
35    {
36        gizmos.circle_2d(world_pos, 10., WHITE);
37        // Should be the same as world_pos
38        gizmos.circle_2d(world_check, 8., RED);
39    }
40}
examples/2d/rotate_to_cursor.rs (line 45)
38fn player_movement_system(
39    mut player: Single<&mut Transform, With<Player>>,
40    camera_query: Single<(&Camera, &GlobalTransform)>,
41    window: Single<&Window>,
42) {
43    let (camera, camera_transform) = *camera_query;
44
45    if let Some(cursor_position) = window.cursor_position()
46        // Calculate a world position based on the cursor's position.
47        && let Ok(cursor_world_pos) = camera.viewport_to_world_2d(camera_transform, cursor_position)
48    {
49        // The angle an entity needs to rotate to face a point is defined
50        // by the vector between the two points (Vec2 - Vec2), which we can then
51        // turn into radians using to_angle.
52        //
53        // FRAC_PI_2 is because our sprite's ship is facing "up" so we rotate it an additional 90 degrees
54        // so that it faces the cursor.
55        player.rotation = Quat::from_rotation_z(
56            (cursor_world_pos - player.translation.xy()).to_angle() - FRAC_PI_2,
57        );
58    }
59}
examples/3d/3d_viewport_to_world.rs (line 21)
13fn draw_cursor(
14    camera_query: Single<(&Camera, &GlobalTransform)>,
15    ground: Single<&GlobalTransform, With<Ground>>,
16    window: Single<&Window>,
17    mut gizmos: Gizmos,
18) {
19    let (camera, camera_transform) = *camera_query;
20
21    if let Some(cursor_position) = window.cursor_position()
22        // Calculate a ray pointing from the camera into the world based on the cursor's position.
23        && let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position)
24        // Calculate if and where the ray is hitting the ground plane.
25        && let Some(point) = ray.plane_intersection_point(ground.translation(), InfinitePlane3d::new(ground.up()))
26    {
27        // Draw a circle just above the ground plane at that position.
28        gizmos.circle(
29            Isometry3d::new(
30                point + ground.up() * 0.01,
31                Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()),
32            ),
33            0.2,
34            Color::WHITE,
35        );
36    }
37}
Source

pub fn physical_cursor_position(&self) -> Option<Vec2>

The cursor position in this window in physical pixels.

Returns None if the cursor is outside the window area.

See WindowResolution for an explanation about logical/physical sizes.

Source

pub fn set_cursor_position(&mut self, position: Option<Vec2>)

Set the cursor position in this window in logical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Source

pub fn set_physical_cursor_position(&mut self, position: Option<DVec2>)

Set the cursor position in this window in physical pixels.

See WindowResolution for an explanation about logical/physical sizes.

Trait Implementations§

Source§

impl Clone for Window

Source§

fn clone(&self) -> Window

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Component for Window
where Window: Send + Sync + 'static,

Required Components: CursorOptions.

A component’s Required Components are inserted whenever it is inserted. Note that this will also insert the required components of the required components, recursively, in depth-first order.

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Window>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

impl Debug for Window

Source§

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

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

impl Default for Window

Source§

fn default() -> Window

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Window

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Window, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl FromArg for Window

Source§

type This<'from_arg> = Window

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<Window as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for Window

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Window>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl GetOwnership for Window

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for Window

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl IntoReturn for Window

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where Window: 'into_return,

Converts Self into a Return value.
Source§

impl PartialReflect for Window

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<Window>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<Window>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<Window>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>

Returns a “partial comparison” result. Read more
Source§

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

Debug formatter for the value. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails.
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for Window

Source§

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

Returns the value as a Box<dyn Any>. Read more
Source§

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

Returns the value as a &dyn Any. Read more
Source§

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

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<Window>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl Serialize for Window

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Struct for Window

Source§

fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>

Gets a reference to the value of the field named name as a &dyn PartialReflect.
Source§

fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>

Gets a mutable reference to the value of the field named name as a &mut dyn PartialReflect.
Source§

fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Gets a reference to the value of the field with index index as a &dyn PartialReflect.
Source§

fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Gets a mutable reference to the value of the field with index index as a &mut dyn PartialReflect.
Source§

fn name_at(&self, index: usize) -> Option<&str>

Gets the name of the field with index index.
Source§

fn index_of_name(&self, name: &str) -> Option<usize>

Gets the index of the field with the given name.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
Source§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
Source§

fn to_dynamic_struct(&self) -> DynamicStruct

Creates a new DynamicStruct from this struct.
Source§

fn get_represented_struct_info(&self) -> Option<&'static StructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for Window

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for Window

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.

Auto Trait Implementations§

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<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Return a iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

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

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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 + Send + Sync>

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<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> ErasedBundleTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Bundle,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>

Clones this template. See Clone.
Source§

impl<T> ErasedComponentTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Component,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>

Clones this template. See Clone.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

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> FromTemplate for T
where T: Clone + Default + Unpin,

Source§

type Template = T

The Template for this type.
Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<S> GetField for S
where S: Struct,

Source§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Gets a reference to the value of the field named name, downcast to T.
Source§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Gets a mutable reference to the value of the field named name, downcast to T.
Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

Source§

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

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
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<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

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

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<G> PatchFromTemplate for G
where G: FromTemplate,

Source§

type Template = <G as FromTemplate>::Template

The Template that will be patched.
Source§

fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
where F: FnOnce(&mut <G as PatchFromTemplate>::Template, &mut ResolveContext<'_>),

Takes a “patch function” func, and turns it into a TemplatePatch.
Source§

impl<T> PatchTemplate for T
where T: Template,

Source§

fn patch_template<F>(func: F) -> TemplatePatch<F, T>
where F: FnOnce(&mut T, &mut ResolveContext<'_>),

Takes a “patch function” func that patches this Template, and turns it into a TemplatePatch.
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Reflectable for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

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

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
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> Template for T
where T: Clone + Default + Unpin,

Source§

type Output = T

The type of value produced by this Template.
Source§

fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>

Uses this template and the given entity context to produce a Template::Output.
Source§

fn clone_template(&self) -> T

Clones this template. See Clone.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of this value.
Source§

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

Source§

fn vzip(self) -> V

Source§

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

Source§

impl<T> WasmNotSendSync for T

Source§

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

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