concinnity-device 0.19.119

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
//! The glass producers of the engine's transparent pass on the D3D12 backend
//! (`transparent.rs` owns the pass itself, the scene snapshot, the shared root
//! signatures and the combined back-to-front draw order; `water.rs` is the third
//! producer). Two live here because they are the same material family:
//!
//!   * `GlassPanel` -- a flat world-space quad built once at init. The fragment
//!     refracts the pass's scene snapshot, tints it, and mixes a reflection over
//!     it by a Schlick Fresnel term.
//!   * A see-through glass MESH -- an imported `Material` flagged `see_through`,
//!     drawn from the shared scene buffers with a per-pixel reflection ray. It is
//!     ray-traced only, so it builds nothing without DXR and its meshes then
//!     rasterize opaque in the main pass instead.
//!
//! The shaders are the shared `shaders/glass.hlsl` and `shaders/glass_mesh.hlsl`,
//! compiled through `builtin_shaders`; the ray-traced fragments need shader model
//! 6.5 for their inline ray query, the base pair 6.0.

use concinnity_core::components::GlassPanel;
use concinnity_core::geometry::glass_quad::build_glass_quad;
use concinnity_core::gfx::mesh_payload::Vertex;
use concinnity_core::render::error::RenderResult;
use concinnity_core::render::uniforms::GlassParams;
use windows::Win32::Graphics::Direct3D12::*;

use super::allocator::DeviceAllocator;
use crate::directx::builtin_shaders;
use crate::directx::builtin_shaders::CompileProgram;
use crate::directx::context::dump_on_err;
use crate::directx::transparent::{
    GlassMeshProducer, RecordUpload, TracedGlassPsos, TransparentProducer, TransparentRecord,
    create_glass_reflection_pso, create_transparent_pso,
};

// Compile the glass vertex + fragment shaders. The fragment comes in an MSAA
// pair, which keeps its depth SRV declaration in sync with the resource's
// sample count; the vertex reads no depth and serves both pipelines. Used at
// init and by shader hot-reload.
pub(in crate::directx) fn compile_glass_shaders(
    msaa_samples: u32,
    hot_reload: bool,
) -> RenderResult<(Vec<u8>, Vec<u8>)> {
    let vs = builtin_shaders::GLASS_VERT.compile(hot_reload)?;
    let ps = builtin_shaders::GLASS_FRAG
        .at(msaa_samples > 1)
        .compile(hot_reload)?;
    Ok((vs, ps))
}

// Rebuild the glass PSO against fresh shader source. Called from the DirectX
// shader hot-reload pass; the root signature is reused.
pub(in crate::directx) fn rebuild_glass_pso(
    device: &ID3D12Device,
    root_sig: &ID3D12RootSignature,
    msaa_samples: u32,
    hot_reload: bool,
    info_queue: Option<&ID3D12InfoQueue>,
) -> RenderResult<ID3D12PipelineState> {
    let (vs, ps) = compile_glass_shaders(msaa_samples, hot_reload)?;
    dump_on_err(
        info_queue,
        create_transparent_pso(device, root_sig, &vs, &ps),
    )
}

// DXIL for the two RT glass fragments, plus the vertex stage they share with the
// base pass (both root signatures put the transparent view CBV at b0).
struct GlassRtShaders {
    vs: Vec<u8>,
    flat_ps: Vec<u8>,
    textured_ps: Vec<u8>,
    // The reflection pre-pass fragments, paired the same way.
    reflection_flat_ps: Vec<u8>,
    reflection_textured_ps: Vec<u8>,
}

// Compile the flat + textured ray-traced fragments (SM 6.5, for the inline ray
// query). Returns an `Err` (which the caller turns into a None RT pipeline +
// the base path) when dxc is unavailable or the shader fails to compile.
fn compile_glass_rt_shaders(msaa_samples: u32, hot_reload: bool) -> RenderResult<GlassRtShaders> {
    use builtin_shaders as sb;
    let msaa = msaa_samples > 1;
    Ok(GlassRtShaders {
        vs: sb::GLASS_VERT.compile(hot_reload)?,
        flat_ps: sb::GLASS_FRAG_RT.at(msaa).compile(hot_reload)?,
        textured_ps: sb::GLASS_FRAG_RT_TEXTURED.at(msaa).compile(hot_reload)?,
        reflection_flat_ps: sb::GLASS_REFLECTION_FRAG.at(msaa).compile(hot_reload)?,
        reflection_textured_ps: sb::GLASS_REFLECTION_FRAG_TEXTURED
            .at(msaa)
            .compile(hot_reload)?,
    })
}

// What building the glass producer needs from the pass that owns it: the
// allocator, the two shared root signatures (the RT one is `None` on a
// non-DXR GPU), and the render-state / hot-reload toggles.
#[derive(Clone, Copy)]
pub(in crate::directx) struct GlassBuild<'a> {
    pub alloc: &'a DeviceAllocator,
    pub root_sig: &'a ID3D12RootSignature,
    pub rt_root_sig: Option<&'a ID3D12RootSignature>,
    pub msaa_samples: u32,
    pub hot_reload: bool,
    pub info_queue: Option<&'a ID3D12InfoQueue>,
}

// Build the glass pipelines and one record per authored panel. The RT pair is
// built whenever the pass has an RT root signature (regardless of whether RT is
// on at launch, so a live `quality-set ray_traced_reflections` selects it with no
// pipeline rebuild); a compile failure leaves it absent and the base
// probe/planar path runs.
pub(in crate::directx) fn build_glass_producer(
    build: GlassBuild,
    panels: &[GlassPanel],
    // Per-pane planar resolve slot (aligned with `panels`); `None` panes keep the
    // probe/sky reflection. From `assign_planar_slots`.
    planar_slots: &[Option<usize>],
) -> RenderResult<TransparentProducer> {
    let GlassBuild {
        alloc,
        root_sig,
        rt_root_sig,
        msaa_samples,
        hot_reload,
        info_queue,
    } = build;
    let device = alloc.device();
    let (vs, ps) = compile_glass_shaders(msaa_samples, hot_reload)?;
    let pso = dump_on_err(
        info_queue,
        create_transparent_pso(device, root_sig, &vs, &ps),
    )?;

    let traced = match rt_root_sig {
        Some(sig) => {
            match build_glass_rt_pipelines(device, sig, msaa_samples, hot_reload, info_queue) {
                Ok(psos) => Some(psos),
                Err(e) => {
                    tracing::warn!(
                        "glass RT reflection pipeline build failed ({e}); \
                     using the probe/planar glass path"
                    );
                    None
                }
            }
        }
        None => None,
    };

    let mut records = Vec::with_capacity(panels.len());
    for (i, panel) in panels.iter().enumerate() {
        let planar_slot = planar_slots.get(i).copied().flatten();
        let (verts, idxs) = build_glass_quad(panel.center, panel.normal, panel.half_size);

        // Flatten into the standard Vertex layout. Tangent is a placeholder (the
        // glass shader rebuilds its frame from the panel normal) and per-vertex
        // color is unused.
        let packed: Vec<Vertex> = verts
            .into_iter()
            .map(|(pos, normal, color, uv)| Vertex {
                pos,
                normal,
                tangent: [1.0, 0.0, 0.0],
                color,
                uv,
            })
            .collect();

        // Bake the planar flag: the pane samples the sharp mirror render only
        // when it was assigned a planar slot.
        let params = GlassParams::from_panel(panel, planar_slot.is_some());
        records.push(TransparentRecord::upload(
            alloc,
            RecordUpload {
                vertices: &packed,
                indices: &idxs,
                params: bytemuck::bytes_of(&params),
                visible: panel.visible,
                center: panel.center,
                planar_slot,
            },
        )?);
    }

    let (flat_rt_pso, textured_rt_pso, reflection_flat_pso, reflection_textured_pso) = match traced
    {
        Some(p) => (
            Some(p.shade_flat),
            Some(p.shade_textured),
            Some(p.reflection_flat),
            Some(p.reflection_textured),
        ),
        None => (None, None, None, None),
    };
    Ok(TransparentProducer {
        pso,
        flat_rt_pso,
        textured_rt_pso,
        reflection_flat_pso,
        reflection_textured_pso,
        records,
    })
}

// Compile and build the traced RT glass PSOs against the pass's RT root
// signature: the shading pair with the base PSO's render state, and the
// reflection pre-pass pair.
fn build_glass_rt_pipelines(
    device: &ID3D12Device,
    rt_root_sig: &ID3D12RootSignature,
    msaa_samples: u32,
    hot_reload: bool,
    info_queue: Option<&ID3D12InfoQueue>,
) -> RenderResult<TracedGlassPsos> {
    let shaders = compile_glass_rt_shaders(msaa_samples, hot_reload)?;
    build_traced_psos(device, rt_root_sig, &shaders, info_queue)
}

// Both traced pairs over one vertex stage.
fn build_traced_psos(
    device: &ID3D12Device,
    rt_root_sig: &ID3D12RootSignature,
    shaders: &GlassRtShaders,
    info_queue: Option<&ID3D12InfoQueue>,
) -> RenderResult<TracedGlassPsos> {
    let shade = |ps: &[u8]| {
        dump_on_err(
            info_queue,
            create_transparent_pso(device, rt_root_sig, &shaders.vs, ps),
        )
    };
    let reflection = |ps: &[u8]| {
        dump_on_err(
            info_queue,
            create_glass_reflection_pso(device, rt_root_sig, &shaders.vs, ps),
        )
    };
    Ok(TracedGlassPsos {
        shade_flat: shade(&shaders.flat_ps)?,
        shade_textured: shade(&shaders.textured_ps)?,
        reflection_flat: reflection(&shaders.reflection_flat_ps)?,
        reflection_textured: reflection(&shaders.reflection_textured_ps)?,
    })
}

// What building the see-through mesh producer needs. There is no base root
// signature here: the producer is ray-traced only, so it is built solely against
// the pass's RT signature.
#[derive(Clone, Copy)]
pub(in crate::directx) struct GlassMeshBuild<'a> {
    pub alloc: &'a DeviceAllocator,
    pub rt_root_sig: &'a ID3D12RootSignature,
    pub msaa_samples: u32,
    pub hot_reload: bool,
    pub info_queue: Option<&'a ID3D12InfoQueue>,
}

// Compile the flat + textured see-through mesh fragments (SM 6.5, for the inline
// ray query) and the vertex stage they share. Unlike the pane family there is no
// non-RT pair: the trace is what makes the mesh see-through.
fn compile_glass_mesh_shaders(msaa_samples: u32, hot_reload: bool) -> RenderResult<GlassRtShaders> {
    use builtin_shaders as sb;
    let msaa = msaa_samples > 1;
    Ok(GlassRtShaders {
        vs: sb::GLASS_MESH_VERT.compile(hot_reload)?,
        flat_ps: sb::GLASS_MESH_FRAG_RT.at(msaa).compile(hot_reload)?,
        textured_ps: sb::GLASS_MESH_FRAG_RT_TEXTURED
            .at(msaa)
            .compile(hot_reload)?,
        reflection_flat_ps: sb::GLASS_MESH_REFLECTION_FRAG
            .at(msaa)
            .compile(hot_reload)?,
        reflection_textured_ps: sb::GLASS_MESH_REFLECTION_FRAG_TEXTURED
            .at(msaa)
            .compile(hot_reload)?,
    })
}

// Build the see-through mesh pipelines and the per-frame params ring one block
// per mesh deep. The producer holds no records: a mesh's geometry lives in the
// shared scene buffers and its params change per frame, so the encoder rebuilds
// its draw list each frame (see `collect_mesh_draws`).
pub(in crate::directx) fn build_glass_mesh_producer(
    build: GlassMeshBuild,
    object_indices: &[usize],
) -> RenderResult<GlassMeshProducer> {
    let GlassMeshBuild {
        alloc,
        rt_root_sig,
        msaa_samples,
        hot_reload,
        info_queue,
    } = build;
    let device = alloc.device();
    let shaders = compile_glass_mesh_shaders(msaa_samples, hot_reload)?;
    let psos = build_traced_psos(device, rt_root_sig, &shaders, info_queue)?;
    GlassMeshProducer::new(alloc, psos, object_indices.to_vec())
}

#[cfg(test)]
mod tests {
    // The `TransparentView` / `GlassParams` layout tests live with the structs
    // in `concinnity_core::render::uniforms`, and are checked against the compiled
    // shader by `shader_layout`.

    // The glass shaders compile at runtime from the shared single source, so a
    // syntax or register error in either MSAA variant would otherwise surface
    // only as an init failure on a GPU host. dxc (bundled, vendored, on PATH or
    // under VULKAN_SDK) may be absent, in which case the runtime path reports
    // its own error and this skips rather than failing.
    #[test]
    fn glass_shaders_compile() {
        concinnity_shader::require_dxc!();
        for msaa in [1u32, 4] {
            super::compile_glass_shaders(msaa, false)
                .unwrap_or_else(|e| panic!("glass shaders (msaa={msaa}) must compile: {e}"));
        }
    }

    // The same for the ray-traced pair, which additionally exercises the shared
    // traversal fragment and the shader model 6.5 the ray query needs. Both MSAA
    // variants and both hit-shading variants go through
    // `compile_glass_rt_shaders`.
    #[test]
    fn glass_rt_shaders_compile() {
        concinnity_shader::require_dxc!();
        for msaa in [1u32, 4] {
            super::compile_glass_rt_shaders(msaa, false)
                .unwrap_or_else(|e| panic!("glass_rt shaders (msaa={msaa}) must compile: {e}"));
        }
    }

    // And the see-through mesh family, whose vertex stage is a second one (it
    // applies the model matrix) and whose fragments carry the same SM 6.5 trace.
    #[test]
    fn glass_mesh_shaders_compile() {
        concinnity_shader::require_dxc!();
        for msaa in [1u32, 4] {
            super::compile_glass_mesh_shaders(msaa, false)
                .unwrap_or_else(|e| panic!("glass_mesh shaders (msaa={msaa}) must compile: {e}"));
        }
    }
}