concinnity-device 0.19.9

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
Documentation
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
#![deny(unsafe_op_in_unsafe_fn)]

use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{MTLDevice as _, MTLPixelFormat, MTLTexture, MTLTextureType, MTLTextureUsage};

use super::allocator::{DeviceAllocator, PooledTexture};
use super::descriptors::TextureDesc;

// Upload a 2-D RGBA texture from raw pixel bytes with a full mip chain.
// The chain is box-filtered on the CPU (`crate::gfx::mipmap`) and every level
// is written so the texture minifies through hardware trilinear / aniso
// selection instead of aliasing from a single mip-0 sample at a distance.
// The texture is created with ShaderRead usage so it can be sampled in
// fragment shaders. StorageModeShared is used so the CPU-side pixel data
// is accessible without an explicit blit encoder.
pub(super) fn upload_texture(
    alloc: &DeviceAllocator,
    width: u32,
    height: u32,
    pixels: &[u8],
) -> Result<PooledTexture, String> {
    let base = (width as usize) * (height as usize) * 4;
    if pixels.len() < base {
        return Err(format!(
            "pixel data too short for {}x{} RGBA texture ({} bytes, need {})",
            width,
            height,
            pixels.len(),
            base
        ));
    }

    let chain = crate::gfx::mipmap::generate_mip_chain(width, height, pixels);

    let desc = TextureDesc {
        width: width as usize,
        height: height as usize,
        mip_count: chain.len(),
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();

    let texture = alloc.alloc_texture(&desc)?;

    for (mip, level) in chain.iter().enumerate() {
        // SAFETY: `region` covers exactly mip `mip` of `texture`, and `level.pixels` is `width *
        // height * 4` bytes -- the size `generate_mip_chain` produced for that level -- so the copy
        // stays in bounds of both.
        unsafe {
            use objc2_metal::MTLRegion;
            let region = MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: level.width as usize,
                    height: level.height as usize,
                    depth: 1,
                },
            };
            let bytes_per_row = (level.width * 4) as usize;
            texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
                region,
                mip,
                std::ptr::NonNull::new(level.pixels.as_ptr() as *mut _)
                    .ok_or("pixel slice is empty")?,
                bytes_per_row,
            );
        }
    }

    Ok(texture)
}

// Upload a decoded texture into a 2-D MTLTexture. RGBA8 images take the CPU
// mip-generation path above; block-compressed images (BC1/BC3/BC5/BC7) upload
// their container mip chain verbatim, one level per `replaceRegion` with a
// block-row stride. All Apple GPUs sample BC formats natively.
pub(super) fn upload_texture_image(
    alloc: &DeviceAllocator,
    image: &concinnity_core::bake::texture::TextureImage,
) -> Result<PooledTexture, String> {
    use concinnity_core::bake::texture::TextureFormat;
    if image.format == TextureFormat::Rgba8 {
        let mip = image
            .mips
            .first()
            .ok_or("RGBA8 texture image has no mip level")?;
        return upload_texture(alloc, mip.width, mip.height, &mip.data);
    }

    let (pixel_format, block_bytes) = match image.format {
        TextureFormat::Bc1 => (MTLPixelFormat::BC1_RGBA, 8usize),
        TextureFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, 16),
        TextureFormat::Bc5 => (MTLPixelFormat::BC5_RGUnorm, 16),
        TextureFormat::Bc7 => (MTLPixelFormat::BC7_RGBAUnorm, 16),
        TextureFormat::Rgba8 => unreachable!("RGBA8 handled above"),
    };

    let base = image
        .mips
        .first()
        .ok_or("compressed texture image has no mip level")?;

    let desc = TextureDesc {
        format: pixel_format,
        width: base.width as usize,
        height: base.height as usize,
        mip_count: image.mips.len(),
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = alloc.alloc_texture(&desc)?;

    for (mip, level) in image.mips.iter().enumerate() {
        let blocks_x = level.width.div_ceil(4) as usize;
        let blocks_y = level.height.div_ceil(4) as usize;
        let bytes_per_row = blocks_x * block_bytes;
        let needed = bytes_per_row * blocks_y;
        if level.data.len() < needed {
            return Err(format!(
                "compressed mip {} ({}x{}) is {} bytes, need {}",
                mip,
                level.width,
                level.height,
                level.data.len(),
                needed
            ));
        }
        // SAFETY: `region` covers exactly mip `mip` of `texture`, and the length check above proved
        // `level.data` holds at least `bytes_per_row * blocks_y` bytes.
        unsafe {
            use objc2_metal::MTLRegion;
            let region = MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: level.width as usize,
                    height: level.height as usize,
                    depth: 1,
                },
            };
            texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
                region,
                mip,
                std::ptr::NonNull::new(level.data.as_ptr() as *mut _)
                    .ok_or("compressed mip data is empty")?,
                bytes_per_row,
            );
        }
    }
    Ok(texture)
}

// Create a 1x1 opaque white RGBA texture used when no Texture asset is present.
pub(super) fn create_fallback_texture(alloc: &DeviceAllocator) -> Result<PooledTexture, String> {
    upload_texture(alloc, 1, 1, &[255u8, 255, 255, 255])
}

// Create a 1x1 Depth32Float texture-array (one layer) with value 1.0, used
// when no ShadowStage is declared. A depth of 1.0 means "maximum depth" so
// sample_compare with LessEqual always returns 1.0 (fully lit).
//
// The fragment shader binds the shadow map as depth2d_array; using a
// 1-layer 2D-array fallback keeps the binding type identical between the
// disabled and enabled cases.
pub(super) fn create_shadow_map_fallback(
    device: &ProtocolObject<dyn objc2_metal::MTLDevice>,
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, String> {
    let desc = TextureDesc {
        kind: MTLTextureType::Type2DArray,
        format: MTLPixelFormat::Depth32Float,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = device
        .newTextureWithDescriptor(&desc)
        .ok_or("failed to create shadow map fallback texture")?;
    let depth: f32 = 1.0;
    // SAFETY: `region` is the texture's single 1x1 texel and `depth` is one f32, matching the
    // Depth32Float format's 4-byte row stride.
    unsafe {
        use objc2_metal::MTLRegion;
        let region = MTLRegion {
            origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
            size: objc2_metal::MTLSize {
                width: 1,
                height: 1,
                depth: 1,
            },
        };
        texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage(
            region,
            0,
            0,
            std::ptr::NonNull::new(std::ptr::addr_of!(depth) as *mut _)
                .ok_or("depth ptr is null")?,
            4,
            4,
        );
    }
    Ok(texture)
}

// Upload a six-face HDR cubemap from a CubemapTexture payload. `bytes` is the
// raw RGBA32F face-major data emitted by build/cubemap.rs::compile_cubemap_payload,
// i.e. 6 * face_size * face_size * 4 floats with face order +X, -X, +Y, -Y, +Z, -Z.
//
pub(super) fn upload_cubemap(
    alloc: &DeviceAllocator,
    face_size: u32,
    bytes: &[u8],
) -> Result<PooledTexture, String> {
    let face_bytes = (face_size as usize) * (face_size as usize) * 4 * 4;
    let needed = 6 * face_bytes;
    if bytes.len() < needed {
        return Err(format!(
            "cubemap data too short for face_size {}: {} bytes, need {}",
            face_size,
            bytes.len(),
            needed
        ));
    }

    let desc = TextureDesc {
        kind: MTLTextureType::TypeCube,
        format: MTLPixelFormat::RGBA32Float,
        width: face_size as usize,
        height: face_size as usize,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();

    let texture = alloc.alloc_texture(&desc)?;

    let bytes_per_row = (face_size as usize) * 4 * 4;
    let bytes_per_image = bytes_per_row * (face_size as usize);
    // SAFETY: `region` covers one cube face and the caller-side length check proved `data` holds
    // all six faces at `bytes_per_image` each.
    unsafe {
        use objc2_metal::MTLRegion;
        let region = MTLRegion {
            origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
            size: objc2_metal::MTLSize {
                width: face_size as usize,
                height: face_size as usize,
                depth: 1,
            },
        };
        for face in 0..6 {
            let face_start = face * face_bytes;
            let face_ptr = bytes.as_ptr().add(face_start) as *mut std::ffi::c_void;
            texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage(
                region,
                0,
                face,
                std::ptr::NonNull::new(face_ptr).ok_or("cube face pointer is null")?,
                bytes_per_row,
                bytes_per_image,
            );
        }
    }
    Ok(texture)
}

// IBL textures produced by a single `EnvironmentMap` asset. Returned together
// so per-frame binding sets both with one lookup. `prefilter_mip_count == 0`
// is the runtime signal for "IBL disabled": the fragment shader keys off it
// to fall back to the legacy ambient/skybox path.
pub(super) struct EnvironmentMapTextures {
    pub irradiance: PooledTexture,
    pub prefilter: PooledTexture,
    pub prefilter_mip_count: u32,
}

// Create a 1x1 RGBA32Float cube of `value` for every face. Used as the
// IBL fallback when no `EnvironmentMap` is bound: the fragment shader keys
// off `prefilter_mip_count == 0` and skips IBL math, but the cube binding
// must still resolve to a valid texture.
pub(super) fn create_fallback_cubemap(
    alloc: &DeviceAllocator,
    value: [f32; 4],
) -> Result<PooledTexture, String> {
    let desc = TextureDesc {
        kind: MTLTextureType::TypeCube,
        format: MTLPixelFormat::RGBA32Float,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = alloc.alloc_texture(&desc)?;
    let bytes_per_row = 4 * 4;
    let bytes_per_image = bytes_per_row;
    // SAFETY: `region` is one 1x1 face and `value` is four f32s, exactly the RGBA32Float texel
    // size.
    unsafe {
        use objc2_metal::MTLRegion;
        let region = MTLRegion {
            origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
            size: objc2_metal::MTLSize {
                width: 1,
                height: 1,
                depth: 1,
            },
        };
        for face in 0..6 {
            texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage(
                region,
                0,
                face,
                std::ptr::NonNull::new(value.as_ptr() as *mut _)
                    .ok_or("fallback cube value pointer null")?,
                bytes_per_row,
                bytes_per_image,
            );
        }
    }
    Ok(texture)
}

// Upload a 3D colour-grading LUT from a ColorLut payload. `bytes` is the raw
// RGBA8 data emitted by build/color_lut.rs: `size`³ texels ordered with the
// red axis fastest, then green, then blue. The result is sampled in the
// composite pass with the tonemapped sRGB colour as the texture coordinate.
pub(super) fn upload_color_lut(
    alloc: &DeviceAllocator,
    size: u32,
    bytes: &[u8],
) -> Result<PooledTexture, String> {
    let n = size as usize;
    let needed = n * n * n * 4;
    if bytes.len() < needed {
        return Err(format!(
            "color LUT data too short for size {}: {} bytes, need {}",
            size,
            bytes.len(),
            needed
        ));
    }

    let desc = TextureDesc {
        kind: MTLTextureType::Type3D,
        width: n,
        height: n,
        depth: n,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = alloc.alloc_texture(&desc)?;

    // SAFETY: `region` covers the whole n^3 volume and the length check above proved `data` holds
    // `n * n * n * 4` bytes.
    unsafe {
        use objc2_metal::MTLRegion;
        let region = MTLRegion {
            origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
            size: objc2_metal::MTLSize {
                width: n,
                height: n,
                depth: n,
            },
        };
        let bytes_per_row = n * 4;
        let bytes_per_image = bytes_per_row * n;
        texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage(
            region,
            0,
            0,
            std::ptr::NonNull::new(bytes.as_ptr() as *mut _).ok_or("color LUT pointer is null")?,
            bytes_per_row,
            bytes_per_image,
        );
    }
    Ok(texture)
}

// Build a 2x2x2 identity colour LUT: the eight corners of the unit RGB cube.
// Trilinear interpolation across the corners reproduces the input exactly, so
// the composite pass becomes a no-op when no `ColorLut` asset is declared.
// The 3D LUT binding must still resolve to a valid texture regardless.
pub(super) fn create_fallback_color_lut(alloc: &DeviceAllocator) -> Result<PooledTexture, String> {
    let mut data = Vec::with_capacity(2 * 2 * 2 * 4);
    for b in 0..2u8 {
        for g in 0..2u8 {
            for r in 0..2u8 {
                data.extend_from_slice(&[r * 255, g * 255, b * 255, 255]);
            }
        }
    }
    upload_color_lut(alloc, 2, &data)
}

// Upload an EnvironmentMap payload into two cube textures: a single-mip
// irradiance cube and a multi-mip prefiltered radiance cube. Both are
// `MTLTextureType::TypeCube` with `RGBA32Float` storage matching the build
// pipeline's payload format.
//
// `irradiance_face` / `prefilter_face` are the mip-0 face sizes. `mip_bytes`
// is one slice per mip in order 0..mip_count; `mip_count` must equal
// `mip_bytes.len()`.
pub(super) fn upload_environment_map(
    alloc: &DeviceAllocator,
    irradiance_face: u32,
    irradiance_bytes: &[u8],
    prefilter_face: u32,
    mip_bytes: &[&[u8]],
) -> Result<EnvironmentMapTextures, String> {
    if mip_bytes.is_empty() {
        return Err("envmap upload: prefilter mip_bytes must not be empty".into());
    }
    let irradiance = upload_cubemap(alloc, irradiance_face, irradiance_bytes)
        .map_err(|e| format!("envmap irradiance: {}", e))?;
    let prefilter = upload_prefilter_cube(alloc, prefilter_face, mip_bytes)
        .map_err(|e| format!("envmap prefilter: {}", e))?;
    Ok(EnvironmentMapTextures {
        irradiance,
        prefilter,
        prefilter_mip_count: mip_bytes.len() as u32,
    })
}

// Create a multi-mip RGBA32Float `MTLTextureType::Cube` and upload each mip
// from `mip_bytes`. `mip_bytes[m]` is expected to be 6 * (face_size >> m)² * 16 bytes.
fn upload_prefilter_cube(
    alloc: &DeviceAllocator,
    face_size: u32,
    mip_bytes: &[&[u8]],
) -> Result<PooledTexture, String> {
    let mip_count = mip_bytes.len() as u32;
    let desc = TextureDesc {
        kind: MTLTextureType::TypeCube,
        format: MTLPixelFormat::RGBA32Float,
        width: face_size as usize,
        height: face_size as usize,
        mip_count: mip_count as usize,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = alloc.alloc_texture(&desc)?;
    for (mip, bytes) in mip_bytes.iter().enumerate() {
        let mip_face_size = face_size >> mip;
        if mip_face_size == 0 {
            return Err(format!(
                "prefilter mip {} would have zero face size (face_size {} too small)",
                mip, face_size
            ));
        }
        let face_bytes = (mip_face_size as usize) * (mip_face_size as usize) * 4 * 4;
        let needed = 6 * face_bytes;
        if bytes.len() < needed {
            return Err(format!(
                "prefilter mip {} too short: {} bytes, need {}",
                mip,
                bytes.len(),
                needed
            ));
        }
        let bytes_per_row = (mip_face_size as usize) * 4 * 4;
        let bytes_per_image = bytes_per_row * (mip_face_size as usize);
        // SAFETY: `region` covers one face of mip `mip`, and the length check above proved that
        // face's slice holds `bytes_per_image` bytes.
        unsafe {
            use objc2_metal::MTLRegion;
            let region = MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: mip_face_size as usize,
                    height: mip_face_size as usize,
                    depth: 1,
                },
            };
            for face in 0..6 {
                let face_start = face * face_bytes;
                let face_ptr = bytes.as_ptr().add(face_start) as *mut std::ffi::c_void;
                texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage(
                    region,
                    mip,
                    face,
                    std::ptr::NonNull::new(face_ptr).ok_or("prefilter face pointer null")?,
                    bytes_per_row,
                    bytes_per_image,
                );
            }
        }
    }
    Ok(texture)
}

// Create a Depth32Float Texture2DArray shadow map with `layers` cascades, each
// `size`x`size`. ShaderRead allows fragment sampling; RenderTarget allows the
// shadow pre-pass to write depth into a specific slice. StorageModePrivate
// keeps it GPU-only.
pub(super) fn create_shadow_map_array(
    device: &ProtocolObject<dyn objc2_metal::MTLDevice>,
    size: u32,
    layers: u32,
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, String> {
    let desc = TextureDesc {
        kind: MTLTextureType::Type2DArray,
        format: MTLPixelFormat::Depth32Float,
        width: size as usize,
        height: size as usize,
        array_length: layers as usize,
        // RenderTarget (0x4) | ShaderRead (0x1)
        usage: MTLTextureUsage(MTLTextureUsage::ShaderRead.0 | MTLTextureUsage::RenderTarget.0),
        ..Default::default()
    }
    .build();
    device
        .newTextureWithDescriptor(&desc)
        .ok_or("failed to create shadow map array texture".to_string())
}

// Off-screen HDR render targets for the post-process pipeline. The main pass
// renders linear-light RGBA16Float into `hdr_color` (MSAA) which resolves
// into `hdr_resolve` at end-of-pass; the composite pass then samples
// `hdr_resolve` for tonemap + FXAA. `depth` is the matching MSAA depth,
// kept alive after the Main pass so post-passes (decals/fog/water/raymarch
// early-out) can sample it as a read-only snapshot of the rasterised
// scene depth. `depth_resolve` is the single-sample sibling (populated by
// the Main pass via a `MultisampleResolve` store action with
// `MTLMultisampleDepthResolveFilter::Sample0`) that the raymarch pass
// uses as a writable depth attachment (and that post-Raymarch passes like
// water/decal/fog sample so they "see" raymarched surface depth alongside
// rasterised depth). The canonical post-rasterise scene depth target
// going forward; any future post-pass that needs to write depth should
// bind this rather than introduce its own depth target.
//
// `hdr_resolve_copy` is a single-sample sibling of `hdr_resolve` reserved
// for the raymarch pass's scene-copy refraction path: at the start of
// the raymarch encoder a blit copies `hdr_resolve` into this texture, so
// user SDF shaders can sample the pre-raymarch scene without violating
// Metal's attachment-aliasing rule (the raymarch pass writes the same
// `hdr_resolve` it would otherwise need to read). Same RGBA16Float
// format / ShaderRead+RenderTarget usage as `hdr_resolve`. Unbound by
// any pass when no `SdfVolume` consumes it; allocated unconditionally
// because the cost (a single full-screen RGBA16F texture ~ 18 MB at
// 1440p) is small relative to the existing HDR target footprint and
// keeps the allocation logic branch-free.
pub(super) struct HdrTargets {
    pub hdr_color: Retained<ProtocolObject<dyn MTLTexture>>,
    pub hdr_resolve: Retained<ProtocolObject<dyn MTLTexture>>,
    pub hdr_resolve_copy: Retained<ProtocolObject<dyn MTLTexture>>,
    // Scene snapshot taken at the head of the transparent pass. A blit copies
    // the latest pre-transparent scene (`scene_pre_taa`) here so translucent
    // shaders (water, glass) sample the opaque scene for refraction without
    // reading the render attachment they are writing. Same descriptor as
    // `hdr_resolve`. Distinct from `hdr_resolve_copy`, which the raymarch pass
    // fills earlier in the frame for SDF refraction.
    pub transparent_scene_copy: Retained<ProtocolObject<dyn MTLTexture>>,
    pub depth: Retained<ProtocolObject<dyn MTLTexture>>,
    pub depth_resolve: Retained<ProtocolObject<dyn MTLTexture>>,
    pub width: u32,
    pub height: u32,
}

// Create or recreate the HDR off-screen targets at `width`x`height`. The
// MSAA color/depth attachments live in private storage; the resolve target
// also lives in private storage but enables ShaderRead so the post pass
// can sample it.
pub(super) fn create_hdr_targets(
    device: &ProtocolObject<dyn objc2_metal::MTLDevice>,
    width: u32,
    height: u32,
    sample_count: u32,
) -> Result<HdrTargets, String> {
    let w = width.max(1) as usize;
    let h = height.max(1) as usize;

    // MSAA HDR color: RGBA16Float, multi-sample 2D, render-target only.
    let color_desc = TextureDesc {
        kind: MTLTextureType::Type2DMultisample,
        format: MTLPixelFormat::RGBA16Float,
        width: w,
        height: h,
        sample_count: sample_count as usize,
        usage: MTLTextureUsage::RenderTarget,
        ..Default::default()
    }
    .build();
    let hdr_color = device
        .newTextureWithDescriptor(&color_desc)
        .ok_or("failed to create MSAA HDR color texture")?;

    // Single-sample resolve target: same RGBA16Float; sampled by the post pass.
    let resolve_desc = TextureDesc {
        format: MTLPixelFormat::RGBA16Float,
        width: w,
        height: h,
        usage: MTLTextureUsage(MTLTextureUsage::ShaderRead.0 | MTLTextureUsage::RenderTarget.0),
        ..Default::default()
    }
    .build();
    let hdr_resolve = device
        .newTextureWithDescriptor(&resolve_desc)
        .ok_or("failed to create HDR resolve texture")?;

    // Scene-copy sibling of `hdr_resolve`. The raymarch pass blits
    // `hdr_resolve` here before drawing so user SDF shaders can sample
    // the pre-raymarch scene as a regular texture without aliasing the
    // render attachment. Same descriptor as `hdr_resolve` so the blit
    // is a plain copy_from_texture.
    let hdr_resolve_copy = device
        .newTextureWithDescriptor(&resolve_desc)
        .ok_or("failed to create HDR resolve-copy texture")?;

    // Scene snapshot for the transparent pass. The transparent encoder blits
    // `scene_pre_taa` here before drawing so water / glass refraction reads a
    // stable copy regardless of whether SSR produced a distinct `scene_pre_taa`
    // or it aliases `hdr_resolve`. Same descriptor as `hdr_resolve`.
    let transparent_scene_copy = device
        .newTextureWithDescriptor(&resolve_desc)
        .ok_or("failed to create transparent scene-copy texture")?;

    // MSAA depth: matches the color sample count. `ShaderRead` is enabled so
    // the decal pass (and any future post-pass that needs scene depth) can
    // sample it as a `depth2d_ms<float>` after the main pass stores it.
    let depth_desc = TextureDesc {
        kind: MTLTextureType::Type2DMultisample,
        format: MTLPixelFormat::Depth32Float,
        width: w,
        height: h,
        sample_count: sample_count as usize,
        usage: MTLTextureUsage(MTLTextureUsage::ShaderRead.0 | MTLTextureUsage::RenderTarget.0),
        ..Default::default()
    }
    .build();
    let depth = device
        .newTextureWithDescriptor(&depth_desc)
        .ok_or("failed to create MSAA depth texture")?;

    // Single-sample depth resolve: populated by the Main pass via a
    // `MTLStoreAction::MultisampleResolve` with depth filter Sample0. The
    // raymarch pass binds this as its writable depth attachment; water /
    // decal / fog sample it so they see raymarched surface depth alongside
    // rasterised depth.
    let depth_resolve_desc = TextureDesc {
        format: MTLPixelFormat::Depth32Float,
        width: w,
        height: h,
        usage: MTLTextureUsage(MTLTextureUsage::ShaderRead.0 | MTLTextureUsage::RenderTarget.0),
        ..Default::default()
    }
    .build();
    let depth_resolve = device
        .newTextureWithDescriptor(&depth_resolve_desc)
        .ok_or("failed to create single-sample depth resolve texture")?;

    Ok(HdrTargets {
        hdr_color,
        hdr_resolve,
        hdr_resolve_copy,
        transparent_scene_copy,
        depth,
        depth_resolve,
        width: w as u32,
        height: h as u32,
    })
}

// Create a 2-D float lookup texture from `texels`, which must hold
// `size * size * components` values. Used for the LTC tables: `components` is 4
// for the transform table and 2 for the magnitude table.
pub(super) fn create_lut_texture(
    alloc: &DeviceAllocator,
    texels: &[f32],
    size: u32,
    components: usize,
) -> Result<PooledTexture, String> {
    let needed = (size as usize) * (size as usize) * components;
    if texels.len() < needed {
        return Err(format!(
            "LUT data too short for {size}x{size}x{components}: {} values, need {needed}",
            texels.len()
        ));
    }
    let format = match components {
        2 => MTLPixelFormat::RG32Float,
        4 => MTLPixelFormat::RGBA32Float,
        n => return Err(format!("unsupported LUT component count {n}")),
    };

    let desc = TextureDesc {
        format,
        width: size as usize,
        height: size as usize,
        storage: objc2_metal::MTLStorageMode::Shared,
        ..Default::default()
    }
    .build();
    let texture = alloc.alloc_texture(&desc)?;

    let bytes_per_row = (size as usize) * components * 4;
    // SAFETY: `region` covers the whole texture and the length check above proved `texels` holds
    // `size * size * components` f32s, matching `bytes_per_row * size`.
    unsafe {
        use objc2_metal::MTLRegion;
        let region = MTLRegion {
            origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
            size: objc2_metal::MTLSize {
                width: size as usize,
                height: size as usize,
                depth: 1,
            },
        };
        let ptr = texels.as_ptr() as *mut std::ffi::c_void;
        texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
            region,
            0,
            std::ptr::NonNull::new(ptr).ok_or("LUT texel pointer is null")?,
            bytes_per_row,
        );
    }
    Ok(texture)
}