Skip to main content

mln_engine/draw/
target.rs

1//! Textures of a layer's own that its draws draw into ahead of a frame and
2//! that its other draws sample: [`Target`]s.
3//!
4//! A layer makes a target of a size and a clear color
5//! ([`Resources::target`]) and keeps it. In a frame it pushes the
6//! draws into the target into the target's group of its draws
7//! ([`Draws::target`](crate::draw::draws::Draws::target)), and binds the
8//! target's [`texture`](Target::texture) to the draws that sample it. The
9//! engine makes the target's texture, and the depth it draws with, of its
10//! size; clears it to its clear color and draws the group into it before the frame, or the
11//! drape, whose draws sample it; and keeps whether it holds what was drawn
12//! into it ([`Target::holds`]), so that a layer whose target holds the same
13//! from frame to frame draws into it once.
14
15use mln_gfx::gpu::{
16    ColorAttachment, DepthStencilAttachment, Gpu, GpuError, LoadOp, Scissor, TargetFormats, TextureFormat,
17};
18use mln_gfx::texture2d::{SamplerState, texture_format};
19use mln_gfx::types::{TextureChannelDataType, TextureFilterType, TexturePixelType, TextureWrapType};
20use mln_gfx::{Rgba, Size};
21
22use crate::draw::context::Context;
23use crate::draw::resources::{GpuTexture, Resources};
24use crate::draw::store::{Shared, TargetKey, Texture};
25use crate::render::paint_parameters::{OpenPass, PaintParameters};
26use crate::render::pass::RenderPass;
27
28/// A texture that a layer's draws draw into ahead of the frame, which its
29/// other draws sample: a handle of the target in the context's store, which
30/// stays while a clone of the handle does.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Target {
33    key: Shared<TargetKey>,
34    texture: Texture,
35}
36
37/// What the context keeps of a [`Target`].
38pub(crate) struct TargetObjects {
39    size: Size,
40    /// The color the target clears to before its draws.
41    clear: Rgba,
42    /// The depth the target's draws draw with, of its size, made with its
43    /// first pass where the backend draws with one
44    /// ([`Context::render_target_depth`]).
45    depth: Option<GpuTexture>,
46    /// Whether the target holds what the draws into it drew, as
47    /// [`Target::holds`] says.
48    holds: bool,
49    /// Whether the frame drew into the target without failing.
50    drawn: bool,
51}
52
53impl Target {
54    /// See [`Resources::target`]: of the type the backend draws into for
55    /// `kind` ([`Context::render_target_type`]).
56    pub(crate) fn new(context: &mut Context, size: Size, kind: TextureChannelDataType, clear: Rgba) -> Target {
57        let format = texture_format(TexturePixelType::Rgba, context.render_target_type(kind));
58        let texture = context.add_texture_with(|texture| {
59            texture.set_size(size);
60            texture.set_format(format);
61            texture.set_render_target();
62            texture.set_sampler(SamplerState {
63                filter: TextureFilterType::Linear,
64                wrap_u: TextureWrapType::Clamp,
65                wrap_v: TextureWrapType::Clamp,
66                ..SamplerState::default()
67            });
68        });
69        let key = context.add_target(TargetObjects { size, clear, depth: None, holds: false, drawn: false });
70        Target { key, texture }
71    }
72
73    pub(crate) fn key(&self) -> &Shared<TargetKey> {
74        &self.key
75    }
76
77    /// The texture the target's draws draw into, which draws sample. It is
78    /// the same through a change of the target's size.
79    #[must_use]
80    pub fn texture(&self) -> &Texture {
81        &self.texture
82    }
83
84    /// Makes the target of `size` from now on: of another size, it then
85    /// holds nothing.
86    pub fn set_size(&self, res: &mut Resources<'_>, size: Size) {
87        let context = &mut *res.context;
88        let Some(objects) = context.target_mut(self).filter(|objects| objects.size != size) else {
89            return;
90        };
91        *objects = TargetObjects { size, clear: objects.clear, depth: None, holds: false, drawn: false };
92        if let Some(mut texture) = context.texture_mut(&self.texture) {
93            texture.set_size(size);
94        }
95    }
96
97    /// Whether the target holds what draws drew into it: from the frame
98    /// whose draws into it were written, until a frame fails to draw them,
99    /// or the target changes size.
100    #[must_use]
101    pub fn holds(&self, res: &Resources<'_>) -> bool {
102        res.context.target(self).is_some_and(|objects| objects.holds)
103    }
104
105    /// Clears the target to its clear color and its depth to 1, and runs
106    /// `draw` with `parameters` into the target in the opaque pass and then
107    /// the translucent one, each as the first layer of a frame of its own,
108    /// outside any other pass, through `gpu`, the context's. `draw` returns
109    /// whether its draws didn't fail. A target that draws without failing
110    /// holds what it drew once the frame is done
111    /// ([`Context::end_targets`]).
112    pub(crate) fn render(
113        &self,
114        gpu: &mut dyn Gpu,
115        parameters: &mut PaintParameters<'_>,
116        mut draw: impl FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) -> bool,
117    ) {
118        let begun = self.pass(gpu, parameters.context).and_then(|pass| parameters.begin_pass(gpu, pass).map(|()| pass));
119        let pass = match begun {
120            Ok(pass) => pass,
121            Err(error) => {
122                parameters.context.fail(format!("Beginning a render target's pass failed: {error}"));
123                return;
124            }
125        };
126        let frame = (parameters.scissor_rect, parameters.pass, parameters.depth_range_size, parameters.current_layer);
127        parameters.scissor_rect = Scissor::whole(pass.size);
128        let num_sublayers = PaintParameters::NUM_SUBLAYERS as usize;
129        let mut drawn = true;
130        for pass in [RenderPass::OPAQUE, RenderPass::TRANSLUCENT] {
131            parameters.pass = pass;
132            parameters.depth_range_size = 1.0 - (3 * num_sublayers) as f32 * PaintParameters::DEPTH_EPSILON;
133            parameters.current_layer = 0;
134            drawn &= draw(gpu, parameters);
135        }
136        let ended = parameters.end_pass(gpu);
137        if let Err(error) = &ended {
138            parameters.context.fail(format!("Ending a render target's pass failed: {error}"));
139        }
140        (parameters.scissor_rect, parameters.pass, parameters.depth_range_size, parameters.current_layer) = frame;
141        if let Some(objects) = parameters.context.target_mut(self) {
142            objects.drawn = ended.is_ok() && drawn;
143        }
144    }
145
146    /// The pass that clears the target to its clear color and its depth to 1,
147    /// making them through `gpu`, the context's.
148    fn pass(&self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<OpenPass, GpuError> {
149        let (color, format, size) = self.color_attachment(gpu, context)?;
150        let depth_format = context.render_target_depth();
151        let objects = context.target(self).ok_or(GpuError::UnknownId("render target"))?;
152        if objects.depth.is_none()
153            && let Some(depth_format) = depth_format
154        {
155            let depth = context.device().attachment(gpu, "render target depth", size, depth_format)?;
156            if let Some(objects) = context.target_mut(self) {
157                objects.depth = Some(depth);
158            }
159        }
160        let depth = context.target(self).and_then(|objects| objects.depth.as_ref()).map(GpuTexture::id);
161        Ok(OpenPass {
162            label: "render target",
163            color: Some(color),
164            depth_stencil: depth.map(|texture| DepthStencilAttachment {
165                texture,
166                depth: LoadOp::Clear(1.0),
167                stencil: LoadOp::Load,
168            }),
169            size,
170            targets: TargetFormats { color: Some(format), depth_stencil: depth.and(depth_format) },
171        })
172    }
173}
174
175impl Target {
176    /// The target's texture as a pass's color attachment that clears it to
177    /// its clear color, with its format and size, making the texture
178    /// through `gpu`, the context's.
179    pub(crate) fn color_attachment(
180        &self,
181        gpu: &mut dyn Gpu,
182        context: &mut Context,
183    ) -> Result<(ColorAttachment, TextureFormat, Size), GpuError> {
184        let texture = context.create_texture(gpu, &self.texture)?;
185        let format = context.texture(&self.texture).ok_or(GpuError::UnknownId("texture"))?.format();
186        let objects = context.target(self).ok_or(GpuError::UnknownId("render target"))?;
187        Ok((ColorAttachment { texture, load: LoadOp::Clear(objects.clear) }, format, objects.size))
188    }
189}
190
191impl TargetObjects {
192    /// Marks the target as holding what the frame's draws into it draw,
193    /// until the frame ends without drawing them.
194    pub(crate) fn declare(&mut self) {
195        self.holds = true;
196        self.drawn = false;
197    }
198
199    /// Ends the frame of the target: it holds what the frame drew into it
200    /// if the frame drew it, and `submitted`, its work reached the GPU.
201    pub(crate) fn end(&mut self, submitted: bool) {
202        self.holds = self.drawn && submitted;
203        self.drawn = false;
204    }
205}