Struct truck_platform::Scene

source ·
pub struct Scene { /* private fields */ }
Expand description

Wraps wgpu and provides an intuitive graphics API.

Scene is the most important in truck-platform. This structure holds information about rendering and serves as a bridge to the actual rendering of Rendered objects.

Implementations§

constructor

Examples found in repository?
src/scene.rs (line 343)
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    pub async fn from_default_device(scene_desc: &SceneDescriptor) -> Scene {
        Scene::new(DeviceHandler::default_device().await, scene_desc)
    }

    /// Creates compatible texture for render attachment.
    ///
    /// # Remarks
    /// The usage of texture is `TextureUsages::RENDER_ATTACHMENT | TetureUsages::COPY_SRC`.
    #[inline(always)]
    pub fn compatible_texture(&self) -> Texture {
        let config = self.scene_desc.render_texture;
        self.device().create_texture(&TextureDescriptor {
            label: None,
            size: Extent3d {
                width: config.canvas_size.0,
                height: config.canvas_size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: TextureDimension::D2,
            format: config.format,
            usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC,
        })
    }

    /// Returns the reference of its own `DeviceHandler`.
    #[inline(always)]
    pub const fn device_handler(&self) -> &DeviceHandler { &self.device_handler }

    /// Returns the reference of the device.
    #[inline(always)]
    pub const fn device(&self) -> &Arc<Device> { &self.device_handler.device }

    /// Returns the reference of the queue.
    #[inline(always)]
    pub const fn queue(&self) -> &Arc<Queue> { &self.device_handler.queue }

    /// Returns the elapsed time since the scene was created.
    #[inline(always)]
    pub fn elapsed(&self) -> std::time::Duration { self.clock.elapsed() }

    /// Returns the reference of the descriptor.
    #[inline(always)]
    pub const fn descriptor(&self) -> &SceneDescriptor { &self.scene_desc }

    /// Returns the mutable reference of the descriptor.
    ///
    /// # Remarks
    ///
    /// When the return value is dropped, the depth buffer and sampling buffer are automatically updated.
    /// Use `studio_config_mut` if you only want to update the colors of the camera, lights, and background.
    #[inline(always)]
    pub fn descriptor_mut(&mut self) -> SceneDescriptorMut<'_> { SceneDescriptorMut(self) }

    /// Returns the reference of the studio configuration.
    #[inline(always)]
    pub const fn studio_config(&self) -> &StudioConfig { &self.scene_desc.studio }

    /// Returns the mutable reference of the studio configuration.
    #[inline(always)]
    pub fn studio_config_mut(&mut self) -> &mut StudioConfig { &mut self.scene_desc.studio }

    /// Returns the bind group layout in the scene.
    #[inline(always)]
    pub const fn bind_group_layout(&self) -> &BindGroupLayout { &self.bind_group_layout }

    /// Creates a `UNIFORM` buffer of the camera.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 0) uniform Camera {
    ///     mat4 camera_matrix;     // the camera matrix
    ///     mat4 camera_projection; // the projection into the normalized view volume
    /// };
    /// ```
    #[inline(always)]
    pub fn camera_buffer(&self) -> BufferHandler { self.scene_desc.camera_buffer(self.device()) }

    /// Creates a `STORAGE` buffer of all lights.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// struct Light {
    ///     vec4 position;      // the position of light, position.w == 1.0
    ///     vec4 color;         // the color of light, color.w == 1.0
    ///     uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
    /// };
    ///
    /// layout(set = 0, binding = 1) buffer Lights {
    ///     Light lights[]; // the number of lights must be gotten from another place
    /// };
    /// ```
    #[inline(always)]
    pub fn lights_buffer(&self) -> BufferHandler { self.scene_desc.lights_buffer(self.device()) }

    /// Creates a `UNIFORM` buffer of the scene status.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 2) uniform Scene {
    ///     vec4 bk_color;  // color of back ground
    ///     float time;     // elapsed time since the scene was created.
    ///     uint nlights;   // the number of lights
    /// };
    /// ```
    #[inline(always)]
    pub fn scene_status_buffer(&self) -> BufferHandler {
        let bk = self.scene_desc.studio.background;
        let size = self.scene_desc.render_texture.canvas_size;
        let scene_info = SceneInfo {
            background_color: [bk.r as f32, bk.g as f32, bk.b as f32, bk.a as f32],
            resolution: [size.0, size.1],
            time: self.elapsed().as_secs_f32(),
            num_of_lights: self.scene_desc.studio.lights.len() as u32,
        };
        BufferHandler::from_slice(&[scene_info], self.device(), BufferUsages::UNIFORM)
    }

    /// Creates bind group.
    /// # Shader Examples
    /// Suppose binded as `set = 0`.
    /// ```glsl
    /// layout(set = 0, binding = 0) uniform Camera {
    ///     mat4 camera_matrix;     // the camera matrix
    ///     mat4 camera_projection; // the projection into the normalized view volume
    /// };
    ///
    /// struct Light {
    ///     vec4 position;      // the position of light, position.w == 1.0
    ///     vec4 color;         // the color of light, color.w == 1.0
    ///     uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
    /// };
    ///
    /// layout(set = 0, binding = 1) buffer Lights {
    ///     Light lights[];
    /// };
    ///
    /// layout(set = 0, binding = 2) uniform Scene {
    ///     float time;     // elapsed time since the scene was created.
    ///     uint nlights;   // the number of lights
    /// };
    /// ```
    #[inline(always)]
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

    /// Adds a render object to the scene.
    ///
    /// If there already exists a render object with the same ID,
    /// replaces the render object and returns false.
    #[inline(always)]
    pub fn add_object<R: Rendered>(&mut self, object: &R) -> bool {
        let render_object = object.render_object(self);
        self.objects
            .insert(object.render_id(), render_object)
            .is_none()
    }
    /// Sets the visibility of a render object.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns `false`.
    #[inline(always)]
    pub fn set_visibility<R: Rendered>(&mut self, object: &R, visible: bool) -> bool {
        self.objects
            .get_mut(&object.render_id())
            .map(|obj| obj.visible = visible)
            .is_some()
    }
    /// Adds render objects to the scene.
    ///
    /// If there already exists a render object with the same ID,
    /// replaces the render object and returns false.
    #[inline(always)]
    pub fn add_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.add_object(object);
        objects.into_iter().fold(true, closure)
    }
    /// Removes a render object from the scene.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns `false`.
    #[inline(always)]
    pub fn remove_object<R: Rendered>(&mut self, object: &R) -> bool {
        self.objects.remove(&object.render_id()).is_some()
    }
    /// Removes render objects from the scene.
    ///
    /// If there exists a render object which does not exist in the scene, returns `false`.
    #[inline(always)]
    pub fn remove_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.remove_object(object);
        objects.into_iter().fold(true, closure)
    }

    /// Removes all render objects from the scene.
    #[inline(always)]
    pub fn clear_objects(&mut self) { self.objects.clear() }

    /// Returns the number of the render objects in the scene.
    #[inline(always)]
    pub fn number_of_objects(&self) -> usize { self.objects.len() }

    /// Synchronizes the information of vertices of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_vertex_buffer<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            None => false,
            Some(render_object) => {
                let (vb, ib) = object.vertex_buffer(handler);
                render_object.vertex_buffer = vb;
                render_object.index_buffer = ib;
                true
            }
        }
    }

    /// Synchronizes the information of vertices of `objects` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_vertex_buffers<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_vertex_buffer(object);
        objects.into_iter().fold(true, closure)
    }

    /// Synchronizes the information of bind group of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_bind_group<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            Some(render_object) => {
                let bind_group = object.bind_group(handler, &render_object.bind_group_layout);
                render_object.bind_group = bind_group;
                true
            }
            _ => false,
        }
    }
    /// Synchronizes the information of bind group of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_bind_groups<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_bind_group(object);
        objects.into_iter().fold(true, closure)
    }
    /// Synchronizes the information of pipeline of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_pipeline<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            Some(render_object) => {
                let device = handler.device();
                let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
                    bind_group_layouts: &[
                        &self.bind_group_layout,
                        &render_object.bind_group_layout,
                    ],
                    push_constant_ranges: &[],
                    label: None,
                });
                render_object.pipeline =
                    object.pipeline(handler, &pipeline_layout, &self.scene_desc);
                true
            }
            _ => false,
        }
    }
    /// Synchronizes the information of pipeline of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_pipelines<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_pipeline(object);
        objects.into_iter().fold(true, closure)
    }
    #[inline(always)]
    fn depth_stencil_attachment_descriptor(
        depth_view: &TextureView,
    ) -> RenderPassDepthStencilAttachment<'_> {
        RenderPassDepthStencilAttachment {
            view: depth_view,
            depth_ops: Some(Operations {
                load: LoadOp::Clear(1.0),
                store: true,
            }),
            stencil_ops: None,
        }
    }

    /// Renders the scene to `view`.
    pub fn render(&self, view: &TextureView) {
        let bind_group = self.scene_bind_group();
        let depth_view = self
            .foward_depth
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let sampled_view = self
            .sampling_buffer
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let mut encoder = self
            .device()
            .create_command_encoder(&CommandEncoderDescriptor { label: None });
        {
            let (attachment, resolve_target) = match sampled_view.as_ref() {
                Some(sampled_view) => (sampled_view, Some(view)),
                None => (view, None),
            };
            let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
                color_attachments: &[Some(RenderPassColorAttachment {
                    view: attachment,
                    resolve_target,
                    ops: Operations {
                        load: LoadOp::Clear(self.scene_desc.studio.background),
                        store: true,
                    },
                })],
                depth_stencil_attachment: depth_view
                    .as_ref()
                    .map(Self::depth_stencil_attachment_descriptor),
                ..Default::default()
            });
            rpass.set_bind_group(0, &bind_group, &[]);
            for (_, object) in &self.objects {
                if !object.visible {
                    continue;
                }
                rpass.set_pipeline(&object.pipeline);
                rpass.set_bind_group(1, &object.bind_group, &[]);
                rpass.set_vertex_buffer(0, object.vertex_buffer.buffer.slice(..));
                match object.index_buffer {
                    Some(ref index_buffer) => {
                        rpass.set_index_buffer(index_buffer.buffer.slice(..), IndexFormat::Uint32);
                        let index_size =
                            index_buffer.size as u32 / std::mem::size_of::<u32>() as u32;
                        rpass.draw_indexed(0..index_size, 0, 0..1);
                    }
                    None => rpass.draw(
                        0..(object.vertex_buffer.size / object.vertex_buffer.stride) as u32,
                        0..1,
                    ),
                }
            }
        }
        self.queue().submit(vec![encoder.finish()]);
    }

    /// Render image to buffer.
    pub async fn render_to_buffer(&self) -> Vec<u8> {
        let texture = self.compatible_texture();
        let view = texture.create_view(&Default::default());
        self.render(&view);
        let (device, queue) = (self.device(), self.queue());

        let (width, height) = self.scene_desc.render_texture.canvas_size;
        let size = (width * height * 4) as u64;
        let buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            mapped_at_creation: false,
            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
            size,
        });
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None });
        encoder.copy_texture_to_buffer(
            ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: Origin3d::ZERO,
                aspect: TextureAspect::All,
            },
            ImageCopyBuffer {
                buffer: &buffer,
                layout: ImageDataLayout {
                    offset: 0,
                    bytes_per_row: (width * 4).try_into().ok(),
                    rows_per_image: height.try_into().ok(),
                },
            },
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));
        let buffer_slice = buffer.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        buffer_slice.map_async(MapMode::Read, move |v| sender.send(v).unwrap());
        device.poll(Maintain::Wait);
        match receiver.receive().await {
            Some(Ok(_)) => buffer_slice.get_mapped_range().iter().copied().collect(),
            Some(Err(e)) => panic!("{}", e),
            None => panic!("Asynchronous processing fails"),
        }
    }
}

impl WindowScene {
    /// Initialize scene compatible with `window`.
    pub async fn from_window(window: Arc<Window>, scene_desc: &WindowSceneDescriptor) -> Self {
        let size = window.inner_size();
        let got = init_default_device(Some(window)).await;
        let (device_handler, window_handler) = (got.0, got.1.unwrap());
        let (device, surface) = (&device_handler.device, &window_handler.surface);
        let render_texture = RenderTextureConfig {
            canvas_size: size.into(),
            format: TextureFormat::Bgra8Unorm,
        };
        let config = render_texture.compatible_surface_config();
        surface.configure(device, &config);

        Self {
            scene: Scene::new(
                device_handler,
                &SceneDescriptor {
                    studio: scene_desc.studio.clone(),
                    backend_buffer: scene_desc.backend_buffer,
                    render_texture,
                },
            ),
            window_handler,
        }
    }

Construct scene from default GPU device.

Arguments
  • size: (width, height)

Creates compatible texture for render attachment.

Remarks

The usage of texture is TextureUsages::RENDER_ATTACHMENT | TetureUsages::COPY_SRC.

Examples found in repository?
src/scene.rs (line 734)
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    pub async fn render_to_buffer(&self) -> Vec<u8> {
        let texture = self.compatible_texture();
        let view = texture.create_view(&Default::default());
        self.render(&view);
        let (device, queue) = (self.device(), self.queue());

        let (width, height) = self.scene_desc.render_texture.canvas_size;
        let size = (width * height * 4) as u64;
        let buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            mapped_at_creation: false,
            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
            size,
        });
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None });
        encoder.copy_texture_to_buffer(
            ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: Origin3d::ZERO,
                aspect: TextureAspect::All,
            },
            ImageCopyBuffer {
                buffer: &buffer,
                layout: ImageDataLayout {
                    offset: 0,
                    bytes_per_row: (width * 4).try_into().ok(),
                    rows_per_image: height.try_into().ok(),
                },
            },
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));
        let buffer_slice = buffer.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        buffer_slice.map_async(MapMode::Read, move |v| sender.send(v).unwrap());
        device.poll(Maintain::Wait);
        match receiver.receive().await {
            Some(Ok(_)) => buffer_slice.get_mapped_range().iter().copied().collect(),
            Some(Err(e)) => panic!("{}", e),
            None => panic!("Asynchronous processing fails"),
        }
    }

Returns the reference of its own DeviceHandler.

Examples found in repository?
src/lib.rs (line 339)
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
    fn render_object(&self, scene: &Scene) -> RenderObject {
        let (vertex_buffer, index_buffer) = self.vertex_buffer(scene.device_handler());
        let bind_group_layout = self.bind_group_layout(scene.device_handler());
        let bind_group = self.bind_group(scene.device_handler(), &bind_group_layout);
        let pipeline_layout = scene
            .device()
            .create_pipeline_layout(&PipelineLayoutDescriptor {
                bind_group_layouts: &[&scene.bind_group_layout, &bind_group_layout],
                push_constant_ranges: &[],
                label: None,
            });
        let pipeline = self.pipeline(scene.device_handler(), &pipeline_layout, &scene.scene_desc);
        RenderObject {
            vertex_buffer,
            index_buffer,
            bind_group_layout,
            bind_group,
            pipeline,
            visible: true,
        }
    }

Returns the reference of the device.

Examples found in repository?
src/scene.rs (line 262)
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    fn drop(&mut self) {
        let (forward_depth, sampling_buffer) = self.backend_buffers(self.0.device());
        self.0.foward_depth = forward_depth;
        self.0.sampling_buffer = sampling_buffer;
    }
}

impl Scene {
    #[inline(always)]
    fn camera_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn lights_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn scene_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn init_scene_bind_group_layout(device: &Device) -> BindGroupLayout {
        bind_group_util::create_bind_group_layout(
            device,
            &[
                Self::camera_bgl_entry(),
                Self::lights_bgl_entry(),
                Self::scene_bgl_entry(),
            ],
        )
    }

    /// constructor
    // About `scene_desc`, entity is better than reference for the performance.
    // This is reference because only for as wgpu is.
    #[inline(always)]
    pub fn new(device_handler: DeviceHandler, scene_desc: &SceneDescriptor) -> Scene {
        let device = device_handler.device();
        let (foward_depth, sampling_buffer) = scene_desc.backend_buffers(device);
        let bind_group_layout = Self::init_scene_bind_group_layout(device);
        Scene {
            objects: Default::default(),
            bind_group_layout,
            foward_depth,
            sampling_buffer,
            clock: instant::Instant::now(),
            scene_desc: scene_desc.clone(),
            device_handler,
        }
    }

    /// Construct scene from default GPU device.
    /// # Arguments
    /// - `size`: (width, height)
    pub async fn from_default_device(scene_desc: &SceneDescriptor) -> Scene {
        Scene::new(DeviceHandler::default_device().await, scene_desc)
    }

    /// Creates compatible texture for render attachment.
    ///
    /// # Remarks
    /// The usage of texture is `TextureUsages::RENDER_ATTACHMENT | TetureUsages::COPY_SRC`.
    #[inline(always)]
    pub fn compatible_texture(&self) -> Texture {
        let config = self.scene_desc.render_texture;
        self.device().create_texture(&TextureDescriptor {
            label: None,
            size: Extent3d {
                width: config.canvas_size.0,
                height: config.canvas_size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: TextureDimension::D2,
            format: config.format,
            usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC,
        })
    }

    /// Returns the reference of its own `DeviceHandler`.
    #[inline(always)]
    pub const fn device_handler(&self) -> &DeviceHandler { &self.device_handler }

    /// Returns the reference of the device.
    #[inline(always)]
    pub const fn device(&self) -> &Arc<Device> { &self.device_handler.device }

    /// Returns the reference of the queue.
    #[inline(always)]
    pub const fn queue(&self) -> &Arc<Queue> { &self.device_handler.queue }

    /// Returns the elapsed time since the scene was created.
    #[inline(always)]
    pub fn elapsed(&self) -> std::time::Duration { self.clock.elapsed() }

    /// Returns the reference of the descriptor.
    #[inline(always)]
    pub const fn descriptor(&self) -> &SceneDescriptor { &self.scene_desc }

    /// Returns the mutable reference of the descriptor.
    ///
    /// # Remarks
    ///
    /// When the return value is dropped, the depth buffer and sampling buffer are automatically updated.
    /// Use `studio_config_mut` if you only want to update the colors of the camera, lights, and background.
    #[inline(always)]
    pub fn descriptor_mut(&mut self) -> SceneDescriptorMut<'_> { SceneDescriptorMut(self) }

    /// Returns the reference of the studio configuration.
    #[inline(always)]
    pub const fn studio_config(&self) -> &StudioConfig { &self.scene_desc.studio }

    /// Returns the mutable reference of the studio configuration.
    #[inline(always)]
    pub fn studio_config_mut(&mut self) -> &mut StudioConfig { &mut self.scene_desc.studio }

    /// Returns the bind group layout in the scene.
    #[inline(always)]
    pub const fn bind_group_layout(&self) -> &BindGroupLayout { &self.bind_group_layout }

    /// Creates a `UNIFORM` buffer of the camera.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 0) uniform Camera {
    ///     mat4 camera_matrix;     // the camera matrix
    ///     mat4 camera_projection; // the projection into the normalized view volume
    /// };
    /// ```
    #[inline(always)]
    pub fn camera_buffer(&self) -> BufferHandler { self.scene_desc.camera_buffer(self.device()) }

    /// Creates a `STORAGE` buffer of all lights.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// struct Light {
    ///     vec4 position;      // the position of light, position.w == 1.0
    ///     vec4 color;         // the color of light, color.w == 1.0
    ///     uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
    /// };
    ///
    /// layout(set = 0, binding = 1) buffer Lights {
    ///     Light lights[]; // the number of lights must be gotten from another place
    /// };
    /// ```
    #[inline(always)]
    pub fn lights_buffer(&self) -> BufferHandler { self.scene_desc.lights_buffer(self.device()) }

    /// Creates a `UNIFORM` buffer of the scene status.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 2) uniform Scene {
    ///     vec4 bk_color;  // color of back ground
    ///     float time;     // elapsed time since the scene was created.
    ///     uint nlights;   // the number of lights
    /// };
    /// ```
    #[inline(always)]
    pub fn scene_status_buffer(&self) -> BufferHandler {
        let bk = self.scene_desc.studio.background;
        let size = self.scene_desc.render_texture.canvas_size;
        let scene_info = SceneInfo {
            background_color: [bk.r as f32, bk.g as f32, bk.b as f32, bk.a as f32],
            resolution: [size.0, size.1],
            time: self.elapsed().as_secs_f32(),
            num_of_lights: self.scene_desc.studio.lights.len() as u32,
        };
        BufferHandler::from_slice(&[scene_info], self.device(), BufferUsages::UNIFORM)
    }

    /// Creates bind group.
    /// # Shader Examples
    /// Suppose binded as `set = 0`.
    /// ```glsl
    /// layout(set = 0, binding = 0) uniform Camera {
    ///     mat4 camera_matrix;     // the camera matrix
    ///     mat4 camera_projection; // the projection into the normalized view volume
    /// };
    ///
    /// struct Light {
    ///     vec4 position;      // the position of light, position.w == 1.0
    ///     vec4 color;         // the color of light, color.w == 1.0
    ///     uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
    /// };
    ///
    /// layout(set = 0, binding = 1) buffer Lights {
    ///     Light lights[];
    /// };
    ///
    /// layout(set = 0, binding = 2) uniform Scene {
    ///     float time;     // elapsed time since the scene was created.
    ///     uint nlights;   // the number of lights
    /// };
    /// ```
    #[inline(always)]
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

    /// Adds a render object to the scene.
    ///
    /// If there already exists a render object with the same ID,
    /// replaces the render object and returns false.
    #[inline(always)]
    pub fn add_object<R: Rendered>(&mut self, object: &R) -> bool {
        let render_object = object.render_object(self);
        self.objects
            .insert(object.render_id(), render_object)
            .is_none()
    }
    /// Sets the visibility of a render object.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns `false`.
    #[inline(always)]
    pub fn set_visibility<R: Rendered>(&mut self, object: &R, visible: bool) -> bool {
        self.objects
            .get_mut(&object.render_id())
            .map(|obj| obj.visible = visible)
            .is_some()
    }
    /// Adds render objects to the scene.
    ///
    /// If there already exists a render object with the same ID,
    /// replaces the render object and returns false.
    #[inline(always)]
    pub fn add_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.add_object(object);
        objects.into_iter().fold(true, closure)
    }
    /// Removes a render object from the scene.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns `false`.
    #[inline(always)]
    pub fn remove_object<R: Rendered>(&mut self, object: &R) -> bool {
        self.objects.remove(&object.render_id()).is_some()
    }
    /// Removes render objects from the scene.
    ///
    /// If there exists a render object which does not exist in the scene, returns `false`.
    #[inline(always)]
    pub fn remove_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.remove_object(object);
        objects.into_iter().fold(true, closure)
    }

    /// Removes all render objects from the scene.
    #[inline(always)]
    pub fn clear_objects(&mut self) { self.objects.clear() }

    /// Returns the number of the render objects in the scene.
    #[inline(always)]
    pub fn number_of_objects(&self) -> usize { self.objects.len() }

    /// Synchronizes the information of vertices of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_vertex_buffer<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            None => false,
            Some(render_object) => {
                let (vb, ib) = object.vertex_buffer(handler);
                render_object.vertex_buffer = vb;
                render_object.index_buffer = ib;
                true
            }
        }
    }

    /// Synchronizes the information of vertices of `objects` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_vertex_buffers<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_vertex_buffer(object);
        objects.into_iter().fold(true, closure)
    }

    /// Synchronizes the information of bind group of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_bind_group<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            Some(render_object) => {
                let bind_group = object.bind_group(handler, &render_object.bind_group_layout);
                render_object.bind_group = bind_group;
                true
            }
            _ => false,
        }
    }
    /// Synchronizes the information of bind group of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_bind_groups<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_bind_group(object);
        objects.into_iter().fold(true, closure)
    }
    /// Synchronizes the information of pipeline of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there does not exist the render object in the scene, does nothing and returns false.
    #[inline(always)]
    pub fn update_pipeline<R: Rendered>(&mut self, object: &R) -> bool {
        let (handler, objects) = (&self.device_handler, &mut self.objects);
        match objects.get_mut(&object.render_id()) {
            Some(render_object) => {
                let device = handler.device();
                let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
                    bind_group_layouts: &[
                        &self.bind_group_layout,
                        &render_object.bind_group_layout,
                    ],
                    push_constant_ranges: &[],
                    label: None,
                });
                render_object.pipeline =
                    object.pipeline(handler, &pipeline_layout, &self.scene_desc);
                true
            }
            _ => false,
        }
    }
    /// Synchronizes the information of pipeline of `object` in the CPU memory
    /// and that in the GPU memory.
    ///
    /// If there exists a render object which does not exist in the scene, returns false.
    #[inline(always)]
    pub fn update_pipelines<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_pipeline(object);
        objects.into_iter().fold(true, closure)
    }
    #[inline(always)]
    fn depth_stencil_attachment_descriptor(
        depth_view: &TextureView,
    ) -> RenderPassDepthStencilAttachment<'_> {
        RenderPassDepthStencilAttachment {
            view: depth_view,
            depth_ops: Some(Operations {
                load: LoadOp::Clear(1.0),
                store: true,
            }),
            stencil_ops: None,
        }
    }

    /// Renders the scene to `view`.
    pub fn render(&self, view: &TextureView) {
        let bind_group = self.scene_bind_group();
        let depth_view = self
            .foward_depth
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let sampled_view = self
            .sampling_buffer
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let mut encoder = self
            .device()
            .create_command_encoder(&CommandEncoderDescriptor { label: None });
        {
            let (attachment, resolve_target) = match sampled_view.as_ref() {
                Some(sampled_view) => (sampled_view, Some(view)),
                None => (view, None),
            };
            let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
                color_attachments: &[Some(RenderPassColorAttachment {
                    view: attachment,
                    resolve_target,
                    ops: Operations {
                        load: LoadOp::Clear(self.scene_desc.studio.background),
                        store: true,
                    },
                })],
                depth_stencil_attachment: depth_view
                    .as_ref()
                    .map(Self::depth_stencil_attachment_descriptor),
                ..Default::default()
            });
            rpass.set_bind_group(0, &bind_group, &[]);
            for (_, object) in &self.objects {
                if !object.visible {
                    continue;
                }
                rpass.set_pipeline(&object.pipeline);
                rpass.set_bind_group(1, &object.bind_group, &[]);
                rpass.set_vertex_buffer(0, object.vertex_buffer.buffer.slice(..));
                match object.index_buffer {
                    Some(ref index_buffer) => {
                        rpass.set_index_buffer(index_buffer.buffer.slice(..), IndexFormat::Uint32);
                        let index_size =
                            index_buffer.size as u32 / std::mem::size_of::<u32>() as u32;
                        rpass.draw_indexed(0..index_size, 0, 0..1);
                    }
                    None => rpass.draw(
                        0..(object.vertex_buffer.size / object.vertex_buffer.stride) as u32,
                        0..1,
                    ),
                }
            }
        }
        self.queue().submit(vec![encoder.finish()]);
    }

    /// Render image to buffer.
    pub async fn render_to_buffer(&self) -> Vec<u8> {
        let texture = self.compatible_texture();
        let view = texture.create_view(&Default::default());
        self.render(&view);
        let (device, queue) = (self.device(), self.queue());

        let (width, height) = self.scene_desc.render_texture.canvas_size;
        let size = (width * height * 4) as u64;
        let buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            mapped_at_creation: false,
            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
            size,
        });
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None });
        encoder.copy_texture_to_buffer(
            ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: Origin3d::ZERO,
                aspect: TextureAspect::All,
            },
            ImageCopyBuffer {
                buffer: &buffer,
                layout: ImageDataLayout {
                    offset: 0,
                    bytes_per_row: (width * 4).try_into().ok(),
                    rows_per_image: height.try_into().ok(),
                },
            },
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));
        let buffer_slice = buffer.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        buffer_slice.map_async(MapMode::Read, move |v| sender.send(v).unwrap());
        device.poll(Maintain::Wait);
        match receiver.receive().await {
            Some(Ok(_)) => buffer_slice.get_mapped_range().iter().copied().collect(),
            Some(Err(e)) => panic!("{}", e),
            None => panic!("Asynchronous processing fails"),
        }
    }
}

impl WindowScene {
    /// Initialize scene compatible with `window`.
    pub async fn from_window(window: Arc<Window>, scene_desc: &WindowSceneDescriptor) -> Self {
        let size = window.inner_size();
        let got = init_default_device(Some(window)).await;
        let (device_handler, window_handler) = (got.0, got.1.unwrap());
        let (device, surface) = (&device_handler.device, &window_handler.surface);
        let render_texture = RenderTextureConfig {
            canvas_size: size.into(),
            format: TextureFormat::Bgra8Unorm,
        };
        let config = render_texture.compatible_surface_config();
        surface.configure(device, &config);

        Self {
            scene: Scene::new(
                device_handler,
                &SceneDescriptor {
                    studio: scene_desc.studio.clone(),
                    backend_buffer: scene_desc.backend_buffer,
                    render_texture,
                },
            ),
            window_handler,
        }
    }
    /// Get the reference of initializing window.
    #[inline(always)]
    pub fn window(&self) -> &Arc<Window> { &self.window_handler.window }
    /// Get the reference of surface.
    #[inline(always)]
    pub fn surface(&self) -> &Arc<Surface> { &self.window_handler.surface }
    /// Adjusts the size of the backend buffers (depth or sampling buffer) to the size of the window.
    pub fn size_alignment(&mut self) {
        let size = self.window().inner_size();
        let canvas_size = self.scene.scene_desc.render_texture.canvas_size;
        if canvas_size != (size.width, size.height) {
            let mut desc = self.scene.descriptor_mut();
            desc.render_texture.canvas_size = size.into();
            let config = desc.render_texture.compatible_surface_config();
            drop(desc);
            self.surface().configure(self.device(), &config);
        }
    }
    /// Render scene to initializing window.
    pub fn render_frame(&mut self) {
        self.size_alignment();
        let surface = self.surface();
        let surface_texture = match surface.get_current_texture() {
            Ok(got) => got,
            Err(_) => {
                let config = self
                    .scene
                    .scene_desc
                    .render_texture
                    .compatible_surface_config();
                surface.configure(self.device(), &config);
                surface
                    .get_current_texture()
                    .expect("Failed to acquire next surface texture!")
            }
        };
        let view = surface_texture
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        self.render(&view);
        surface_texture.present();
    }
More examples
Hide additional examples
src/lib.rs (line 343)
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
    fn render_object(&self, scene: &Scene) -> RenderObject {
        let (vertex_buffer, index_buffer) = self.vertex_buffer(scene.device_handler());
        let bind_group_layout = self.bind_group_layout(scene.device_handler());
        let bind_group = self.bind_group(scene.device_handler(), &bind_group_layout);
        let pipeline_layout = scene
            .device()
            .create_pipeline_layout(&PipelineLayoutDescriptor {
                bind_group_layouts: &[&scene.bind_group_layout, &bind_group_layout],
                push_constant_ranges: &[],
                label: None,
            });
        let pipeline = self.pipeline(scene.device_handler(), &pipeline_layout, &scene.scene_desc);
        RenderObject {
            vertex_buffer,
            index_buffer,
            bind_group_layout,
            bind_group,
            pipeline,
            visible: true,
        }
    }

Returns the reference of the queue.

Examples found in repository?
src/scene.rs (line 729)
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    pub fn render(&self, view: &TextureView) {
        let bind_group = self.scene_bind_group();
        let depth_view = self
            .foward_depth
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let sampled_view = self
            .sampling_buffer
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let mut encoder = self
            .device()
            .create_command_encoder(&CommandEncoderDescriptor { label: None });
        {
            let (attachment, resolve_target) = match sampled_view.as_ref() {
                Some(sampled_view) => (sampled_view, Some(view)),
                None => (view, None),
            };
            let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
                color_attachments: &[Some(RenderPassColorAttachment {
                    view: attachment,
                    resolve_target,
                    ops: Operations {
                        load: LoadOp::Clear(self.scene_desc.studio.background),
                        store: true,
                    },
                })],
                depth_stencil_attachment: depth_view
                    .as_ref()
                    .map(Self::depth_stencil_attachment_descriptor),
                ..Default::default()
            });
            rpass.set_bind_group(0, &bind_group, &[]);
            for (_, object) in &self.objects {
                if !object.visible {
                    continue;
                }
                rpass.set_pipeline(&object.pipeline);
                rpass.set_bind_group(1, &object.bind_group, &[]);
                rpass.set_vertex_buffer(0, object.vertex_buffer.buffer.slice(..));
                match object.index_buffer {
                    Some(ref index_buffer) => {
                        rpass.set_index_buffer(index_buffer.buffer.slice(..), IndexFormat::Uint32);
                        let index_size =
                            index_buffer.size as u32 / std::mem::size_of::<u32>() as u32;
                        rpass.draw_indexed(0..index_size, 0, 0..1);
                    }
                    None => rpass.draw(
                        0..(object.vertex_buffer.size / object.vertex_buffer.stride) as u32,
                        0..1,
                    ),
                }
            }
        }
        self.queue().submit(vec![encoder.finish()]);
    }

    /// Render image to buffer.
    pub async fn render_to_buffer(&self) -> Vec<u8> {
        let texture = self.compatible_texture();
        let view = texture.create_view(&Default::default());
        self.render(&view);
        let (device, queue) = (self.device(), self.queue());

        let (width, height) = self.scene_desc.render_texture.canvas_size;
        let size = (width * height * 4) as u64;
        let buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            mapped_at_creation: false,
            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
            size,
        });
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None });
        encoder.copy_texture_to_buffer(
            ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: Origin3d::ZERO,
                aspect: TextureAspect::All,
            },
            ImageCopyBuffer {
                buffer: &buffer,
                layout: ImageDataLayout {
                    offset: 0,
                    bytes_per_row: (width * 4).try_into().ok(),
                    rows_per_image: height.try_into().ok(),
                },
            },
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));
        let buffer_slice = buffer.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        buffer_slice.map_async(MapMode::Read, move |v| sender.send(v).unwrap());
        device.poll(Maintain::Wait);
        match receiver.receive().await {
            Some(Ok(_)) => buffer_slice.get_mapped_range().iter().copied().collect(),
            Some(Err(e)) => panic!("{}", e),
            None => panic!("Asynchronous processing fails"),
        }
    }

Returns the elapsed time since the scene was created.

Examples found in repository?
src/scene.rs (line 461)
455
456
457
458
459
460
461
462
463
464
465
    pub fn scene_status_buffer(&self) -> BufferHandler {
        let bk = self.scene_desc.studio.background;
        let size = self.scene_desc.render_texture.canvas_size;
        let scene_info = SceneInfo {
            background_color: [bk.r as f32, bk.g as f32, bk.b as f32, bk.a as f32],
            resolution: [size.0, size.1],
            time: self.elapsed().as_secs_f32(),
            num_of_lights: self.scene_desc.studio.lights.len() as u32,
        };
        BufferHandler::from_slice(&[scene_info], self.device(), BufferUsages::UNIFORM)
    }

Returns the reference of the descriptor.

Returns the mutable reference of the descriptor.

Remarks

When the return value is dropped, the depth buffer and sampling buffer are automatically updated. Use studio_config_mut if you only want to update the colors of the camera, lights, and background.

Examples found in repository?
src/scene.rs (line 819)
815
816
817
818
819
820
821
822
823
824
825
    pub fn size_alignment(&mut self) {
        let size = self.window().inner_size();
        let canvas_size = self.scene.scene_desc.render_texture.canvas_size;
        if canvas_size != (size.width, size.height) {
            let mut desc = self.scene.descriptor_mut();
            desc.render_texture.canvas_size = size.into();
            let config = desc.render_texture.compatible_surface_config();
            drop(desc);
            self.surface().configure(self.device(), &config);
        }
    }

Returns the reference of the studio configuration.

Returns the mutable reference of the studio configuration.

Returns the bind group layout in the scene.

Creates a UNIFORM buffer of the camera.

The bind group provides Scene holds this uniform buffer.

Shader Example
layout(set = 0, binding = 0) uniform Camera {
    mat4 camera_matrix;     // the camera matrix
    mat4 camera_projection; // the projection into the normalized view volume
};
Examples found in repository?
src/scene.rs (line 497)
492
493
494
495
496
497
498
499
500
501
502
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

Creates a STORAGE buffer of all lights.

The bind group provides Scene holds this uniform buffer.

Shader Example
struct Light {
    vec4 position;      // the position of light, position.w == 1.0
    vec4 color;         // the color of light, color.w == 1.0
    uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
};

layout(set = 0, binding = 1) buffer Lights {
    Light lights[]; // the number of lights must be gotten from another place
};
Examples found in repository?
src/scene.rs (line 498)
492
493
494
495
496
497
498
499
500
501
502
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

Creates a UNIFORM buffer of the scene status.

The bind group provides Scene holds this uniform buffer.

Shader Example
layout(set = 0, binding = 2) uniform Scene {
    vec4 bk_color;  // color of back ground
    float time;     // elapsed time since the scene was created.
    uint nlights;   // the number of lights
};
Examples found in repository?
src/scene.rs (line 499)
492
493
494
495
496
497
498
499
500
501
502
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

Creates bind group.

Shader Examples

Suppose binded as set = 0.

layout(set = 0, binding = 0) uniform Camera {
    mat4 camera_matrix;     // the camera matrix
    mat4 camera_projection; // the projection into the normalized view volume
};

struct Light {
    vec4 position;      // the position of light, position.w == 1.0
    vec4 color;         // the color of light, color.w == 1.0
    uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
};

layout(set = 0, binding = 1) buffer Lights {
    Light lights[];
};

layout(set = 0, binding = 2) uniform Scene {
    float time;     // elapsed time since the scene was created.
    uint nlights;   // the number of lights
};
Examples found in repository?
src/scene.rs (line 676)
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
    pub fn render(&self, view: &TextureView) {
        let bind_group = self.scene_bind_group();
        let depth_view = self
            .foward_depth
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let sampled_view = self
            .sampling_buffer
            .as_ref()
            .map(|tex| tex.create_view(&Default::default()));
        let mut encoder = self
            .device()
            .create_command_encoder(&CommandEncoderDescriptor { label: None });
        {
            let (attachment, resolve_target) = match sampled_view.as_ref() {
                Some(sampled_view) => (sampled_view, Some(view)),
                None => (view, None),
            };
            let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
                color_attachments: &[Some(RenderPassColorAttachment {
                    view: attachment,
                    resolve_target,
                    ops: Operations {
                        load: LoadOp::Clear(self.scene_desc.studio.background),
                        store: true,
                    },
                })],
                depth_stencil_attachment: depth_view
                    .as_ref()
                    .map(Self::depth_stencil_attachment_descriptor),
                ..Default::default()
            });
            rpass.set_bind_group(0, &bind_group, &[]);
            for (_, object) in &self.objects {
                if !object.visible {
                    continue;
                }
                rpass.set_pipeline(&object.pipeline);
                rpass.set_bind_group(1, &object.bind_group, &[]);
                rpass.set_vertex_buffer(0, object.vertex_buffer.buffer.slice(..));
                match object.index_buffer {
                    Some(ref index_buffer) => {
                        rpass.set_index_buffer(index_buffer.buffer.slice(..), IndexFormat::Uint32);
                        let index_size =
                            index_buffer.size as u32 / std::mem::size_of::<u32>() as u32;
                        rpass.draw_indexed(0..index_size, 0, 0..1);
                    }
                    None => rpass.draw(
                        0..(object.vertex_buffer.size / object.vertex_buffer.stride) as u32,
                        0..1,
                    ),
                }
            }
        }
        self.queue().submit(vec![encoder.finish()]);
    }

Adds a render object to the scene.

If there already exists a render object with the same ID, replaces the render object and returns false.

Examples found in repository?
src/scene.rs (line 534)
530
531
532
533
534
535
536
    pub fn add_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.add_object(object);
        objects.into_iter().fold(true, closure)
    }

Sets the visibility of a render object.

If there does not exist the render object in the scene, does nothing and returns false.

Adds render objects to the scene.

If there already exists a render object with the same ID, replaces the render object and returns false.

Removes a render object from the scene.

If there does not exist the render object in the scene, does nothing and returns false.

Examples found in repository?
src/scene.rs (line 552)
548
549
550
551
552
553
554
    pub fn remove_objects<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object| flag && self.remove_object(object);
        objects.into_iter().fold(true, closure)
    }

Removes render objects from the scene.

If there exists a render object which does not exist in the scene, returns false.

Removes all render objects from the scene.

Returns the number of the render objects in the scene.

Synchronizes the information of vertices of object in the CPU memory and that in the GPU memory.

If there does not exist the render object in the scene, does nothing and returns false.

Examples found in repository?
src/scene.rs (line 591)
587
588
589
590
591
592
593
    pub fn update_vertex_buffers<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_vertex_buffer(object);
        objects.into_iter().fold(true, closure)
    }

Synchronizes the information of vertices of objects in the CPU memory and that in the GPU memory.

If there exists a render object which does not exist in the scene, returns false.

Synchronizes the information of bind group of object in the CPU memory and that in the GPU memory.

If there does not exist the render object in the scene, does nothing and returns false.

Examples found in repository?
src/scene.rs (line 620)
616
617
618
619
620
621
622
    pub fn update_bind_groups<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_bind_group(object);
        objects.into_iter().fold(true, closure)
    }

Synchronizes the information of bind group of object in the CPU memory and that in the GPU memory.

If there exists a render object which does not exist in the scene, returns false.

Synchronizes the information of pipeline of object in the CPU memory and that in the GPU memory.

If there does not exist the render object in the scene, does nothing and returns false.

Examples found in repository?
src/scene.rs (line 657)
653
654
655
656
657
658
659
    pub fn update_pipelines<'a, R, I>(&mut self, objects: I) -> bool
    where
        R: 'a + Rendered,
        I: IntoIterator<Item = &'a R>, {
        let closure = move |flag, object: &R| flag && self.update_pipeline(object);
        objects.into_iter().fold(true, closure)
    }

Synchronizes the information of pipeline of object in the CPU memory and that in the GPU memory.

If there exists a render object which does not exist in the scene, returns false.

Renders the scene to view.

Examples found in repository?
src/scene.rs (line 736)
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    pub async fn render_to_buffer(&self) -> Vec<u8> {
        let texture = self.compatible_texture();
        let view = texture.create_view(&Default::default());
        self.render(&view);
        let (device, queue) = (self.device(), self.queue());

        let (width, height) = self.scene_desc.render_texture.canvas_size;
        let size = (width * height * 4) as u64;
        let buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            mapped_at_creation: false,
            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
            size,
        });
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor { label: None });
        encoder.copy_texture_to_buffer(
            ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: Origin3d::ZERO,
                aspect: TextureAspect::All,
            },
            ImageCopyBuffer {
                buffer: &buffer,
                layout: ImageDataLayout {
                    offset: 0,
                    bytes_per_row: (width * 4).try_into().ok(),
                    rows_per_image: height.try_into().ok(),
                },
            },
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));
        let buffer_slice = buffer.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        buffer_slice.map_async(MapMode::Read, move |v| sender.send(v).unwrap());
        device.poll(Maintain::Wait);
        match receiver.receive().await {
            Some(Ok(_)) => buffer_slice.get_mapped_range().iter().copied().collect(),
            Some(Err(e)) => panic!("{}", e),
            None => panic!("Asynchronous processing fails"),
        }
    }
}

impl WindowScene {
    /// Initialize scene compatible with `window`.
    pub async fn from_window(window: Arc<Window>, scene_desc: &WindowSceneDescriptor) -> Self {
        let size = window.inner_size();
        let got = init_default_device(Some(window)).await;
        let (device_handler, window_handler) = (got.0, got.1.unwrap());
        let (device, surface) = (&device_handler.device, &window_handler.surface);
        let render_texture = RenderTextureConfig {
            canvas_size: size.into(),
            format: TextureFormat::Bgra8Unorm,
        };
        let config = render_texture.compatible_surface_config();
        surface.configure(device, &config);

        Self {
            scene: Scene::new(
                device_handler,
                &SceneDescriptor {
                    studio: scene_desc.studio.clone(),
                    backend_buffer: scene_desc.backend_buffer,
                    render_texture,
                },
            ),
            window_handler,
        }
    }
    /// Get the reference of initializing window.
    #[inline(always)]
    pub fn window(&self) -> &Arc<Window> { &self.window_handler.window }
    /// Get the reference of surface.
    #[inline(always)]
    pub fn surface(&self) -> &Arc<Surface> { &self.window_handler.surface }
    /// Adjusts the size of the backend buffers (depth or sampling buffer) to the size of the window.
    pub fn size_alignment(&mut self) {
        let size = self.window().inner_size();
        let canvas_size = self.scene.scene_desc.render_texture.canvas_size;
        if canvas_size != (size.width, size.height) {
            let mut desc = self.scene.descriptor_mut();
            desc.render_texture.canvas_size = size.into();
            let config = desc.render_texture.compatible_surface_config();
            drop(desc);
            self.surface().configure(self.device(), &config);
        }
    }
    /// Render scene to initializing window.
    pub fn render_frame(&mut self) {
        self.size_alignment();
        let surface = self.surface();
        let surface_texture = match surface.get_current_texture() {
            Ok(got) => got,
            Err(_) => {
                let config = self
                    .scene
                    .scene_desc
                    .render_texture
                    .compatible_surface_config();
                surface.configure(self.device(), &config);
                surface
                    .get_current_texture()
                    .expect("Failed to acquire next surface texture!")
            }
        };
        let view = surface_texture
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        self.render(&view);
        surface_texture.present();
    }

Render image to buffer.

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.