three_rs/renderer/render_target.rs
1//! Port of `three.js/src/core/RenderTarget.js` (the subset rungs 1–2 need).
2
3use std::cell::RefCell;
4use std::rc::Rc;
5
6use crate::error::Error;
7use crate::math::Vector4;
8use crate::textures::{DepthTexture, MinFilter, Texture, TextureFilter, TextureType};
9
10/// `getTextureType( texture )` (`src/nodes/core/NodeUtils.js`), which
11/// `NodeBuilder.getOutputType( index )` returns for a target's attachment:
12/// the channel count picks the length and `texture.type` the component —
13/// `uint` for `UnsignedIntType`, `int` for `IntType`, `float` otherwise.
14/// The port's texture carries its GPU format alone, which says both.
15///
16/// Three's `RGBFormat` length 3 has no counterpart: there is no
17/// three-channel colour format to render into.
18pub(crate) fn output_type(format: wgpu::TextureFormat) -> crate::nodes::Type {
19 use crate::nodes::Type;
20 // `texture.type === UnsignedIntType` / `IntType`. A depth format (three
21 // checks `isDepthTexture` first) samples as depth, i.e. `float`.
22 let integer = match format.sample_type(None, None) {
23 Some(wgpu::TextureSampleType::Uint) => Some(false),
24 Some(wgpu::TextureSampleType::Sint) => Some(true),
25 _ => None,
26 };
27 match (format.components(), integer) {
28 (1, None) => Type::F32,
29 (1, Some(false)) => Type::U32,
30 (1, Some(true)) => Type::I32,
31 (2, None) => Type::Vec2,
32 (2, Some(false)) => Type::UVec2,
33 (2, Some(true)) => Type::IVec2,
34 (_, None) => Type::Vec4,
35 (_, Some(false)) => Type::UVec4,
36 (_, Some(true)) => Type::IVec4,
37 }
38}
39
40/// `renderTarget.texture` and each `getTexture( name )` clone of it: a colour
41/// attachment carrying the target's filter pair, which is what
42/// `pass( scene, camera, { minFilter, magFilter } )` sets and what decides
43/// whether the shader that samples it gets a sampler at all
44/// ([`Texture::is_unfilterable`]).
45fn color_attachment(
46 width: u32,
47 height: u32,
48 format: wgpu::TextureFormat,
49 min_filter: TextureFilter,
50 mag_filter: TextureFilter,
51) -> Texture {
52 let texture = Texture::render_target(width, height, format);
53 texture.set_min_filter(match min_filter {
54 TextureFilter::Nearest => MinFilter::Nearest,
55 TextureFilter::Linear => MinFilter::Linear,
56 });
57 texture.set_mag_filter(mag_filter);
58 texture
59}
60
61/// The name three.js gives `renderTarget.textures[ 0 ]` through
62/// `PassNode`: `getTextureNode()`'s default argument, and the key the scene
63/// pass's own colour lands on in `mrt( { output, … } )`.
64pub const OUTPUT_ATTACHMENT: &str = "output";
65
66/// `new RenderTarget( width, height, options )` — the options the port reads.
67#[derive(Clone, Copy, Debug)]
68#[non_exhaustive]
69pub struct RenderTargetOptions {
70 /// `options.type` — the colour attachment's pixel format.
71 pub texture_type: TextureType,
72 /// `RenderTarget`'s default `samples` is 0; the renderer's `antialias`
73 /// option does **not** propagate to user render targets, only to the
74 /// internal framebuffer target.
75 pub samples: u32,
76 /// `options.depthBuffer` — whether the target gets a depth attachment.
77 pub depth_buffer: bool,
78 /// `options.minFilter` — the colour attachment's minification filter.
79 pub min_filter: TextureFilter,
80 /// `options.magFilter` — the colour attachment's magnification filter.
81 pub mag_filter: TextureFilter,
82}
83
84impl Default for RenderTargetOptions {
85 fn default() -> Self {
86 Self {
87 texture_type: TextureType::UnsignedByte,
88 samples: 0,
89 depth_buffer: true,
90 min_filter: TextureFilter::Linear,
91 mag_filter: TextureFilter::Linear,
92 }
93 }
94}
95
96#[derive(Debug)]
97pub(crate) struct RenderTargetInner {
98 pub width: u32,
99 pub height: u32,
100 pub samples: u32,
101 pub texture_type: TextureType,
102 pub depth_buffer: bool,
103 /// `renderTarget.stencilBuffer` — set only on the renderer's own
104 /// framebuffer target, from `renderer.stencil`; the auto-allocated depth
105 /// buffer then has a stencil aspect.
106 pub stencil_buffer: bool,
107 pub min_filter: TextureFilter,
108 pub mag_filter: TextureFilter,
109 /// A `DepthTexture` the application attached, which it can then sample.
110 pub depth_texture: Option<DepthTexture>,
111 /// `renderTarget.texture` — a real `Texture` so `texture( rt.texture )`
112 /// works; the renderer owns its GPU object (`own_gpu` is false). This is
113 /// `renderTarget.textures[ 0 ]`, whose `name` three.js leaves empty and
114 /// `PassNode` treats as [`OUTPUT_ATTACHMENT`].
115 pub texture: Texture,
116 /// `renderTarget.textures[ 0 ].name` when something other than
117 /// [`OUTPUT_ATTACHMENT`] — `OITPassNode` names its accumulation target's
118 /// first attachment `accum`. `None` everywhere else. It is what
119 /// [`RenderTarget::attachment_names`] reports and so what an MRT output
120 /// resolves against; [`RenderTarget::add_texture`] and the previous-texture
121 /// toggle still answer to `output`, which is the only name a `PassNode`'s
122 /// own target ever gives attachment 0.
123 pub texture_name: Option<String>,
124 /// `renderTarget.textures` past the first: the extra MRT colour
125 /// attachments, in the order `PassNode.getTexture( name )` pushed them,
126 /// which is the order their `@location`s are assigned in.
127 ///
128 /// Three clones `renderTarget.texture` for each, so every attachment shares
129 /// the target's size, type and filters; only the name differs.
130 pub extra_textures: Vec<(String, Texture)>,
131 /// `PassNode._previousTextures` — a second texture per output name, sized
132 /// and allocated with the target but **never** a colour attachment. See
133 /// [`RenderTarget::add_previous_texture`].
134 pub previous_textures: Vec<(String, Texture)>,
135 /// The MSAA colour texture `samples > 1` asks for; the single-sample
136 /// `color` texture is then its resolve target.
137 pub msaa: Option<wgpu::Texture>,
138 /// The same, one per entry of `extra_textures`: a multisampled target
139 /// whose resolve is that attachment. `webgpu_mrt` is `antialias: true`
140 /// with four attachments, and WebGPU requires every colour attachment of a
141 /// pass to have the same sample count.
142 pub msaa_extra: Vec<wgpu::Texture>,
143 /// The depth buffer auto-allocated when `depth_buffer` is set and no
144 /// `DepthTexture` was attached.
145 pub depth: Option<wgpu::Texture>,
146 /// `renderTarget.viewport` — `new Vector4( 0, 0, width, height )`, in the
147 /// target's own pixels (a render target has no pixel ratio). A pass into
148 /// this target restricts itself to this rectangle; see
149 /// [`Renderer::set_viewport`](super::Renderer::set_viewport) for the origin
150 /// convention, which is the same one.
151 pub viewport: Vector4,
152 /// `renderTarget.scissor`, applied only when `scissor_test` is set.
153 pub scissor: Vector4,
154 /// `renderTarget.scissorTest`.
155 pub scissor_test: bool,
156 /// `_textures.get( renderTarget ).depthInitialized` — whether anything has
157 /// yet rendered into this target's depth attachment. See
158 /// `Renderer::render`'s manual first clear.
159 pub depth_initialized: bool,
160 /// Whether the colour texture is also a copy destination
161 /// (`COPY_DST`) — see [`RenderTarget::set_copy_destination`].
162 pub copy_destination: bool,
163 /// The colour texture's mip level count — see
164 /// [`RenderTarget::set_mip_level_count`].
165 pub mip_level_count: u32,
166}
167
168/// Cloning is a handle copy, matching JS object identity.
169#[derive(Clone, Debug)]
170pub struct RenderTarget(Rc<RefCell<RenderTargetInner>>);
171
172impl RenderTarget {
173 /// `renderTarget.dispose()` — drops this handle, and nothing more: the
174 /// attachments live on the target, so they go with its last handle, and
175 /// the renderer lets go of the views it cached for them at the top of the
176 /// next render (`docs/scene-graph.md`, "Identity and eviction"). Dropping
177 /// the handle does the same; this exists so three.js code ports line for
178 /// line.
179 pub fn dispose(self) {}
180
181 /// `new RenderTarget( width, height )` — the default options' texture type
182 /// is `UnsignedByteType`, so this one cannot fail.
183 pub fn new(width: u32, height: u32) -> Self {
184 Self::new_with_options(width, height, RenderTargetOptions::default())
185 .expect("three-rs: the default render target options are a colour type")
186 }
187
188 /// Errors when `options.texture_type` has no colour format — three.js
189 /// would have produced a target that fails at the first pass instead.
190 pub fn new_with_options(
191 width: u32,
192 height: u32,
193 options: RenderTargetOptions,
194 ) -> Result<Self, Error> {
195 if !options.texture_type.is_color() {
196 return Err(Error::UnsupportedTextureType {
197 what: "colour",
198 texture_type: options.texture_type,
199 });
200 }
201
202 Ok(Self(Rc::new(RefCell::new(RenderTargetInner {
203 width,
204 height,
205 samples: options.samples,
206 texture_type: options.texture_type,
207 depth_buffer: options.depth_buffer,
208 stencil_buffer: false,
209 min_filter: options.min_filter,
210 mag_filter: options.mag_filter,
211 depth_texture: None,
212 texture: color_attachment(
213 width,
214 height,
215 options.texture_type.color_gpu_format(),
216 options.min_filter,
217 options.mag_filter,
218 ),
219 texture_name: None,
220 extra_textures: Vec::new(),
221 previous_textures: Vec::new(),
222 msaa: None,
223 msaa_extra: Vec::new(),
224 depth: None,
225 viewport: Vector4::new(0.0, 0.0, width as f64, height as f64),
226 scissor: Vector4::new(0.0, 0.0, width as f64, height as f64),
227 scissor_test: false,
228 depth_initialized: false,
229 copy_destination: false,
230 mip_level_count: 1,
231 }))))
232 }
233
234 /// `renderTarget.clone()` — a second target with the same descriptor and
235 /// its **own** textures, which is what `SSAAPassNode.setup()` builds its
236 /// `_sampleRenderTarget` from.
237 ///
238 /// Not `Clone::clone`: that is the handle copy, and it has to stay one,
239 /// because a `RenderTarget` is a JS object identity everywhere else in the
240 /// port. `RenderTarget.copy()` copies the depth texture *reference*; this
241 /// gives the copy a fresh `DepthTexture` instead, because `RenderTarget`'s
242 /// constructor is what attached the original's and three.js' own
243 /// `_sampleRenderTarget` ends up with a depth texture of its own (the
244 /// dump's textures 5 and 28, one per target).
245 pub fn clone_target(&self) -> Self {
246 let inner = self.0.borrow();
247 let clone = Self::new_with_options(
248 inner.width,
249 inner.height,
250 RenderTargetOptions {
251 texture_type: inner.texture_type,
252 samples: inner.samples,
253 depth_buffer: inner.depth_buffer,
254 min_filter: inner.min_filter,
255 mag_filter: inner.mag_filter,
256 },
257 )
258 .expect("three-rs: the source target's texture type is already a colour type");
259 clone.0.borrow().texture.set_format(inner.texture.format());
260 clone.0.borrow_mut().texture_name = inner.texture_name.clone();
261 if inner.depth_texture.is_some() {
262 clone.set_depth_texture(DepthTexture::new());
263 }
264 for (name, _) in &inner.extra_textures {
265 clone.add_texture(name);
266 }
267 clone
268 }
269
270 /// `PassNode.getTexture( name )`'s second half: `renderTarget.texture`
271 /// cloned, named, and pushed onto `renderTarget.textures`. Idempotent, as
272 /// three.js's own `_textures[ name ]` memo makes it.
273 ///
274 /// The clone is a *fresh* texture, not a handle copy: each attachment needs
275 /// its own GPU object, and its own identity so that `texture( … )` on it
276 /// binds the right one.
277 #[doc(hidden)]
278 pub fn add_texture(&self, name: &str) -> Texture {
279 if name == OUTPUT_ATTACHMENT {
280 return self.texture();
281 }
282 let mut inner = self.0.borrow_mut();
283 if let Some((_, texture)) = inner.extra_textures.iter().find(|(n, _)| n == name) {
284 return texture.clone();
285 }
286 let texture = color_attachment(
287 inner.width,
288 inner.height,
289 inner.texture.format(),
290 inner.min_filter,
291 inner.mag_filter,
292 );
293 inner
294 .extra_textures
295 .push((name.to_string(), texture.clone()));
296 texture
297 }
298
299 /// `PassNode.getPreviousTexture( name )`: a second texture behind one
300 /// output name, holding the frame before this one. It shares the target's
301 /// descriptor and is allocated and resized with it, but it is never a
302 /// colour attachment — nothing is ever rendered into it directly.
303 ///
304 /// **How the toggle is modelled.** `PassNode.toggleTexture()` swaps the
305 /// two `Texture` objects — the one in `renderTarget.textures` and the one
306 /// held aside — and then calls `updateTexture()` on the two `TextureNode`s
307 /// so that "current" and "previous" follow them. A `NodeRef` in this port
308 /// is immutable, so the port alternates the other end:
309 /// `getTextureNode()`'s node always samples the attachment's texture,
310 /// `getPreviousTextureNode()`'s always samples this one, and
311 /// [`Self::toggle_texture`] exchanges the **GPU textures** behind the two
312 /// handles. The GPU sees the same two allocations alternating in the same
313 /// order; what differs is that the port's bind groups keep their texture
314 /// ids across the swap, where three.js' change every frame.
315 ///
316 /// Idempotent, as `_previousTextures[ name ]` makes it.
317 pub(crate) fn add_previous_texture(&self, name: &str) -> Texture {
318 let mut inner = self.0.borrow_mut();
319 if let Some((_, texture)) = inner.previous_textures.iter().find(|(n, _)| n == name) {
320 return texture.clone();
321 }
322 let texture = color_attachment(
323 inner.width,
324 inner.height,
325 inner.texture.format(),
326 inner.min_filter,
327 inner.mag_filter,
328 );
329 inner
330 .previous_textures
331 .push((name.to_string(), texture.clone()));
332 texture
333 }
334
335 /// `PassNode.toggleTexture( name )` — see [`Self::add_previous_texture`].
336 /// A no-op for a name that has no previous texture, exactly as three's is.
337 pub(crate) fn toggle_texture(&self, name: &str) {
338 let inner = self.0.borrow();
339 let Some((_, previous)) = inner.previous_textures.iter().find(|(n, _)| n == name) else {
340 return;
341 };
342 let current = if name == OUTPUT_ATTACHMENT {
343 inner.texture.clone()
344 } else {
345 match inner.extra_textures.iter().find(|(n, _)| n == name) {
346 Some((_, texture)) => texture.clone(),
347 None => return,
348 }
349 };
350 current.swap_gpu(previous);
351 }
352
353 /// `renderTarget.textures.map( texture => texture.name )` — what
354 /// `MRTNode.setup()` resolves its output names against, so the position of
355 /// a name here is the `@location` its value is written to.
356 #[doc(hidden)]
357 pub fn attachment_names(&self) -> Vec<String> {
358 let inner = self.0.borrow();
359 let mut names = vec![inner
360 .texture_name
361 .clone()
362 .unwrap_or_else(|| OUTPUT_ATTACHMENT.to_string())];
363 names.extend(inner.extra_textures.iter().map(|(n, _)| n.clone()));
364 names
365 }
366
367 /// `renderTarget.textures.map( ( t, i ) => builder.getOutputType( i ) )`
368 /// — the type `MRTNode.setup()` converts each member to, by
369 /// [`output_type`].
370 #[doc(hidden)]
371 pub fn output_types(&self) -> Vec<crate::nodes::Type> {
372 self.textures()
373 .iter()
374 .map(|texture| output_type(texture.format()))
375 .collect()
376 }
377
378 /// `new RenderTarget( width, height, { count } )`: `count - 1` clones of
379 /// `renderTarget.texture` pushed onto `renderTarget.textures`, each with
380 /// the target's size, type and filters and an empty `name` — the page
381 /// names them afterwards ([`Self::set_texture_name`]), and `MRTNode`
382 /// writes only the ones whose name its outputs carry.
383 ///
384 /// A setter rather than a [`RenderTargetOptions`] field, for the same
385 /// reason as [`Self::set_rg_format`]. It only ever grows the list, and it
386 /// has to run before the target is first drawn into, as three's
387 /// constructor option does by construction.
388 pub fn set_count(&self, count: usize) {
389 let mut inner = self.0.borrow_mut();
390 while inner.extra_textures.len() + 1 < count {
391 let texture = color_attachment(
392 inner.width,
393 inner.height,
394 inner.texture.format(),
395 inner.min_filter,
396 inner.mag_filter,
397 );
398 inner.extra_textures.push((String::new(), texture));
399 }
400 }
401
402 /// `renderTarget.textures[ index ].name = name` — what the attachment
403 /// answers to in `mrt( { name: … } )` and in [`Self::add_texture`].
404 ///
405 /// Attachment 0 answers to [`OUTPUT_ATTACHMENT`] until it is named
406 /// otherwise — three leaves `textures[ 0 ].name` empty and `PassNode`
407 /// treats it as `output`, while `OITPassNode` names its accumulation
408 /// target's first attachment `accum`. The name lives on the target, not
409 /// the texture.
410 pub fn set_texture_name(&self, index: usize, name: &str) {
411 let mut inner = self.0.borrow_mut();
412 if index == 0 {
413 inner.texture_name = (name != OUTPUT_ATTACHMENT).then(|| name.to_string());
414 return;
415 }
416 let entry = inner
417 .extra_textures
418 .get_mut(index - 1)
419 .expect("three-rs: set_texture_name past renderTarget.textures' count");
420 entry.0 = name.to_string();
421 }
422
423 /// `renderTarget.textures` — attachment 0 first.
424 pub fn textures(&self) -> Vec<Texture> {
425 let inner = self.0.borrow();
426 let mut textures = vec![inner.texture.clone()];
427 textures.extend(inner.extra_textures.iter().map(|(_, t)| t.clone()));
428 textures
429 }
430
431 /// `renderTarget.depthTexture = texture`.
432 pub fn set_depth_texture(&self, depth_texture: DepthTexture) {
433 let mut inner = self.0.borrow_mut();
434 depth_texture.set_multisample(inner.samples > 1);
435 inner.depth_texture = Some(depth_texture);
436 }
437
438 /// Let the colour texture be the destination of a texture copy —
439 /// `renderer.copyTextureToTexture( …, renderTarget.texture )`, which
440 /// `TRAANode` updates its history with. WebGPU fixes a texture's usage at
441 /// creation, and three's backend gives every render target `COPY_DST`;
442 /// the port asks only where a copy lands, so no other target's texture
443 /// changes. Drops the GPU texture if it was created without the flag.
444 pub(crate) fn set_copy_destination(&self) {
445 let mut inner = self.0.borrow_mut();
446 if !inner.copy_destination {
447 inner.copy_destination = true;
448 inner.texture.clear_gpu();
449 }
450 }
451
452 /// `renderTarget.depthTexture`.
453 pub fn depth_texture(&self) -> Option<DepthTexture> {
454 self.0.borrow().depth_texture.clone()
455 }
456
457 /// `options.format = RGFormat` — a two-channel colour attachment, which
458 /// is what `ShadowNode` asks for its VSM blur targets
459 /// (`{ format: RGFormat, type: HalfFloatType }`). The fragment programs
460 /// drawn into it then write a `vec2` (`NodeBuilder.getOutputType()`).
461 ///
462 /// A setter rather than a [`RenderTargetOptions`] field, so that adding
463 /// the one format the ladder needs does not break every literal
464 /// construction of the options.
465 pub fn set_rg_format(&self) {
466 let inner = self.0.borrow();
467 let format = match inner.texture_type {
468 TextureType::HalfFloat => wgpu::TextureFormat::Rg16Float,
469 _ => wgpu::TextureFormat::Rg8Unorm,
470 };
471 inner.texture.set_format(format);
472 inner.texture.clear_gpu();
473 }
474
475 /// `renderTarget.texture.mipmaps.push( {}, … )` — `count` levels in the
476 /// colour texture instead of one, each to be drawn into on its own with
477 /// [`Renderer::set_render_target_level`](super::Renderer::set_render_target_level).
478 ///
479 /// `Textures.getMipLevels()` takes `texture.mipmaps.length` as the level
480 /// count whenever it is non-zero, which is how `SSRNode` gives its blur
481 /// target five levels without generating any: nothing fills them but the
482 /// node's own passes. Drops the GPU texture so it is recreated.
483 pub fn set_mip_level_count(&self, count: u32) {
484 let mut inner = self.0.borrow_mut();
485 let count = count.max(1);
486 if inner.mip_level_count != count {
487 inner.mip_level_count = count;
488 inner.texture.clear_gpu();
489 }
490 }
491
492 /// The colour texture's mip level count, 1 unless
493 /// [`set_mip_level_count`](Self::set_mip_level_count) said otherwise.
494 pub fn mip_level_count(&self) -> u32 {
495 self.0.borrow().mip_level_count
496 }
497
498 /// `options.format = RedFormat` — a one-channel colour attachment:
499 /// `DepthOfFieldNode`'s CoC targets (`{ format: RedFormat, type:
500 /// HalfFloatType }`). The fragment programs drawn into it write an `f32`
501 /// (`NodeBuilder.getOutputType()`), and a texture node sampling it is a
502 /// `float` node, so every tap reads `.x`.
503 ///
504 /// Call it before [`set_count`](Self::set_count): the extra attachments
505 /// take the first one's format when they are made.
506 ///
507 /// The match is spelled out rather than defaulting to `R8Unorm`, so a
508 /// type with no red format here can never be quantised to eight bits:
509 /// `FloatType` / `UnsignedIntType` colour targets are refused by
510 /// [`RenderTarget::new_with_options`], as they are for `RGBAFormat`, so
511 /// they cannot reach this setter.
512 pub fn set_red_format(&self) {
513 let inner = self.0.borrow();
514 let format = match inner.texture_type {
515 TextureType::UnsignedByte => wgpu::TextureFormat::R8Unorm,
516 TextureType::HalfFloat => wgpu::TextureFormat::R16Float,
517 other => panic!(
518 "three-rs: a RedFormat render target needs an UnsignedByteType \
519 or HalfFloatType colour attachment, got {other:?}"
520 ),
521 };
522 inner.texture.set_format(format);
523 inner.texture.clear_gpu();
524 }
525
526 /// `(renderTarget.width, renderTarget.height)`.
527 pub fn size(&self) -> (u32, u32) {
528 let inner = self.0.borrow();
529 (inner.width, inner.height)
530 }
531
532 /// `RenderTarget.setSize()` — drops the GPU textures so they are recreated.
533 pub fn set_size(&self, width: u32, height: u32) {
534 self.set_size_keeping_depth(width, height, false)
535 }
536
537 /// `setSize()` for a target whose `depthTexture` belongs to *another*
538 /// target — `pass( scene, camera, { depthTexture } )`. Dropping the shared
539 /// texture's GPU handle here would throw away the depth the owning pass
540 /// has already rendered, which is the whole point of sharing it.
541 pub(crate) fn set_size_keeping_depth(&self, width: u32, height: u32, shared_depth: bool) {
542 let mut inner = self.0.borrow_mut();
543 if inner.width != width || inner.height != height {
544 inner.width = width;
545 inner.height = height;
546 inner.texture.set_size(width, height);
547 inner.texture.clear_gpu();
548 // `RenderTarget.setSize()`: the viewport and the scissor go back to
549 // the whole target.
550 inner.viewport = Vector4::new(0.0, 0.0, width as f64, height as f64);
551 inner.scissor = Vector4::new(0.0, 0.0, width as f64, height as f64);
552 inner.msaa = None;
553 inner.msaa_extra.clear();
554 inner.depth = None;
555 if !shared_depth {
556 if let Some(depth_texture) = &inner.depth_texture {
557 depth_texture.inner().borrow_mut().gpu = None;
558 }
559 }
560 for (_, texture) in inner.extra_textures.iter().chain(&inner.previous_textures) {
561 texture.set_size(width, height);
562 texture.clear_gpu();
563 }
564 }
565 }
566
567 /// `_textures.get( renderTarget ).depthInitialized`.
568 pub(crate) fn depth_initialized(&self) -> bool {
569 self.0.borrow().depth_initialized
570 }
571
572 pub(crate) fn set_depth_initialized(&self, initialized: bool) {
573 self.0.borrow_mut().depth_initialized = initialized;
574 }
575
576 /// `renderTarget.depthBuffer`.
577 pub fn depth_buffer(&self) -> bool {
578 self.0.borrow().depth_buffer
579 }
580
581 /// `renderTarget.texture`.
582 pub fn texture(&self) -> Texture {
583 self.0.borrow().texture.clone()
584 }
585
586 /// `renderTarget.samples`.
587 pub fn samples(&self) -> u32 {
588 self.0.borrow().samples
589 }
590
591 /// `renderTarget.samples = renderer.samples`, which is what
592 /// `PassNode.setup()` does before the first nested render.
593 pub fn set_samples(&self, samples: u32) {
594 let mut inner = self.0.borrow_mut();
595 if inner.samples == samples {
596 return;
597 }
598 inner.samples = samples;
599 inner.msaa = None;
600 inner.msaa_extra.clear();
601 inner.depth = None;
602 // An attached `DepthTexture` is allocated with the target's sample
603 // count, so the flag the node builder reads has to move with it —
604 // `pass( scene, camera )` under `antialias: true` binds
605 // `texture_depth_multisampled_2d`.
606 if let Some(depth_texture) = &inner.depth_texture {
607 depth_texture.set_multisample(samples > 1);
608 }
609 }
610
611 /// `renderTarget.viewport`.
612 pub fn viewport(&self) -> Vector4 {
613 self.0.borrow().viewport
614 }
615
616 /// `renderTarget.viewport.set( x, y, width, height )` — the rectangle of
617 /// *this* target a render into it is confined to, and what
618 /// `PMREMGenerator._setViewport()` sets before each tile of the cubeUV
619 /// atlas is rendered, so that 21 passes share two textures. Origin
620 /// top-left, in the target's own pixels; see
621 /// [`Renderer::set_viewport`](super::Renderer::set_viewport).
622 ///
623 /// `( 0, 0, width, height )` — the default, and what [`Self::set_size`]
624 /// restores — is the whole target, which is the rectangle wgpu would use
625 /// anyway.
626 pub fn set_viewport(&self, x: f64, y: f64, width: f64, height: f64) {
627 self.0.borrow_mut().viewport = Vector4::new(x, y, width, height);
628 }
629
630 /// `renderTarget.scissor`.
631 pub fn scissor(&self) -> Vector4 {
632 self.0.borrow().scissor
633 }
634
635 /// `renderTarget.scissor.set( x, y, width, height )`.
636 pub fn set_scissor(&self, x: f64, y: f64, width: f64, height: f64) {
637 self.0.borrow_mut().scissor = Vector4::new(x, y, width, height);
638 }
639
640 /// `renderTarget.scissorTest`.
641 pub fn scissor_test(&self) -> bool {
642 self.0.borrow().scissor_test
643 }
644
645 /// `renderTarget.scissorTest = value`.
646 pub fn set_scissor_test(&self, scissor_test: bool) {
647 self.0.borrow_mut().scissor_test = scissor_test;
648 }
649
650 pub(crate) fn inner(&self) -> &RefCell<RenderTargetInner> {
651 &self.0
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::output_type;
658 use crate::nodes::Type;
659 use wgpu::TextureFormat as F;
660
661 /// `getTextureType()`: the channel count picks the length, an integer
662 /// format the `u` / `i` component — `OITPassNode`'s `r8unorm`
663 /// `revealage` is an `f32`, its `rgba16float` `accum` a `vec4`.
664 #[test]
665 fn output_type_follows_channels_and_component_type() {
666 for (format, ty) in [
667 (F::R8Unorm, Type::F32),
668 (F::R16Float, Type::F32),
669 (F::Rg8Unorm, Type::Vec2),
670 (F::Rg16Float, Type::Vec2),
671 (F::Rgba8Unorm, Type::Vec4),
672 (F::Rgba16Float, Type::Vec4),
673 (F::Bgra8UnormSrgb, Type::Vec4),
674 (F::R32Uint, Type::U32),
675 (F::R32Sint, Type::I32),
676 (F::Rg32Uint, Type::UVec2),
677 (F::Rg16Sint, Type::IVec2),
678 (F::Rgba8Uint, Type::UVec4),
679 (F::Rgba32Sint, Type::IVec4),
680 (F::Depth32Float, Type::F32),
681 ] {
682 assert_eq!(output_type(format), ty, "{format:?}");
683 }
684 }
685}