Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

14.1 KB
Raw Blame
//! The live passes' GPU side: the shader module and its pipelines (`Passes`), the screen-size buffers and the bind
//! groups (`Targets`), from the layout live.wgsl declares and `layout`'s table; and the colour table of the final pass.

use super::*;

/// The colour table the final pass samples (`lut`): colour grading and the tone curve of a preset (`post::Tonemapper`)
/// for exposed linear sRGB on a log2 axis (`post::lut_coord`, the same in live.wgsl `post`), as sRGB-encoded display
/// values (the pass has no encoding left to do; half floats hold them to 1 / 2048). LUT texels a side.
pub(super) const LUT: u32 = post::LUT_SIZE;

pub(super) fn tonemap_lut(p: &crate::desc::PostPreset) -> Vec<u16> {
    let tm = post::Tonemapper::new(p);
    let mut out = Vec::with_capacity((LUT * LUT * LUT * 4) as usize);
    for b in 0..LUT {
        for g in 0..LUT {
            for r in 0..LUT {
                let at = |k: u32| post::lut_value(k as f32 / (LUT - 1) as f32);
                let d = tm.apply(Vec3::new(at(r), at(g), at(b)));
                for c in [d.x, d.y, d.z, 1.0] {
                    out.push(half::f16::from_f32(post::linear_to_srgb(c.clamp(0.0, 1.0))).to_bits());
                }
            }
        }
    }
    out
}

/// The live passes' source: records.wgsl (what they share with the kernel) and live.wgsl, natively and in a browser
/// alike (each pass binds at most a browser's storage buffers: `layout`). build.rs reads the same two.
pub(crate) fn live_source() -> &'static str {
    concat!(include_str!("../../shaders/records.wgsl"), include_str!("../../shaders/live.wgsl"))
}

pub(super) struct Passes {
    /// Each pass's bind group layout: the bindings it uses.
    pub(super) layouts: Vec<wgpu::BindGroupLayout>,
    /// The passes in `layout::PASSES`' order, with the grid each runs over.
    pub(super) pipes: Vec<(&'static str, layout::Grid, wgpu::ComputePipeline)>,
}

/// A binding's layout entry (live.wgsl's kind of it).
fn layout_entry(b: &layout::Binding) -> wgpu::BindGroupLayoutEntry {
    let ty = match b.kind {
        layout::Kind::Uniform => wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
        layout::Kind::Storage { read_only, .. } => wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
        layout::Kind::Texture(view_dimension) => wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension, multisampled: false },
        layout::Kind::Sampler => wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
    };
    wgpu::BindGroupLayoutEntry { binding: b.binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }
}

impl Passes {
    pub(super) fn new(g: &gpu::Gpu) -> Passes {
        layout::check();
        if g.merged {
            // (A browser's stage binds at most eight storage buffers; the device here is held to them.)
            let over: Vec<String> = layout::PASSES.iter().map(|p| (p.0, layout::storage_count(p.0))).filter(|p| p.1 as u32 > crate::merged::STORAGE_BUFFERS).map(|p| format!("{} binds {}", p.0, p.1)).collect();
            assert!(over.is_empty(), "live passes over a browser's storage buffers: {}", over.join(", "));
        }
        let d = &g.device;
        let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("live"), source: wgpu::ShaderSource::Wgsl(live_source().into()) });
        let pipe = |name: &str, layout: &wgpu::BindGroupLayout| {
            let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(layout)], immediate_size: 0 });
            d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(name), layout: Some(&pl), module: &module, entry_point: Some(name), compilation_options: Default::default(), cache: g.cache() })
        };
        // A layout a pass, of the bindings it uses.
        let mut layouts = vec![];
        let mut pipes = vec![];
        for &(name, grid) in layout::PASSES {
            let entries: Vec<wgpu::BindGroupLayoutEntry> = layout::uses(name).iter().map(|&b| layout_entry(layout::BINDINGS.iter().find(|x| x.binding == b).expect("a binding of live.wgsl"))).collect();
            let l = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(name), entries: &entries });
            pipes.push((name, grid, pipe(name, &l)));
            layouts.push(l);
        }
        g.save_pipeline_cache();
        Passes { layouts, pipes }
    }

    /// The layout pass `k` binds.
    pub(super) fn layout(&self, k: usize) -> &wgpu::BindGroupLayout {
        &self.layouts[k]
    }
}

/// The view's targets: every buffer that follows its size (the trace's samples, what the kernel leaves the passes,
/// the passes' own, the output), the radiance cache, the passes' parameters and tone-map table, and the bind groups
/// over them. A scene reload leaves them; another size makes the ones that follow it again (`resize`).
pub struct Targets {
    pub(super) params: wgpu::Buffer,
    /// The trace's samples, a `Pixel` a pixel (`gpu::Uploaded::accum` is a handle of it, for the scene's bind group).
    pub(super) accum: wgpu::Buffer,
    /// The passes' own buffers (`layout::RESOURCES`' `Own`), by binding: what each holds and when is live.wgsl's
    /// table ("The live passes' buffers").
    pub(super) bufs: Vec<(u32, Buf)>,
    /// The output (`out_px`: sRGB BGRA8 a pixel), what the hosts draw.
    pub out: wgpu::Buffer,
    /// The kernel's group 1 (`gpu::KernelBufs`): the radiance cache, and what the passes here read of
    /// a trace: the specular-lobe rays (`refl`), motion vectors per traced pixel (pathtrace.wgsl `motion_out`) and the
    /// deterministic direct light per traced pixel (`direct_out`).
    pub kernel: gpu::KernelBufs,
    /// Translucent particles per traced pixel (`gpu::Gpu::translucent_low`): made for the first scene that draws them.
    pub(super) translucent_low: Option<wgpu::Buffer>,
    pub(super) lut_tex: wgpu::Texture,
    pub(super) lut_view: wgpu::TextureView,
    pub(super) sampler: wgpu::Sampler,
    /// The bind group of each pass, in `Passes::pipes`' order.
    pub(super) bgs: Vec<wgpu::BindGroup>,
    size: (u32, u32),
    /// The direct light's buffer, in outputs of vec4s (`kernel_bytes`).
    pub(super) direct: u64,
}

/// What a view of `w` x `h` holds of each of the kernel's buffers that follow its size, bytes (`gpu::VIEW_BUFFERS`).
/// `direct`: the direct light's buffer in outputs of vec4s: 1, the traced pixels' direct light alone; 3 with the
/// output grid's guides after it (two vec4s an output pixel: pathtrace.wgsl `guide_at`), 4 with a medium's record a
/// traced pixel after those (`seen_medium_at`).
fn kernel_bytes(w: u32, h: u32, direct: u64) -> [u64; 5] {
    let n = (w * h) as u64;
    [n * 32, n * 16, n * 16 * direct, layout::light_lists(w, h) as u64 * 16, n * 32]
}

impl Targets {
    /// For a view of `w` x `h` and a radiance cache of `cache` entries.
    pub(super) fn new(g: &gpu::Gpu, passes: &Passes, w: u32, h: u32, lut: &[u16], cache: u64) -> Targets {
        let d = &g.device;
        let lut_tex = d.create_texture(&wgpu::TextureDescriptor {
            label: Some("tonemap lut"),
            size: wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D3,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        g.queue.write_texture(
            wgpu::TexelCopyTextureInfo { texture: &lut_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
            bytemuck::cast_slice(lut),
            wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(LUT * 8), rows_per_image: Some(LUT) },
            wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },
        );
        let (bufs, out) = Self::own(d, w, h);
        let mut t = Targets {
            params: d.create_buffer(&wgpu::BufferDescriptor { label: Some("live params"), size: std::mem::size_of::<LiveParams>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),
            accum: g.accum_buffer(w, h),
            bufs,
            out,
            kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, kernel_bytes(w, h, 1)),
            direct: 1,
            translucent_low: None,
            lut_view: lut_tex.create_view(&Default::default()),
            lut_tex,
            sampler: d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }),
            bgs: vec![],
            size: (w, h),
        };
        t.bgs = t.bind_groups(d, passes);
        t
    }

    /// The kernel's buffers with the camera hits' of `bytes` (`gpu::KernelBufs::with_first`), and the passes' bind
    /// groups over them (the merged layout's sections are all in another buffer then).
    pub(super) fn grow_first(&mut self, g: &gpu::Gpu, passes: &Passes, bytes: u64) {
        self.kernel = self.kernel.with_first(&g.device, bytes);
        self.bgs = self.bind_groups(&g.device, passes);
    }

    /// The kernel's buffers with the direct light's of `direct` outputs of vec4s (`kernel_bytes`: room for the output
    /// grid's guides, and a medium's records), and the passes' bind groups over them. As `grow_first`.
    pub(super) fn grow_direct(&mut self, g: &gpu::Gpu, passes: &Passes, direct: u64) {
        self.direct = direct;
        self.kernel = self.kernel.with_direct(&g.device, kernel_bytes(self.size.0, self.size.1, direct)[2]);
        self.bgs = self.bind_groups(&g.device, passes);
    }

    /// For another size: what follows it is made again (the samples, the passes' own buffers and the output, the
    /// kernel's four, the translucent particles'), with the bind groups over them. The radiance cache, which is the
    /// world's, the passes' parameters and the tone-map table stay. (The merged layout keeps the cache in one buffer
    /// with the rest: it starts empty.)
    pub(super) fn resize(&mut self, g: &gpu::Gpu, passes: &Passes, w: u32, h: u32) {
        let d = &g.device;
        (self.bufs, self.out) = Self::own(d, w, h);
        self.accum = g.accum_buffer(w, h);
        self.kernel = self.kernel.resized(d, kernel_bytes(w, h, self.direct));
        self.translucent_low = None;
        self.size = (w, h);
        self.bgs = self.bind_groups(d, passes);
    }

    /// The passes' own buffers for a view of `w` x `h`, in binding order, and the output among them.
    fn own(d: &wgpu::Device, w: u32, h: u32) -> (Vec<(u32, Buf)>, wgpu::Buffer) {
        let n = (w * h) as u64;
        let sb = |label: &str, bytes: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
        let quarter = (w.div_ceil(4) * h.div_ceil(4)) as u64;
        let bloom_texels = post::bloom_texels(w, h);
        let bufs: Vec<(u32, Buf)> = layout::BINDINGS
            .iter()
            .filter_map(|b| {
                let layout::Res::Own(count) = layout::resource(b) else { return None };
                let layout::Kind::Storage { stride, len, .. } = b.kind else { unreachable!("layout::check") };
                let elements = match count {
                    layout::Count::Pixels(k) => k * n,
                    layout::Count::Quarter => quarter,
                    layout::Count::Bloom => bloom_texels,
                    layout::Count::Declared => len,
                };
                Some((b.binding, Buf::whole(sb(b.name, elements * stride))))
            })
            .collect();
        let out = bufs.iter().find(|b| b.0 == layout::binding("out_px").binding).expect("out_px").1.buffer.clone();
        (bufs, out)
    }

    /// The buffer translucent particles are drawn into below full resolution, made on first use.
    pub(super) fn translucent_low(&mut self, g: &gpu::Gpu) -> &wgpu::Buffer {
        let (w, h) = self.size;
        self.translucent_low.get_or_insert_with(|| g.translucent_low(w, h))
    }

    /// The buffer live.wgsl binds as `name` (the passes' own, or the kernel's).
    pub(super) fn buf(&self, name: &str) -> &Buf {
        self.buf_at(layout::binding(name))
    }

    fn buf_at(&self, b: &layout::Binding) -> &Buf {
        match layout::resource(b) {
            layout::Res::KernelRefl => &self.kernel.refl,
            layout::Res::KernelMotion => &self.kernel.motion,
            layout::Res::KernelDirect | layout::Res::KernelReports => &self.kernel.direct,
            layout::Res::KernelLists => &self.kernel.lists,
            layout::Res::Own(_) => &self.bufs.iter().find(|x| x.0 == b.binding).expect("an own buffer").1,
            r => panic!("`{}` is bound to {r:?}, not a buffer of the passes'", b.name),
        }
    }

    /// The bind group of each pass, in `Passes::pipes`' order.
    fn bind_groups(&self, d: &wgpu::Device, passes: &Passes) -> Vec<wgpu::BindGroup> {
        let entry = |b: &'_ layout::Binding| -> wgpu::BindGroupEntry<'_> {
            let resource = match layout::resource(b) {
                layout::Res::Params => self.params.as_entire_binding(),
                layout::Res::Samples => self.accum.as_entire_binding(),
                layout::Res::Lut => wgpu::BindingResource::TextureView(&self.lut_view),
                layout::Res::LutSampler => wgpu::BindingResource::Sampler(&self.sampler),
                _ => self.buf_at(b).binding(),
            };
            wgpu::BindGroupEntry { binding: b.binding, resource }
        };
        passes
            .pipes
            .iter()
            .enumerate()
            .map(|(k, (name, ..))| {
                let entries: Vec<wgpu::BindGroupEntry> = layout::uses(name).iter().map(|&b| entry(layout::BINDINGS.iter().find(|x| x.binding == b).expect("a binding of live.wgsl"))).collect();
                d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(name), layout: passes.layout(k), entries: &entries })
            })
            .collect()
    }
}