-
Notifications
You must be signed in to change notification settings - Fork 39
/
mod.rs
1834 lines (1672 loc) · 68.6 KB
/
mod.rs
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
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use indexmap::IndexMap;
/// the compose module allows construction of shaders from modules (which are themselves shaders).
///
/// it does this by treating shaders as modules, and
/// - building each module independently to naga IR
/// - creating "header" files for each supported language, which are used to build dependent modules/shaders
/// - making final shaders by combining the shader IR with the IR for imported modules
///
/// for multiple small shaders with large common imports, this can be faster than parsing the full source for each shader, and it allows for constructing shaders in a cleaner modular manner with better scope control.
///
/// ## imports
///
/// shaders can be added to the composer as modules. this makes their types, constants, variables and functions available to modules/shaders that import them. note that importing a module will affect the final shader's global state if the module defines globals variables with bindings.
///
/// modules must include a `#define_import_path` directive that names the module.
///
/// ```ignore
/// #define_import_path my_module
///
/// fn my_func() -> f32 {
/// return 1.0;
/// }
/// ```
///
/// shaders can then import the module with an `#import` directive (with an optional `as` name). at point of use, imported items must be qualified:
///
/// ```ignore
/// #import my_module
/// #import my_other_module as Mod2
///
/// fn main() -> f32 {
/// let x = my_module::my_func();
/// let y = Mod2::my_other_func();
/// return x*y;
/// }
/// ```
///
/// or import a comma-separated list of individual items with a `#from` directive. at point of use, imported items must be prefixed with `::` :
///
/// ```ignore
/// #from my_module import my_func, my_const
///
/// fn main() -> f32 {
/// return ::my_func(::my_const);
/// }
/// ```
///
/// imports can be nested - modules may import other modules, but not recursively. when a new module is added, all its `#import`s must already have been added.
/// the same module can be imported multiple times by different modules in the import tree.
/// there is no overlap of namespaces, so the same function names (or type, constant, or variable names) may be used in different modules.
///
/// note: when importing an item with the `#from` directive, the final shader will include the required dependencies (bindings, globals, consts, other functions) of the imported item, but will not include the rest of the imported module. it will however still include all of any modules imported by the imported module. this is probably not desired in general and may be fixed in a future version. currently for a more complete culling of unused dependencies the `prune` module can be used.
///
/// ## overriding functions
///
/// virtual functions can be declared with the `virtual` keyword:
/// ```ignore
/// virtual fn point_light(world_position: vec3<f32>) -> vec3<f32> { ... }
/// ```
/// virtual functions defined in imported modules can then be overridden using the `override` keyword:
///
/// ```ignore
/// #import bevy_pbr::lighting as Lighting
///
/// override fn Lighting::point_light (world_position: vec3<f32>) -> vec3<f32> {
/// let original = Lighting::point_light(world_position);
/// let quantized = vec3<u32>(original * 3.0);
/// return vec3<f32>(quantized) / 3.0;
/// }
/// ```
///
/// override function definitions cause *all* calls to the original function in the entire shader scope to be replaced by calls to the new function, with the exception of calls within the override function itself.
///
/// the function signature of the override must match the base function.
///
/// overrides can be specified at any point in the final shader's import tree.
///
/// multiple overrides can be applied to the same function. for example, given :
/// - a module `a` containing a function `f`,
/// - a module `b` that imports `a`, and containing an `override a::f` function,
/// - a module `c` that imports `a` and `b`, and containing an `override a::f` function,
/// then b and c both specify an override for `a::f`.
/// the `override fn a::f` declared in module `b` may call to `a::f` within its body.
/// the `override fn a::f` declared in module 'c' may call to `a::f` within its body, but the call will be redirected to `b::f`.
/// any other calls to `a::f` (within modules 'a' or `b`, or anywhere else) will end up redirected to `c::f`
/// in this way a chain or stack of overrides can be applied.
///
/// different overrides of the same function can be specified in different import branches. the final stack will be ordered based on the first occurrence of the override in the import tree (using a depth first search).
///
/// note that imports into a module/shader are processed in order, but are processed before the body of the current shader/module regardless of where they occur in that module, so there is no way to import a module containing an override and inject a call into the override stack prior to that imported override. you can instead create two modules each containing an override and import them into a parent module/shader to order them as required.
/// override functions can currently only be defined in wgsl.
///
/// if the `override_any` crate feature is enabled, then the `virtual` keyword is not required for the function being overridden.
///
/// ## languages
///
/// modules can we written in GLSL or WGSL. shaders with entry points can be imported as modules (provided they have a `#define_import_path` directive). entry points are available to call from imported modules either via their name (for WGSL) or via `module::main` (for GLSL).
///
/// final shaders can also be written in GLSL or WGSL. for GLSL users must specify whether the shader is a vertex shader or fragment shader via the `ShaderType` argument (GLSL compute shaders are not supported).
///
/// ## preprocessing
///
/// when generating a final shader or adding a composable module, a set of `shader_def` string/value pairs must be provided. The value can be a bool (`ShaderDefValue::Bool`), an i32 (`ShaderDefValue::Int`) or a u32 (`ShaderDefValue::UInt`).
///
/// these allow conditional compilation of parts of modules and the final shader. conditional compilation is performed with `#if` / `#ifdef` / `#ifndef`, `#else` and `#endif` preprocessor directives:
///
/// ```ignore
/// fn get_number() -> f32 {
/// #ifdef BIG_NUMBER
/// return 999.0;
/// #else
/// return 0.999;
/// #endif
/// }
/// ```
/// the `#ifdef` directive matches when the def name exists in the input binding set (regardless of value). the `#ifndef` directive is the reverse.
///
/// the `#if` directive requires a def name, an operator, and a value for comparison:
/// - the def name must be a provided `shader_def` name.
/// - the operator must be one of `==`, `!=`, `>=`, `>`, `<`, `<=`
/// - the value must be an integer literal if comparing to a `ShaderDef::Int`, or `true` or `false` if comparing to a `ShaderDef::Bool`.
///
/// shader defs can also be used in the shader source with `#SHADER_DEF` or `#{SHADER_DEF}`, and will be substituted for their value.
///
/// ## error reporting
///
/// codespan reporting for errors is available using the error `emit_to_string` method. this requires validation to be enabled, which is true by default. `Composer::non_validating()` produces a non-validating composer that is not able to give accurate error reporting.
///
use naga::EntryPoint;
use regex::Regex;
use std::collections::{hash_map::Entry, BTreeMap, HashMap, HashSet};
use tracing::{debug, trace};
use crate::{
compose::preprocess::{PreprocessOutput, PreprocessorMetaData},
derive::DerivedModule,
redirect::Redirector,
};
pub use self::error::{ComposerError, ComposerErrorInner, ErrSource};
use self::preprocess::Preprocessor;
pub mod comment_strip_iter;
pub mod error;
pub mod parse_imports;
pub mod preprocess;
mod test;
pub mod tokenizer;
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum ShaderLanguage {
#[default]
Wgsl,
#[cfg(feature = "glsl")]
Glsl,
}
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum ShaderType {
#[default]
Wgsl,
#[cfg(feature = "glsl")]
GlslVertex,
#[cfg(feature = "glsl")]
GlslFragment,
}
impl From<ShaderType> for ShaderLanguage {
fn from(ty: ShaderType) -> Self {
match ty {
ShaderType::Wgsl => ShaderLanguage::Wgsl,
#[cfg(feature = "glsl")]
ShaderType::GlslVertex | ShaderType::GlslFragment => ShaderLanguage::Glsl,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum ShaderDefValue {
Bool(bool),
Int(i32),
UInt(u32),
}
impl Default for ShaderDefValue {
fn default() -> Self {
ShaderDefValue::Bool(true)
}
}
impl ShaderDefValue {
fn value_as_string(&self) -> String {
match self {
ShaderDefValue::Bool(val) => val.to_string(),
ShaderDefValue::Int(val) => val.to_string(),
ShaderDefValue::UInt(val) => val.to_string(),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct OwnedShaderDefs(BTreeMap<String, ShaderDefValue>);
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
struct ModuleKey(OwnedShaderDefs);
impl ModuleKey {
fn from_members(key: &HashMap<String, ShaderDefValue>, universe: &[String]) -> Self {
let mut acc = OwnedShaderDefs::default();
for item in universe {
if let Some(value) = key.get(item) {
acc.0.insert(item.to_owned(), *value);
}
}
ModuleKey(acc)
}
}
// a module built with a specific set of shader_defs
#[derive(Default, Debug)]
pub struct ComposableModule {
// module decoration, prefixed to all items from this module in the final source
pub decorated_name: String,
// module names required as imports, optionally with a list of items to import
pub imports: Vec<ImportDefinition>,
// types exported
pub owned_types: HashSet<String>,
// constants exported
pub owned_constants: HashSet<String>,
// vars exported
pub owned_vars: HashSet<String>,
// functions exported
pub owned_functions: HashSet<String>,
// local functions that can be overridden
pub virtual_functions: HashSet<String>,
// overriding functions defined in this module
// target function -> Vec<replacement functions>
pub override_functions: IndexMap<String, Vec<String>>,
// naga module, built against headers for any imports
module_ir: naga::Module,
// headers in different shader languages, used for building modules/shaders that import this module
// headers contain types, constants, global vars and empty function definitions -
// just enough to convert source strings that want to import this module into naga IR
// headers: HashMap<ShaderLanguage, String>,
header_ir: naga::Module,
// character offset of the start of the owned module string
start_offset: usize,
}
// data used to build a ComposableModule
#[derive(Debug)]
pub struct ComposableModuleDefinition {
pub name: String,
// shader text (with auto bindings replaced - we do this on module add as we only want to do it once to avoid burning slots)
pub sanitized_source: String,
// language
pub language: ShaderLanguage,
// source path for error display
pub file_path: String,
// shader def values bound to this module
pub shader_defs: HashMap<String, ShaderDefValue>,
// list of shader_defs that can affect this module
effective_defs: Vec<String>,
// full list of possible imports (regardless of shader_def configuration)
all_imports: HashSet<String>,
// additional imports to add (as though they were included in the source after any other imports)
additional_imports: Vec<ImportDefinition>,
// built composable modules for a given set of shader defs
modules: HashMap<ModuleKey, ComposableModule>,
// used in spans when this module is included
module_index: usize,
// preprocessor meta data
// metadata: PreprocessorMetaData,
}
impl ComposableModuleDefinition {
fn get_module(
&self,
shader_defs: &HashMap<String, ShaderDefValue>,
) -> Option<&ComposableModule> {
self.modules
.get(&ModuleKey::from_members(shader_defs, &self.effective_defs))
}
fn insert_module(
&mut self,
shader_defs: &HashMap<String, ShaderDefValue>,
module: ComposableModule,
) -> &ComposableModule {
match self
.modules
.entry(ModuleKey::from_members(shader_defs, &self.effective_defs))
{
Entry::Occupied(_) => panic!("entry already populated"),
Entry::Vacant(v) => v.insert(module),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImportDefinition {
pub import: String,
pub items: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ImportDefWithOffset {
definition: ImportDefinition,
offset: usize,
}
/// module composer.
/// stores any modules that can be imported into a shader
/// and builds the final shader
#[derive(Debug)]
pub struct Composer {
pub validate: bool,
pub module_sets: HashMap<String, ComposableModuleDefinition>,
pub module_index: HashMap<usize, String>,
pub capabilities: naga::valid::Capabilities,
preprocessor: Preprocessor,
check_decoration_regex: Regex,
undecorate_regex: Regex,
virtual_fn_regex: Regex,
override_fn_regex: Regex,
undecorate_override_regex: Regex,
auto_binding_regex: Regex,
auto_binding_index: u32,
}
// shift for module index
// 21 gives
// max size for shader of 2m characters
// max 2048 modules
const SPAN_SHIFT: usize = 21;
impl Default for Composer {
fn default() -> Self {
Self {
validate: true,
capabilities: Default::default(),
module_sets: Default::default(),
module_index: Default::default(),
preprocessor: Preprocessor::default(),
check_decoration_regex: Regex::new(
format!(
"({}|{})",
regex_syntax::escape(DECORATION_PRE),
regex_syntax::escape(DECORATION_OVERRIDE_PRE)
)
.as_str(),
)
.unwrap(),
undecorate_regex: Regex::new(
format!(
r"(\x1B\[\d+\w)?([\w\d_]+){}([A-Z0-9]*){}",
regex_syntax::escape(DECORATION_PRE),
regex_syntax::escape(DECORATION_POST)
)
.as_str(),
)
.unwrap(),
virtual_fn_regex: Regex::new(
r"(?P<lead>[\s]*virtual\s+fn\s+)(?P<function>[^\s]+)(?P<trail>\s*)\(",
)
.unwrap(),
override_fn_regex: Regex::new(
format!(
r"(override\s+fn\s+)([^\s]+){}([\w\d]+){}(\s*)\(",
regex_syntax::escape(DECORATION_PRE),
regex_syntax::escape(DECORATION_POST)
)
.as_str(),
)
.unwrap(),
undecorate_override_regex: Regex::new(
format!(
"{}([A-Z0-9]*){}",
regex_syntax::escape(DECORATION_OVERRIDE_PRE),
regex_syntax::escape(DECORATION_POST)
)
.as_str(),
)
.unwrap(),
auto_binding_regex: Regex::new(r"@binding\(auto\)").unwrap(),
auto_binding_index: 0,
}
}
}
const DECORATION_PRE: &str = "X_naga_oil_mod_X";
const DECORATION_POST: &str = "X";
// must be same length as DECORATION_PRE for spans to work
const DECORATION_OVERRIDE_PRE: &str = "X_naga_oil_vrt_X";
struct IrBuildResult {
module: naga::Module,
start_offset: usize,
override_functions: IndexMap<String, Vec<String>>,
}
impl Composer {
pub fn decorated_name(module_name: Option<&str>, item_name: &str) -> String {
match module_name {
Some(module_name) => format!("{}{}", item_name, Self::decorate(module_name)),
None => item_name.to_owned(),
}
}
fn decorate(module: &str) -> String {
let encoded = data_encoding::BASE32_NOPAD.encode(module.as_bytes());
format!("{DECORATION_PRE}{encoded}{DECORATION_POST}")
}
fn decode(from: &str) -> String {
String::from_utf8(data_encoding::BASE32_NOPAD.decode(from.as_bytes()).unwrap()).unwrap()
}
fn undecorate(&self, string: &str) -> String {
let undecor = self
.undecorate_regex
.replace_all(string, |caps: ®ex::Captures| {
format!(
"{}{}::{}",
caps.get(1).map(|cc| cc.as_str()).unwrap_or(""),
Self::decode(caps.get(3).unwrap().as_str()),
caps.get(2).unwrap().as_str()
)
});
let undecor =
self.undecorate_override_regex
.replace_all(&undecor, |caps: ®ex::Captures| {
format!(
"override fn {}::",
Self::decode(caps.get(1).unwrap().as_str())
)
});
undecor.to_string()
}
fn sanitize_and_set_auto_bindings(&mut self, source: &str) -> String {
let mut substituted_source = source.replace("\r\n", "\n").replace('\r', "\n");
if !substituted_source.ends_with('\n') {
substituted_source.push('\n');
}
// replace @binding(auto) with an incrementing index
struct AutoBindingReplacer<'a> {
auto: &'a mut u32,
}
impl<'a> regex::Replacer for AutoBindingReplacer<'a> {
fn replace_append(&mut self, _: ®ex::Captures<'_>, dst: &mut String) {
dst.push_str(&format!("@binding({})", self.auto));
*self.auto += 1;
}
}
let substituted_source = self.auto_binding_regex.replace_all(
&substituted_source,
AutoBindingReplacer {
auto: &mut self.auto_binding_index,
},
);
substituted_source.into_owned()
}
fn naga_to_string(
&self,
naga_module: &mut naga::Module,
language: ShaderLanguage,
#[allow(unused)] header_for: &str, // Only used when GLSL is enabled
) -> Result<String, ComposerErrorInner> {
// TODO: cache headers again
let info =
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), self.capabilities)
.validate(naga_module)
.map_err(ComposerErrorInner::HeaderValidationError)?;
match language {
ShaderLanguage::Wgsl => naga::back::wgsl::write_string(
naga_module,
&info,
naga::back::wgsl::WriterFlags::EXPLICIT_TYPES,
)
.map_err(ComposerErrorInner::WgslBackError),
#[cfg(feature = "glsl")]
ShaderLanguage::Glsl => {
let vec4 = naga_module.types.insert(
naga::Type {
name: None,
inner: naga::TypeInner::Vector {
size: naga::VectorSize::Quad,
scalar: naga::Scalar::F32,
},
},
naga::Span::UNDEFINED,
);
// add a dummy entry point for glsl headers
let dummy_entry_point = "dummy_module_entry_point".to_owned();
let func = naga::Function {
name: Some(dummy_entry_point.clone()),
arguments: Default::default(),
result: Some(naga::FunctionResult {
ty: vec4,
binding: Some(naga::Binding::BuiltIn(naga::BuiltIn::Position {
invariant: false,
})),
}),
local_variables: Default::default(),
expressions: Default::default(),
named_expressions: Default::default(),
body: Default::default(),
};
let ep = EntryPoint {
name: dummy_entry_point.clone(),
stage: naga::ShaderStage::Vertex,
function: func,
early_depth_test: None,
workgroup_size: [0, 0, 0],
};
naga_module.entry_points.push(ep);
let info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
self.capabilities,
)
.validate(naga_module)
.map_err(ComposerErrorInner::HeaderValidationError)?;
let mut string = String::new();
let options = naga::back::glsl::Options {
version: naga::back::glsl::Version::Desktop(450),
writer_flags: naga::back::glsl::WriterFlags::INCLUDE_UNUSED_ITEMS,
..Default::default()
};
let pipeline_options = naga::back::glsl::PipelineOptions {
shader_stage: naga::ShaderStage::Vertex,
entry_point: dummy_entry_point,
multiview: None,
};
let mut writer = naga::back::glsl::Writer::new(
&mut string,
naga_module,
&info,
&options,
&pipeline_options,
naga::proc::BoundsCheckPolicies::default(),
)
.map_err(ComposerErrorInner::GlslBackError)?;
writer.write().map_err(ComposerErrorInner::GlslBackError)?;
// strip version decl and main() impl
let lines: Vec<_> = string.lines().collect();
let string = lines[1..lines.len() - 3].join("\n");
trace!("glsl header for {}:\n\"\n{:?}\n\"", header_for, string);
Ok(string)
}
}
}
// build naga module for a given shader_def configuration. builds a minimal self-contained module built against headers for imports
fn create_module_ir(
&self,
name: &str,
source: String,
language: ShaderLanguage,
imports: &[ImportDefinition],
shader_defs: &HashMap<String, ShaderDefValue>,
) -> Result<IrBuildResult, ComposerError> {
debug!("creating IR for {} with defs: {:?}", name, shader_defs);
let mut module_string = match language {
ShaderLanguage::Wgsl => String::new(),
#[cfg(feature = "glsl")]
ShaderLanguage::Glsl => String::from("#version 450\n"),
};
let mut override_functions: IndexMap<String, Vec<String>> = IndexMap::default();
let mut added_imports: HashSet<String> = HashSet::new();
let mut header_module = DerivedModule::default();
for import in imports {
if added_imports.contains(&import.import) {
continue;
}
// add to header module
self.add_import(
&mut header_module,
import,
shader_defs,
true,
&mut added_imports,
);
// // we must have ensured these exist with Composer::ensure_imports()
trace!("looking for {}", import.import);
let import_module_set = self.module_sets.get(&import.import).unwrap();
trace!("with defs {:?}", shader_defs);
let module = import_module_set.get_module(shader_defs).unwrap();
trace!("ok");
// gather overrides
if !module.override_functions.is_empty() {
for (original, replacements) in &module.override_functions {
match override_functions.entry(original.clone()) {
indexmap::map::Entry::Occupied(o) => {
let existing = o.into_mut();
let new_replacements: Vec<_> = replacements
.iter()
.filter(|rep| !existing.contains(rep))
.cloned()
.collect();
existing.extend(new_replacements);
}
indexmap::map::Entry::Vacant(v) => {
v.insert(replacements.clone());
}
}
}
}
}
let composed_header = self
.naga_to_string(&mut header_module.into(), language, name)
.map_err(|inner| ComposerError {
inner,
source: ErrSource::Module {
name: name.to_owned(),
offset: 0,
defs: shader_defs.clone(),
},
})?;
module_string.push_str(&composed_header);
let start_offset = module_string.len();
module_string.push_str(&source);
trace!(
"parsing {}: {}, header len {}, total len {}",
name,
module_string,
start_offset,
module_string.len()
);
let module = match language {
ShaderLanguage::Wgsl => naga::front::wgsl::parse_str(&module_string).map_err(|e| {
debug!("full err'd source file: \n---\n{}\n---", module_string);
ComposerError {
inner: ComposerErrorInner::WgslParseError(e),
source: ErrSource::Module {
name: name.to_owned(),
offset: start_offset,
defs: shader_defs.clone(),
},
}
})?,
#[cfg(feature = "glsl")]
ShaderLanguage::Glsl => naga::front::glsl::Frontend::default()
.parse(
&naga::front::glsl::Options {
stage: naga::ShaderStage::Vertex,
defines: Default::default(),
},
&module_string,
)
.map_err(|e| {
debug!("full err'd source file: \n---\n{}\n---", module_string);
ComposerError {
inner: ComposerErrorInner::GlslParseError(e),
source: ErrSource::Module {
name: name.to_owned(),
offset: start_offset,
defs: shader_defs.clone(),
},
}
})?,
};
Ok(IrBuildResult {
module,
start_offset,
override_functions,
})
}
// check that identifiers exported by a module do not get modified in string export
fn validate_identifiers(
source_ir: &naga::Module,
lang: ShaderLanguage,
header: &str,
module_decoration: &str,
owned_types: &HashSet<String>,
) -> Result<(), ComposerErrorInner> {
// TODO: remove this once glsl front support is complete
#[cfg(feature = "glsl")]
if lang == ShaderLanguage::Glsl {
return Ok(());
}
let recompiled = match lang {
ShaderLanguage::Wgsl => naga::front::wgsl::parse_str(header).unwrap(),
#[cfg(feature = "glsl")]
ShaderLanguage::Glsl => naga::front::glsl::Frontend::default()
.parse(
&naga::front::glsl::Options {
stage: naga::ShaderStage::Vertex,
defines: Default::default(),
},
&format!("{}\n{}", header, "void main() {}"),
)
.map_err(|e| {
debug!("full err'd source file: \n---\n{header}\n---");
ComposerErrorInner::GlslParseError(e)
})?,
};
let recompiled_types: IndexMap<_, _> = recompiled
.types
.iter()
.flat_map(|(h, ty)| ty.name.as_deref().map(|name| (name, h)))
.collect();
for (h, ty) in source_ir.types.iter() {
if let Some(name) = &ty.name {
let decorated_type_name = format!("{name}{module_decoration}");
if !owned_types.contains(&decorated_type_name) {
continue;
}
match recompiled_types.get(decorated_type_name.as_str()) {
Some(recompiled_h) => {
if let naga::TypeInner::Struct { members, .. } = &ty.inner {
let recompiled_ty = recompiled.types.get_handle(*recompiled_h).unwrap();
let naga::TypeInner::Struct {
members: recompiled_members,
..
} = &recompiled_ty.inner
else {
panic!();
};
for (member, recompiled_member) in
members.iter().zip(recompiled_members)
{
if member.name != recompiled_member.name {
return Err(ComposerErrorInner::InvalidIdentifier {
original: member.name.clone().unwrap_or_default(),
at: source_ir.types.get_span(h),
});
}
}
}
}
None => {
return Err(ComposerErrorInner::InvalidIdentifier {
original: name.clone(),
at: source_ir.types.get_span(h),
})
}
}
}
}
let recompiled_consts: HashSet<_> = recompiled
.constants
.iter()
.flat_map(|(_, c)| c.name.as_deref())
.filter(|name| name.ends_with(module_decoration))
.collect();
for (h, c) in source_ir.constants.iter() {
if let Some(name) = &c.name {
if name.ends_with(module_decoration) && !recompiled_consts.contains(name.as_str()) {
return Err(ComposerErrorInner::InvalidIdentifier {
original: name.clone(),
at: source_ir.constants.get_span(h),
});
}
}
}
let recompiled_globals: HashSet<_> = recompiled
.global_variables
.iter()
.flat_map(|(_, c)| c.name.as_deref())
.filter(|name| name.ends_with(module_decoration))
.collect();
for (h, gv) in source_ir.global_variables.iter() {
if let Some(name) = &gv.name {
if name.ends_with(module_decoration) && !recompiled_globals.contains(name.as_str())
{
return Err(ComposerErrorInner::InvalidIdentifier {
original: name.clone(),
at: source_ir.global_variables.get_span(h),
});
}
}
}
let recompiled_fns: HashSet<_> = recompiled
.functions
.iter()
.flat_map(|(_, c)| c.name.as_deref())
.filter(|name| name.ends_with(module_decoration))
.collect();
for (h, f) in source_ir.functions.iter() {
if let Some(name) = &f.name {
if name.ends_with(module_decoration) && !recompiled_fns.contains(name.as_str()) {
return Err(ComposerErrorInner::InvalidIdentifier {
original: name.clone(),
at: source_ir.functions.get_span(h),
});
}
}
}
Ok(())
}
// build a ComposableModule from a ComposableModuleDefinition, for a given set of shader defs
// - build the naga IR (against headers)
// - record any types/vars/constants/functions that are defined within this module
// - build headers for each supported language
#[allow(clippy::too_many_arguments)]
fn create_composable_module(
&mut self,
module_definition: &ComposableModuleDefinition,
module_decoration: String,
shader_defs: &HashMap<String, ShaderDefValue>,
create_headers: bool,
demote_entrypoints: bool,
source: &str,
imports: Vec<ImportDefWithOffset>,
) -> Result<ComposableModule, ComposerError> {
let mut imports: Vec<_> = imports
.into_iter()
.map(|import_with_offset| import_with_offset.definition)
.collect();
imports.extend(module_definition.additional_imports.to_vec());
trace!(
"create composable module {}: source len {}",
module_definition.name,
source.len()
);
// record virtual/overridable functions
let mut virtual_functions: HashSet<String> = Default::default();
let source = self
.virtual_fn_regex
.replace_all(source, |cap: ®ex::Captures| {
let target_function = cap.get(2).unwrap().as_str().to_owned();
let replacement_str = format!(
"{}fn {}{}(",
" ".repeat(cap.get(1).unwrap().range().len() - 3),
target_function,
" ".repeat(cap.get(3).unwrap().range().len()),
);
virtual_functions.insert(target_function);
replacement_str
});
// record and rename override functions
let mut local_override_functions: IndexMap<String, String> = Default::default();
#[cfg(not(feature = "override_any"))]
let mut override_error = None;
let source =
self.override_fn_regex
.replace_all(&source, |cap: ®ex::Captures| {
let target_module = cap.get(3).unwrap().as_str().to_owned();
let target_function = cap.get(2).unwrap().as_str().to_owned();
#[cfg(not(feature = "override_any"))]
{
let wrap_err = |inner: ComposerErrorInner| -> ComposerError {
ComposerError {
inner,
source: ErrSource::Module {
name: module_definition.name.to_owned(),
offset: 0,
defs: shader_defs.clone(),
},
}
};
// ensure overrides are applied to virtual functions
let raw_module_name = Self::decode(&target_module);
let module_set = self.module_sets.get(&raw_module_name);
match module_set {
None => {
// TODO this should be unreachable?
let pos = cap.get(3).unwrap().start();
override_error = Some(wrap_err(
ComposerErrorInner::ImportNotFound(raw_module_name, pos),
));
}
Some(module_set) => {
let module = module_set.get_module(shader_defs).unwrap();
if !module.virtual_functions.contains(&target_function) {
let pos = cap.get(2).unwrap().start();
override_error =
Some(wrap_err(ComposerErrorInner::OverrideNotVirtual {
name: target_function.clone(),
pos,
}));
}
}
}
}
let base_name = format!(
"{}{}{}{}",
target_function.as_str(),
DECORATION_PRE,
target_module.as_str(),
DECORATION_POST,
);
let rename = format!(
"{}{}{}{}",
target_function.as_str(),
DECORATION_OVERRIDE_PRE,
target_module.as_str(),
DECORATION_POST,
);
let replacement_str = format!(
"{}fn {}{}(",
" ".repeat(cap.get(1).unwrap().range().len() - 3),
rename,
" ".repeat(cap.get(4).unwrap().range().len()),
);
local_override_functions.insert(rename, base_name);
replacement_str
})
.to_string();
#[cfg(not(feature = "override_any"))]
if let Some(err) = override_error {
return Err(err);
}
trace!("local overrides: {:?}", local_override_functions);
trace!(
"create composable module {}: source len {}",
module_definition.name,
source.len()
);
let IrBuildResult {
module: mut source_ir,
start_offset,
mut override_functions,
} = self.create_module_ir(
&module_definition.name,
source,
module_definition.language,
&imports,
shader_defs,
)?;
// from here on errors need to be reported using the modified source with start_offset
let wrap_err = |inner: ComposerErrorInner| -> ComposerError {
ComposerError {
inner,
source: ErrSource::Module {
name: module_definition.name.to_owned(),
offset: start_offset,
defs: shader_defs.clone(),
},
}
};
// add our local override to the total set of overrides for the given function
for (rename, base_name) in &local_override_functions {
override_functions
.entry(base_name.clone())
.or_default()
.push(format!("{rename}{module_decoration}"));
}
// rename and record owned items (except types which can't be mutably accessed)
let mut owned_constants = IndexMap::new();
for (h, c) in source_ir.constants.iter_mut() {
if let Some(name) = c.name.as_mut() {
if !name.contains(DECORATION_PRE) {
*name = format!("{name}{module_decoration}");
owned_constants.insert(name.clone(), h);