yum/demomo

A graphics engine built on wgpu.

git clone https://git.yummers.dev/yum/demomo

yumSmall cleanups7977998

master
58.3 KiB1839 linesraw
1use anyhow::Context;
2use bytemuck::NoUninit;
3use derive_builder::Builder;
4use std::borrow::Cow;
5use std::num::NonZeroU64;
6#[cfg(feature = "window")]
7use std::sync::Arc;
8use std::sync::mpsc::{Receiver, Sender};
9use wgpu::naga;
10use wgpu::util::DeviceExt;
11
12#[macro_export]
13macro_rules! include_wgsl {
14    ($filename:literal) => {
15        include_str!(concat!(env!("OUT_DIR"), "/shaders/", $filename))
16    };
17}
18
19// Magic to allow converting a primitive type, a Vec, or a slice into a slice of bytes.
20pub trait Buffer<T> {
21    fn as_bytes(&self) -> &[T];
22}
23impl<T: bytemuck::Pod> Buffer<T> for T {
24    fn as_bytes(&self) -> &[T] {
25        std::slice::from_ref(self)
26    }
27}
28impl<T> Buffer<T> for Vec<T> {
29    fn as_bytes(&self) -> &[T] {
30        self.as_slice()
31    }
32}
33impl<T> Buffer<T> for &[T] {
34    fn as_bytes(&self) -> &[T] {
35        self
36    }
37}
38
39pub struct BufferBuilder<'a> {
40    label: Option<String>,
41    size: u64,
42    usage: wgpu::BufferUsages,
43    mapped_at_creation: bool,
44    gpu: &'a Gpu,
45}
46
47impl<'a> BufferBuilder<'a> {
48    fn new<T: bytemuck::Pod>(data: &impl Buffer<T>, gpu: &'a Gpu) -> Self {
49        Self::new_by_sz(std::mem::size_of_val(data.as_bytes()), gpu)
50    }
51
52    fn new_by_sz(sz: usize, gpu: &'a Gpu) -> Self {
53        Self {
54            label: None,
55            size: wgpu::util::align_to(sz, 16) as u64,
56            usage: wgpu::BufferUsages::empty(),
57            mapped_at_creation: false,
58            gpu: gpu,
59        }
60    }
61
62    pub fn copy_dst(&mut self) -> &mut Self {
63        self.usage |= wgpu::BufferUsages::COPY_DST;
64        self
65    }
66
67    pub fn copy_src(&mut self) -> &mut Self {
68        self.usage |= wgpu::BufferUsages::COPY_SRC;
69        self
70    }
71
72    pub fn map_read(&mut self) -> &mut Self {
73        self.usage |= wgpu::BufferUsages::MAP_READ;
74        self
75    }
76
77    pub fn query_resolve(&mut self) -> &mut Self {
78        self.usage |= wgpu::BufferUsages::QUERY_RESOLVE;
79        self
80    }
81
82    pub fn storage(&mut self) -> &mut Self {
83        self.usage |= wgpu::BufferUsages::STORAGE;
84        self
85    }
86
87    pub fn uniform(&mut self) -> &mut Self {
88        self.usage |= wgpu::BufferUsages::UNIFORM;
89        self
90    }
91
92    pub fn build(&self) -> wgpu::Buffer {
93        self.gpu.device.create_buffer(&wgpu::BufferDescriptor {
94            label: self.label.as_deref(),
95            size: self.size,
96            usage: self.usage,
97            mapped_at_creation: self.mapped_at_creation,
98        })
99    }
100}
101
102pub struct GpuBuilder {
103    required_features: wgpu::Features,
104    #[cfg(feature = "window")]
105    window: Option<Arc<winit::window::Window>>,
106}
107
108impl GpuBuilder {
109    pub fn new() -> Self {
110        Self {
111            required_features: wgpu::Features::empty(),
112            #[cfg(feature = "window")]
113            window: None,
114        }
115    }
116
117    pub fn enable_profiling(mut self) -> Self {
118        self.required_features |= wgpu::Features::TIMESTAMP_QUERY;
119        self
120    }
121
122    #[cfg(feature = "window")]
123    pub fn window(mut self, window: winit::window::Window) -> Self {
124        self.window = Some(Arc::new(window));
125        self
126    }
127
128    pub async fn build(self) -> anyhow::Result<Gpu> {
129        #[cfg(feature = "window")]
130        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
131            backends: wgpu::Backends::PRIMARY,
132            flags: Default::default(),
133            memory_budget_thresholds: Default::default(),
134            backend_options: Default::default(),
135            display: None,
136        });
137        #[cfg(not(feature = "window"))]
138        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
139
140        #[cfg(feature = "window")]
141        let surface = self
142            .window
143            .as_ref()
144            .map(|window| instance.create_surface(window.clone()))
145            .transpose()?;
146        #[cfg(feature = "window")]
147        let adapter_req_opt = wgpu::RequestAdapterOptions {
148            power_preference: wgpu::PowerPreference::default(),
149            compatible_surface: surface.as_ref(),
150            force_fallback_adapter: false,
151            apply_limit_buckets: true,
152        };
153        #[cfg(not(feature = "window"))]
154        let adapter_req_opt = wgpu::RequestAdapterOptions::default();
155        let adapter = instance.request_adapter(&adapter_req_opt).await?;
156        println!("Got adapter: {:#?}", adapter.get_info());
157
158        let supported = adapter.limits();
159        let mut limits = wgpu::Limits::downlevel_defaults();
160        limits.max_compute_invocations_per_workgroup =
161            supported.max_compute_invocations_per_workgroup;
162        limits.max_compute_workgroup_storage_size = supported.max_compute_workgroup_storage_size;
163        println!(
164            "Max compute invocations per workgroup: {}",
165            limits.max_compute_invocations_per_workgroup
166        );
167
168        let (device, queue) = adapter
169            .request_device(&wgpu::DeviceDescriptor {
170                label: None,
171                required_features: self.required_features,
172                required_limits: limits,
173                experimental_features: wgpu::ExperimentalFeatures::disabled(),
174                memory_hints: wgpu::MemoryHints::MemoryUsage,
175                trace: wgpu::Trace::Off,
176            })
177            .await?;
178
179        let mut timestamps = None;
180        if self
181            .required_features
182            .contains(wgpu::Features::TIMESTAMP_QUERY)
183        {
184            timestamps = Some(device.create_query_set(&wgpu::QuerySetDescriptor {
185                label: None,
186                ty: wgpu::QueryType::Timestamp,
187                count: 2,
188            }));
189        }
190
191        Ok(Gpu {
192            instance,
193            adapter,
194            device,
195            queue,
196            #[cfg(feature = "window")]
197            window: self.window,
198            #[cfg(feature = "window")]
199            surface: surface,
200            timestamps,
201        })
202    }
203}
204
205pub struct Gpu {
206    pub instance: wgpu::Instance,
207    pub adapter: wgpu::Adapter,
208    pub device: wgpu::Device,
209    pub queue: wgpu::Queue,
210    #[cfg(feature = "window")]
211    pub window: Option<Arc<winit::window::Window>>,
212    #[cfg(feature = "window")]
213    pub surface: Option<wgpu::Surface<'static>>,
214    pub timestamps: Option<wgpu::QuerySet>,
215}
216
217impl Gpu {
218    pub fn buffer<T: bytemuck::Pod>(&self, data: &impl Buffer<T>) -> BufferBuilder<'_> {
219        BufferBuilder::new(data, self)
220    }
221
222    pub fn buffer_by_sz(&self, sz: usize) -> BufferBuilder<'_> {
223        BufferBuilder::new_by_sz(sz, self)
224    }
225}
226
227fn get_entry_point_names(module: &naga::Module) -> anyhow::Result<Vec<String>> {
228    if module.entry_points.is_empty() {
229        anyhow::bail!("Expected at least one entry point, found none.");
230    }
231    Ok(module.entry_points.iter().map(|e| e.name.clone()).collect())
232}
233
234fn get_entry_point_workgroup_size(module: &naga::Module, name: &str) -> anyhow::Result<[u32; 3]> {
235    for entry_point in module.entry_points.iter() {
236        if entry_point.name != name {
237            continue;
238        }
239        return Ok(entry_point.workgroup_size);
240    }
241    anyhow::bail!("Could not find entry point named {}", name);
242}
243
244fn get_bind_group_layout(
245    gpu: &Gpu,
246    module: &naga::Module,
247    module_info: &naga::valid::ModuleInfo,
248    module_layout: &naga::proc::Layouter,
249) -> anyhow::Result<wgpu::BindGroupLayout> {
250    let mut entries = Vec::<wgpu::BindGroupLayoutEntry>::new();
251    for (global_handle, global) in module.global_variables.iter() {
252        let Some(binding) = &global.binding else {
253            continue;
254        };
255
256        let buffer_type = match global.space {
257            naga::AddressSpace::Storage { access } => wgpu::BufferBindingType::Storage {
258                read_only: !access
259                    .intersects(naga::StorageAccess::STORE | naga::StorageAccess::ATOMIC),
260            },
261            naga::AddressSpace::Uniform => wgpu::BufferBindingType::Uniform,
262            _ => {
263                eprintln!(
264                    "Skipping global {:?} with address space {:?}",
265                    global.name, global.space
266                );
267                continue;
268            }
269        };
270
271        let mut stages = wgpu::ShaderStages::empty();
272        for (entry_idx, entry) in module.entry_points.iter().enumerate() {
273            let usage = module_info.get_entry_point(entry_idx)[global_handle];
274            if usage.is_empty() {
275                continue;
276            }
277
278            stages |= match entry.stage {
279                naga::ShaderStage::Vertex => wgpu::ShaderStages::VERTEX,
280                naga::ShaderStage::Fragment => wgpu::ShaderStages::FRAGMENT,
281                naga::ShaderStage::Compute => wgpu::ShaderStages::COMPUTE,
282                _ => continue,
283            }
284        }
285        if stages.is_empty() {
286            eprintln!(
287                "Skipping bound global {:?} which is not referenced by any stage",
288                global.name
289            );
290            continue;
291        }
292
293        let min_size = module_layout[global.ty].size;
294        entries.push(wgpu::BindGroupLayoutEntry {
295            binding: binding.binding,
296            visibility: stages,
297            ty: wgpu::BindingType::Buffer {
298                ty: buffer_type,
299                min_binding_size: NonZeroU64::new(min_size as u64),
300                has_dynamic_offset: false,
301            },
302            count: None,
303        });
304    }
305    let layout = wgpu::BindGroupLayoutDescriptor {
306        label: None,
307        entries: &entries,
308    };
309    Ok(gpu.device.create_bind_group_layout(&layout))
310}
311
312pub struct ShaderEntryPoint {
313    pub name: String,
314    pub workgroup_size: [u32; 3],
315}
316
317#[derive(PartialEq, Eq)]
318pub enum VertexSemantic {
319    Position,
320    Normal,
321    Uv0,
322    Tangent,
323    Bitangent,
324}
325
326/// The layout of vertex data that a specific shader expects.
327pub struct VertexLayout {
328    pub semantics: Vec<VertexSemantic>,
329    pub attributes: Vec<wgpu::VertexAttribute>,
330    pub stride: u64,
331}
332
333// Vertex data is conceived of as zero or more streams of data. We need a way
334// to translate various higher-level types (f32, i32, etc) into these untyped
335// streams, and finally at the end, get an array of them. This builder handles
336// doing exactly that.
337// Example usage:
338//  let positions = [[-0.5_f32, -0.5, 0.5], [0.5, -0.5, 0.5], [0.0, 0.5, 0.5]];
339//  let normals = [[0.0_f32, 0.0, 1.0]; 3];
340//  let uvs = [[0.0_f32, 0.0], [1.0, 0.0], [0.5, 1.0]];
341//  let data_streams = VertexDataStreamBuilder::new()
342//      .stream(VertexSemantic::Position, &positions)
343//      .stream(VertexSemantic::Normal, &normals)
344//      .stream(VertexSemantic::Uv0, &uvs)
345//      .build();
346pub struct VertexDataStreamBuilder<'a> {
347    streams: Vec<(VertexSemantic, &'a [u8])>,
348}
349
350impl<'a> VertexDataStreamBuilder<'a> {
351    pub fn new() -> Self {
352        Self {
353            streams: Vec::new(),
354        }
355    }
356
357    pub fn stream<T: NoUninit>(mut self, semantic: VertexSemantic, data: &'a [T]) -> Self {
358        let raw_data: &[u8] = bytemuck::cast_slice(&data);
359        self.streams.push((semantic, raw_data));
360        self
361    }
362
363    pub fn build(self) -> Vec<(VertexSemantic, &'a [u8])> {
364        self.streams
365    }
366}
367
368impl VertexLayout {
369    pub fn vertex_buffer_layout(&self) -> wgpu::VertexBufferLayout<'_> {
370        wgpu::VertexBufferLayout {
371            array_stride: self.stride,
372            step_mode: wgpu::VertexStepMode::Vertex,
373            attributes: &self.attributes,
374        }
375    }
376
377    // Assembles streams of vertex data into an interleaved stream.
378    fn interleave_data(
379        &self,
380        n_vertices: usize,
381        data_streams: Vec<(VertexSemantic, &[u8])>,
382    ) -> anyhow::Result<Vec<u8>> {
383        let mut streams: Vec<_> = self
384            .semantics
385            .iter()
386            .zip(&self.attributes)
387            .map(|(semantic, attr)| {
388                let (_, data) = data_streams
389                    .iter()
390                    .find(|(s, _)| s == semantic)
391                    .context("Vertex shader given unrecognized input semantic")?;
392                let size = attr.format.size() as usize;
393                let start = attr.offset as usize;
394                Ok((start..start + size, data.chunks_exact(size)))
395            })
396            .collect::<anyhow::Result<_>>()?;
397
398        let stride = self.stride as usize;
399        let mut data = vec![0; n_vertices * stride];
400
401        for vertex in data.chunks_exact_mut(stride) {
402            for (range, source) in &mut streams {
403                let value = source.next().context("Not enough vertex data")?;
404                vertex[range.clone()].copy_from_slice(value);
405            }
406        }
407
408        Ok(data)
409    }
410
411    pub fn vertex_buffer(
412        &self,
413        gpu: &Gpu,
414        data_streams: Vec<(VertexSemantic, &[u8])>,
415        n_vertices: usize,
416    ) -> anyhow::Result<wgpu::Buffer> {
417        let vertex_data_bytes = self.interleave_data(n_vertices, data_streams)?;
418        Ok(gpu
419            .device
420            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
421                label: None,
422                contents: &vertex_data_bytes,
423                usage: wgpu::BufferUsages::VERTEX,
424            }))
425    }
426}
427
428pub struct Shader {
429    pub bind_group_layout: wgpu::BindGroupLayout,
430    pub naga_module: naga::Module,
431    pub shader_module: wgpu::ShaderModule,
432    pub entry_points: Vec<ShaderEntryPoint>,
433    pub camera_binding: Option<naga::ResourceBinding>,
434    pub transform_binding: Option<naga::ResourceBinding>,
435    pub light_binding: Option<naga::ResourceBinding>,
436    pub cfg_binding: Option<naga::ResourceBinding>,
437}
438
439impl Shader {
440    pub fn new(gpu: &Gpu, shader: &str) -> anyhow::Result<Self> {
441        let naga_module = naga::front::wgsl::parse_str(shader)?;
442        let module_info = naga::valid::Validator::new(
443            naga::valid::ValidationFlags::all(),
444            naga::valid::Capabilities::all(),
445        )
446        .validate(&naga_module)?;
447        let mut module_layout = naga::proc::Layouter::default();
448        module_layout.update(naga_module.to_ctx())?;
449
450        Self::ensure_compute_compatibility(gpu, &naga_module)?;
451        let bind_group_layout =
452            get_bind_group_layout(gpu, &naga_module, &module_info, &module_layout)?;
453
454        let find_uniform_binding = |name: &str| {
455            naga_module.global_variables.iter().find_map(|(_, global)| {
456                if global.space != naga::AddressSpace::Uniform {
457                    return None;
458                }
459                let Some(global_name) = &global.name else {
460                    return None;
461                };
462                if global_name.split('_').next() != Some(name) {
463                    return None;
464                }
465                return global.binding;
466            })
467        };
468        let camera_binding = find_uniform_binding("camera");
469        let transform_binding = find_uniform_binding("transform");
470        let light_binding = find_uniform_binding("light");
471        let cfg_binding = find_uniform_binding("cfg");
472
473        let entry_point_names = get_entry_point_names(&naga_module)?;
474        let entry_points = entry_point_names
475            .iter()
476            .map(|name| {
477                let workgroup_size = get_entry_point_workgroup_size(&naga_module, name)?;
478                Ok(ShaderEntryPoint {
479                    name: name.clone(),
480                    workgroup_size,
481                })
482            })
483            .collect::<anyhow::Result<Vec<_>>>()?;
484
485        let module_descriptor = wgpu::ShaderModuleDescriptor {
486            label: None,
487            source: wgpu::ShaderSource::Naga(Cow::Owned(naga_module.clone())),
488        };
489        let shader_module = gpu.device.create_shader_module(module_descriptor.clone());
490
491        Ok(Self {
492            bind_group_layout,
493            naga_module: naga_module,
494            shader_module,
495            entry_points,
496            camera_binding,
497            transform_binding,
498            light_binding,
499            cfg_binding,
500        })
501    }
502
503    fn ensure_compute_compatibility(gpu: &Gpu, module: &naga::Module) -> anyhow::Result<()> {
504        let mut has_compute_stage = false;
505        for entry_point in module.entry_points.iter() {
506            if entry_point.stage == naga::ShaderStage::Compute {
507                has_compute_stage = true;
508            }
509        }
510        if !has_compute_stage {
511            return Ok(());
512        }
513        let downlevel_caps = gpu.adapter.get_downlevel_capabilities();
514        if !downlevel_caps
515            .flags
516            .contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
517        {
518            anyhow::bail!(
519                "GPU {} does not support compute shaders.",
520                gpu.adapter.get_info().name
521            )
522        }
523        Ok(())
524    }
525
526    // Returns the first shader entry point for the given stage.
527    pub fn get_shader_by_stage(
528        &self,
529        stage: naga::ir::ShaderStage,
530    ) -> anyhow::Result<&naga::EntryPoint> {
531        let Some(shader) = self
532            .naga_module
533            .entry_points
534            .iter()
535            .find(|ep| ep.stage == stage)
536        else {
537            anyhow::bail!("Shader not found for stage {:?}", stage);
538        };
539        Ok(shader)
540    }
541
542    fn vertex_member_to_semantic(&self, name: &str) -> anyhow::Result<VertexSemantic> {
543        // Vertex members might be suffixed with _0 by slangc. Since none of our reserved names have underscores, we
544        // can safely split by underscore.
545        let name = name.split('_').collect::<Vec<_>>()[0];
546        match name {
547            "objPos" => Ok(VertexSemantic::Position),
548            "normal" => Ok(VertexSemantic::Normal),
549            "uv0" => Ok(VertexSemantic::Uv0),
550            "tangent" => Ok(VertexSemantic::Tangent),
551            "bitangent" => Ok(VertexSemantic::Bitangent),
552            _ => anyhow::bail!("Unknown vertex member: {}", name),
553        }
554    }
555
556    fn struct_member_to_vertex_format(
557        &self,
558        member: &naga::ir::StructMember,
559    ) -> anyhow::Result<wgpu::VertexFormat> {
560        let inner_type = &self.naga_module.types[member.ty].inner;
561        match inner_type {
562            naga::TypeInner::Vector { size, scalar } => match (scalar.kind, scalar.width) {
563                (naga::ScalarKind::Float, 4) => match size {
564                    naga::VectorSize::Bi => Ok(wgpu::VertexFormat::Float32x2),
565                    naga::VectorSize::Tri => Ok(wgpu::VertexFormat::Float32x3),
566                    naga::VectorSize::Quad => Ok(wgpu::VertexFormat::Float32x4),
567                },
568                _ => anyhow::bail!("Unsupported vertex member vector type: {:?}", inner_type),
569            },
570            _ => anyhow::bail!("Unsupported vertex member type: {:?}", inner_type),
571        }
572    }
573
574    fn struct_member_shader_location(
575        &self,
576        member: &naga::ir::StructMember,
577    ) -> anyhow::Result<wgpu::ShaderLocation> {
578        match &member.binding {
579            Some(naga::Binding::Location { location, .. }) => Ok(*location),
580            // TODO should handle built-in bindings
581            _ => anyhow::bail!("Unsupported vertex member binding: {:?}", member.binding),
582        }
583    }
584
585    pub fn get_vertex_layout(&self) -> anyhow::Result<VertexLayout> {
586        let vertex_shader = self.get_shader_by_stage(naga::ir::ShaderStage::Vertex)?;
587        if vertex_shader.function.arguments.len() != 1 {
588            anyhow::bail!(
589                "Vertex shader must have exactly one argument; got {}",
590                vertex_shader.function.arguments.len()
591            );
592        }
593        let arg = &vertex_shader.function.arguments[0];
594        let arg_ty = &self.naga_module.types[arg.ty];
595        match &arg_ty.inner {
596            naga::ir::TypeInner::Struct { members, .. } => {
597                let semantics = members
598                    .iter()
599                    .map(|m| {
600                        let Some(name) = &m.name else {
601                            // This should never happen
602                            anyhow::bail!("Vertex shader input member missing name");
603                        };
604                        self.vertex_member_to_semantic(name.as_str())
605                    })
606                    .collect::<anyhow::Result<Vec<_>>>()?;
607                let mut acc_offset = 0;
608                let attributes = members
609                    .iter()
610                    .map(|m| -> anyhow::Result<wgpu::VertexAttribute> {
611                        let vertex_fmt = self.struct_member_to_vertex_format(m)?;
612                        let location = self.struct_member_shader_location(m)?;
613                        let offset = acc_offset;
614                        acc_offset += vertex_fmt.size();
615                        Ok(wgpu::VertexAttribute {
616                            format: vertex_fmt,
617                            offset,
618                            shader_location: location,
619                        })
620                    })
621                    .collect::<anyhow::Result<Vec<_>>>()?;
622                let stride = attributes.iter().fold(0, |acc, a| acc + a.format.size());
623                Ok(VertexLayout {
624                    semantics,
625                    attributes,
626                    stride,
627                })
628            }
629            _ => {
630                anyhow::bail!("Argument type must be a struct; got {:?}", arg_ty.inner);
631            }
632        }
633    }
634}
635
636pub struct MaterialPass {
637    pub buffers: Vec<wgpu::Buffer>,
638    pub bind_group: wgpu::BindGroup,
639}
640
641pub struct MaterialPassBuilder {
642    buffers: Vec<wgpu::Buffer>,
643    bind_group: Option<wgpu::BindGroup>,
644}
645
646impl MaterialPassBuilder {
647    pub fn new() -> Self {
648        Self {
649            buffers: Vec::new(),
650            bind_group: None,
651        }
652    }
653
654    pub fn buffers(mut self, buffers: Vec<wgpu::Buffer>) -> Self {
655        self.buffers = buffers;
656        self
657    }
658
659    // Must be run after buffers(), etc.
660    pub fn bind_group(mut self, gpu: &Gpu, shader: &Shader) -> Self {
661        let mut descriptor_entries = Vec::<wgpu::BindGroupEntry>::new();
662        let entries =
663            self.buffers
664                .iter()
665                .enumerate()
666                .fold(Vec::new(), |mut entries, (index, buf)| {
667                    entries.push(wgpu::BindGroupEntry {
668                        binding: index as u32,
669                        resource: buf.as_entire_binding(),
670                    });
671                    entries
672                });
673        descriptor_entries.extend(entries);
674        let descriptor = wgpu::BindGroupDescriptor {
675            label: None,
676            layout: &shader.bind_group_layout,
677            entries: &descriptor_entries,
678        };
679        let bind_group = gpu.device.create_bind_group(&descriptor);
680        self.bind_group = Some(bind_group);
681        self
682    }
683
684    pub fn build(self) -> anyhow::Result<MaterialPass> {
685        if self.bind_group.is_none() {
686            anyhow::bail!("bind_group not set");
687        }
688        Ok(MaterialPass {
689            buffers: self.buffers,
690            bind_group: self.bind_group.unwrap(),
691        })
692    }
693}
694
695pub struct MaterialInstance {
696    pub passes: Vec<MaterialPass>,
697    pub readback: Option<wgpu::Buffer>,
698}
699
700impl MaterialInstance {
701    pub fn new(passes: Vec<MaterialPass>, readback: Option<wgpu::Buffer>) -> Self {
702        Self {
703            passes: passes,
704            readback: readback,
705        }
706    }
707}
708
709// A batch of Material work to be submitted together. This allows us to send a
710// batch of work while another is still processing on the GPU.
711pub struct MaterialBatch {
712    pub instances: Vec<MaterialInstance>,
713    pub ready_tx: Sender<(usize, Result<(), wgpu::BufferAsyncError>)>,
714    pub ready_rx: Receiver<(usize, Result<(), wgpu::BufferAsyncError>)>,
715    // Optional timestamp (ts) buffers for profiling.
716    pub timing: Option<MaterialTiming>,
717    // Whether the batch is currently processing. This is set true as soon as a batch is reserved with get_batch().
718    // The caller is responsible for setting this false
719    pub busy: bool,
720    // How many instances in the batch are currently processing. Set to
721    // batch_size (n_instancces) when the batch is reserved The caller may use
722    // this to track completion as each instance in the batch completes.
723    pub n_busy: usize,
724}
725
726impl MaterialBatch {
727    // Use MaterialBuilder instead. It handles creating batches.
728    fn new(
729        gpu: &Gpu,
730        mut passes_generator: impl FnMut() -> (Vec<MaterialPass>, Option<wgpu::Buffer>),
731        n_instances: usize,
732        enable_timing: bool,
733    ) -> Self {
734        let mut instances = Vec::<MaterialInstance>::new();
735        instances.reserve(n_instances);
736        for _ in 0..n_instances {
737            let (passes, readback) = passes_generator();
738            instances.push(MaterialInstance::new(passes, readback));
739        }
740        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
741        let mut timing = None;
742        if enable_timing {
743            std::hint::cold_path();
744            timing = Some(MaterialTiming::new(gpu));
745        }
746        Self {
747            instances: instances,
748            ready_tx: ready_tx,
749            ready_rx: ready_rx,
750            timing: timing,
751            busy: false,
752            n_busy: 0,
753        }
754    }
755
756    pub fn enable_profiling(mut self, gpu: &Gpu) -> Self {
757        self.timing = Some(MaterialTiming::new(gpu));
758        self
759    }
760}
761
762pub struct MaterialTiming {
763    pub ts_buf: wgpu::Buffer,
764    pub ts_readback: wgpu::Buffer,
765    pub ready_tx: Sender<Result<(), wgpu::BufferAsyncError>>,
766    pub ready_rx: Receiver<Result<(), wgpu::BufferAsyncError>>,
767    pub busy: bool,
768}
769
770impl MaterialTiming {
771    pub fn new(gpu: &Gpu) -> Self {
772        let ts_buf = gpu.buffer_by_sz(16).query_resolve().copy_src().build();
773        let ts_readback = gpu.buffer_by_sz(16).copy_dst().map_read().build();
774        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
775        Self {
776            ts_buf: ts_buf,
777            ts_readback: ts_readback,
778            ready_tx: ready_tx,
779            ready_rx: ready_rx,
780            busy: false,
781        }
782    }
783}
784
785pub struct Material {
786    pub batches: Vec<MaterialBatch>,
787    pub batch_size: usize,
788}
789
790impl Material {
791    pub fn get_batch(&mut self) -> Option<&mut MaterialBatch> {
792        let batch = self.batches.iter_mut().find(|batch| {
793            if batch.busy {
794                return false;
795            }
796            if let Some(timing) = &batch.timing {
797                std::hint::cold_path();
798                if timing.busy {
799                    return false;
800                }
801            }
802            true
803        })?;
804        // Found a batch.
805        batch.busy = true;
806        if let Some(timing) = &mut batch.timing {
807            std::hint::cold_path();
808            timing.busy = true;
809        }
810        batch.n_busy = self.batch_size;
811        Some(batch)
812    }
813}
814
815pub struct MaterialBuilder {
816    batch_size: usize, // instances per batch
817    n_batches: usize,
818    enable_timing: bool,
819}
820
821impl MaterialBuilder {
822    pub fn new() -> Self {
823        Self {
824            batch_size: 1,
825            n_batches: 1,
826            enable_timing: false,
827        }
828    }
829
830    pub fn batch_size(mut self, batch_size: usize) -> Self {
831        self.batch_size = batch_size;
832        self
833    }
834
835    pub fn n_batches(mut self, n_batches: usize) -> Self {
836        self.n_batches = n_batches;
837        self
838    }
839
840    pub fn enable_timing(mut self) -> Self {
841        self.enable_timing = true;
842        self
843    }
844
845    pub fn build(
846        self,
847        gpu: &Gpu,
848        mut passes_generator: impl FnMut() -> (Vec<MaterialPass>, Option<wgpu::Buffer>),
849    ) -> Material {
850        let mut batches = Vec::<MaterialBatch>::new();
851        batches.reserve(self.n_batches);
852        for _ in 0..self.n_batches {
853            batches.push(MaterialBatch::new(
854                gpu,
855                &mut passes_generator,
856                self.batch_size,
857                self.enable_timing,
858            ));
859        }
860        Material {
861            batches: batches,
862            batch_size: self.batch_size,
863        }
864    }
865}
866
867pub struct PipelineBuilder<'a> {
868    shader: &'a Shader,
869    zero_initialize: bool,
870    color_target: Option<wgpu::ColorTargetState>,
871    vertex_buffer_layout: Option<wgpu::VertexBufferLayout<'a>>,
872    depth_stencil: Option<wgpu::DepthStencilState>,
873}
874
875impl<'a> PipelineBuilder<'a> {
876    pub fn new(shader: &'a Shader) -> Self {
877        Self {
878            shader,
879            zero_initialize: true,
880            color_target: None,
881            vertex_buffer_layout: None,
882            depth_stencil: None,
883        }
884    }
885
886    pub fn zero_initialize(mut self, zero_initialize: bool) -> Self {
887        self.zero_initialize = zero_initialize;
888        self
889    }
890
891    pub fn color_target(mut self, color_target: wgpu::ColorTargetState) -> Self {
892        self.color_target = Some(color_target);
893        self
894    }
895
896    pub fn vertex_buffer_layout(
897        mut self,
898        vertex_buffer_layout: wgpu::VertexBufferLayout<'a>,
899    ) -> Self {
900        self.vertex_buffer_layout = Some(vertex_buffer_layout);
901        self
902    }
903
904    pub fn depth_stencil(mut self, depth_stencil: wgpu::DepthStencilState) -> Self {
905        self.depth_stencil = Some(depth_stencil);
906        self
907    }
908
909    // Build a ComputePipeline. Assumes the shader has exactly one compute shader.
910    pub fn build_compute(
911        self,
912        gpu: &Gpu,
913        entry_point: &str,
914    ) -> anyhow::Result<wgpu::ComputePipeline> {
915        let pipeline_layout = gpu
916            .device
917            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
918                label: None,
919                bind_group_layouts: &[Some(&self.shader.bind_group_layout)],
920                immediate_size: 0,
921            });
922
923        if !self
924            .shader
925            .naga_module
926            .entry_points
927            .iter()
928            .any(|ep| ep.name == entry_point && ep.stage == naga::ir::ShaderStage::Compute)
929        {
930            anyhow::bail!(
931                "Shader entry point '{}' with compute type not found.",
932                entry_point
933            );
934        }
935        let compilation_options = wgpu::PipelineCompilationOptions {
936            zero_initialize_workgroup_memory: self.zero_initialize,
937            ..Default::default()
938        };
939        Ok(gpu
940            .device
941            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
942                label: None,
943                layout: Some(&pipeline_layout),
944                module: &self.shader.shader_module,
945                entry_point: Some(entry_point),
946                compilation_options: compilation_options,
947                cache: None,
948            }))
949    }
950
951    // Build a RenderPipeline. Assumes the shader has exactly one vertex and one fragment shader.
952    pub fn build_render(self, gpu: &Gpu) -> anyhow::Result<wgpu::RenderPipeline> {
953        let pipeline_layout = gpu
954            .device
955            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
956                label: None,
957                bind_group_layouts: &[Some(&self.shader.bind_group_layout)],
958                immediate_size: 0,
959            });
960        let vertex_shader = self
961            .shader
962            .get_shader_by_stage(naga::ir::ShaderStage::Vertex)?;
963        let fragment_shader = self
964            .shader
965            .get_shader_by_stage(naga::ir::ShaderStage::Fragment)?;
966        let compilation_options = wgpu::PipelineCompilationOptions {
967            zero_initialize_workgroup_memory: self.zero_initialize,
968            ..Default::default()
969        };
970        let color_target = self
971            .color_target
972            .context("RenderPipelineBuilder requires a color target")?;
973        let vertex_buffer_layout = self
974            .vertex_buffer_layout
975            .context("RenderPipelineBuilder requires a vertex buffer layout")?;
976        Ok(gpu
977            .device
978            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
979                label: None,
980                layout: Some(&pipeline_layout),
981                vertex: wgpu::VertexState {
982                    module: &self.shader.shader_module,
983                    entry_point: Some(&vertex_shader.name),
984                    compilation_options: compilation_options.clone(),
985                    buffers: &vec![Some(vertex_buffer_layout)],
986                },
987                fragment: Some(wgpu::FragmentState {
988                    module: &self.shader.shader_module,
989                    entry_point: Some(&fragment_shader.name),
990                    targets: &vec![Some(color_target)],
991                    compilation_options: compilation_options,
992                }),
993                primitive: wgpu::PrimitiveState::default(),
994                depth_stencil: self.depth_stencil,
995                multisample: wgpu::MultisampleState::default(),
996                multiview_mask: None,
997                cache: None,
998            }))
999    }
1000}
1001
1002#[derive(Builder)]
1003#[builder(build_fn(skip))]
1004pub struct Transform {
1005    pub position: [f32; 3],
1006    pub scale: [f32; 3],
1007    // TODO abstract to support euler angles and quaternions
1008    pub orientation: [f32; 3],
1009    #[builder(setter(custom))]
1010    pub buffer: wgpu::Buffer,
1011}
1012
1013impl TransformBuilder {
1014    pub fn build(self, gpu: &Gpu) -> Transform {
1015        let buffer = gpu.buffer_by_sz(128).uniform().copy_dst().build();
1016        let transform = Transform {
1017            position: self.position.unwrap_or([0.0, 0.0, 0.0]),
1018            scale: self.scale.unwrap_or([1.0, 1.0, 1.0]),
1019            orientation: self.orientation.unwrap_or([0.0, 0.0, 0.0]),
1020            buffer,
1021        };
1022        transform.update(gpu);
1023        transform
1024    }
1025}
1026
1027impl Transform {
1028    pub fn new(gpu: &Gpu) -> Self {
1029        TransformBuilder::default().build(gpu)
1030    }
1031
1032    pub fn matrix(&self) -> glam::Mat4 {
1033        let [x, y, z] = self.orientation;
1034        let rotation = glam::Quat::from_euler(glam::EulerRot::XYZ, x, y, z);
1035        glam::Mat4::from_scale_rotation_translation(
1036            glam::Vec3::from(self.scale),
1037            rotation,
1038            glam::Vec3::from(self.position),
1039        )
1040    }
1041
1042    pub fn update(&self, gpu: &Gpu) {
1043        let model = self.matrix();
1044        let model_it = model.inverse().transpose();
1045        let data = [model.to_cols_array_2d(), model_it.to_cols_array_2d()];
1046        gpu.queue
1047            .write_buffer(&self.buffer, 0, bytemuck::bytes_of(&data));
1048    }
1049}
1050
1051pub struct Object {
1052    pub name: String,
1053    pub transform: Transform,
1054    pub vertex_buffer: wgpu::Buffer,
1055    pub index_buffer: wgpu::Buffer,
1056    pub shader: Shader,
1057    // Could hoist this into Scene to have more than one mesh per pipeline, but
1058    // this is good enough for prototype.
1059    pub pipeline: wgpu::RenderPipeline,
1060    pub bind_group: Option<wgpu::BindGroup>,
1061    pub n_indices: u32,
1062    pub cfg_uniforms: Option<CfgUniforms>,
1063}
1064
1065pub struct ObjectBuilder<'a> {
1066    name: Option<&'a str>,
1067    transform: Transform,
1068    vertex_layout: Option<VertexLayout>,
1069    vertex_data_streams: Option<Vec<(VertexSemantic, &'a [u8])>>,
1070    /// indices passed to draw_indexed
1071    vertex_indices: Option<&'a [u32]>,
1072    shader: Option<Shader>,
1073    pipeline: Option<wgpu::RenderPipeline>,
1074    camera: Option<&'a Camera>,
1075    light: Option<&'a Light>,
1076}
1077
1078impl<'a> ObjectBuilder<'a> {
1079    pub fn new(gpu: &Gpu) -> Self {
1080        Self {
1081            name: None,
1082            transform: Transform::new(gpu),
1083            vertex_layout: None,
1084            vertex_data_streams: None,
1085            vertex_indices: None,
1086            shader: None,
1087            pipeline: None,
1088            camera: None,
1089            light: None,
1090        }
1091    }
1092
1093    pub fn name(mut self, name: &'a str) -> Self {
1094        self.name = Some(name);
1095        self
1096    }
1097
1098    pub fn transform(mut self, transform: Transform) -> Self {
1099        self.transform = transform;
1100        self
1101    }
1102
1103    pub fn vertex_layout(mut self, vertex_layout: VertexLayout) -> Self {
1104        self.vertex_layout = Some(vertex_layout);
1105        self
1106    }
1107
1108    pub fn vertex_data_streams(
1109        mut self,
1110        vertex_data_streams: Vec<(VertexSemantic, &'a [u8])>,
1111    ) -> Self {
1112        self.vertex_data_streams = Some(vertex_data_streams);
1113        self
1114    }
1115
1116    pub fn vertex_indices(mut self, vertex_indices: &'a [u32]) -> Self {
1117        self.vertex_indices = Some(vertex_indices);
1118        self
1119    }
1120
1121    pub fn shader(mut self, shader: Shader) -> Self {
1122        self.shader = Some(shader);
1123        self
1124    }
1125
1126    pub fn pipeline(mut self, pipeline: wgpu::RenderPipeline) -> Self {
1127        self.pipeline = Some(pipeline);
1128        self
1129    }
1130
1131    pub fn camera(mut self, camera: &'a Camera) -> Self {
1132        self.camera = Some(camera);
1133        self
1134    }
1135
1136    pub fn light(mut self, light: &'a Light) -> Self {
1137        self.light = Some(light);
1138        self
1139    }
1140
1141    pub fn build(self, gpu: &Gpu) -> anyhow::Result<Object> {
1142        let name = self.name.context("Cannot build Object without name")?;
1143        let shader = self.shader.context("Cannot build Object without shader")?;
1144        let vertex_layout = self
1145            .vertex_layout
1146            .context("Cannot build Object without vertex layout")?;
1147        let data_streams = self
1148            .vertex_data_streams
1149            .context("Cannot build Object without vertex data streams")?;
1150        let indices = self
1151            .vertex_indices
1152            .context("Cannot build Object without vertex indices")?;
1153        let n_vertices = data_streams
1154            .iter()
1155            .find_map(|(semantic, data)| {
1156                if *semantic == VertexSemantic::Position {
1157                    Some(data.len() / size_of::<glam::Vec3>())
1158                } else {
1159                    None
1160                }
1161            })
1162            .expect("Vertex position data stream not found");
1163
1164        let vertex_buffer = vertex_layout.vertex_buffer(gpu, data_streams, n_vertices)?;
1165        let index_buffer = gpu
1166            .device
1167            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
1168                label: None,
1169                contents: bytemuck::cast_slice(indices),
1170                usage: wgpu::BufferUsages::INDEX,
1171            });
1172        let pipeline = self
1173            .pipeline
1174            .context("Cannot build Object without pipeline")?;
1175
1176        let mut bg_entries = Vec::new();
1177        let cfg_uniforms_opt = CfgUniforms::new(gpu, &shader)?;
1178        if let Some(cfg_uniforms) = &cfg_uniforms_opt {
1179            bg_entries.push(wgpu::BindGroupEntry {
1180                binding: cfg_uniforms.binding.binding,
1181                resource: cfg_uniforms.buffer.as_entire_binding(),
1182            });
1183        }
1184
1185        if let Some(camera_binding) = shader.camera_binding {
1186            let camera = &self.camera.context("Shader needs a camera")?;
1187            bg_entries.push(wgpu::BindGroupEntry {
1188                binding: camera_binding.binding,
1189                resource: camera.buffer.as_entire_binding(),
1190            });
1191        }
1192
1193        if let Some(transform_binding) = shader.transform_binding {
1194            let transform = &self.transform;
1195            bg_entries.push(wgpu::BindGroupEntry {
1196                binding: transform_binding.binding,
1197                resource: transform.buffer.as_entire_binding(),
1198            });
1199        }
1200
1201        if let Some(light_binding) = shader.light_binding {
1202            let light = &self.light.context("Shader needs a light")?;
1203            bg_entries.push(wgpu::BindGroupEntry {
1204                binding: light_binding.binding,
1205                resource: light.buffer.as_entire_binding(),
1206            });
1207        }
1208
1209        let bind_group = if bg_entries.is_empty() {
1210            None
1211        } else {
1212            Some(gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
1213                label: None,
1214                layout: &shader.bind_group_layout,
1215                entries: &bg_entries,
1216            }))
1217        };
1218
1219        Ok(Object {
1220            name: name.to_string(),
1221            transform: self.transform,
1222            vertex_buffer,
1223            index_buffer,
1224            shader,
1225            pipeline,
1226            bind_group,
1227            n_indices: indices.len() as u32,
1228            cfg_uniforms: cfg_uniforms_opt,
1229        })
1230    }
1231}
1232
1233#[derive(Builder)]
1234#[builder(build_fn(skip))]
1235pub struct Camera {
1236    pub eye: glam::Vec3,
1237    pub target: glam::Vec3,
1238    pub up: glam::Vec3,
1239    pub vertical_fov: f32,
1240    pub near: f32,
1241    pub far: f32,
1242    #[builder(setter(custom))]
1243    pub buffer: wgpu::Buffer,
1244}
1245
1246impl CameraBuilder {
1247    pub fn build(&self, gpu: &Gpu, aspect: f32) -> anyhow::Result<Camera> {
1248        let buffer = gpu.buffer_by_sz(80).uniform().copy_dst().build();
1249        let camera = Camera {
1250            eye: self.eye.context("eye is not set")?,
1251            target: self.target.context("target is not set")?,
1252            up: self.up.context("up is not set")?.normalize(),
1253            vertical_fov: self.vertical_fov.context("vertical_fov is not set")?,
1254            near: self.near.context("near is not set")?,
1255            far: self.far.context("far is not set")?,
1256            buffer,
1257        };
1258        camera.update(gpu, aspect);
1259        Ok(camera)
1260    }
1261}
1262
1263impl Camera {
1264    /// Moves the camera closer or farther from `target`.
1265    ///
1266    /// `amount` should be in the range [0, 1].
1267    pub fn zoom(&mut self, amount: f32) {
1268        // vector from target to eye
1269        let view_dir = self.eye - self.target;
1270        let view_dist = view_dir.length();
1271
1272        let min_dist = self.near * 1.01;
1273        let new_dist = (view_dist * (1.0 - amount)).max(min_dist);
1274
1275        self.eye = self.target + view_dir * (new_dist / view_dist);
1276    }
1277
1278    /// Orbits around `target`, turntable style.
1279    ///
1280    /// Orbits horizontally by `dx` radians and vertically by `dy` radians.
1281    pub fn orbit(&mut self, dx: f32, dy: f32) {
1282        let view = self.eye - self.target;
1283
1284        // Recall that we are in a right-handed coordinate system with +y up,
1285        // +x right, +z near.
1286        let orbit_up = glam::Vec3::Y;
1287        let yaw = glam::Quat::from_axis_angle(orbit_up, dx);
1288        let view = yaw * view;
1289        let up = yaw * self.up;
1290
1291        let right = up.cross(view.normalize()).normalize();
1292        let pitch = glam::Quat::from_axis_angle(right, dy);
1293
1294        self.eye = self.target + pitch * view;
1295        self.up = (pitch * up).normalize();
1296    }
1297
1298    /// Pans the camera on its local right/up axes.
1299    pub fn pan(&mut self, dx: f32, dy: f32) {
1300        let view = self.eye - self.target;
1301        let radius = view.length();
1302
1303        let radial = view.normalize();
1304        let right = self.up.cross(radial).normalize();
1305        let up = radial.cross(right);
1306
1307        // Scale the translation by `radius` so that we have the same
1308        // sensitivity when near and far.
1309        let offset = (right * dx + up * dy) * radius;
1310
1311        self.eye += offset;
1312        self.target += offset;
1313    }
1314
1315    pub fn update(&self, gpu: &Gpu, aspect: f32) {
1316        let matrix = self.view_projection(aspect).to_cols_array_2d();
1317        let world_pos = self.eye.to_array();
1318        let mut data = [0u8; 80];
1319        data[..64].copy_from_slice(bytemuck::bytes_of(&matrix));
1320        data[64..76].copy_from_slice(bytemuck::bytes_of(&world_pos));
1321        gpu.queue
1322            .write_buffer(&self.buffer, 0, bytemuck::bytes_of(&data));
1323    }
1324
1325    fn view_projection(&self, aspect: f32) -> glam::Mat4 {
1326        // right x, up y. right handed -> near z
1327        use glam::camera::rh::{proj, view};
1328        let view = view::look_at_mat4(self.eye, self.target, self.up);
1329        // 0-1 depth.
1330        let projection = proj::directx::perspective(self.vertical_fov, aspect, self.near, self.far);
1331        projection * view
1332    }
1333}
1334
1335#[derive(Clone)]
1336pub enum LightKind {
1337    Directional { direction: glam::Vec3 },
1338    Point { position: glam::Vec3 },
1339}
1340
1341#[derive(Builder)]
1342#[builder(build_fn(skip))]
1343pub struct Light {
1344    pub kind: LightKind,
1345    pub color: glam::Vec3,
1346    #[builder(setter(custom))]
1347    pub buffer: wgpu::Buffer,
1348}
1349
1350impl LightBuilder {
1351    pub fn build(&self, gpu: &Gpu) -> anyhow::Result<Light> {
1352        let buffer = gpu.buffer_by_sz(32).uniform().copy_dst().build();
1353        let light = Light {
1354            kind: self.kind.clone().context("kind is not set")?,
1355            color: self.color.context("color is not set")?,
1356            buffer,
1357        };
1358        light.update(gpu);
1359        Ok(light)
1360    }
1361}
1362
1363impl Light {
1364    pub fn update(&self, gpu: &Gpu) {
1365        let (location, kind): (glam::Vec3, u32) = match &self.kind {
1366            // Kind here must match demomo.slang
1367            LightKind::Directional { direction } => (*direction, 1),
1368            LightKind::Point { position } => (*position, 2),
1369        };
1370
1371        let location = location.extend(0.0).to_array();
1372        let color = self.color.to_array();
1373        let mut data = [0_u8; 32];
1374        data[..16].copy_from_slice(bytemuck::bytes_of(&location));
1375        data[16..28].copy_from_slice(bytemuck::bytes_of(&color));
1376        data[28..32].copy_from_slice(bytemuck::bytes_of(&kind));
1377        gpu.queue
1378            .write_buffer(&self.buffer, 0, bytemuck::bytes_of(&data));
1379    }
1380}
1381
1382/// Trait used to turn cpu-side uniforms into gpu-compatible data.
1383pub trait UniformValue: Copy {
1384    const TY: naga::TypeInner;
1385
1386    fn encode(self) -> Vec<u8>;
1387}
1388
1389impl UniformValue for i32 {
1390    const TY: naga::TypeInner = naga::TypeInner::Scalar(naga::Scalar::I32);
1391
1392    fn encode(self) -> Vec<u8> {
1393        self.to_le_bytes().to_vec()
1394    }
1395}
1396
1397impl UniformValue for f32 {
1398    const TY: naga::TypeInner = naga::TypeInner::Scalar(naga::Scalar::F32);
1399
1400    fn encode(self) -> Vec<u8> {
1401        self.to_le_bytes().to_vec()
1402    }
1403}
1404
1405impl UniformValue for glam::Vec2 {
1406    const TY: naga::TypeInner = naga::TypeInner::Vector {
1407        size: naga::VectorSize::Bi,
1408        scalar: naga::Scalar::F32,
1409    };
1410
1411    fn encode(self) -> Vec<u8> {
1412        self.to_array()
1413            .into_iter()
1414            .flat_map(f32::to_le_bytes)
1415            .collect()
1416    }
1417}
1418
1419impl UniformValue for glam::Vec3 {
1420    const TY: naga::TypeInner = naga::TypeInner::Vector {
1421        size: naga::VectorSize::Tri,
1422        scalar: naga::Scalar::F32,
1423    };
1424
1425    fn encode(self) -> Vec<u8> {
1426        self.to_array()
1427            .into_iter()
1428            .flat_map(f32::to_le_bytes)
1429            .collect()
1430    }
1431}
1432
1433impl UniformValue for glam::Vec4 {
1434    const TY: naga::TypeInner = naga::TypeInner::Vector {
1435        size: naga::VectorSize::Quad,
1436        scalar: naga::Scalar::F32,
1437    };
1438
1439    fn encode(self) -> Vec<u8> {
1440        self.to_array()
1441            .into_iter()
1442            .flat_map(f32::to_le_bytes)
1443            .collect()
1444    }
1445}
1446
1447pub struct CfgUniform {
1448    pub name: String,
1449    pub offset: u32,
1450    pub ty: naga::TypeInner,
1451}
1452
1453/// User-defined uniforms, i.e. for material settings.
1454pub struct CfgUniforms {
1455    pub binding: naga::ResourceBinding,
1456    pub size: u32,
1457    pub fields: Vec<CfgUniform>,
1458    pub buffer: wgpu::Buffer,
1459    data: Vec<u8>,
1460}
1461
1462impl CfgUniforms {
1463    pub fn new(gpu: &Gpu, shader: &Shader) -> anyhow::Result<Option<CfgUniforms>> {
1464        let Some(binding) = shader.cfg_binding else {
1465            return Ok(None);
1466        };
1467        let (_, global) = shader
1468            .naga_module
1469            .global_variables
1470            .iter()
1471            .find(|(_, global)| global.binding == Some(binding))
1472            .context("cfg binding does not refer to a global")?;
1473        if global.space != naga::AddressSpace::Uniform {
1474            anyhow::bail!("cfg global is not a uniform: {:?}", global.space);
1475        }
1476        let cfg_type = &shader.naga_module.types[global.ty];
1477        let naga::TypeInner::Struct { members, span } = &cfg_type.inner else {
1478            anyhow::bail!("cfg global is not a struct: {:?}", cfg_type.inner);
1479        };
1480
1481        let buffer = BufferBuilder::new_by_sz(*span as usize, gpu)
1482            .uniform()
1483            .copy_dst()
1484            .build();
1485
1486        let mut fields = Vec::new();
1487        fields.reserve(members.len());
1488        for member in members {
1489            let name = member.name.as_ref().context("member has no name?")?;
1490            let offset = member.offset;
1491            let ty = &shader.naga_module.types[member.ty].inner;
1492            fields.push(CfgUniform {
1493                name: name.to_string(),
1494                offset,
1495                ty: ty.clone(),
1496            });
1497        }
1498
1499        let data = vec![0u8; *span as usize];
1500        Ok(Some(CfgUniforms {
1501            binding,
1502            size: *span,
1503            fields,
1504            buffer,
1505            data,
1506        }))
1507    }
1508
1509    pub fn set<T: UniformValue>(&mut self, name: &str, value: T) -> anyhow::Result<()> {
1510        let field = self
1511            .fields
1512            .iter()
1513            .find(|f| f.name == name)
1514            .with_context(|| format!("cfg uniform does not contain field {name}"))?;
1515        if field.ty != T::TY {
1516            anyhow::bail!(
1517                "cfg uniform field {name} has type {:?}, expected {:?}",
1518                field.ty,
1519                T::TY
1520            );
1521        }
1522
1523        let data = value.encode();
1524        let start = field.offset as usize;
1525        let end = start + data.len();
1526        let dst_slice = self
1527            .data
1528            .get_mut(start..end)
1529            .context("cfg field out of bounds?")?;
1530
1531        dst_slice.copy_from_slice(&data);
1532        Ok(())
1533    }
1534
1535    pub fn update(&self, gpu: &Gpu) {
1536        gpu.queue.write_buffer(&self.buffer, 0, &self.data);
1537    }
1538
1539    #[cfg(feature = "window")]
1540    pub fn ui(&mut self, ui: &mut egui::Ui) -> anyhow::Result<bool> {
1541        let mut changed = false;
1542
1543        for field in &self.fields {
1544            let (scalar, components) = match &field.ty {
1545                naga::TypeInner::Scalar(scalar) => (*scalar, 1),
1546                naga::TypeInner::Vector { scalar, size } => (
1547                    *scalar,
1548                    match size {
1549                        naga::VectorSize::Bi => 2,
1550                        naga::VectorSize::Tri => 3,
1551                        naga::VectorSize::Quad => 4,
1552                    },
1553                ),
1554                _ => {
1555                    anyhow::bail!(format!("unsupported type: {:?}", field.ty))
1556                }
1557            };
1558            if scalar.width != 4 {
1559                anyhow::bail!(format!("unsupported scalar width: {}", scalar.width))
1560            }
1561            ui.push_id(&field.name, |ui| {
1562                ui.horizontal(|ui| {
1563                    ui.label(&field.name);
1564                    for component in 0..components {
1565                        let start = field.offset as usize + component * 4;
1566                        let bytes = &mut self.data[start..start + 4];
1567                        ui.push_id(component, |ui| {
1568                            if components > 1 {
1569                                ui.label(["x", "y", "z", "w"][component]);
1570                            }
1571                            macro_rules! edit {
1572                                ($ty:ty, $speed:expr) => {{
1573                                    let mut value = <$ty>::from_le_bytes(
1574                                        bytes[..].try_into().expect("could not parse bytes"),
1575                                    );
1576                                    if ui
1577                                        .add(egui::DragValue::new(&mut value).speed($speed))
1578                                        .changed()
1579                                    {
1580                                        bytes.copy_from_slice(&value.to_le_bytes());
1581                                        changed = true;
1582                                    }
1583                                }};
1584                            }
1585                            match scalar.kind {
1586                                naga::ScalarKind::Float => edit!(f32, 0.01),
1587                                naga::ScalarKind::Sint => edit!(i32, 1.0),
1588                                naga::ScalarKind::Uint => edit!(u32, 1.0),
1589                                _ => unreachable!(),
1590                            }
1591                        });
1592                    }
1593                });
1594            });
1595        }
1596
1597        Ok(changed)
1598    }
1599}
1600
1601pub struct Scene {
1602    pub camera: Camera,
1603    pub light: Option<Light>,
1604    pub objects: Vec<Object>,
1605}
1606
1607pub struct SceneBuilder {
1608    camera: Option<Camera>,
1609    light: Option<Light>,
1610    objects: Vec<Object>,
1611}
1612
1613impl SceneBuilder {
1614    pub fn new() -> Self {
1615        Self {
1616            camera: None,
1617            light: None,
1618            objects: Vec::new(),
1619        }
1620    }
1621
1622    pub fn camera(mut self, camera: Camera) -> Self {
1623        self.camera = Some(camera);
1624        self
1625    }
1626
1627    pub fn light(mut self, light: Light) -> Self {
1628        self.light = Some(light);
1629        self
1630    }
1631
1632    pub fn object(mut self, object: Object) -> Self {
1633        self.objects.push(object);
1634        self
1635    }
1636
1637    pub fn build(self) -> anyhow::Result<Scene> {
1638        let Some(camera) = self.camera else {
1639            anyhow::bail!("camera is not set");
1640        };
1641        Ok(Scene {
1642            camera,
1643            light: self.light,
1644            objects: self.objects,
1645        })
1646    }
1647}
1648
1649pub struct ImportedMesh {
1650    pub positions: Vec<glam::Vec3>,
1651    pub normals: Vec<glam::Vec3>,
1652    pub tangents: Vec<glam::Vec4>,
1653    pub bitangents: Vec<glam::Vec3>,
1654    pub uvs: Vec<glam::Vec2>,
1655    pub indices: Vec<u32>,
1656}
1657
1658impl ImportedMesh {
1659    pub fn vertex_data_streams<'a>(&'a self) -> Vec<(VertexSemantic, &'a [u8])> {
1660        VertexDataStreamBuilder::new()
1661            .stream(VertexSemantic::Position, &self.positions)
1662            .stream(VertexSemantic::Uv0, &self.uvs)
1663            .stream(VertexSemantic::Normal, &self.normals)
1664            .stream(VertexSemantic::Tangent, &self.tangents)
1665            .stream(VertexSemantic::Bitangent, &self.bitangents)
1666            .build()
1667    }
1668}
1669
1670pub struct GltfImporter {
1671    pub meshes: Vec<ImportedMesh>,
1672}
1673
1674impl GltfImporter {
1675    #[cfg(not(target_arch = "wasm32"))]
1676    pub fn from_fs(path: &str) -> anyhow::Result<Self> {
1677        let data = std::fs::read(path)?;
1678        Self::from_slice(&data)
1679    }
1680
1681    #[cfg(target_arch = "wasm32")]
1682    pub async fn from_web(path: &str) -> anyhow::Result<Self> {
1683        use wasm_bindgen::JsCast;
1684        use wasm_bindgen_futures::{JsFuture, js_sys};
1685
1686        let js_to_err = |err: wasm_bindgen::JsValue| anyhow::anyhow!("{err:?}");
1687        let window = wgpu::web_sys::window().expect("No browser window");
1688        let response = JsFuture::from(window.fetch_with_str(path))
1689            .await
1690            .map_err(js_to_err)?
1691            .dyn_into::<wgpu::web_sys::Response>()
1692            .map_err(js_to_err)?;
1693        if !response.ok() {
1694            anyhow::bail!("Failed to fetch data from {path}: {}", response.status());
1695        }
1696        let buffer = JsFuture::from(response.array_buffer().map_err(js_to_err)?)
1697            .await
1698            .map_err(js_to_err)?;
1699        let slice = js_sys::Uint8Array::new(&buffer).to_vec();
1700
1701        Self::from_slice(&slice)
1702    }
1703
1704    fn from_slice(data: &[u8]) -> anyhow::Result<Self> {
1705        let gltf = gltf::Gltf::from_slice(&data)?;
1706        let blob = gltf
1707            .blob
1708            .as_deref()
1709            .context("Mesh is missing vertex buffer")?;
1710
1711        let mut meshes = Vec::<ImportedMesh>::new();
1712        for mesh in gltf.meshes() {
1713            for primitive in mesh.primitives() {
1714                let reader = primitive.reader(|_| Some(blob));
1715                let positions: Vec<glam::Vec3> = reader
1716                    .read_positions()
1717                    .context("Mesh is missing vertex positions")?
1718                    .map(glam::Vec3::from_array)
1719                    .collect();
1720                let normals: Vec<glam::Vec3> = reader
1721                    .read_normals()
1722                    .context("Mesh is missing vertex normals")?
1723                    .map(glam::Vec3::from_array)
1724                    .collect();
1725                let uvs: Vec<glam::Vec2> = reader
1726                    .read_tex_coords(0)
1727                    .context("Mesh is missing UVs")?
1728                    .into_f32()
1729                    .map(glam::Vec2::from_array)
1730                    .collect();
1731                let indices: Vec<u32> = reader
1732                    .read_indices()
1733                    .context("Mesh is missing indices")?
1734                    .into_u32()
1735                    .collect();
1736                let (tangents, bitangents) =
1737                    Self::calculate_tangents(&positions, &indices, &uvs, &normals);
1738                meshes.push(ImportedMesh {
1739                    positions,
1740                    normals,
1741                    tangents,
1742                    bitangents,
1743                    uvs,
1744                    indices,
1745                });
1746            }
1747        }
1748
1749        Ok(GltfImporter { meshes })
1750    }
1751
1752    /// Calculates tangents and bitangents from positions.
1753    fn calculate_tangents(
1754        positions: &[glam::Vec3],
1755        indices: &[u32],
1756        uvs: &[glam::Vec2],
1757        normals: &[glam::Vec3],
1758    ) -> (Vec<glam::Vec4>, Vec<glam::Vec3>) {
1759        let mut tangents = vec![glam::Vec3::ZERO; positions.len()];
1760        let mut bitangents = vec![glam::Vec3::ZERO; positions.len()];
1761
1762        // Calculate tangents and bitangents from triangles
1763        // Based on https://learnopengl.com/Advanced-Lighting/Normal-Mapping
1764        for tri_indices in indices.chunks_exact(3) {
1765            let v0 = positions[tri_indices[0] as usize];
1766            let v1 = positions[tri_indices[1] as usize];
1767            let v2 = positions[tri_indices[2] as usize];
1768
1769            let uv0 = uvs[tri_indices[0] as usize];
1770            let uv1 = uvs[tri_indices[1] as usize];
1771            let uv2 = uvs[tri_indices[2] as usize];
1772
1773            let e0 = v1 - v0;
1774            let e1 = v2 - v0;
1775            let duv0 = uv1 - uv0;
1776            let duv1 = uv2 - uv0;
1777
1778            let f = 1.0f32 / (duv0.x * duv1.y - duv0.y * duv1.x);
1779
1780            let t = (e0 * duv1.y - e1 * duv0.y) * f;
1781            let b = (e1 * duv0.x - e0 * duv1.x) * f;
1782
1783            for &idx in tri_indices {
1784                tangents[idx as usize] += t;
1785                bitangents[idx as usize] += b;
1786            }
1787        }
1788
1789        // Orthogonalize and calculate handedness
1790        // ("One last thing" in opengl tutorial linked above.)
1791        let tangents = tangents
1792            .into_iter()
1793            .enumerate()
1794            .map(|(i, raw_tangent)| {
1795                let n = normals[i];
1796                // Subtract out the normal component to orthogonalize
1797                let t = (raw_tangent - n * n.dot(raw_tangent)).normalize();
1798                let sign = if n.cross(t).dot(bitangents[i]) < 0.0 {
1799                    -1.0
1800                } else {
1801                    1.0
1802                };
1803                bitangents[i] = n.cross(t) * sign;
1804                t.extend(sign)
1805            })
1806            .collect();
1807        (tangents, bitangents)
1808    }
1809}
1810
1811#[cfg(feature = "window")]
1812pub struct UI {
1813    pub ctx: egui::Context,
1814    pub input: egui_winit::State,
1815    pub renderer: egui_wgpu::Renderer,
1816}
1817
1818#[cfg(feature = "window")]
1819impl UI {
1820    pub fn new(gpu: &Gpu, window: &winit::window::Window, format: wgpu::TextureFormat) -> Self {
1821        let ctx = egui::Context::default();
1822        let input = egui_winit::State::new(
1823            ctx.clone(),
1824            egui::ViewportId::ROOT,
1825            window,
1826            Some(window.scale_factor() as f32),
1827            window.theme(),
1828            Some(gpu.device.limits().max_texture_dimension_2d as usize),
1829        );
1830        let renderer =
1831            egui_wgpu::Renderer::new(&gpu.device, format, egui_wgpu::RendererOptions::default());
1832
1833        UI {
1834            ctx,
1835            input,
1836            renderer,
1837        }
1838    }
1839}