1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! This module provides a tool for automatically recompiling a shader-slang
//! file any time it changes.
//!
//! This works so long as `slangc` is in your PATH. `slangc` is now shipped as
//! part of the Vulkan SDK.

use {
    super::vulkan::VulkanContext,
    crate::{
        graphics::vulkan::{compile_slang, raii},
        trace,
    },
    anyhow::{anyhow, Context, Result},
    notify_debouncer_full::{
        new_debouncer, notify::RecursiveMode, DebounceEventResult,
    },
    std::{
        path::{Path, PathBuf},
        sync::{
            mpsc::{sync_channel, Receiver, SyncSender, TryRecvError},
            Arc,
        },
        thread::JoinHandle,
        time::Duration,
    },
};

/// Automatically recompiles a slang source file any time it changes.
pub struct Recompiler {
    shader: Arc<raii::ShaderModule>,
    compile_thread_join_handle: Option<JoinHandle<()>>,
    shutdown_sender: SyncSender<()>,
    shader_receiver: Receiver<raii::ShaderModule>,
}

impl Recompiler {
    /// Creates a new recompiler that attempts to compile the given shader
    /// source. Returns an error if the initial compilation fails.
    pub fn new(
        ctx: Arc<VulkanContext>,
        shader_source_path: &Path,
        additional_watch_paths: &[PathBuf],
    ) -> Result<Self> {
        let shader = compile_slang(&ctx, shader_source_path)
            .with_context(trace!("Initial build for shader failed!"))?;

        let (shutdown_sender, shutdown_receiver) = sync_channel::<()>(1);
        let (source_sender, source_receiver) =
            sync_channel::<raii::ShaderModule>(1);

        let compile_thread_join_handle = spawn_compiler_thread(
            ctx,
            shader_source_path,
            additional_watch_paths,
            source_sender,
            shutdown_receiver,
        )
        .with_context(trace!("Error while spawning the compiler thread!"))?;

        Ok(Self {
            shader: Arc::new(shader),
            compile_thread_join_handle: Some(compile_thread_join_handle),
            shutdown_sender,
            shader_receiver: source_receiver,
        })
    }

    /// Clones the current fragment shader instance.
    pub fn shader(&self) -> Arc<raii::ShaderModule> {
        self.shader.clone()
    }

    /// Checks for an updated copy of the compiled source code.
    ///
    /// # Returns
    ///
    /// - true: when there was an updated version of the source available
    /// - false: there was no pending update
    pub fn check_for_update(&mut self) -> Result<bool> {
        match self.shader_receiver.try_recv() {
            Ok(new_shader) => {
                self.shader = Arc::new(new_shader);
                Ok(true)
            }
            Err(TryRecvError::Empty) => Ok(false),
            Err(TryRecvError::Disconnected) => {
                Err(anyhow!(TryRecvError::Disconnected))
                    .with_context(trace!("Compiler thread disconnected!"))
            }
        }
    }
}

impl Drop for Recompiler {
    fn drop(&mut self) {
        self.shutdown_sender
            .send(())
            .expect("Unable to send shutdown signal to the compiler thread!");
        self.compile_thread_join_handle
            .take()
            .unwrap()
            .join()
            .expect("Unable to join compiler thread!");
    }
}

fn spawn_compiler_thread(
    ctx: Arc<VulkanContext>,
    shader_source_path: &Path,
    additional_watch_paths: &[PathBuf],
    shader_sender: SyncSender<raii::ShaderModule>,
    shutdown_receiver: Receiver<()>,
) -> Result<JoinHandle<()>> {
    let additional_watch_paths = additional_watch_paths.to_vec();
    let shader_source_path = shader_source_path.to_owned();

    let compile_thread_join_handle = std::thread::spawn(move || {
        let mut debouncer = {
            let shader_source_path = shader_source_path.clone();
            new_debouncer(Duration::from_millis(250), None, move |result| {
                handle_debounced_event_result(
                    &ctx,
                    result,
                    &shader_source_path,
                    &shader_sender,
                );
            })
            .unwrap()
        };

        debouncer
            .watch(&shader_source_path, RecursiveMode::NonRecursive)
            .unwrap();

        for additional_path in additional_watch_paths {
            debouncer
                .watch(&additional_path, RecursiveMode::Recursive)
                .unwrap();
        }

        // block until shutdown
        shutdown_receiver.recv().unwrap();

        debouncer.stop();
    });
    Ok(compile_thread_join_handle)
}

/// Handles a set of debounced file change events to conditionally invoke the
/// compiler.
fn handle_debounced_event_result(
    ctx: &VulkanContext,
    result: DebounceEventResult,
    shader_source_path: &Path,
    shader_sender: &SyncSender<raii::ShaderModule>,
) {
    if let Err(err) = result {
        log::error!("Error receiving file change notifications!\n{:#?}", err);
        return;
    }

    log::info!("Compiling {:?}...", shader_source_path);
    match compile_slang(ctx, shader_source_path) {
        Ok(shader_src_bytes) => {
            log::info!("{:?} succeeded!", shader_source_path);
            shader_sender
                .send(shader_src_bytes)
                .expect("Unable to send updated shader source!");
        }
        Err(e) => {
            log::error!("{}", e);
        }
    }
}