셰이더 드로잉: 환경 06

이전 글에서 이어집니다.

새로고침

지금 프로그램은 include_str으로 셰이더 파일을 읽고 있다. include_str은 매크로다. 컴파일 시 입력받은 경로 파일 내용을 문자열 참조로 실행 파일에 포함시킨다. 따라서 프로그램 실행 중 셰이더 코드는 고정된다. 이를 컴파일 단계가 아니라 프로그램이 실행될 때 읽게 하면 실행 중에 셰이더 코드를 고쳐도 반영할 수 있게 된다. read_to_string은 경로를 입력받아 파일 내용을 Result<String> 타입으로 반환한다. 셰이더 코드가 직접 포함되어 실행되는 게 아니라, 프로그램 실행 시 성공과 실패의 형태로 셰이더 코드를 반환하게 된다. 실패 가능성을 컴파일 이후 단계에 부여하는 셈이다.

fn main() {
    let shader_path = match std::env::args().nth(1) {
        Some(path) => path,
        None => {
            eprintln!("Shader 경로 미입력: cargo run -- []");
            return
        },
    };

    let event_loop = EventLoop::new().expect("EventLoop 생성 실패");
    let mut app = App::new(shader_path);
    event_loop.run_app(&mut app).expect("애플리케이션 실행 실패");
}
pub struct App {
    window: Option<Arc<Window>>,
    gpu_state: Option<GpuState>,
    shader_path: String,
    playback_state: PlaybackState,
    pressed_keys: HashSet<PhysicalKey>,
}

impl App {
    pub fn new(shader_path: String) -> Self {
        App {
            window: None,
            gpu_state: None,
            shader_path: shader_path,
            playback_state: PlaybackState::Paused { base: 0 },
            pressed_keys: HashSet::new(),
        }
    }
    ...
}

args로 경로 입력을 받아준다. args는 프로그램 실행 시 입력되는 인자를 반환한다. 일단 프로그램은 경로 입력이 없으면 오류를 출력하고 종료되도록 하고, App의 생성 함수가 해당 경로를 받아 보관할 수 있도록 한다.

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        ...
        match create_window {
            Ok(window) => {
                // window 초기화
                ...

                // shader_code 읽기
                let shader_code = match std::fs::read_to_string(&self.shader_path) {
                    Ok(code) => code,
                    Err(err) => {
                        eprintln!("{err}");
                        return
                    }
                };

                // gpu 초기화
                let gpu_state = block_on(GpuState::new(window.clone(), shader_code));
                ...
            },
            ...
        }
    }
}
impl GpuState {
    pub async fn new(window: Arc<Window>, shader_code: String) -> anyhow::Result<Self> {
        ...
        let shader_module = device.create_shader_module(
            wgpu::ShaderModuleDescriptor {
                label: Some("shader_module"),
                source: wgpu::ShaderSource::Wgsl(shader_code.into()),
            }
        );
        ...
    }
}

App의 resumed 콜백 내에서 read_to_string으로 경로의 셰이더 코드를 읽고 GpuState 생성 함수에 넘긴다. GpuState 내에서 전달받은 shader_code로 ShaderModule을 생성하도록 한다. 여기까지 기존 include_str에서 read_to_string으로 전환했다.

오류 처리

지금은 셰이더 파일에 문제가 있다면 그냥 프로그램이 터진다. wgpu는 WebGPU 표준에 따라 비동기적으로 작동해서, 곧바로 성공 여부를 반환하지 않고 처리 명령만 보낸 채 돌아온다. 그래서 create_shader_module이나 create_render_pipeline은 Result를 반환하는 메서드가 아니며, 셰이더 파일 안에서 오류가 나면 오류를 받을 대상이 없어 프로그램이 터지는 것이다. 이를 해결하기 위해 push_error_scope를 사용한다. push_error_scope를 호출하면 pop할 때까지 해당 Device에서 생긴 오류를 모아 두고, pop은 그 결과를 Future<Option<Error>>로 돌려준다.

let shader_error = device.push_error_scope(wgpu::ErrorFilter::Validation);

let shader_module = device.create_shader_module(...);
let render_pipeline = device.create_render_pipeline(...);

if let Some(err) = shader_error.pop().await {
    return Err(anyhow!("{err}"))
}

ErrorFilter를 Validation으로 설정해 검증 오류를 받아오게 한다. pop 결과에 오류가 있으면 anyhow 오류로 바꿔 반환한다.

Caused by:
  In Device::create_shader_module, label = 'shader_module'
    
Shader 'shader_module' parsing error: no definition in scope for identifier: `time`
   ┌─ wgsl:40:35
   │
40 │     var circle = sdCircle(uv, sin(time) * 0.5 + 0.5);
   │                                   ^^^^ unknown identifier


: GpuState 생성 실패

실패 시 터미널 출력도 간결해진다.

키보드 입력

이다음은 간단하다. App의 키보드 이벤트 콜백 내에서 Cmd + R 키가 눌렸을 때 셰이더 파일을 새로 반영하면 된다. read_to_string으로 shader_code를 다시 읽고, 그로 만들어지는 ShaderModule, 그리고 RenderPipeline까지 전부 새로 만들어 GpuState의 render_pipeline을 교체해주면 된다.

pub struct GpuState {
    ...
    pipeline_layout: wgpu::PipelineLayout,
    ...
}

impl GpuState {
    pub async fn new(window: Arc<Window>, shader_code: String) -> anyhow::Result<Self> {
        ...
        let pipeline_layout = device.create_pipeline_layout(...);
        ...
        Ok(GpuState {
            ...
            pipeline_layout: pipeline_layout,
            ...
        })
    }
}

과정 중 PipelineLayout을 입력할 필요가 있으니 필드에 보관하게 한다.

async fn create_render_pipeline(
    device: &wgpu::Device,
    pipeline_layout: &wgpu::PipelineLayout,
    format: wgpu::TextureFormat,
    shader_code: String,
) -> anyhow::Result<wgpu::RenderPipeline> {
    // 오류 스코프
    let shader_error = device.push_error_scope(wgpu::ErrorFilter::Validation);
    let shader_module = device.create_shader_module(
        wgpu::ShaderModuleDescriptor {
            label: Some("shader_module"),
            source: wgpu::ShaderSource::Wgsl(shader_code.into()),
        }
    );
    let render_pipeline = device.create_render_pipeline(
        &wgpu::RenderPipelineDescriptor {
            label: Some("render_pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader_module,
                entry_point: Some("vertex_main"),
                compilation_options: Default::default(),
                buffers: &[Some(wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &wgpu::vertex_attr_array![
                        0 => Float32x2,
                        1 => Float32x2,
                        2 => Float32x3,
                    ],
                })],
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: Default::default(),
            fragment: Some(wgpu::FragmentState {
                module: &shader_module,
                entry_point: Some("fragment_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        }
    );
    if let Some(err) = shader_error.pop().await {
        return Err(anyhow!("{err}"))
    }
    Ok(render_pipeline)
}

RenderPipeline 생성 블록을 함수로 만든다.

pub async fn new(window: Arc<Window>, shader_code: String) -> anyhow::Result<Self> {
    ...
    let render_pipeline = create_render_pipeline(
        &device,
        &pipeline_layout,
        config.format,
        shader_code,
    ).await?;
    ...
}
pub async fn reload_shader(&mut self, shader_code: String) -> anyhow::Result<()> {
    self.render_pipeline = create_render_pipeline(
        &self.device,
        &self.pipeline_layout,
        self.config.format,
        shader_code,
    ).await?;
    Ok(())
}

RenderPipeline을 반환하는 일반 함수 create_render_pipeline을 이용해 GpuState 초기화 때 파이프라인을 만들고, App의 이벤트 콜백에서 사용할 reload_shader 메서드도 만든다.

WindowEvent::KeyboardInput { event, .. } => {
    ...
    if state == winit::event::ElementState::Pressed {
        ...
        if self.pressed_keys.contains(&PhysicalKey::Code(KeyCode::KeyR))
            && self.pressed_keys.contains(&PhysicalKey::Code(KeyCode::SuperLeft))
        {
            if let Some(state) = &mut self.gpu_state {
                let shader_code = match std::fs::read_to_string(&self.shader_path) {
                    Ok(code) => code,
                    Err(err) => {
                        eprintln!("{err}");
                        return
                    }
                };
                match pollster::block_on(state.reload_shader(shader_code)) {
                    Ok(()) => {
                        if let Some(window) = &self.window {
                            window.request_redraw();
                        };
                    },
                    Err(err) => {
                        eprintln!("{err}");
                    },
                }
            }
        }
    }
},

키보드 이벤트 콜백에서 이 동작을 호출한다. 이제 Cmd + R을 누르면 셰이더 코드를 새로 읽고, ShaderModule과 RenderPipeline을 새로 만들어 기존 파이프라인과 교체한다.

파이프라인 생성을 일반 함수로 분리하는 게 깔끔하지 못하다고 생각해 GpuState의 메서드로 만들어 진행했다. 그러나 메서드로 만들려면 RenderPipeline을 Option으로 두고 초기화 뒤에 채워 넣어야 했고, 그러자 오히려 코드가 전반적으로 복잡해졌다. 메서드로 통일하는 쪽은 파일 단위로는 더 깔끔해 보일 수 있지만 KISS(Keep It Simple, Stupid)에 반한다. 더 좋은 방법이 있을지 모르겠지만, 일단 일반 함수로 분리하는 방향이 최선인 듯하다.

다음 글로 이어집니다.