Vala プログラミング

WebGPU プログラミング

おなが@京都先端科学大

Rust Vulkano Two Objects

f:id:onagat12:20190209180312p:plain

2つのオブジェクト(Two Objects)の描画方法
オブジェクト1(obj-1):キューブ(cube)
オブジェクト2(obj-2):床と壁(floor and Walls)

1 Vertex buffer と Index buffer
Vertex buffer と Index buffer はそれぞれのオブジェクトについて準備します。
オブジェクト1: vertex_buffer1, index_buffer1
オブジェクト2: vertex_buffer2, index_buffer2

2 shader と pipeline
・shader
2つのオブジェクトで同じvertex shader と fragmant shader を使用します。
vertex shader と fragment shader は、David Wolff「OpenGL 4.0
シェーディング言語 ( OpenGL 4.0 Shading Language Cookbook )」を
参考にしています。(オブジェクトの描画には、phongモデルを使用して
います。)
・pipeline
2つのオブジェクトで同じvertex shader と fragmant shader を使うので、
pipelineは一つだけになります。

3 uniform buffer
・shader内 uniform の記述

vertex shader
layout(set = 0, binding = 0) uniform MVP {
    mat4 view;
    mat4 mvp;
} mvp;

fragment shader
layout(set = 1, binding = 0) uniform Material {
    vec3 kd;
    float shininess;
    vec3 ks;
    float shininess2; // dummy
    vec3 ka;
} material;
  注)変数を上記のような順番にし、さらにdummy変数を追加しないとビルドできません。
layout(set = 1, binding = 1) uniform Light {
    vec4 position;
    vec3 intensity;
} light;

これらに対応した uniform buffer を生成します。

let ubo_mvp = vulkano::buffer::cpu_pool::CpuBufferPool::<vs::ty::MVP>
        ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());

let ubo_material = vulkano::buffer::cpu_pool::CpuBufferPool::<fs::ty::Material>
    ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());

let ubo_light = vulkano::buffer::cpu_pool::CpuBufferPool::<fs::ty::Light>
    ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());

・uniform データの設定

// uniform_buffer
        // mvp obj-1 and obj-2
        let ubo_mvp_subbuffer = {
            let uniform_data = vs::ty::MVP {
                view : view.into(),
                mvp : mvp.into(),
            };
            ubo_mvp.next(uniform_data).unwrap()
        };
        // material obj-1
        let ubo_material1_subbuffer = {
            let uniform_data = fs::ty::Material {
                kd : [0.5, 0.2, 0.1],
                shininess : 100.0,
                ks : [0.95, 0.95, 0.95],
                shininess2 : 100.0, // dummy
                ka : [0.1, 0.1, 0.1],
            };
            ubo_material.next(uniform_data).unwrap()
        };

        // material obj-2
        let ubo_material2_subbuffer = {
            let uniform_data = fs::ty::Material {
                kd : [0.4, 0.4, 0.4],
                shininess : 1.0,
                ks : [0.0, 0.0, 0.0],
                shininess2 : 1.0, // dummy
                ka : [0.1, 0.1, 0.1],
            };
            ubo_material.next(uniform_data).unwrap()
        };
        
        // light obj-1 and obj-2
        let ubo_light_subbuffer = {
            let uniform_data = fs::ty::Light {
                position : [0.0, 0.0, 0.0, 1.0],
                intensity : [1.0, 1.0, 1.0],
            };
            ubo_light.next(uniform_data).unwrap()
        };

・DescriptorSet
DescriptorSetの記述は以下のようにします。
obj-1の設定
vertex shaderの
layout(set = 0, binding = 0) uniform MVP
に対応させて、

let set10 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 0)
   .add_buffer(ubo_mvp_subbuffer.clone()).unwrap()
   .build().unwrap()
);

と記述する。

fragment shaderの
layout(set = 1, binding = 0) uniform Material
layout(set = 1, binding = 1) uniform Light
に対応させて、

let set11 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 1)
   .add_buffer(ubo_material1_subbuffer).unwrap()
   .add_buffer(ubo_light_subbuffer.clone()).unwrap()
   .build().unwrap()
);

と記述する。
obj-2も同様に記述する。

4 2つのオブジェクトの描画
command buffer における draw コマンドは次のように記述する。

// draw obj-2: first draw
.draw_indexed(pipeline.clone(), &dynamic_state,
    vertex_buffer2.clone(), index_buffer2.clone(),
    (set20.clone(), set21.clone()), ()).unwrap()
// draw obj-1: second draw
.draw_indexed(pipeline.clone(), &dynamic_state,
    vertex_buffer1.clone(), index_buffer1.clone(),
    (set10.clone(), set11.clone()), ()).unwrap()


プログラム

#[macro_use]
extern crate vulkano;
extern crate vulkano_shaders;
extern crate winit;
extern crate vulkano_win;
extern crate arcball;
extern crate cgmath;
extern crate image;

use vulkano_win::VkSurfaceBuild;
use vulkano::buffer::BufferUsage;
use vulkano::buffer::cpu_access::CpuAccessibleBuffer;
use vulkano::command_buffer::{AutoCommandBufferBuilder, DynamicState};
use vulkano::device::{Device, DeviceExtensions};
use vulkano::framebuffer::{Framebuffer, Subpass, FramebufferAbstract, RenderPassAbstract};
use vulkano::format::Format;
use vulkano::instance::{Instance, PhysicalDevice};
use vulkano::image::SwapchainImage;
use vulkano::image::attachment::AttachmentImage;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::viewport::Viewport;
use vulkano::swapchain;
use vulkano::swapchain::{Swapchain, PresentMode, SurfaceTransform, AcquireError,
        SwapchainCreationError};
use vulkano::sync;
use vulkano::sync::now;
use vulkano::sync::GpuFuture;
use vulkano::descriptor::descriptor_set::PersistentDescriptorSet;

use winit::{Window, EventsLoop, WindowBuilder};
use std::sync::Arc;

static WINDOW_NAME: &str = "Tow Objects";
static WIN_WIDTH: f64 = 700.0;
static WIN_HEIGHT: f64 = 650.0;

struct Vulkan {
    images: Vec<std::sync::Arc<vulkano::image::SwapchainImage<winit::Window>>>,
    swapchain: Arc<vulkano::swapchain::Swapchain<winit::Window>>,
    device: Arc<vulkano::device::Device>,
    queue: Arc<vulkano::device::Queue>,
    events_loop: winit::EventsLoop,
    surface: Arc<vulkano::swapchain::Surface<winit::Window>>,
}

impl Vulkan {
    pub fn init_vk() -> Vulkan {
        let extensions = vulkano_win::required_extensions();
        let instance = Instance::new(None, &extensions, None).unwrap();

        let physical = PhysicalDevice::enumerate(&instance).next().unwrap();
        println!("Using device: {} (type: {:?})", physical.name(), physical.ty());

        // events_loop, surface, window
        let  events_loop = EventsLoop::new();
        let surface = WindowBuilder::new()
            .with_dimensions(winit::dpi::LogicalSize {width:WIN_WIDTH, height:WIN_HEIGHT})
            .with_title(WINDOW_NAME.to_string())
            .build_vk_surface(&events_loop, instance.clone()).unwrap();
        
        // (device, queues), queue_family
        let queue_family = physical.queue_families().find(|&q| {
            q.supports_graphics() && surface.is_supported(q).unwrap_or(false)
        }).unwrap();

        let device_ext = DeviceExtensions { khr_swapchain: true, .. DeviceExtensions::none() };
        let (device, mut queues) = Device::new(physical, physical.supported_features(),
            &device_ext, [(queue_family, 0.5)].iter().cloned()).unwrap();
        // first queue
        let queue = queues.next().unwrap();

        let initial_dimensions  = [WIN_WIDTH as u32, WIN_HEIGHT as u32];
        let caps = surface.capabilities(physical).unwrap();
    
        let (swapchain, images) = {
            let usage = caps.supported_usage_flags;
            let alpha = caps.supported_composite_alpha.iter().next().unwrap();
            let format = caps.supported_formats[1].0; // formats[1]
            //
            Swapchain::new(device.clone(), surface.clone(), caps.min_image_count, format,
                initial_dimensions, 1, usage, &queue, SurfaceTransform::Identity, alpha,
                PresentMode::Fifo, true, None).unwrap()
        };
      
        Vulkan {
            images,
            swapchain,
            device,
            queue,
            surface,
            events_loop,
        } 
    }
}

fn main() {
    let mut vk = Vulkan::init_vk();

    #[derive(Debug, Clone)]
    struct Vertex { position: [f32; 3], normal: [f32; 3] }
    impl_vertex!(Vertex, position, normal);
    
    // obj-1
    let vertex_buffer1 = {
        let side2: f32 = 0.5 / 2.0;

        CpuAccessibleBuffer::from_iter(vk.device.clone(), BufferUsage::all(), [
            // Front
            Vertex { position: [-side2, -side2,  side2], normal: [0.0, 0.0, 1.0] },
    	    Vertex { position: [ side2, -side2,  side2], normal: [0.0, 0.0, 1.0] },
    	    Vertex { position: [ side2,  side2,  side2], normal: [0.0, 0.0, 1.0] },
            Vertex { position: [-side2,  side2,  side2], normal: [0.0, 0.0, 1.0] },
    	    // Right
    	    Vertex { position: [ side2, -side2,  side2], normal: [1.0, 0.0, 0.0] },
    	    Vertex { position: [ side2, -side2, -side2], normal: [1.0, 0.0, 0.0] },
    	    Vertex { position: [ side2,  side2, -side2], normal: [1.0, 0.0, 0.0] },
            Vertex { position: [ side2,  side2,  side2], normal: [1.0, 0.0, 0.0] },
    	    // Back
    	    Vertex { position: [-side2, -side2, -side2], normal: [0.0, 0.0, -1.0] },
    	    Vertex { position: [-side2,  side2, -side2], normal: [0.0, 0.0, -1.0] },
    	    Vertex { position: [ side2,  side2, -side2], normal: [0.0, 0.0, -1.0] },
            Vertex { position: [ side2, -side2, -side2], normal: [0.0, 0.0, -1.0] },
    	    // Left
    	    Vertex { position: [-side2, -side2,  side2], normal: [-1.0, 0.0, 0.0] },
    	    Vertex { position: [-side2,  side2,  side2], normal: [-1.0, 0.0, 0.0] },
            Vertex { position: [-side2,  side2, -side2], normal: [-1.0, 0.0, 0.0] },
            Vertex { position: [-side2, -side2, -side2], normal: [-1.0, 0.0, 0.0] },
            // Bottom
    	    Vertex { position: [-side2, -side2,  side2], normal: [0.0, -1.0, 0.0] },
    	    Vertex { position: [-side2, -side2, -side2], normal: [0.0, -1.0, 0.0] },
    	    Vertex { position: [ side2, -side2, -side2], normal: [0.0, -1.0, 0.0] },
            Vertex { position: [ side2, -side2,  side2], normal: [0.0, -1.0, 0.0] },
    	    // Top
            Vertex { position: [-side2,  side2,  side2], normal: [0.0, 1.0, 0.0] },
    	    Vertex { position: [ side2,  side2,  side2], normal: [0.0, 1.0, 0.0] },
    	    Vertex { position: [ side2,  side2, -side2], normal: [0.0, 1.0, 0.0] },
            Vertex { position: [-side2,  side2, -side2], normal: [0.0, 1.0, 0.0] }
        ].iter().cloned()).expect("failed to create buffer")
    };
    
    let index_buffer1 = vulkano::buffer::cpu_access::CpuAccessibleBuffer::from_iter(
        vk.device.clone(), vulkano::buffer::BufferUsage::all(), [
            // Front
            0u16, 1, 2, 2, 3, 0,
            // Right
            4, 5, 6, 6, 7, 4,
            // Back
            8, 9, 10, 10, 11, 8,
            // Left
            12, 13, 14, 14, 15, 12,
            // Bottom
            16, 17, 18, 18, 19, 16,
            // Top
            20, 21, 22, 22, 23, 20,
        ].iter().cloned()).expect("failed to create buffer");
    
    // obj-2
    let vertex_buffer2 = {    
        CpuAccessibleBuffer::from_iter(vk.device.clone(), BufferUsage::all(),
        [ Vertex { position: [-0.5, -0.5,  0.5], normal: [ 0.0, 1.0, 0.0] },
          Vertex { position: [ 0.5, -0.5,  0.5], normal: [ 0.0, 1.0, 0.0] },
          Vertex { position: [ 0.5, -0.5, -0.5], normal: [ 0.0, 1.0, 0.0] },
          Vertex { position: [-0.5, -0.5, -0.5], normal: [ 0.0, 1.0, 0.0] },
          //
          Vertex { position: [ 0.5, -0.5,  0.5], normal: [-1.0, 0.0, 0.0] },
          Vertex { position: [ 0.5,  0.5,  0.5], normal: [-1.0, 0.0, 0.0] },
          Vertex { position: [ 0.5,  0.5, -0.5], normal: [-1.0, 0.0, 0.0] },
          Vertex { position: [ 0.5, -0.5, -0.5], normal: [-1.0, 0.0, 0.0] },
          //
          Vertex { position: [-0.5, -0.5, -0.5], normal: [ 0.0, 0.0, 1.0] },
          Vertex { position: [ 0.5, -0.5, -0.5], normal: [ 0.0, 0.0, 1.0] },
          Vertex { position: [ 0.5,  0.5, -0.5], normal: [ 0.0, 0.0, 1.0] },
          Vertex { position: [-0.5,  0.5, -0.5], normal: [ 0.0, 0.0, 1.0] },
        ].iter().cloned()).expect("failed to create buffer")
    };
    
    let index_buffer2 = vulkano::buffer::cpu_access::CpuAccessibleBuffer::from_iter(
        vk.device.clone(), vulkano::buffer::BufferUsage::all(), [
            0u16, 1, 2, 2, 3, 0,
            4, 5, 6, 6, 7, 4,
            8, 9, 10, 10, 11, 8
        ].iter().cloned()).expect("failed to create buffer");
    
    let ubo_mvp = vulkano::buffer::cpu_pool::CpuBufferPool::<vs::ty::MVP>
        ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());
    //
    let ubo_material = vulkano::buffer::cpu_pool::CpuBufferPool::<fs::ty::Material>
        ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());
    //
    let ubo_light = vulkano::buffer::cpu_pool::CpuBufferPool::<fs::ty::Light>
        ::new(vk.device.clone(), vulkano::buffer::BufferUsage::all());
    
    let vs = vs::Shader::load(vk.device.clone()).expect("failed to create shader module");
    let fs = fs::Shader::load(vk.device.clone()).expect("failed to create shader module");

    // render pass
    let render_pass = Arc::new(single_pass_renderpass!(vk.device.clone(),
        attachments: {
            color: {
                load: Clear,
                store: Store,
                format: vk.swapchain.format(),
                samples: 1,
            },
            depth: {
                load: Clear,
                store: DontCare,
                format: vulkano::format::Format::D16Unorm,
                samples: 1,
            } // depth
        },
        pass: {
            color: [color],
            depth_stencil: {depth} // depth
        }
    ).unwrap());

    let window = vk.surface.window();

    let mut dimensions = if let Some(dimensions) = window.get_inner_size() {
        let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into();
        [dimensions.0, dimensions.1]
    } else {
        return;
    };

    // framebuffer(use dynamic_state viewport) 
    let mut dynamic_state = DynamicState { line_width: None, viewports: None, scissors: None };
    let mut framebuffers = window_size_dependent_setup(vk.device.clone(),
        &vk.images, render_pass.clone(), &mut dynamic_state);

    // pipeliner(use dynamic_state viewport)
    let pipeline = Arc::new(GraphicsPipeline::start()
        .vertex_input_single_buffer()
        .vertex_shader(vs.main_entry_point(), ())
        .triangle_list()
        .viewports_dynamic_scissors_irrelevant(1)
        .fragment_shader(fs.main_entry_point(), ())
        .depth_stencil_simple_depth()
        .render_pass(Subpass::from(render_pass.clone(), 0).unwrap())
        .build(vk.device.clone())
        .unwrap());
    
    let mut recreate_swapchain = false;
    let mut previous_frame = Box::new(now(vk.device.clone())) as Box<GpuFuture>;

    let persp_proj:cgmath::Matrix4<f32> = cgmath::perspective(cgmath::Deg(65.0),
        dimensions[0] as f32 / dimensions[1] as f32, 0.01, 100.0);
    let mut arcball_camera = {
        let look_at = cgmath::Matrix4::look_at(cgmath::Point3::new(0.0, 0.0, 2.0),
                      cgmath::Point3::new(0.0, 0.0, 0.0), cgmath::Vector3::new(0.0, 1.0, 0.0));
        arcball::ArcballCamera::new(&look_at, 0.05, 4.0, [dimensions[0] as f32, dimensions[1] as f32])
    };
    //
    let mut arcball_camera_mat4: [[f32;4];4] = arcball_camera.get_mat4().into();
    
    let mut mouse_pressed = [false, false];
    let mut prev_mouse: Option<(f64,f64)> = None;

    loop {
        previous_frame.cleanup_finished();

        if recreate_swapchain {
            dimensions = if let Some(dimensions) = window.get_inner_size() {
                let dimensions: (u32, u32) =
                    dimensions.to_physical(window.get_hidpi_factor()).into();
                [dimensions.0, dimensions.1]
            } else {
                return;
            };
            
            let (new_swapchain, new_images) = match vk.swapchain.recreate_with_dimension(dimensions) {
                Ok(r) => r,
                Err(SwapchainCreationError::UnsupportedDimensions) => continue,
                Err(err) => panic!("{:?}", err)
            };

            vk.swapchain = new_swapchain;

            framebuffers = window_size_dependent_setup(vk.device.clone(),
               &new_images, render_pass.clone(), &mut dynamic_state);

            recreate_swapchain = false;
        }

        let view = arcball_camera.get_mat4();
        let mvp = persp_proj * view;
        
        // uniform_buffer
        // mvp obj-1 and obj-2
        let ubo_mvp_subbuffer = {
            let uniform_data = vs::ty::MVP {
                view : view.into(),
                mvp : mvp.into(),
            };
            ubo_mvp.next(uniform_data).unwrap()
        };
        // material obj-1
        let ubo_material1_subbuffer = {
            let uniform_data = fs::ty::Material {
                kd : [0.5, 0.2, 0.1],
                shininess : 100.0,
                ks : [0.95, 0.95, 0.95],
                shininess2 : 100.0, // dummy
                ka : [0.1, 0.1, 0.1],
            };
            ubo_material.next(uniform_data).unwrap()
        };

        // material obj-2
        let ubo_material2_subbuffer = {
            let uniform_data = fs::ty::Material {
                kd : [0.4, 0.4, 0.4],
                shininess : 1.0,
                ks : [0.0, 0.0, 0.0],
                shininess2 : 1.0, // dummy
                ka : [0.1, 0.1, 0.1],
            };
            ubo_material.next(uniform_data).unwrap()
        };
        
        // light obj-1 and obj-2
        let ubo_light_subbuffer = {
            let uniform_data = fs::ty::Light {
                position : [0.0, 0.0, 0.0, 1.0],
                intensity : [1.0, 1.0, 1.0],
            };
            ubo_light.next(uniform_data).unwrap()
        };

        // uniform set
        // obj-1 set10, set11
        let set10 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 0)
            .add_buffer(ubo_mvp_subbuffer.clone()).unwrap()
            .build().unwrap()
        );
        let set11 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 1)
            .add_buffer(ubo_material1_subbuffer).unwrap()
            .add_buffer(ubo_light_subbuffer.clone()).unwrap()
            .build().unwrap()
        );
        // obj-2 set20, set21
        let set20 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 0)
            .add_buffer(ubo_mvp_subbuffer).unwrap()
            .build().unwrap()
        );
        let set21 = Arc::new(PersistentDescriptorSet::start(pipeline.clone(), 1)
            .add_buffer(ubo_material2_subbuffer).unwrap()
            .add_buffer(ubo_light_subbuffer.clone()).unwrap()
            .build().unwrap()
        );
        
        let (image_num, acquire_future) =
            match swapchain::acquire_next_image(vk.swapchain.clone(), None) {
                Ok(r) => r,
                Err(AcquireError::OutOfDate) => {
                    recreate_swapchain = true;
                    continue;
                },
                Err(err) => panic!("{:?}", err)
            };

        let command_buffer =
            AutoCommandBufferBuilder::primary_one_time_submit(vk.device.clone(), vk.queue.family()).unwrap() // Ok
            .begin_render_pass(framebuffers[image_num].clone(), false,
                vec![[0.2, 0.2, 0.3, 1.0].into(), 1f32.into()]).unwrap()
            // draw obj-2: first draw
            .draw_indexed(pipeline.clone(), &dynamic_state,
                vertex_buffer2.clone(), index_buffer2.clone(),
                (set20.clone(), set21.clone()), ()).unwrap()
            // draw obj-1: second draw
            .draw_indexed(pipeline.clone(), &dynamic_state,
                vertex_buffer1.clone(), index_buffer1.clone(),
                (set10.clone(), set11.clone()), ()).unwrap()
            .end_render_pass().unwrap()
            .build().unwrap();

        let future = previous_frame.join(acquire_future)
            .then_execute(vk.queue.clone(), command_buffer).unwrap()
            .then_swapchain_present(vk.queue.clone(), vk.swapchain.clone(), image_num)
            .then_signal_fence_and_flush();

        match future {
            Ok(future) => {
                previous_frame = Box::new(future) as Box<_>;
            }
            Err(sync::FlushError::OutOfDate) => {
                recreate_swapchain = true;
                previous_frame = Box::new(sync::now(vk.device.clone())) as Box<_>;
            }
            Err(e) => {
                println!("{:?}", e);
                previous_frame = Box::new(sync::now(vk.device.clone())) as Box<_>;
            }
        }

        let mut done = false;
        vk.events_loop.poll_events(|ev| {
            match ev {
                winit::Event::WindowEvent {
                    event: winit::WindowEvent::CursorMoved { position: winit::dpi::LogicalPosition {x, y}, ..}, ..}
                       if prev_mouse.is_none() => {
                                    prev_mouse = Some((x, y));
                },
                winit::Event::WindowEvent {
                    event: winit::WindowEvent::CursorMoved { position: winit::dpi::LogicalPosition {x, y}, .. }, ..}  => {
                        //println!("MouseMoved {},{}", x, y);
                        let prev = prev_mouse.unwrap();
                        if mouse_pressed[0] {
                            arcball_camera.rotate(cgmath::Vector2::new(prev.0 as f32, prev.1 as f32),
                                                  cgmath::Vector2::new(x as f32, y as f32));
                            arcball_camera_mat4 = arcball_camera.get_mat4().into();
                            //println!("rotate mat4: {:?}", arcball_camera_mat4);
                        } else if mouse_pressed[1] {
                            let mouse_delta = cgmath::Vector2::new((x - prev.0) as f32, -(y - prev.1) as f32);
                            arcball_camera.pan(mouse_delta, 0.16);
                            arcball_camera_mat4 = arcball_camera.get_mat4().into();
                            //println!("pan mat4: {:?}", arcball_camera_mat4);
                        }
                        prev_mouse = Some((x, y));
                },
                winit::Event::WindowEvent {
                    event: winit::WindowEvent::MouseInput { state: _state, button: _button, ..}, ..} => {
                        //println!("button {:?}", _button);
                        if _button == winit::MouseButton::Left {
                            mouse_pressed[0] = _state == winit::ElementState::Pressed;
                        } else if _button == winit::MouseButton::Right {
                            mouse_pressed[1] = _state == winit::ElementState::Pressed;
                        }
                },
                winit::Event::WindowEvent {
                    event: winit::WindowEvent::MouseWheel {
                        delta: winit::MouseScrollDelta::LineDelta(_, y), .. }, ..}  => {
                            //println!("ScrollDelta {}", y);
                            arcball_camera.zoom(y, 0.1);
                            arcball_camera_mat4 = arcball_camera.get_mat4().into();
                            //println!("zoom mat4: {:?}", arcball_camera_mat4);
                },
                winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => done = true,
                _ => ()
            }
        });
        if done { return; }
    }
}

fn window_size_dependent_setup(
    device: Arc<Device>,
    images: &[Arc<SwapchainImage<Window>>],
    render_pass: Arc<RenderPassAbstract + Send + Sync>,
    dynamic_state: &mut DynamicState
) -> Vec<Arc<FramebufferAbstract + Send + Sync>> {
    let dimensions = images[0].dimensions();
    // dynamic viewport
    let viewport = Viewport {
        origin: [0.0, 0.0],
        dimensions: [dimensions[0] as f32, dimensions[1] as f32],
        depth_range: 0.0 .. 1.0,
    };
    dynamic_state.viewports = Some(vec!(viewport));

    let depth_buffer = AttachmentImage::transient(device.clone(), dimensions, Format::D16Unorm).unwrap();

    images.iter().map(|image| {
        Arc::new(
            Framebuffer::start(render_pass.clone())
                .add(image.clone()).unwrap()
                .add(depth_buffer.clone()).unwrap()
                .build().unwrap()
        ) as Arc<FramebufferAbstract + Send + Sync>
    }).collect::<Vec<_>>()
}

mod vs {
    vulkano_shaders::shader!{
        ty: "vertex",
        src: "
            #version 450

            layout(location = 0) in vec3 position;
            layout(location = 1) in vec3 normal;

            layout(location = 0) out vec4 EyePosition;
            layout(location = 1) out vec3 EyeNormal;

            layout(set = 0, binding = 0) uniform MVP {
                mat4 view;
                mat4 mvp;
            } mvp;

            void main()
            {
                vec4 pos4 = vec4(position, 1.0);

                EyeNormal = normalize((mvp.view * vec4(normal,0)).xyz);
                EyePosition = mvp.view * pos4;
                gl_Position = mvp.mvp * vec4(position, 1.0);
            }"
    }
}
//
mod fs {
    vulkano_shaders::shader!{
        ty: "fragment",
        src: "
            #version 450

            layout(location = 0) in vec4 EyePosition;
            layout(location = 1) in vec3 EyeNormal;

            layout(location = 0) out vec4 f_color;

            layout(set = 1, binding = 0) uniform Material {
                vec3 kd;
                float shininess;
                vec3 ks;
                float shininess2; // dummy
                vec3 ka;
            } material;

            layout(set = 1, binding = 1) uniform Light {
                vec4 position;
                vec3 intensity;
            } light;

            vec3 phongModel( vec3 pos, vec3 norm ) {
                vec3 s = normalize(vec3(light.position) - pos);
                vec3 v = normalize(-pos.xyz);
                vec3 r = reflect( -s, norm );
                vec3 ambient = light.intensity * material.ka;
                float sDotN = max( dot(s,norm), 0.0 );
                vec3 diffuse = light.intensity * material.kd * sDotN;
                vec3 spec = vec3(0.0);
                if( sDotN > 0.0 )
                    spec = light.intensity * material.ks *
                    pow( max( dot(r,v), 0.0 ), material.shininess );

                return ambient + diffuse + spec;
            }

            void main()
            {
                vec3 color = phongModel(vec3(EyePosition), EyeNormal);

	            f_color = vec4(color, 1.0);
            }"
    }
}