1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Batteries-included offscreen rendering with Metal.
//!
//! The Metal counterpart of [`crate::renderer::HeadlessRenderer`]: owns the
//! device, the renderer and an offscreen target, and hands back RGBA bytes.
use super::device::{MetalDevice, MetalError};
use super::enums::*;
use super::objc::{msg0, sel, AutoreleasePool, Owned};
use super::postfx::{PostFxChain, SsaoSettings};
use super::renderer::{MetalRenderStats, MetalRenderer, RenderView};
use super::target::MetalRenderTarget;
use crate::cameras::Camera;
use crate::scene::Scene;
/// A GPU readback in flight (Metal blit committed, not yet waited on).
struct PendingMetalReadback {
/// Retained so it outlives the enqueue autorelease pool.
cmd: Owned,
staging: Owned,
width: u32,
height: u32,
/// When true, unpack via the render target colour attachment layout.
from_target: bool,
}
/// Configuration for a [`MetalHeadlessRenderer`].
#[derive(Clone, Copy, Debug)]
pub struct MetalHeadlessConfig {
/// Output width in pixels.
pub width: u32,
/// Output height in pixels.
pub height: u32,
/// MSAA sample count; 1 disables it.
pub sample_count: u32,
/// Colour attachment format. `RGBA8_UNORM_SRGB` by default, matching the
/// wgpu headless renderer.
pub color_format: NSUInteger,
/// Render at `width × height × supersample / render_scale` and resolve on
/// the GPU before readback (defaults: 1, 1 = native).
pub supersample: u32,
pub render_scale: u32,
}
impl Default for MetalHeadlessConfig {
fn default() -> Self {
Self {
width: 1024,
height: 1024,
sample_count: 1,
color_format: pixel_format::RGBA8_UNORM_SRGB,
supersample: 1,
render_scale: 1,
}
}
}
/// Fluent builder for [`MetalHeadlessRenderer`].
#[derive(Clone, Copy, Debug, Default)]
pub struct MetalHeadlessBuilder {
config: MetalHeadlessConfig,
}
impl MetalHeadlessBuilder {
/// Output size in pixels.
pub fn size(mut self, width: u32, height: u32) -> Self {
self.config.width = width;
self.config.height = height;
self
}
/// MSAA sample count (1, 2, 4 or 8; 1 disables).
pub fn msaa(mut self, sample_count: u32) -> Self {
self.config.sample_count = sample_count.max(1);
self
}
/// Colour attachment format.
pub fn color_format(mut self, format: NSUInteger) -> Self {
self.config.color_format = format;
self
}
/// Supersample factor (render larger, GPU-downsample on readback).
pub fn supersample(mut self, factor: u32) -> Self {
self.config.supersample = factor.max(1);
self
}
/// Render at `1/N` resolution and GPU-upscale on readback.
pub fn render_scale(mut self, scale: u32) -> Self {
self.config.render_scale = scale.max(1);
self
}
/// Acquire the GPU, compile the shaders and allocate the target.
pub fn build(self) -> Result<MetalHeadlessRenderer, MetalError> {
MetalHeadlessRenderer::new(self.config)
}
/// As [`build`](Self::build), on `device` (a clone: the same GPU and
/// command queue), so what it draws can be sampled by another renderer
/// on that device and is drawn before that renderer's later work — a
/// window drawing this renderer's post-processed frame
/// ([`MetalRenderer::draw_texture`](super::MetalRenderer::draw_texture)).
pub fn build_on(self, device: &MetalDevice) -> Result<MetalHeadlessRenderer, MetalError> {
MetalHeadlessRenderer::new_on(device.clone(), self.config)
}
}
/// Renders a [`Scene`] to a pixel buffer with Metal, no window involved.
///
/// ```no_run
/// # #[cfg(all(feature = "metal", target_os = "macos"))] {
/// use threers::metal::MetalHeadlessRenderer;
/// use threers::{PerspectiveCamera, Scene};
///
/// let mut hr = MetalHeadlessRenderer::builder().size(512, 512).msaa(4).build().unwrap();
/// let mut scene = Scene::new();
/// let camera = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
/// let rgba = hr.render_to_rgba(&mut scene, &camera).unwrap();
/// # }
/// ```
pub struct MetalHeadlessRenderer {
device: MetalDevice,
renderer: MetalRenderer,
target: MetalRenderTarget,
config: MetalHeadlessConfig,
export_w: u32,
export_h: u32,
postfx: Option<PostFxChain>,
ssao_cfg: Option<SsaoSettings>,
bloom_cfg: Option<(f32, f32, f32)>,
last_stats: MetalRenderStats,
/// Staging buffers recycled across frames.
staging_pool: Vec<Owned>,
/// Previous frame's readback, returned on the next call.
pending: Option<PendingMetalReadback>,
staging_bytes: usize,
/// [`copy_into`](Self::copy_into)'s event, made on first use, and the
/// frames it has signalled.
copy_event: Option<Owned>,
copy_count: u64,
}
impl MetalHeadlessRenderer {
/// Start a fluent builder.
pub fn builder() -> MetalHeadlessBuilder {
MetalHeadlessBuilder::default()
}
/// Construct from a config, acquiring the GPU.
pub fn new(config: MetalHeadlessConfig) -> Result<Self, MetalError> {
Self::new_on(MetalDevice::new()?, config)
}
/// Construct from a config, on `device`.
pub fn new_on(device: MetalDevice, config: MetalHeadlessConfig) -> Result<Self, MetalError> {
let postfx = PostFxChain::new(&device).ok();
let mut renderer = MetalRenderer::with_device(device.clone())?;
let (export_w, export_h) = (config.width.max(1), config.height.max(1));
let (render_w, render_h) = render_dimensions(
export_w,
export_h,
config.supersample,
config.render_scale,
);
let target = MetalRenderTarget::new(
&device,
render_w,
render_h,
config.color_format,
config.sample_count,
)?;
// Viewport and scissor rectangles are given in output pixels; the
// target is `supersample / render_scale` attachment pixels to each.
let pixel_ratio = config.supersample.max(1) as f32 / config.render_scale.max(1) as f32;
renderer.set_pixel_ratio(pixel_ratio);
renderer.set_drawing_buffer_size(render_w, render_h);
log::info!(
"metal headless: export {export_w}×{export_h}, render target {render_w}×{render_h} \
(ss {}, scale {}), postfx {}",
config.supersample.max(1),
config.render_scale.max(1),
if postfx.is_some() { "ready" } else { "UNAVAILABLE" }
);
Ok(Self {
device,
renderer,
target,
config,
export_w,
export_h,
postfx,
ssao_cfg: None,
bloom_cfg: None,
last_stats: MetalRenderStats::default(),
staging_pool: Vec::new(),
pending: None,
staging_bytes: 0,
copy_event: None,
copy_count: 0,
})
}
fn needs_postfx(&self) -> bool {
// An HDR target must run the chain to be tone mapped down to the 8-bit
// readback, whatever else is off.
self.config.color_format == pixel_format::RGBA16_FLOAT
|| self.config.supersample > 1
|| self.config.render_scale > 1
|| self.ssao_cfg.is_some_and(|s| s.strength > 0.0)
|| self
.bloom_cfg
.is_some_and(|(s, _, _)| s > 0.0)
}
fn staging_buffer(&mut self) -> Result<Owned, MetalError> {
let (width, height) = if self.needs_postfx() {
(self.export_w, self.export_h)
} else {
self.target.size()
};
let padded = ((width as usize * 4).div_ceil(256)) * 256;
let need = padded * height as usize;
if need != self.staging_bytes {
self.staging_pool.clear();
self.staging_bytes = need;
}
if let Some(buf) = self.staging_pool.pop() {
return Ok(buf);
}
self.device.new_buffer(&vec![0u8; need])
}
fn recycle_staging(&mut self, buf: Owned) {
self.staging_pool.push(buf);
}
/// GPU bloom on readback: `strength` scales the add, `threshold` is linear
/// luminance, `radius` widens the blur (in quarter-res texels).
pub fn set_bloom(&mut self, strength: f32, threshold: f32, radius: f32) {
let rebuild = self
.bloom_cfg
.map(|(_, t, r)| (t, r) != (threshold, radius))
.unwrap_or(true);
self.bloom_cfg = Some((strength, threshold, radius));
if rebuild && let Some(p) = self.postfx.as_mut() {
p.invalidate();
}
}
/// Depth-only ambient occlusion. `None` (or zero strength) disables it.
///
/// `near`/`far`/`tan_half_fov`/`aspect` must describe the camera the frame
/// is drawn with, so a shot that reframes itself should call this each
/// frame; stale values do not fail loudly, they just slide the occlusion
/// off the creases.
pub fn set_ssao(&mut self, settings: Option<SsaoSettings>) {
// The pass samples the depth attachment after the fact, so the renderer
// has to be told to keep it. Without this the texture is discarded and
// reads back as the clear value.
self.renderer.set_store_depth(settings.is_some());
self.ssao_cfg = settings;
}
/// Draw lines as coverage-weighted quads of this pixel width; 0 = hardware
/// lines.
pub fn set_line_width(&mut self, px: f32) {
self.renderer.set_line_width(px);
}
/// Exposure and white point for the HDR tone map. Inert on an LDR target.
pub fn set_tonemap(&mut self, exposure: f32, white: f32) {
if let Some(p) = self.postfx.as_mut() {
p.set_tonemap(exposure, white);
}
}
/// Vignette and grain, the two things that read as *film* rather than as
/// render. Both 0 disables the pass.
///
/// Matches [`HeadlessRenderer::set_film_grade`](crate::HeadlessRenderer::set_film_grade)
/// line for line — a look that differs by backend is a look nobody can
/// rely on.
pub fn set_film_grade(&mut self, vignette: f32, grain: f32) {
if let Some(p) = self.postfx.as_mut() {
p.set_film_grade(vignette, grain);
}
}
/// Advance the grain's seed so it moves between frames. Anything that
/// changes per frame will do.
pub fn set_grain_seed(&mut self, seed: f32) {
if let Some(p) = self.postfx.as_mut() {
p.set_grain_seed(seed);
}
}
/// GPU chroma punch in the bloom composite (replaces CPU full-frame grade).
pub fn set_chroma(&mut self, sat_scale: f32, lift: f32) {
if let Some(p) = self.postfx.as_mut() {
p.set_chroma(sat_scale, lift);
}
}
/// The chain sized for this frame: the supersample resolve, an upscale
/// to the export size, SSAO and bloom as set. Run before encoding it.
fn prepare_postfx(&mut self) -> Result<(), MetalError> {
let (rw, rh) = self.target.size();
let format = self.config.color_format;
let (ew, eh) = (self.export_w, self.export_h);
let Some(postfx) = self.postfx.as_mut() else { return Ok(()) };
// Supersampling already resolves rw×rh down to rw/ss × rh/ss, so the
// upscale must be judged against that, not the raw target size.
// Comparing (rw, rh) meant a supersampled render also queued an upscale
// configured for a source that no longer existed — which both rescaled
// wrongly and flipped the frame, since fs_upscale samples by `uv`
// (origin bottom) while the resolve samples by `position` (origin top).
let (dw, dh) = if self.config.supersample > 1 {
let ss = self.config.supersample.max(1);
postfx.ensure_downsample(&self.device, rw, rh, ss, format)?;
(rw / ss, rh / ss)
} else {
(rw, rh)
};
if (dw, dh) != (ew, eh) {
postfx.ensure_upscale(&self.device, dw, dh, ew, eh, format)?;
}
// MSAA depth is a `texture2d_ms` and will not bind to the pass's
// `depth2d`, so AO is skipped rather than wrong when MSAA is on.
// Supersampling is the sharper choice here anyway (+8.4 dB measured).
// Under MSAA the main pass resolves its depth into the target's
// single-sampled one while depth is stored, which SSAO turns on.
postfx.ensure_ssao(&self.device, rw, rh, format, self.ssao_cfg)?;
if let Some((strength, threshold, radius)) = self.bloom_cfg
&& strength > 0.0
{
let (bw, bh) = if self.config.supersample > 1 {
(
rw / self.config.supersample.max(1),
rh / self.config.supersample.max(1),
)
} else {
(rw, rh)
};
postfx.set_bloom(&self.device, bw, bh, strength, threshold, radius)?;
}
Ok(())
}
fn queue_postfx_readback(&mut self) -> Result<PendingMetalReadback, MetalError> {
let (rw, rh) = self.target.size();
let format = self.config.color_format;
let (ew, eh) = (self.export_w, self.export_h);
let staging = self.staging_buffer()?;
let padded = ((ew as usize * 4).div_ceil(256)) * 256;
if self.postfx.is_none() {
let cmd = self.target.queue_readback(&self.device, &staging)?;
// `queue_readback` hands back an owned reference already.
return Ok(PendingMetalReadback {
cmd,
staging,
width: ew,
height: eh,
from_target: true,
});
}
self.prepare_postfx()?;
let postfx = self.postfx.as_mut().expect("there is a chain");
let src = self.target.color_texture();
// Keep the pool live only while building encoders; retain the CB after.
let cmd = {
let _pool = AutoreleasePool::new();
let cmd = self.device.command_buffer();
if cmd.is_null() {
return Err(MetalError::NoCommandQueue);
}
let depth = self.target.resolved_depth_texture();
match postfx.encode_on(&self.device, cmd, src, depth, rw, rh, format)? {
None => {
let cmd = self.target.queue_readback(&self.device, &staging)?;
return Ok(PendingMetalReadback {
cmd,
staging,
width: ew,
height: eh,
from_target: true,
});
}
Some(tex) => {
crate::metal::target::blit_texture_to_buffer_on_cmd(
cmd, tex, ew, eh, &staging, padded,
)?;
unsafe {
let _: () = msg0(cmd, sel!("commit"));
}
unsafe { Owned::retain(cmd) }.ok_or(MetalError::NoCommandQueue)?
}
}
};
Ok(PendingMetalReadback {
cmd,
staging,
width: ew,
height: eh,
from_target: false,
})
}
fn run_postfx_and_readback(&mut self, out: &mut Vec<u8>) -> Result<(), MetalError> {
let pending = self.queue_postfx_readback()?;
self.finish_pending_into(pending, out)
}
/// Format of the texture that actually reaches the staging buffer.
fn readback_format(&self) -> NSUInteger {
if self.config.color_format == pixel_format::RGBA16_FLOAT {
pixel_format::RGBA8_UNORM_SRGB
} else {
self.config.color_format
}
}
fn finish_pending_into(
&mut self,
pending: PendingMetalReadback,
out: &mut Vec<u8>,
) -> Result<(), MetalError> {
// The chain's OUTPUT format, which is not the target's when the target
// is HDR: the tone map has already converted to 8-bit sRGB by the time
// anything is read back.
let format = self.readback_format();
if pending.from_target {
self.target
.finish_readback_into(pending.cmd.id(), &pending.staging, out)?;
} else {
crate::metal::target::finish_texture_readback_into(
pending.cmd.id(),
&pending.staging,
pending.width,
pending.height,
format,
out,
)?;
}
self.recycle_staging(pending.staging);
Ok(())
}
/// Draw one frame and read it back as tightly-packed RGBA8, top row first.
pub fn render_to_rgba(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
) -> Result<Vec<u8>, MetalError> {
let mut out = Vec::new();
self.render_to_rgba_into(scene, camera, &mut out)?;
Ok(out)
}
/// Render and unpack into `out`, reusing pooled staging and `out`'s capacity.
pub fn render_to_rgba_into(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
out: &mut Vec<u8>,
) -> Result<(), MetalError> {
self.render_into(scene, camera, out)
}
/// Pipelined export: render now, return the *previous* frame's pixels.
///
/// Overlaps GPU draw (+ bloom) with CPU unpack of the last frame. Works
/// with postfx — previously postfx forced a fully synchronous path.
pub fn render_to_rgba_pipelined(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
out: &mut Vec<u8>,
) -> Result<Option<()>, MetalError> {
let prev = self.drain_pending_into(out)?;
self.last_stats = self
.renderer
.render(scene, camera, &self.target.attachments())?;
self.pending = Some(self.queue_postfx_readback()?);
if prev {
Ok(Some(()))
} else {
Ok(None)
}
}
/// Draw one frame and queue its post-processing and readback without
/// waiting for either: [`finish_queued_into`](Self::finish_queued_into)
/// collects the pixels if they are wanted. A frame still queued from an
/// earlier call is dropped unread.
pub fn render_queued(&mut self, scene: &mut Scene, camera: &dyn Camera) -> Result<(), MetalError> {
if let Some(old) = self.pending.take() {
// The queue runs in order: the next frame's copy into this
// staging buffer lands after the one in flight.
self.recycle_staging(old.staging);
}
self.last_stats = self
.renderer
.render(scene, camera, &self.target.attachments())?;
self.pending = Some(self.queue_postfx_readback()?);
Ok(())
}
/// The pixels of the frame [`render_queued`](Self::render_queued) drew,
/// into `out`, waiting for the GPU; `false` when nothing is queued.
pub fn finish_queued_into(&mut self, out: &mut Vec<u8>) -> Result<bool, MetalError> {
self.drain_pending_into(out)
}
/// Wait for the queued frame's GPU work, leaving its pixels to
/// [`finish_queued_into`](Self::finish_queued_into).
pub fn wait_queued(&self) -> Result<(), MetalError> {
match &self.pending {
// SAFETY: a retained, committed command buffer.
Some(p) => unsafe { crate::metal::device::wait_until_completed(p.cmd.id()) },
None => Ok(()),
}
}
/// Copy the frame just drawn into `texture`'s first level (same size
/// and format: a
/// texture someone else shows — RealityKit's `LowLevelTexture`), the
/// copy encoded into `command_buffer`, theirs, on the same device: this
/// renderer's frame is waited for on the GPU (a shared event), as
/// theirs runs on another queue.
///
/// # Safety
/// `texture` must be a live `MTLTexture` and `command_buffer` a live,
/// uncommitted `MTLCommandBuffer`, both on this renderer's device.
pub unsafe fn copy_into(&mut self, texture: super::objc::Id, command_buffer: super::objc::Id) -> Result<(), MetalError> {
let _pool = AutoreleasePool::new();
// the queue runs in order: an event signalled after the frame is
// the frame done; their buffer waits for it on the GPU, so neither
// side's CPU stalls
let event = self.copy_event.get_or_insert_with(|| unsafe { Owned::from_retained(msg0(self.device.device_id(), sel!("newSharedEvent"))) }.expect("MTLSharedEvent")).id();
self.copy_count += 1;
let n = self.copy_count;
let signal = self.device.command_buffer();
// the post-processing (SSAO, bloom, a resolve) on the frame first,
// when any is on: its output is what is copied
let mut source = self.target.color_texture();
if self.needs_postfx() {
self.prepare_postfx()?;
let (rw, rh) = self.target.size();
let format = self.config.color_format;
let depth = self.target.resolved_depth_texture();
if let Some(postfx) = self.postfx.as_mut()
&& let Some(out) = postfx.encode_on(&self.device, signal, source, depth, rw, rh, format)?
{
source = out;
}
}
unsafe {
let _: () = super::objc::msg2(signal, sel!("encodeSignalEvent:value:"), event, n);
let _: () = msg0(signal, sel!("commit"));
let _: () = super::objc::msg2(command_buffer, sel!("encodeWaitForEvent:value:"), event, n);
let blit: super::objc::Id = msg0(command_buffer, sel!("blitCommandEncoder"));
// into its first level: it may carry mips (made from it after)
let (w, h) = (self.export_w as NSUInteger, self.export_h as NSUInteger);
let _: () = super::objc::msg9(
blit,
sel!("copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:"),
source,
0 as NSUInteger,
0 as NSUInteger,
MTLOrigin::default(),
MTLSize { width: w, height: h, depth: 1 },
texture,
0 as NSUInteger,
0 as NSUInteger,
MTLOrigin::default(),
);
let _: () = msg0(blit, sel!("endEncoding"));
}
Ok(())
}
/// Drop a queued frame unread.
pub fn discard_queued(&mut self) {
if let Some(old) = self.pending.take() {
self.recycle_staging(old.staging);
}
}
/// Drain the last queued readback (end of a pipelined sequence).
pub fn finish_readback_into(&mut self, out: &mut Vec<u8>) -> Result<bool, MetalError> {
self.drain_pending_into(out)
}
fn drain_pending_into(&mut self, out: &mut Vec<u8>) -> Result<bool, MetalError> {
let Some(pending) = self.pending.take() else {
return Ok(false);
};
self.finish_pending_into(pending, out)?;
Ok(true)
}
/// Draw one frame for each view and read back as tightly-packed RGBA8.
pub fn render_views_into(
&mut self,
scene: &mut Scene,
views: &[RenderView],
out: &mut Vec<u8>,
) -> Result<(), MetalError> {
self.last_stats = self
.renderer
.render_views(scene, views, &self.target.attachments())?;
self.run_postfx_and_readback(out)
}
/// Pipelined multi-view export: render now, return the *previous* frame.
pub fn render_views_pipelined(
&mut self,
scene: &mut Scene,
views: &[RenderView],
out: &mut Vec<u8>,
) -> Result<Option<()>, MetalError> {
let prev = self.drain_pending_into(out)?;
self.last_stats = self
.renderer
.render_views(scene, views, &self.target.attachments())?;
self.pending = Some(self.queue_postfx_readback()?);
if prev {
Ok(Some(()))
} else {
Ok(None)
}
}
/// Optimized read path: pooled staging buffer, reused output `Vec`.
pub fn render_into(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
out: &mut Vec<u8>,
) -> Result<(), MetalError> {
self.last_stats = self
.renderer
.render(scene, camera, &self.target.attachments())?;
self.run_postfx_and_readback(out)
}
/// Draw one frame and its post-processing (SSAO, bloom, a resolve —
/// whatever is on), leaving the result on the GPU: the texture to
/// sample, this renderer's, good until the next frame. Nothing is read
/// back. Committed on this renderer's queue: a renderer on the same
/// device ([`build_on`](MetalHeadlessBuilder::build_on)) sees it done.
pub fn render_to_texture(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
) -> Result<super::objc::Id, MetalError> {
let _pool = AutoreleasePool::new();
self.last_stats = self
.renderer
.render(scene, camera, &self.target.attachments())?;
let mut source = self.target.color_texture();
if self.needs_postfx() {
self.prepare_postfx()?;
let (rw, rh) = self.target.size();
let format = self.config.color_format;
let depth = self.target.resolved_depth_texture();
let cmd = self.device.command_buffer();
if cmd.is_null() {
return Err(MetalError::NoCommandQueue);
}
if let Some(postfx) = self.postfx.as_mut()
&& let Some(out) = postfx.encode_on(&self.device, cmd, source, depth, rw, rh, format)?
{
source = out;
}
unsafe {
let _: () = msg0(cmd, sel!("commit"));
}
}
Ok(source)
}
/// Draw one frame, leaving the result on the GPU. Pair with
/// [`target`](Self::target) to read it back or sample it.
pub fn render(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
) -> Result<MetalRenderStats, MetalError> {
self.last_stats = self
.renderer
.render(scene, camera, &self.target.attachments())?;
Ok(self.last_stats)
}
/// Reallocate the target at a new size. Caches survive — geometry and
/// textures are not attachment-dependent.
pub fn resize(&mut self, width: u32, height: u32) -> Result<(), MetalError> {
let (export_w, export_h) = (width.max(1), height.max(1));
if (export_w, export_h) == (self.export_w, self.export_h) {
return Ok(());
}
self.export_w = export_w;
self.export_h = export_h;
self.config.width = export_w;
self.config.height = export_h;
let (render_w, render_h) = render_dimensions(
export_w,
export_h,
self.config.supersample,
self.config.render_scale,
);
self.target = MetalRenderTarget::new(
&self.device,
render_w,
render_h,
self.config.color_format,
self.config.sample_count,
)?;
self.renderer.set_drawing_buffer_size(render_w, render_h);
if let Some(p) = self.postfx.as_mut() {
p.invalidate();
}
Ok(())
}
/// Fill the offscreen target with `color` — the scissor rectangle when the
/// renderer's scissor test is on, all of it otherwise. See
/// [`MetalRenderer::clear`]; the counterpart of
/// [`HeadlessRenderer::clear`](crate::HeadlessRenderer::clear).
pub fn clear(&mut self, color: crate::math::Color, alpha: f32) -> Result<(), MetalError> {
self.renderer.clear(&self.target.attachments(), color, alpha)
}
/// Read the target back as it stands — no render, no post-processing —
/// as tightly-packed RGBA8, top row first, sized
/// [`render_size`](Self::render_size). Blocks until the GPU is done.
pub fn read_rgba(&self) -> Result<Vec<u8>, MetalError> {
self.target.read_rgba(&self.device)
}
/// The last frame as [`copy_into`](Self::copy_into) hands it on: through
/// the post-processing (SSAO, bloom, a resolve) when any is on, else as
/// [`read_rgba`](Self::read_rgba) reads it.
pub fn read_rgba_processed(&mut self) -> Result<Vec<u8>, MetalError> {
if !self.needs_postfx() {
return self.read_rgba();
}
let mut out = Vec::new();
self.run_postfx_and_readback(&mut out)?;
Ok(out)
}
/// The underlying renderer — its viewport, scissor and auto-clear state
/// as well as cache control. Same as [`renderer_mut`](Self::renderer_mut).
pub fn renderer(&mut self) -> &mut MetalRenderer {
&mut self.renderer
}
/// Export/readback size in pixels (after GPU upscale/downsample).
pub fn export_size(&self) -> (u32, u32) {
(self.export_w, self.export_h)
}
/// Output size in pixels (export resolution).
pub fn size(&self) -> (u32, u32) {
(self.export_w, self.export_h)
}
/// Internal render target size (before postfx).
pub fn render_size(&self) -> (u32, u32) {
self.target.size()
}
/// Statistics from the most recent frame.
pub fn stats(&self) -> MetalRenderStats {
self.last_stats
}
/// The underlying device.
pub fn device(&self) -> &MetalDevice {
&self.device
}
/// The underlying renderer, for cache control.
pub fn renderer_mut(&mut self) -> &mut MetalRenderer {
&mut self.renderer
}
/// The offscreen target.
pub fn target(&self) -> &MetalRenderTarget {
&self.target
}
}
fn render_dimensions(export_w: u32, export_h: u32, supersample: u32, render_scale: u32) -> (u32, u32) {
let ss = supersample.max(1);
let rs = render_scale.max(1);
(
(export_w * ss).div_ceil(rs).max(1),
(export_h * ss).div_ceil(rs).max(1),
)
}
impl std::fmt::Debug for MetalHeadlessRenderer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MetalHeadlessRenderer")
.field("device", &self.device.name())
.field("size", &self.target.size())
.field("sample_count", &self.target.sample_count())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_carries_its_settings() {
let b = MetalHeadlessBuilder::default()
.size(320, 240)
.msaa(4)
.color_format(pixel_format::BGRA8_UNORM_SRGB);
assert_eq!(b.config.width, 320);
assert_eq!(b.config.height, 240);
assert_eq!(b.config.sample_count, 4);
assert_eq!(b.config.color_format, pixel_format::BGRA8_UNORM_SRGB);
}
#[test]
fn msaa_never_goes_below_one() {
assert_eq!(
MetalHeadlessBuilder::default().msaa(0).config.sample_count,
1
);
}
}
#[cfg(test)]
mod draw_texture_tests {
use super::*;
use crate::cameras::PerspectiveCamera;
use crate::math::Color;
/// A frame drawn and post-processed offscreen on one device
/// ([`MetalHeadlessBuilder::build_on`], `render_to_texture`) and drawn
/// over another renderer's frame on that device (`draw_texture`)
/// replaces it whole: the window's path for a scene with SSAO.
#[test]
fn a_frame_drawn_offscreen_is_shown_by_a_renderer_on_the_same_device() {
let Ok(device) = MetalDevice::new() else { return };
let camera = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
let mut red = Scene::new();
red.background = Color::new(1.0, 0.0, 0.0);
let mut blue = Scene::new();
blue.background = Color::new(0.0, 0.0, 1.0);
let mut offscreen = MetalHeadlessRenderer::builder().size(32, 32).msaa(4).build_on(&device).unwrap();
let mut window = MetalHeadlessRenderer::builder().size(32, 32).msaa(1).build_on(&device).unwrap();
// an SSAO pass on, so the post-processed texture is the one shown
offscreen.set_ssao(Some(SsaoSettings { strength: 1.0, radius: 0.5, near: 0.1, far: 100.0, tan_half_fov: 0.47, aspect: 1.0 }));
let texture = offscreen.render_to_texture(&mut red, &camera).unwrap();
window.render(&mut blue, &camera).unwrap();
let pass = window.target().attachments();
window.renderer_mut().draw_texture(texture, &pass).unwrap();
let px = window.read_rgba().unwrap();
for p in px.chunks_exact(4).step_by(37) {
assert!(p[0] > 200 && p[2] < 40, "red over blue: {p:?}");
}
}
}