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