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.

32.9 KB
Raw Blame
//! Descriptor parsing: the JSON the JS layer sends for creation calls (WebGPU dictionaries with
//! every GPU object replaced by its integer id) → owned specs → wgpu objects.
//!
//! Parse errors are WebIDL-level (`TypeError` in the page: missing required members, unknown
//! enum strings); everything else is left to wgpu's validation, which reports GPU errors.
use serde_json::Value as J;
use wgpu::TextureFormat;

use crate::fmt;
use crate::res::{Res, Slab, ViewRes};

pub type R<T> = Result<T, String>;

// ------------------------------------------------------------------------------------- helpers

/// A member, treating `null` like a missing one.
fn get<'a>(j: &'a J, k: &str) -> Option<&'a J> {
    j.get(k).filter(|v| !v.is_null())
}

fn num(j: &J, k: &str, default: f64) -> R<f64> {
    match get(j, k) {
        None => Ok(default),
        Some(J::Number(n)) => Ok(n.as_f64().unwrap_or(default)),
        Some(J::Bool(b)) => Ok(*b as u8 as f64),
        Some(v) => Err(format!("'{k}' must be a number, got {v}")),
    }
}

/// WebIDL `[EnforceRange] unsigned long`-ish: finite, truncated, clamped into u32.
fn u32_of(j: &J, k: &str, default: u32) -> R<u32> {
    let d = num(j, k, default as f64)?;
    if !d.is_finite() || d < 0.0 || d > u32::MAX as f64 {
        return Err(format!("'{k}' is out of range: {d}"));
    }
    Ok(d as u32)
}

fn u64_of(j: &J, k: &str, default: u64) -> R<u64> {
    let d = num(j, k, default as f64)?;
    if !d.is_finite() || d < 0.0 || d > 9007199254740991.0 {
        return Err(format!("'{k}' is out of range: {d}"));
    }
    Ok(d as u64)
}

fn req_u32(j: &J, k: &str) -> R<u32> {
    if get(j, k).is_none() {
        return Err(format!("required member '{k}' is missing"));
    }
    u32_of(j, k, 0)
}

fn boolean(j: &J, k: &str, default: bool) -> bool {
    match get(j, k) {
        None => default,
        Some(J::Bool(b)) => *b,
        Some(J::Number(n)) => n.as_f64().is_some_and(|x| x != 0.0),
        Some(J::String(s)) => !s.is_empty(),
        Some(_) => true,
    }
}

fn string<'a>(j: &'a J, k: &str) -> Option<&'a str> {
    get(j, k).and_then(|v| v.as_str())
}

fn enum_of<T>(j: &J, k: &str, default: T, parse: impl Fn(&str) -> Option<T>) -> R<T> {
    match get(j, k) {
        None => Ok(default),
        Some(J::String(s)) => parse(s).ok_or_else(|| format!("'{s}' is not a valid value for '{k}'")),
        Some(v) => Err(format!("'{k}' must be a string, got {v}")),
    }
}

fn req_enum<T>(j: &J, k: &str, parse: impl Fn(&str) -> Option<T>) -> R<T> {
    match get(j, k) {
        None => Err(format!("required member '{k}' is missing")),
        Some(J::String(s)) => parse(s).ok_or_else(|| format!("'{s}' is not a valid value for '{k}'")),
        Some(v) => Err(format!("'{k}' must be a string, got {v}")),
    }
}

fn label(j: &J) -> Option<String> {
    string(j, "label").filter(|s| !s.is_empty()).map(str::to_owned)
}

fn array<'a>(j: &'a J, k: &str) -> &'a [J] {
    get(j, k).and_then(|v| v.as_array()).map(|v| v.as_slice()).unwrap_or(&[])
}

/// GPUExtent3D: `[w, h?, d?]` or `{width, height?, depthOrArrayLayers?}`.
pub fn extent(j: &J) -> R<wgpu::Extent3d> {
    if let Some(a) = j.as_array() {
        let at = |i: usize, d: u32| -> R<u32> {
            match a.get(i) {
                None | Some(J::Null) => Ok(d),
                Some(v) => v.as_f64().filter(|x| x.is_finite() && *x >= 0.0 && *x <= u32::MAX as f64).map(|x| x as u32).ok_or_else(|| format!("bad extent component {v}")),
            }
        };
        if a.is_empty() || a.len() > 3 {
            return Err("GPUExtent3D sequence must have 1 to 3 elements".into());
        }
        return Ok(wgpu::Extent3d { width: at(0, 1)?, height: at(1, 1)?, depth_or_array_layers: at(2, 1)? });
    }
    if j.is_object() {
        return Ok(wgpu::Extent3d { width: req_u32(j, "width")?, height: u32_of(j, "height", 1)?, depth_or_array_layers: u32_of(j, "depthOrArrayLayers", 1)? });
    }
    Err("GPUExtent3D must be a sequence or a dictionary".into())
}

/// GPUOrigin3D: `[x?, y?, z?]` or `{x?, y?, z?}`.
pub fn origin(j: Option<&J>) -> R<wgpu::Origin3d> {
    let Some(j) = j.filter(|v| !v.is_null()) else { return Ok(wgpu::Origin3d::ZERO) };
    if let Some(a) = j.as_array() {
        let at = |i: usize| a.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0).max(0.0) as u32;
        return Ok(wgpu::Origin3d { x: at(0), y: at(1), z: at(2) });
    }
    Ok(wgpu::Origin3d { x: u32_of(j, "x", 0)?, y: u32_of(j, "y", 0)?, z: u32_of(j, "z", 0)? })
}

// ------------------------------------------------------------------------------------- textures

#[derive(Debug, Clone, PartialEq)]
pub struct TextureSpec {
    pub label: Option<String>,
    pub size: wgpu::Extent3d,
    pub mips: u32,
    pub samples: u32,
    pub dimension: wgpu::TextureDimension,
    pub format: TextureFormat,
    pub usage: wgpu::TextureUsages,
    pub view_formats: Vec<TextureFormat>,
}

pub fn texture(j: &J) -> R<TextureSpec> {
    let size = extent(get(j, "size").ok_or("required member 'size' is missing")?)?;
    let usage = req_u32(j, "usage")?;
    let mut view_formats = Vec::new();
    for v in array(j, "viewFormats") {
        let s = v.as_str().ok_or("viewFormats must be strings")?;
        view_formats.push(fmt::texture_format(s).ok_or_else(|| format!("'{s}' is not a valid GPUTextureFormat"))?);
    }
    Ok(TextureSpec {
        label: label(j),
        size,
        mips: u32_of(j, "mipLevelCount", 1)?,
        samples: u32_of(j, "sampleCount", 1)?,
        dimension: enum_of(j, "dimension", wgpu::TextureDimension::D2, fmt::texture_dimension)?,
        format: req_enum(j, "format", fmt::texture_format)?,
        usage: texture_usage(usage),
        view_formats,
    })
}

/// WebGPU GPUTextureUsage bits are wgpu's for the five core usages; unknown bits are kept so
/// wgpu reports them.
pub fn texture_usage(bits: u32) -> wgpu::TextureUsages {
    wgpu::TextureUsages::from_bits_retain(bits)
}

impl TextureSpec {
    pub fn desc(&self) -> wgpu::TextureDescriptor<'_> {
        wgpu::TextureDescriptor {
            label: self.label.as_deref(),
            size: self.size,
            mip_level_count: self.mips,
            sample_count: self.samples,
            dimension: self.dimension,
            format: self.format,
            usage: self.usage,
            view_formats: &self.view_formats,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct ViewSpec {
    pub label: Option<String>,
    pub format: Option<TextureFormat>,
    pub dimension: Option<wgpu::TextureViewDimension>,
    pub usage: Option<wgpu::TextureUsages>,
    pub aspect: wgpu::TextureAspect,
    pub base_mip: u32,
    pub mip_count: Option<u32>,
    pub base_layer: u32,
    pub layer_count: Option<u32>,
}

pub fn view(j: &J) -> R<ViewSpec> {
    if j.is_null() {
        return Ok(ViewSpec::default());
    }
    let opt_u32 = |k: &str| -> R<Option<u32>> { if get(j, k).is_some() { Ok(Some(u32_of(j, k, 0)?)) } else { Ok(None) } };
    let usage = opt_u32("usage")?.filter(|u| *u != 0).map(texture_usage);
    Ok(ViewSpec {
        label: label(j),
        format: if get(j, "format").is_some() { Some(req_enum(j, "format", fmt::texture_format)?) } else { None },
        dimension: if get(j, "dimension").is_some() { Some(req_enum(j, "dimension", fmt::view_dimension)?) } else { None },
        usage,
        aspect: enum_of(j, "aspect", wgpu::TextureAspect::All, fmt::aspect)?,
        base_mip: u32_of(j, "baseMipLevel", 0)?,
        mip_count: opt_u32("mipLevelCount")?,
        base_layer: u32_of(j, "baseArrayLayer", 0)?,
        layer_count: opt_u32("arrayLayerCount")?,
    })
}

impl ViewSpec {
    pub fn desc(&self) -> wgpu::TextureViewDescriptor<'_> {
        wgpu::TextureViewDescriptor {
            label: self.label.as_deref(),
            format: self.format,
            dimension: self.dimension,
            usage: self.usage,
            aspect: self.aspect,
            base_mip_level: self.base_mip,
            mip_level_count: self.mip_count,
            base_array_layer: self.base_layer,
            array_layer_count: self.layer_count,
        }
    }
}

pub fn sampler(j: &J) -> R<wgpu::SamplerDescriptor<'static>> {
    let am = |k: &str| enum_of(j, k, wgpu::AddressMode::ClampToEdge, fmt::address_mode);
    let f = |k: &str| enum_of(j, k, wgpu::FilterMode::Nearest, fmt::filter);
    let aniso = u32_of(j, "maxAnisotropy", 1)?.clamp(1, u16::MAX as u32) as u16;
    Ok(wgpu::SamplerDescriptor {
        label: None,
        address_mode_u: am("addressModeU")?,
        address_mode_v: am("addressModeV")?,
        address_mode_w: am("addressModeW")?,
        mag_filter: f("magFilter")?,
        min_filter: f("minFilter")?,
        mipmap_filter: f("mipmapFilter")?,
        lod_min_clamp: num(j, "lodMinClamp", 0.0)? as f32,
        lod_max_clamp: num(j, "lodMaxClamp", 32.0)? as f32,
        compare: if get(j, "compare").is_some() { Some(req_enum(j, "compare", fmt::compare)?) } else { None },
        anisotropy_clamp: aniso,
        border_color: None,
    })
}

// ------------------------------------------------------------------------------------- bindings

pub fn bind_group_layout(j: &J) -> R<Vec<wgpu::BindGroupLayoutEntry>> {
    let mut out = Vec::new();
    for e in array(j, "entries") {
        let binding = req_u32(e, "binding")?;
        let visibility = wgpu::ShaderStages::from_bits_truncate(req_u32(e, "visibility")?);
        let ty = if let Some(b) = get(e, "buffer") {
            let ty = match string(b, "type").unwrap_or("uniform") {
                "uniform" => wgpu::BufferBindingType::Uniform,
                "storage" => wgpu::BufferBindingType::Storage { read_only: false },
                "read-only-storage" => wgpu::BufferBindingType::Storage { read_only: true },
                s => return Err(format!("'{s}' is not a valid GPUBufferBindingType")),
            };
            wgpu::BindingType::Buffer { ty, has_dynamic_offset: boolean(b, "hasDynamicOffset", false), min_binding_size: wgpu::BufferSize::new(u64_of(b, "minBindingSize", 0)?) }
        } else if let Some(s) = get(e, "sampler") {
            wgpu::BindingType::Sampler(match string(s, "type").unwrap_or("filtering") {
                "filtering" => wgpu::SamplerBindingType::Filtering,
                "non-filtering" => wgpu::SamplerBindingType::NonFiltering,
                "comparison" => wgpu::SamplerBindingType::Comparison,
                s => return Err(format!("'{s}' is not a valid GPUSamplerBindingType")),
            })
        } else if let Some(t) = get(e, "texture") {
            let sample_type = match string(t, "sampleType").unwrap_or("float") {
                "float" => wgpu::TextureSampleType::Float { filterable: true },
                "unfilterable-float" => wgpu::TextureSampleType::Float { filterable: false },
                "depth" => wgpu::TextureSampleType::Depth,
                "sint" => wgpu::TextureSampleType::Sint,
                "uint" => wgpu::TextureSampleType::Uint,
                s => return Err(format!("'{s}' is not a valid GPUTextureSampleType")),
            };
            wgpu::BindingType::Texture {
                sample_type,
                view_dimension: enum_of(t, "viewDimension", wgpu::TextureViewDimension::D2, fmt::view_dimension)?,
                multisampled: boolean(t, "multisampled", false),
            }
        } else if let Some(t) = get(e, "storageTexture") {
            let access = match string(t, "access").unwrap_or("write-only") {
                "write-only" => wgpu::StorageTextureAccess::WriteOnly,
                "read-only" => wgpu::StorageTextureAccess::ReadOnly,
                "read-write" => wgpu::StorageTextureAccess::ReadWrite,
                s => return Err(format!("'{s}' is not a valid GPUStorageTextureAccess")),
            };
            wgpu::BindingType::StorageTexture {
                access,
                format: req_enum(t, "format", fmt::texture_format)?,
                view_dimension: enum_of(t, "viewDimension", wgpu::TextureViewDimension::D2, fmt::view_dimension)?,
            }
        } else if get(e, "externalTexture").is_some() {
            return Err("externalTexture bindings are not supported".into());
        } else {
            // WebGPU: an entry with no binding member is a validation error, but the buffer
            // default is what pages that rely on `{}` dictionaries expect.
            wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }
        };
        out.push(wgpu::BindGroupLayoutEntry { binding, visibility, ty, count: None });
    }
    Ok(out)
}

/// `bindGroupLayouts`: ids, `None` for null entries (filled with an empty layout).
pub fn pipeline_layout(j: &J) -> R<Vec<Option<u32>>> {
    array(j, "bindGroupLayouts")
        .iter()
        .map(|v| match v {
            J::Null => Ok(None),
            J::Number(n) => Ok(Some(n.as_u64().unwrap_or(0) as u32)),
            v => Err(format!("bindGroupLayouts entries must be GPUBindGroupLayout, got {v}")),
        })
        .collect()
}

#[derive(Debug, Clone, PartialEq)]
pub enum BgResource {
    /// GPUBufferBinding
    Buffer { id: u32, offset: u64, size: Option<u64> },
    /// a GPUSampler, GPUTextureView, GPUTexture or GPUBuffer by id
    Object(u32),
}

#[derive(Debug, Clone, PartialEq)]
pub struct BindGroupSpec {
    pub label: Option<String>,
    pub layout: u32,
    pub entries: Vec<(u32, BgResource)>,
}

pub fn bind_group(j: &J) -> R<BindGroupSpec> {
    let layout = req_u32(j, "layout")?;
    let mut entries = Vec::new();
    for e in array(j, "entries") {
        let binding = req_u32(e, "binding")?;
        let r = get(e, "resource").ok_or("required member 'resource' is missing")?;
        let res = match r {
            J::Number(n) => BgResource::Object(n.as_u64().unwrap_or(0) as u32),
            J::Object(_) => BgResource::Buffer {
                id: req_u32(r, "buffer")?,
                offset: u64_of(r, "offset", 0)?,
                size: if get(r, "size").is_some() { Some(u64_of(r, "size", 0)?) } else { None },
            },
            v => return Err(format!("invalid binding resource {v}")),
        };
        entries.push((binding, res));
    }
    Ok(BindGroupSpec { label: label(j), layout, entries })
}

impl BindGroupSpec {
    /// Resolve ids. Bare textures are bound through a default view (kept in `scratch_views`).
    pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::BindGroup> {
        let layout = slab.bind_group_layout(self.layout)?;
        let mut views = Vec::new();
        for (_, r) in &self.entries {
            if let BgResource::Object(id) = r {
                if let Some(Res::Texture(t)) = slab.get(*id) {
                    views.push((*id, t.tex.create_view(&Default::default())));
                }
            }
        }
        let mut entries = Vec::with_capacity(self.entries.len());
        for (binding, r) in &self.entries {
            let resource = match r {
                BgResource::Buffer { id, offset, size } => {
                    let b = slab.buffer(*id)?;
                    wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &b.buf, offset: *offset, size: size.and_then(wgpu::BufferSize::new) })
                }
                BgResource::Object(id) => match slab.get(*id) {
                    Some(Res::Sampler(s)) => wgpu::BindingResource::Sampler(s),
                    Some(Res::View(ViewRes { view, .. })) => wgpu::BindingResource::TextureView(view),
                    Some(Res::Texture(_)) => wgpu::BindingResource::TextureView(&views.iter().find(|(i, _)| i == id).unwrap().1),
                    Some(Res::Buffer(b)) => wgpu::BindingResource::Buffer(b.buf.as_entire_buffer_binding()),
                    Some(other) => return Err(format!("binding {binding}: a {} cannot be bound", other.kind())),
                    None => return Err(format!("binding {binding}: invalid or destroyed object id {id}")),
                },
            };
            entries.push(wgpu::BindGroupEntry { binding: *binding, resource });
        }
        Ok(dev.create_bind_group(&wgpu::BindGroupDescriptor { label: self.label.as_deref(), layout, entries: &entries }))
    }
}

// ------------------------------------------------------------------------------------- pipelines

#[derive(Debug, Clone, PartialEq)]
pub struct StageSpec {
    pub module: u32,
    pub entry: Option<String>,
    pub constants: Vec<(String, f64)>,
}

fn stage(j: &J) -> R<StageSpec> {
    let mut constants = Vec::new();
    if let Some(c) = get(j, "constants").and_then(|c| c.as_object()) {
        for (k, v) in c {
            constants.push((k.clone(), v.as_f64().ok_or_else(|| format!("constant '{k}' must be a number"))?));
        }
    }
    Ok(StageSpec { module: req_u32(j, "module")?, entry: string(j, "entryPoint").map(str::to_owned), constants })
}

/// `"auto"` → `None`.
fn layout_ref(j: &J) -> R<Option<u32>> {
    match get(j, "layout") {
        Some(J::String(s)) if s == "auto" => Ok(None),
        Some(J::Number(n)) => Ok(Some(n.as_u64().unwrap_or(0) as u32)),
        None => Err("required member 'layout' is missing".into()),
        Some(v) => Err(format!("invalid pipeline layout {v}")),
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct VertexBufferSpec {
    pub stride: u64,
    pub step: wgpu::VertexStepMode,
    pub attributes: Vec<wgpu::VertexAttribute>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RenderPipelineSpec {
    pub label: Option<String>,
    pub layout: Option<u32>,
    pub vertex: StageSpec,
    pub buffers: Vec<VertexBufferSpec>,
    pub primitive: wgpu::PrimitiveState,
    pub depth_stencil: Option<wgpu::DepthStencilState>,
    pub multisample: wgpu::MultisampleState,
    pub fragment: Option<(StageSpec, Vec<Option<wgpu::ColorTargetState>>)>,
}

fn stencil_face(j: Option<&J>) -> R<wgpu::StencilFaceState> {
    let Some(j) = j else { return Ok(wgpu::StencilFaceState::IGNORE) };
    let op = |k: &str| enum_of(j, k, wgpu::StencilOperation::Keep, fmt::stencil_op);
    Ok(wgpu::StencilFaceState {
        compare: enum_of(j, "compare", wgpu::CompareFunction::Always, fmt::compare)?,
        fail_op: op("failOp")?,
        depth_fail_op: op("depthFailOp")?,
        pass_op: op("passOp")?,
    })
}

fn blend_component(j: Option<&J>) -> R<wgpu::BlendComponent> {
    let Some(j) = j else { return Ok(wgpu::BlendComponent::REPLACE) };
    Ok(wgpu::BlendComponent {
        src_factor: enum_of(j, "srcFactor", wgpu::BlendFactor::One, fmt::blend_factor)?,
        dst_factor: enum_of(j, "dstFactor", wgpu::BlendFactor::Zero, fmt::blend_factor)?,
        operation: enum_of(j, "operation", wgpu::BlendOperation::Add, fmt::blend_op)?,
    })
}

pub fn render_pipeline(j: &J) -> R<RenderPipelineSpec> {
    let vj = get(j, "vertex").ok_or("required member 'vertex' is missing")?;
    let mut buffers = Vec::new();
    for b in array(vj, "buffers") {
        if b.is_null() {
            buffers.push(VertexBufferSpec { stride: 0, step: wgpu::VertexStepMode::Vertex, attributes: Vec::new() });
            continue;
        }
        let mut attributes = Vec::new();
        for a in array(b, "attributes") {
            attributes.push(wgpu::VertexAttribute {
                format: req_enum(a, "format", fmt::vertex_format)?,
                offset: u64_of(a, "offset", 0)?,
                shader_location: req_u32(a, "shaderLocation")?,
            });
        }
        let step = match string(b, "stepMode").unwrap_or("vertex") {
            "vertex" => wgpu::VertexStepMode::Vertex,
            "instance" => wgpu::VertexStepMode::Instance,
            s => return Err(format!("'{s}' is not a valid GPUVertexStepMode")),
        };
        buffers.push(VertexBufferSpec { stride: u64_of(b, "arrayStride", 0)?, step, attributes });
    }
    let p = get(j, "primitive").cloned().unwrap_or(J::Null);
    let primitive = wgpu::PrimitiveState {
        topology: enum_of(&p, "topology", wgpu::PrimitiveTopology::TriangleList, fmt::topology)?,
        strip_index_format: if get(&p, "stripIndexFormat").is_some() { Some(req_enum(&p, "stripIndexFormat", fmt::index_format)?) } else { None },
        front_face: match string(&p, "frontFace").unwrap_or("ccw") {
            "ccw" => wgpu::FrontFace::Ccw,
            "cw" => wgpu::FrontFace::Cw,
            s => return Err(format!("'{s}' is not a valid GPUFrontFace")),
        },
        cull_mode: match string(&p, "cullMode").unwrap_or("none") {
            "none" => None,
            "front" => Some(wgpu::Face::Front),
            "back" => Some(wgpu::Face::Back),
            s => return Err(format!("'{s}' is not a valid GPUCullMode")),
        },
        unclipped_depth: boolean(&p, "unclippedDepth", false),
        polygon_mode: wgpu::PolygonMode::Fill,
        conservative: false,
    };
    let depth_stencil = match get(j, "depthStencil") {
        None => None,
        Some(d) => Some(wgpu::DepthStencilState {
            format: req_enum(d, "format", fmt::texture_format)?,
            depth_write_enabled: boolean(d, "depthWriteEnabled", false),
            depth_compare: enum_of(d, "depthCompare", wgpu::CompareFunction::Always, fmt::compare)?,
            stencil: wgpu::StencilState {
                front: stencil_face(get(d, "stencilFront"))?,
                back: stencil_face(get(d, "stencilBack"))?,
                read_mask: u32_of(d, "stencilReadMask", 0xFFFF_FFFF)?,
                write_mask: u32_of(d, "stencilWriteMask", 0xFFFF_FFFF)?,
            },
            bias: wgpu::DepthBiasState {
                constant: num(d, "depthBias", 0.0)? as i32,
                slope_scale: num(d, "depthBiasSlopeScale", 0.0)? as f32,
                clamp: num(d, "depthBiasClamp", 0.0)? as f32,
            },
        }),
    };
    let m = get(j, "multisample").cloned().unwrap_or(J::Null);
    let multisample = wgpu::MultisampleState {
        count: u32_of(&m, "count", 1)?,
        mask: u32_of(&m, "mask", 0xFFFF_FFFF)? as u64,
        alpha_to_coverage_enabled: boolean(&m, "alphaToCoverageEnabled", false),
    };
    let fragment = match get(j, "fragment") {
        None => None,
        Some(f) => {
            let mut targets = Vec::new();
            for t in array(f, "targets") {
                if t.is_null() {
                    targets.push(None);
                    continue;
                }
                let blend = match get(t, "blend") {
                    None => None,
                    Some(b) => Some(wgpu::BlendState { color: blend_component(get(b, "color"))?, alpha: blend_component(get(b, "alpha"))? }),
                };
                targets.push(Some(wgpu::ColorTargetState {
                    format: req_enum(t, "format", fmt::texture_format)?,
                    blend,
                    write_mask: wgpu::ColorWrites::from_bits_truncate(u32_of(t, "writeMask", 0xF)?),
                }));
            }
            Some((stage(f)?, targets))
        }
    };
    Ok(RenderPipelineSpec { label: label(j), layout: layout_ref(j)?, vertex: stage(vj)?, buffers, primitive, depth_stencil, multisample, fragment })
}

fn constants(s: &StageSpec) -> Vec<(&str, f64)> {
    s.constants.iter().map(|(k, v)| (k.as_str(), *v)).collect()
}

fn options<'a>(c: &'a [(&'a str, f64)]) -> wgpu::PipelineCompilationOptions<'a> {
    wgpu::PipelineCompilationOptions { constants: c, zero_initialize_workgroup_memory: true }
}

impl RenderPipelineSpec {
    pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::RenderPipeline> {
        let layout = match self.layout {
            Some(id) => Some(slab.pipeline_layout(id)?),
            None => None,
        };
        let vmod = &slab.shader(self.vertex.module)?.module;
        let vconst = constants(&self.vertex);
        let buffers: Vec<wgpu::VertexBufferLayout> =
            self.buffers.iter().map(|b| wgpu::VertexBufferLayout { array_stride: b.stride, step_mode: b.step, attributes: &b.attributes }).collect();
        let fconst = self.fragment.as_ref().map(|(s, _)| constants(s)).unwrap_or_default();
        let fragment = match &self.fragment {
            None => None,
            Some((s, targets)) => Some(wgpu::FragmentState {
                module: &slab.shader(s.module)?.module,
                entry_point: s.entry.as_deref(),
                compilation_options: options(&fconst),
                targets,
            }),
        };
        Ok(dev.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: self.label.as_deref(),
            layout,
            vertex: wgpu::VertexState { module: vmod, entry_point: self.vertex.entry.as_deref(), compilation_options: options(&vconst), buffers: &buffers },
            primitive: self.primitive,
            depth_stencil: self.depth_stencil.clone(),
            multisample: self.multisample,
            fragment,
            multiview: None,
            cache: None,
        }))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ComputePipelineSpec {
    pub label: Option<String>,
    pub layout: Option<u32>,
    pub stage: StageSpec,
}

pub fn compute_pipeline(j: &J) -> R<ComputePipelineSpec> {
    let c = get(j, "compute").ok_or("required member 'compute' is missing")?;
    Ok(ComputePipelineSpec { label: label(j), layout: layout_ref(j)?, stage: stage(c)? })
}

impl ComputePipelineSpec {
    pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::ComputePipeline> {
        let layout = match self.layout {
            Some(id) => Some(slab.pipeline_layout(id)?),
            None => None,
        };
        let c = constants(&self.stage);
        Ok(dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: self.label.as_deref(),
            layout,
            module: &slab.shader(self.stage.module)?.module,
            entry_point: self.stage.entry.as_deref(),
            compilation_options: options(&c),
            cache: None,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn texture_descriptor() {
        let t = texture(&json!({"size": [256, 128], "format": "rgba8unorm-srgb", "usage": 0x16, "mipLevelCount": 9, "label": "albedo"})).unwrap();
        assert_eq!(t.size, wgpu::Extent3d { width: 256, height: 128, depth_or_array_layers: 1 });
        assert_eq!(t.format, TextureFormat::Rgba8UnormSrgb);
        assert_eq!(t.mips, 9);
        assert_eq!(t.samples, 1);
        assert_eq!(t.dimension, wgpu::TextureDimension::D2);
        assert_eq!(t.usage, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT);
        assert_eq!(t.label.as_deref(), Some("albedo"));
        let t = texture(&json!({"size": {"width": 4, "depthOrArrayLayers": 6}, "format": "depth24plus", "usage": 16, "dimension": "2d", "viewFormats": []})).unwrap();
        assert_eq!(t.size, wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 6 });
        assert!(texture(&json!({"size": [4, 4], "format": "rgba9unorm", "usage": 1})).unwrap_err().contains("rgba9unorm"));
        assert!(texture(&json!({"format": "rgba8unorm", "usage": 1})).unwrap_err().contains("size"));
        assert!(texture(&json!({"size": [], "format": "rgba8unorm", "usage": 1})).is_err());
    }

    #[test]
    fn view_and_sampler() {
        let v = view(&json!({"dimension": "cube", "aspect": "depth-only", "baseMipLevel": 2, "mipLevelCount": 1})).unwrap();
        assert_eq!(v.dimension, Some(wgpu::TextureViewDimension::Cube));
        assert_eq!(v.aspect, wgpu::TextureAspect::DepthOnly);
        assert_eq!((v.base_mip, v.mip_count, v.layer_count), (2, Some(1), None));
        assert_eq!(view(&J::Null).unwrap(), ViewSpec::default());
        let s = sampler(&json!({"magFilter": "linear", "addressModeU": "repeat", "compare": "less-equal", "maxAnisotropy": 4})).unwrap();
        assert_eq!(s.mag_filter, wgpu::FilterMode::Linear);
        assert_eq!(s.min_filter, wgpu::FilterMode::Nearest);
        assert_eq!(s.address_mode_u, wgpu::AddressMode::Repeat);
        assert_eq!(s.address_mode_v, wgpu::AddressMode::ClampToEdge);
        assert_eq!(s.compare, Some(wgpu::CompareFunction::LessEqual));
        assert_eq!((s.anisotropy_clamp, s.lod_max_clamp), (4, 32.0));
        assert!(sampler(&json!({"magFilter": "cubic"})).is_err());
    }

    #[test]
    fn layouts_and_groups() {
        let e = bind_group_layout(&json!({"entries": [
            {"binding": 0, "visibility": 3, "buffer": {"type": "uniform", "hasDynamicOffset": true}},
            {"binding": 1, "visibility": 2, "sampler": {"type": "comparison"}},
            {"binding": 2, "visibility": 2, "texture": {"sampleType": "depth", "viewDimension": "2d-array"}},
            {"binding": 3, "visibility": 4, "storageTexture": {"format": "rgba16float", "access": "read-write"}},
            {"binding": 4, "visibility": 2, "texture": {}},
        ]}))
        .unwrap();
        assert_eq!(e.len(), 5);
        assert_eq!(e[0].visibility, wgpu::ShaderStages::VERTEX_FRAGMENT);
        assert!(matches!(e[0].ty, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: None }));
        assert!(matches!(e[1].ty, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)));
        assert!(matches!(e[2].ty, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false }));
        assert!(matches!(e[3].ty, wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::ReadWrite, format: TextureFormat::Rgba16Float, .. }));
        assert!(matches!(e[4].ty, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, .. }));
        assert_eq!(pipeline_layout(&json!({"bindGroupLayouts": [5, null, 7]})).unwrap(), vec![Some(5), None, Some(7)]);
        let g = bind_group(&json!({"layout": 9, "entries": [{"binding": 0, "resource": {"buffer": 3, "offset": 256, "size": 64}}, {"binding": 1, "resource": 12}]})).unwrap();
        assert_eq!(g.layout, 9);
        assert_eq!(g.entries, vec![(0, BgResource::Buffer { id: 3, offset: 256, size: Some(64) }), (1, BgResource::Object(12))]);
        assert!(bind_group(&json!({"layout": 9, "entries": [{"binding": 0}]})).is_err());
    }

    #[test]
    fn render_pipeline_descriptor() {
        let p = render_pipeline(&json!({
            "layout": "auto",
            "vertex": {"module": 4, "entryPoint": "main", "buffers": [
                {"arrayStride": 12, "attributes": [{"format": "float32x3", "offset": 0, "shaderLocation": 0}]},
                null,
                {"arrayStride": 64, "stepMode": "instance", "attributes": [{"format": "float32x4", "offset": 16, "shaderLocation": 3}]}
            ]},
            "primitive": {"topology": "triangle-strip", "stripIndexFormat": "uint32", "cullMode": "back", "frontFace": "cw"},
            "depthStencil": {"format": "depth24plus-stencil8", "depthWriteEnabled": true, "depthCompare": "less-equal", "stencilFront": {"passOp": "replace"}, "depthBias": -2},
            "multisample": {"count": 4, "alphaToCoverageEnabled": true},
            "fragment": {"module": 5, "constants": {"k": 2}, "targets": [
                {"format": "bgra8unorm", "blend": {"color": {"srcFactor": "src-alpha", "dstFactor": "one-minus-src-alpha"}, "alpha": {}}, "writeMask": 7},
                null
            ]}
        }))
        .unwrap();
        assert_eq!(p.layout, None);
        assert_eq!(p.vertex, StageSpec { module: 4, entry: Some("main".into()), constants: vec![] });
        assert_eq!(p.buffers.len(), 3);
        assert_eq!(p.buffers[1].stride, 0);
        assert_eq!(p.buffers[2].step, wgpu::VertexStepMode::Instance);
        assert_eq!(p.buffers[2].attributes[0].shader_location, 3);
        assert_eq!(p.primitive.topology, wgpu::PrimitiveTopology::TriangleStrip);
        assert_eq!(p.primitive.strip_index_format, Some(wgpu::IndexFormat::Uint32));
        assert_eq!(p.primitive.cull_mode, Some(wgpu::Face::Back));
        assert_eq!(p.primitive.front_face, wgpu::FrontFace::Cw);
        let ds = p.depth_stencil.unwrap();
        assert!(ds.depth_write_enabled);
        assert_eq!(ds.depth_compare, wgpu::CompareFunction::LessEqual);
        assert_eq!(ds.stencil.front.pass_op, wgpu::StencilOperation::Replace);
        assert_eq!(ds.stencil.back, wgpu::StencilFaceState::IGNORE);
        assert_eq!(ds.bias.constant, -2);
        assert_eq!((p.multisample.count, p.multisample.mask, p.multisample.alpha_to_coverage_enabled), (4, 0xFFFF_FFFF, true));
        let (fs, targets) = p.fragment.unwrap();
        assert_eq!(fs.entry, None);
        assert_eq!(fs.constants, vec![("k".to_string(), 2.0)]);
        let t = targets[0].clone().unwrap();
        assert_eq!(t.write_mask, wgpu::ColorWrites::RED | wgpu::ColorWrites::GREEN | wgpu::ColorWrites::BLUE);
        assert_eq!(t.blend.unwrap().color.src_factor, wgpu::BlendFactor::SrcAlpha);
        assert_eq!(t.blend.unwrap().alpha, wgpu::BlendComponent::REPLACE);
        assert!(targets[1].is_none());
        assert!(render_pipeline(&json!({"layout": "auto", "vertex": {"module": 1}, "primitive": {"topology": "quads"}})).is_err());
        assert!(render_pipeline(&json!({"vertex": {"module": 1}})).unwrap_err().contains("layout"));
        let c = compute_pipeline(&json!({"layout": 8, "compute": {"module": 2, "entryPoint": "cs"}})).unwrap();
        assert_eq!((c.layout, c.stage.module, c.stage.entry.as_deref()), (Some(8), 2, Some("cs")));
    }
}