Skip to main content

bevy_render/texture/
manual_texture_view.rs

1use bevy_camera::ManualTextureViewHandle;
2use bevy_ecs::resource::Resource;
3use bevy_math::UVec2;
4use bevy_platform::collections::HashMap;
5use bevy_render_macros::ExtractResource;
6use wgpu::TextureFormat;
7
8use crate::render_resource::TextureView;
9
10/// A manually managed [`TextureView`] for use as a [`bevy_camera::RenderTarget`].
11#[derive(Debug, Clone)]
12pub struct ManualTextureView {
13    pub texture_view: TextureView,
14    pub size: UVec2,
15    pub view_format: TextureFormat,
16}
17
18impl ManualTextureView {
19    pub fn with_default_format(texture_view: TextureView, size: UVec2) -> Self {
20        Self {
21            texture_view,
22            size,
23            view_format: TextureFormat::Rgba8UnormSrgb,
24        }
25    }
26}
27
28/// Resource that stores manually managed [`ManualTextureView`]s for use as a [`RenderTarget`](bevy_camera::RenderTarget).
29/// This type dereferences to a `HashMap<ManualTextureViewHandle, ManualTextureView>`.
30/// To add a new texture view, pick a new [`ManualTextureViewHandle`] and insert it into the map.
31/// Then, to render to the view, set a [`Camera`](bevy_camera::Camera)s `target` to `RenderTarget::TextureView(handle)`.
32/// ```ignore
33/// # use bevy_ecs::prelude::*;
34/// # let mut world = World::default();
35/// # world.insert_resource(ManualTextureViews::default());
36/// # let texture_view = todo!();
37/// let manual_views = world.resource_mut::<ManualTextureViews>();
38/// let manual_view = ManualTextureView::with_default_format(texture_view, UVec2::new(1024, 1024));
39///
40/// // Choose an unused handle value; it's likely only you are inserting manual views.
41/// const MANUAL_VIEW_HANDLE: ManualTextureViewHandle = ManualTextureViewHandle::new(42);
42/// manual_views.insert(MANUAL_VIEW_HANDLE, manual_view);
43///
44/// // Now you can spawn a Camera that renders to the manual view:
45/// # use bevy_camera::{Camera, RenderTarget};
46/// world.spawn(Camera {
47///     target: RenderTarget::TextureView(MANUAL_VIEW_HANDLE),
48///     ..Default::default()
49/// });
50/// ```
51/// Bevy will then use the `ManualTextureViews` resource to find your texture view and render to it.
52#[derive(Default, Clone, Resource, ExtractResource)]
53pub struct ManualTextureViews(HashMap<ManualTextureViewHandle, ManualTextureView>);
54
55impl core::ops::Deref for ManualTextureViews {
56    type Target = HashMap<ManualTextureViewHandle, ManualTextureView>;
57
58    fn deref(&self) -> &Self::Target {
59        &self.0
60    }
61}
62
63impl core::ops::DerefMut for ManualTextureViews {
64    fn deref_mut(&mut self) -> &mut Self::Target {
65        &mut self.0
66    }
67}