summaryrefslogtreecommitdiff
path: root/engine/src/shader_preprocessor.rs
blob: 70696ac3e5d9e603ac994c444f094f2d8bc51595 (plain)
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
use std::path::{Path, PathBuf};
use std::string::FromUtf8Error;

const PREINCLUDE_DIRECTIVE: &str = "#preinclude";

/// Preprocessor for shaders written in the OpenGL Shading Language.
pub struct ShaderPreprocessor
{
    read_file: fn(&Path) -> Result<Vec<u8>, std::io::Error>,
    base_dir: PathBuf,
}

impl ShaderPreprocessor
{
    pub fn new(base_dir: PathBuf) -> Self
    {
        Self {
            read_file: |path| std::fs::read(path),
            base_dir,
        }
    }

    pub fn preprocess(
        &self,
        shader_content: String,
        shader_file_path: &Path,
    ) -> Result<String, Error>
    {
        let mut preincludes = shader_content
            .match_indices(PREINCLUDE_DIRECTIVE)
            .peekable();

        if preincludes.peek().is_none() {
            // Shader content contains no preincludes
            return Ok(shader_content);
        };

        let mut preprocessed = shader_content.clone();

        let mut curr = shader_content.find(PREINCLUDE_DIRECTIVE);

        let mut last_start = 0;
        let mut span_line_offset = 0;

        while let Some(preinclude_start) = curr {
            let replacement_job = self.handle_preinclude(
                &preprocessed,
                shader_file_path,
                preinclude_start,
                span_line_offset,
            )?;

            let path = replacement_job.path.clone();

            let mut included = String::from_utf8(
                (self.read_file)(&self.base_dir.join(replacement_job.path.clone()))
                    .map_err(|err| Error::ReadIncludedShaderFailed {
                        source: err,
                        path: replacement_job.path.clone(),
                    })?,
            )
            .map_err(|err| Error::IncludedShaderInvalidUtf8 {
                source: err,
                path: path.clone(),
            })?;

            if let Some(first_line) = included.lines().next() {
                if first_line.starts_with("#version") {
                    included = included
                        .chars()
                        .skip_while(|character| *character != '\n')
                        .collect();
                }
            }

            let included_preprocessed =
                self.preprocess(included, &replacement_job.path)?;

            let start = replacement_job.start_index;
            let end = replacement_job.end_index;

            preprocessed.replace_range(start..end, &included_preprocessed);

            curr = preprocessed[last_start + 1..]
                .find(PREINCLUDE_DIRECTIVE)
                .map(|index| index + 1);

            last_start = preinclude_start + included_preprocessed.len();

            span_line_offset += included_preprocessed.lines().count();
        }

        Ok(preprocessed)
    }

    fn handle_preinclude(
        &self,
        shader_content: &str,
        shader_file_path: &Path,
        preinclude_start_index: usize,
        span_line_offset: usize,
    ) -> Result<ReplacementJob, Error>
    {
        let expect_token = |token: char, index: usize| {
            let token_found = shader_content.chars().nth(index).ok_or_else(|| {
                Error::ExpectedToken {
                    expected: token,
                    span: Span::new(
                        shader_content,
                        &self.base_dir.join(shader_file_path),
                        index,
                        span_line_offset,
                        preinclude_start_index,
                    ),
                }
            })?;

            if token_found != token {
                return Err(Error::InvalidToken {
                    expected: token,
                    found: token_found,
                    span: Span::new(
                        shader_content,
                        &self.base_dir.join(shader_file_path),
                        index,
                        span_line_offset,
                        preinclude_start_index,
                    ),
                });
            }

            Ok(())
        };

        let space_index = preinclude_start_index + PREINCLUDE_DIRECTIVE.len();
        let quote_open_index = space_index + 1;

        expect_token(' ', space_index)?;
        expect_token('"', quote_open_index)?;

        let buf = shader_content[quote_open_index + 1..]
            .chars()
            .take_while(|character| *character != '"')
            .map(|character| character as u8)
            .collect::<Vec<_>>();

        if buf.is_empty() {
            return Err(Error::ExpectedToken {
                expected: '"',
                span: Span::new(
                    shader_content,
                    &self.base_dir.join(shader_file_path),
                    shader_content.len() - 1,
                    span_line_offset,
                    preinclude_start_index,
                ),
            });
        }

        let path_len = buf.len();

        let path = PathBuf::from(String::from_utf8(buf).map_err(|err| {
            Error::PreincludePathInvalidUtf8 {
                source: err,
                span: Span::new(
                    shader_content,
                    &self.base_dir.join(shader_file_path),
                    quote_open_index + 1,
                    span_line_offset,
                    preinclude_start_index,
                ),
            }
        })?);

        Ok(ReplacementJob {
            start_index: preinclude_start_index,
            end_index: quote_open_index + 1 + path_len + 1,
            path,
        })
    }
}

struct ReplacementJob
{
    start_index: usize,
    end_index: usize,
    path: PathBuf,
}

/// Shader preprocessing error.
#[derive(Debug, thiserror::Error)]
pub enum Error
{
    #[error(
        "Invalid token at line {}, column {} of {}. Expected '{}', found '{}'",
        span.line,
        span.column,
        span.file.display(),
        expected,
        found
    )]
    InvalidToken
    {
        expected: char,
        found: char,
        span: Span,
    },

    #[error(
        "Expected token '{}' at line {}, column {} of {}. Found eof",
        expected,
        span.line,
        span.column,
        span.file.display(),
    )]
    ExpectedToken
    {
        expected: char, span: Span
    },

    #[error(
        "Preinclude path at line {}, column {} of {} is invalid UTF-8",
        span.line,
        span.column,
        span.file.display(),
    )]
    PreincludePathInvalidUtf8
    {
        #[source]
        source: FromUtf8Error,
        span: Span,
    },

    #[error("Failed to read included shader")]
    ReadIncludedShaderFailed
    {
        #[source]
        source: std::io::Error,
        path: PathBuf,
    },

    #[error("Included shader is not valid UTF-8")]
    IncludedShaderInvalidUtf8
    {
        #[source]
        source: FromUtf8Error,
        path: PathBuf,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span
{
    line: usize,
    column: usize,
    file: PathBuf,
}

impl Span
{
    fn new(
        file_content: &str,
        file_path: &Path,
        char_index: usize,
        line_offset: usize,
        line_start_index: usize,
    ) -> Self
    {
        let line = find_line_of_index(file_content, char_index) + 1
            - line_offset.saturating_sub(1);

        Self {
            line,
            column: char_index - line_start_index + 1,
            file: file_path.to_path_buf(),
        }
    }
}

fn find_line_of_index(text: &str, index: usize) -> usize
{
    text.chars()
        .take(index + 1)
        .enumerate()
        .filter(|(_, character)| *character == '\n')
        .count()
}

#[cfg(test)]
mod tests
{
    use std::ffi::OsStr;
    use std::path::{Path, PathBuf};

    use super::{Error, ShaderPreprocessor};

    #[test]
    fn preprocess_no_directives_is_same()
    {
        assert_eq!(
            ShaderPreprocessor {
                read_file: |_| { unreachable!() },
                base_dir: PathBuf::new()
            }
            .preprocess("#version 330 core\n".to_string(), Path::new("foo.glsl"),)
            .unwrap(),
            "#version 330 core\n".to_string()
        );
    }

    #[test]
    fn preprocess_with_directives_works()
    {
        assert_eq!(
            ShaderPreprocessor {
                read_file: |_| { Ok(b"out vec4 FragColor;".to_vec()) },
                base_dir: PathBuf::new()
            }
            .preprocess(
                concat!(
                    "#version 330 core\n",
                    "\n",
                    "#preinclude \"foo.glsl\"\n",
                    "\n",
                    "void main() {}",
                )
                .to_string(),
                Path::new("foo.glsl"),
            )
            .unwrap(),
            concat!(
                "#version 330 core\n",
                "\n",
                "out vec4 FragColor;\n",
                "\n",
                "void main() {}",
            )
        );

        assert_eq!(
            ShaderPreprocessor {
                read_file: |_| { Ok(b"out vec4 FragColor;".to_vec()) },
                base_dir: PathBuf::new()
            }
            .preprocess(
                concat!(
                    "#version 330 core\n",
                    "\n",
                    "#preinclude \"bar.glsl\"\n",
                    "\n",
                    "in vec3 in_frag_color;\n",
                    "\n",
                    "void main() {}",
                )
                .to_string(),
                Path::new("foo.glsl"),
            )
            .unwrap(),
            concat!(
                "#version 330 core\n",
                "\n",
                "out vec4 FragColor;\n",
                "\n",
                "in vec3 in_frag_color;\n",
                "\n",
                "void main() {}",
            )
        );

        assert_eq!(
            ShaderPreprocessor {
                read_file: |path| {
                    if path == OsStr::new("bar.glsl") {
                        Ok(b"out vec4 FragColor;".to_vec())
                    } else {
                        Ok(concat!(
                            "uniform sampler2D input_texture;\n",
                            "in vec2 in_texture_coords;"
                        )
                        .as_bytes()
                        .to_vec())
                    }
                },
                base_dir: PathBuf::new()
            }
            .preprocess(
                concat!(
                    "#version 330 core\n",
                    "\n",
                    "#preinclude \"bar.glsl\"\n",
                    "\n",
                    "in vec3 in_frag_color;\n",
                    "\n",
                    "#preinclude \"foo.glsl\"\n",
                    "\n",
                    "void main() {}",
                )
                .to_string(),
                Path::new("foo.glsl"),
            )
            .unwrap(),
            concat!(
                "#version 330 core\n",
                "\n",
                "out vec4 FragColor;\n",
                "\n",
                "in vec3 in_frag_color;\n",
                "\n",
                "uniform sampler2D input_texture;\n",
                "in vec2 in_texture_coords;\n",
                "\n",
                "void main() {}",
            )
        );
    }

    #[test]
    fn preprocess_invalid_shader_does_not_work()
    {
        let path = Path::new("foo.glsl");

        let res = ShaderPreprocessor {
            read_file: |_| Ok(b"out vec4 FragColor;".to_vec()),
            base_dir: PathBuf::new(),
        }
        .preprocess(
            concat!(
                "#version 330 core\n",
                "\n",
                // Missing "
                "#preinclude foo.glsl\"\n",
                "\n",
                "void main() {}",
            )
            .to_string(),
            path,
        );

        let Err(Error::InvalidToken { expected, found, span }) = res else {
            panic!(
                "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}"
            );
        };

        assert_eq!(expected, '"');
        assert_eq!(found, 'f');
        assert_eq!(span.line, 3);
        assert_eq!(span.column, 13);
        assert_eq!(span.file, path);
    }

    #[test]
    fn preprocess_error_has_correct_span()
    {
        let path = Path::new("foo.glsl");

        let res = ShaderPreprocessor {
            read_file: |path| {
                if path == OsStr::new("bar.glsl") {
                    Ok(concat!(
                        "out vec4 FragColor;\n",
                        "in vec2 in_texture_coords;\n",
                        "in float foo;"
                    )
                    .as_bytes()
                    .to_vec())
                } else {
                    Ok(b"uniform sampler2D input_texture;".to_vec())
                }
            },
            base_dir: PathBuf::new(),
        }
        .preprocess(
            concat!(
                "#version 330 core\n",
                "\n",
                "#preinclude \"bar.glsl\"\n",
                "\n",
                "in vec3 in_frag_color;\n",
                "\n",
                "#preinclude\"foo.glsl\"\n",
                "\n",
                "void main() {}",
            )
            .to_string(),
            Path::new("foo.glsl"),
        );

        let Err(Error::InvalidToken { expected, found, span }) = res else {
            panic!(
                "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}"
            );
        };

        assert_eq!(expected, ' ');
        assert_eq!(found, '"');
        assert_eq!(span.line, 7);
        assert_eq!(span.column, 12);
        assert_eq!(span.file, path);
    }

    #[test]
    fn preprocess_included_shader_with_include_works()
    {
        assert_eq!(
            ShaderPreprocessor {
                read_file: |path| {
                    if path == OsStr::new("bar.glsl") {
                        Ok(concat!(
                            "#preinclude \"foo.glsl\"\n",
                            "\n",
                            "out vec4 FragColor;"
                        )
                        .as_bytes()
                        .to_vec())
                    } else {
                        Ok(concat!(
                            "uniform sampler2D input_texture;\n",
                            "in vec2 in_texture_coords;"
                        )
                        .as_bytes()
                        .to_vec())
                    }
                },
                base_dir: PathBuf::new()
            }
            .preprocess(
                concat!(
                    "#version 330 core\n",
                    "\n",
                    "#preinclude \"bar.glsl\"\n",
                    "\n",
                    "in vec3 in_frag_color;\n",
                    "\n",
                    "void main() {}",
                )
                .to_string(),
                Path::new("foo.glsl"),
            )
            .unwrap(),
            concat!(
                "#version 330 core\n",
                "\n",
                "uniform sampler2D input_texture;\n",
                "in vec2 in_texture_coords;\n",
                "\n",
                "out vec4 FragColor;\n",
                "\n",
                "in vec3 in_frag_color;\n",
                "\n",
                "void main() {}",
            )
        );
    }

    #[test]
    fn preprocess_included_shader_with_include_error_span_is_correct()
    {
        let res = ShaderPreprocessor {
            read_file: |path| {
                if path == OsStr::new("bar.glsl") {
                    Ok(concat!(
                        // ' instead of "
                        "#preinclude 'foo.glsl\"\n",
                        "\n",
                        "out vec4 FragColor;"
                    )
                    .as_bytes()
                    .to_vec())
                } else {
                    Ok(concat!(
                        "uniform sampler2D input_texture;\n",
                        "in vec2 in_texture_coords;"
                    )
                    .as_bytes()
                    .to_vec())
                }
            },
            base_dir: PathBuf::new(),
        }
        .preprocess(
            concat!(
                "#version 330 core\n",
                "\n",
                "#preinclude \"bar.glsl\"\n",
                "\n",
                "in vec3 in_frag_color;\n",
                "\n",
                "void main() {}",
            )
            .to_string(),
            Path::new("foo.glsl"),
        );

        let Err(Error::InvalidToken { expected, found, span }) = res else {
            panic!(
                "Expected result to be Err(Error::InvalidToken {{ ... }}), is {res:?}"
            );
        };

        assert_eq!(expected, '"');
        assert_eq!(found, '\'');
        assert_eq!(span.line, 1);
        assert_eq!(span.column, 13);
        assert_eq!(span.file, Path::new("bar.glsl"));
    }
}