1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3use std::sync::{Arc, PoisonError, RwLockReadGuard, RwLockWriteGuard};
4
5use alpha2_gpu::CapabilityTier;
6
7use crate::effect::EffectKey;
8use crate::gpu_errors::{Answer, CreationErrorScopes, ScopeErrors, create_checked};
9use crate::loop_bound::{BUDGET, MAX_LOOP_ITERATIONS, blank_comments, bound_for_loops};
10use crate::uniform::{PARAM_SLOT_BYTES, RUNTIME_UNIFORM_WORDS, param_uniform_bytes};
11
12use crate::{
13 DiagnosticSeverity, EffectDef, EffectId, EffectKind, EffectResourceKind, InputSpec, ParamSpec,
14 ParamType, ParamUnit, ParamValue, Renderer, ResourceSpec, ShaderDiagnostic, ShaderDiagnostics,
15 UniformField, UniformLayout,
16};
17
18const MAX_REGISTERED_EFFECTS: usize = 256;
20const MAX_WGSL_BODY_BYTES: usize = 32 * 1024;
21const MAX_WGSL_NESTING: usize = 64;
22const MAX_ARRAY_SLOTS: u64 = 128;
26const MAX_ARRAY_TYPES: usize = 32;
28const MAX_WGSL_STATEMENT_OPERATORS: usize = 256;
34const RESERVED_PREFIX: &str = "alpha2_";
36const MAX_EFFECT_RESOURCES: usize = 8;
37pub const MAX_EFFECT_INPUTS: usize = 8;
40#[allow(clippy::cast_possible_truncation)]
43const INPUT_BINDING_BASE: u32 = 5 + 2 * MAX_EFFECT_RESOURCES as u32;
44const RESOURCE_METADATA_BYTES: usize = 32;
46
47#[cfg(not(target_arch = "wasm32"))]
51const COMPILE_STACK: usize = 8 << 20;
52
53#[cfg(not(target_arch = "wasm32"))]
56fn on_compile_stack<T: Send>(make: impl FnOnce() -> T + Send) -> T {
57 std::thread::scope(|scope| {
58 let compile = std::thread::Builder::new()
59 .name("alpha2 shader compile".to_owned())
60 .stack_size(COMPILE_STACK)
61 .spawn_scoped(scope, make)
62 .expect("the shader compile thread starts");
63 compile
64 .join()
65 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
66 })
67}
68
69#[cfg(target_arch = "wasm32")]
70fn on_compile_stack<T>(make: impl FnOnce() -> T) -> T {
71 make()
72}
73
74pub struct PendingEffect {
80 compiled: CompiledEffect,
81 compilation: Answer<wgpu::CompilationInfo>,
82 shader_errors: ScopeErrors,
83 pipeline_errors: ScopeErrors,
84}
85
86impl std::fmt::Debug for PendingEffect {
87 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 formatter
89 .debug_struct("PendingEffect")
90 .field("id", &self.compiled.id)
91 .finish_non_exhaustive()
92 }
93}
94
95impl PendingEffect {
96 pub async fn compiled(self) -> Result<CompiledEffect, ShaderDiagnostics> {
101 let mut diagnostics = compilation_diagnostics(self.compilation.await);
102 for error in self.shader_errors.await {
103 diagnostics.messages.push(ShaderDiagnostic {
104 severity: DiagnosticSeverity::Error,
105 message: error.to_string(),
106 line: None,
107 column: None,
108 });
109 }
110 if diagnostics
112 .messages
113 .iter()
114 .any(|message| message.severity == DiagnosticSeverity::Error)
115 {
116 return Err(diagnostics);
117 }
118 let errors = self.pipeline_errors.await;
119 if !errors.is_empty() {
120 return Err(ShaderDiagnostics {
121 messages: errors
122 .into_iter()
123 .map(|error| ShaderDiagnostic {
124 severity: DiagnosticSeverity::Error,
125 message: error.to_string(),
126 line: None,
127 column: None,
128 })
129 .collect(),
130 });
131 }
132 Ok(self.compiled)
133 }
134}
135
136pub struct CompiledEffect {
138 device: wgpu::Device,
139 id: EffectId,
140 effect: RegisteredEffect,
141}
142
143impl std::fmt::Debug for CompiledEffect {
144 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 formatter
146 .debug_struct("CompiledEffect")
147 .field("id", &self.id)
148 .finish_non_exhaustive()
149 }
150}
151
152impl CompiledEffect {
153 #[must_use]
155 pub const fn id(&self) -> &EffectId {
156 &self.id
157 }
158}
159
160#[derive(Debug, Default)]
162pub(crate) struct EffectRegistry {
163 entries: HashMap<EffectId, crate::Shared<RegisteredEffect>>,
164 builtins: HashSet<EffectId>,
165 internal: HashSet<EffectId>,
166}
167
168impl EffectRegistry {
169 fn check_room(&self, id: &EffectId) -> Result<(), ShaderDiagnostics> {
171 if self.entries.contains_key(id) {
172 return Err(ShaderDiagnostics::error(format!(
173 "effect {} version {} is already registered",
174 id.as_str(),
175 id.version()
176 )));
177 }
178 if self.entries.len() - self.builtins.len() >= MAX_REGISTERED_EFFECTS {
179 return Err(ShaderDiagnostics::error(format!(
180 "effect registry is full (maximum {MAX_REGISTERED_EFFECTS})"
181 )));
182 }
183 Ok(())
184 }
185}
186
187#[derive(Debug)]
188pub(crate) struct RegisteredEffect {
189 pub(crate) definition: Arc<EffectDef>,
190 pub(crate) uniform_layout: UniformLayout,
191 reads_time: bool,
192 pub(crate) cost: crate::effect_cost::EffectCost,
194 pipeline: std::sync::OnceLock<EffectPipeline>,
196}
197
198#[derive(Debug)]
199pub(crate) struct EffectPipeline {
200 _shader: wgpu::ShaderModule,
201 pub(crate) bind_group_layout: wgpu::BindGroupLayout,
202 pub(crate) pipeline: wgpu::RenderPipeline,
203 pub(crate) sampler: wgpu::Sampler,
204}
205
206impl Renderer {
207 pub async fn register_effect(
216 &self,
217 definition: EffectDef,
218 ) -> Result<EffectId, ShaderDiagnostics> {
219 let compiled = self.compile_effect(definition)?.compiled().await?;
220 self.register_compiled(compiled)
221 }
222
223 pub fn compile_effect(
232 &self,
233 definition: EffectDef,
234 ) -> Result<PendingEffect, ShaderDiagnostics> {
235 let id = self.check_registration(&definition)?;
236 let device = self.gpu.device();
237 let format = self.intermediate_format();
238 let (compilation, shader_errors, pipeline, pipeline_errors) = on_compile_stack(|| {
239 let shader_scope = CreationErrorScopes::push(device);
240 let shader = effect_shader(device, &definition);
241 let compilation: Answer<wgpu::CompilationInfo> =
242 Box::pin(shader.get_compilation_info());
243 let shader_errors = shader_scope.pop();
244 let pipeline_scope = CreationErrorScopes::push(device);
245 let pipeline = effect_pipeline(device, &definition, shader, format);
246 (compilation, shader_errors, pipeline, pipeline_scope.pop())
247 });
248 Ok(PendingEffect {
249 compiled: CompiledEffect {
250 device: device.clone(),
251 id,
252 effect: RegisteredEffect {
253 pipeline: std::sync::OnceLock::from(pipeline),
254 ..registered_effect(definition)
255 },
256 },
257 compilation,
258 shader_errors,
259 pipeline_errors,
260 })
261 }
262
263 pub(crate) fn register_lazily(
270 &self,
271 definition: EffectDef,
272 ) -> Result<EffectId, ShaderDiagnostics> {
273 let id = self.check_registration(&definition)?;
274 let mut effects = self.effects_mut();
275 effects.check_room(&id)?;
276 effects.entries.insert(
277 id.clone(),
278 crate::Shared::new(registered_effect(definition)),
279 );
280 Ok(id)
281 }
282
283 pub(crate) fn effects(&self) -> RwLockReadGuard<'_, EffectRegistry> {
285 self.effects.read().unwrap_or_else(PoisonError::into_inner)
286 }
287
288 pub(crate) fn effects_mut(&self) -> RwLockWriteGuard<'_, EffectRegistry> {
289 self.effects.write().unwrap_or_else(PoisonError::into_inner)
290 }
291
292 fn check_registration(&self, definition: &EffectDef) -> Result<EffectId, ShaderDiagnostics> {
294 validate_definition(definition)?;
295 self.validate_parameter_uniform(definition)?;
296 self.validate_texture_bindings(definition)?;
297 if definition.tier_min == CapabilityTier::TierA
298 && self.gpu.capabilities().tier == CapabilityTier::TierB
299 {
300 return Err(ShaderDiagnostics::error(
301 "effect requires capability tier A on a tier B adapter",
302 ));
303 }
304 let id = EffectId::new(definition.id.clone(), definition.version);
305 self.effects().check_room(&id)?;
306 Ok(id)
307 }
308
309 pub(crate) fn effect_pipeline<'a>(
314 &self,
315 effect: &'a RegisteredEffect,
316 ) -> Result<&'a EffectPipeline, crate::RenderError> {
317 if let Some(pipeline) = effect.pipeline.get() {
318 return Ok(pipeline);
319 }
320 let created = crate::diagnostics::timed_pipeline_creation(
321 &self.diagnostics,
322 || effect.definition.id.as_str().to_owned(),
323 || {
324 let device = self.gpu.device();
325 let format = self.intermediate_format();
326 on_compile_stack(|| {
328 let shader = create_checked(device, || self.lazy_effect_shader(effect))?;
329 create_checked(device, || {
330 effect_pipeline(device, &effect.definition, shader, format)
331 })
332 })
333 },
334 )
335 .map_err(|kind| crate::RenderError::Gpu { kind })?;
336 Ok(effect.pipeline.get_or_init(|| created))
337 }
338
339 fn lazy_effect_shader(&self, effect: &RegisteredEffect) -> wgpu::ShaderModule {
340 let device = self.gpu.device();
341 #[cfg(test)]
342 if self
343 .fail_next_pipeline
344 .swap(false, std::sync::atomic::Ordering::Relaxed)
345 {
346 return device.create_shader_module(wgpu::ShaderModuleDescriptor {
348 label: Some("alpha2 test module without entry points"),
349 source: wgpu::ShaderSource::Wgsl("fn unused() {}".into()),
350 });
351 }
352 effect_shader(device, &effect.definition)
353 }
354
355 pub fn register_compiled(
360 &self,
361 compiled: CompiledEffect,
362 ) -> Result<EffectId, ShaderDiagnostics> {
363 if compiled.device != *self.gpu.device() {
364 return Err(ShaderDiagnostics::error(format!(
365 "effect {} version {} was compiled on another GPU device",
366 compiled.id.as_str(),
367 compiled.id.version()
368 )));
369 }
370 let mut effects = self.effects_mut();
371 effects.check_room(&compiled.id)?;
372 effects
373 .entries
374 .insert(compiled.id.clone(), crate::Shared::new(compiled.effect));
375 Ok(compiled.id)
376 }
377
378 fn validate_parameter_uniform(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
384 let limit = self
385 .limits
386 .max_uniform_buffer_binding_size
387 .min(wgpu::Limits::downlevel_webgl2_defaults().max_uniform_buffer_binding_size);
388 let bytes = u64::try_from(param_uniform_bytes(definition.params.len())).unwrap_or(u64::MAX);
389 if bytes > limit {
390 let most = limit / u64::try_from(PARAM_SLOT_BYTES).unwrap_or(u64::MAX);
391 return Err(ShaderDiagnostics::error(format!(
392 "effect declares {} parameters, a {bytes}-byte uniform past the {limit}-byte \
393 limit every alpha2 runtime binds (at most {most} parameters)",
394 definition.params.len()
395 )));
396 }
397 Ok(())
398 }
399
400 fn validate_texture_bindings(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
403 let textures = 2 + definition.resources.len() + definition.inputs.len();
404 let limit =
405 usize::try_from(self.limits.max_sampled_textures_per_shader_stage.min(
406 wgpu::Limits::downlevel_webgl2_defaults().max_sampled_textures_per_shader_stage,
407 ))
408 .unwrap_or(usize::MAX);
409 if textures > limit {
410 return Err(ShaderDiagnostics::error(format!(
411 "effect samples {textures} textures (its source pair, {} resources, and {} \
412 named inputs), past this device's {limit} per shader stage",
413 definition.resources.len(),
414 definition.inputs.len()
415 )));
416 }
417 Ok(())
418 }
419
420 #[must_use]
422 pub fn effect_uniform_layout(&self, id: &EffectId) -> Option<UniformLayout> {
423 self.effects()
424 .entries
425 .get(id)
426 .map(|entry| entry.uniform_layout.clone())
427 }
428
429 #[must_use]
431 pub fn effect_definition(&self, id: &EffectId) -> Option<Arc<EffectDef>> {
432 self.effects()
433 .entries
434 .get(id)
435 .map(|entry| Arc::clone(&entry.definition))
436 }
437
438 #[must_use]
444 pub fn effect_reads_time(&self, id: &EffectId) -> bool {
445 if let Some(passes) = crate::gaussian_blur::expanded_passes(id.as_str()) {
446 return passes
447 .iter()
448 .any(|pass| self.effect_reads_time(&EffectId::from_static(pass, 1)));
449 }
450 self.effects()
451 .entries
452 .get(id)
453 .is_none_or(|entry| entry.reads_time)
454 }
455
456 #[must_use]
458 pub fn is_effect_registered(&self, id: &EffectId) -> bool {
459 self.effects().entries.contains_key(id)
460 }
461
462 #[must_use]
464 pub fn is_effect_project_visible(&self, id: &EffectId) -> bool {
465 let effects = self.effects();
466 effects.entries.contains_key(id) && !effects.internal.contains(id)
467 }
468
469 #[must_use]
472 pub fn project_effect_id(&self, id: &str, version: u32) -> Option<EffectId> {
473 let key: &dyn EffectKey = &(id, version);
474 let effects = self.effects();
475 effects
476 .entries
477 .get_key_value(key)
478 .map(|(id, _)| id)
479 .filter(|id| !effects.internal.contains(*id))
480 .cloned()
481 }
482
483 #[must_use]
485 pub fn is_builtin_effect(&self, id: &EffectId) -> bool {
486 self.effects().builtins.contains(id)
487 }
488
489 pub fn unregister_effect(&self, id: &EffectId) -> bool {
491 let removed = {
492 let mut effects = self.effects_mut();
493 !effects.builtins.contains(id) && effects.entries.remove(id).is_some()
494 };
495 if removed {
496 self.clear_result_cache_for(crate::CacheInvalidation::Effects);
497 }
498 removed
499 }
500
501 pub fn clear_effects(&self) {
503 {
504 let mut effects = self.effects_mut();
505 let EffectRegistry {
506 entries, builtins, ..
507 } = &mut *effects;
508 entries.retain(|id, _| builtins.contains(id));
509 }
510 self.clear_result_cache_for(crate::CacheInvalidation::Effects);
511 }
512
513 pub fn warmup(&self, effects: &[EffectId]) -> Result<(), ShaderDiagnostics> {
519 let create = |effect: &EffectId, registered: &RegisteredEffect| {
520 self.effect_pipeline(registered)
521 .map(|_| ())
522 .map_err(|error| {
523 ShaderDiagnostics::error(format!(
524 "effect {} version {}: {error}",
525 effect.as_str(),
526 effect.version()
527 ))
528 })
529 };
530 for effect in effects {
531 let Some(registered) = self.effects().get(effect) else {
532 return Err(ShaderDiagnostics::error(format!(
533 "effect {} version {} is not registered",
534 effect.as_str(),
535 effect.version()
536 )));
537 };
538 create(effect, ®istered)?;
539 for pass in crate::gaussian_blur::expanded_passes(effect.as_str()).unwrap_or_default() {
540 let pass = EffectId::from_static(pass, 1);
541 if let Some(registered) = self.effects().get(&pass) {
542 create(&pass, ®istered)?;
543 }
544 }
545 }
546 Ok(())
547 }
548}
549
550impl EffectRegistry {
551 pub(crate) fn get(&self, id: &EffectId) -> Option<crate::Shared<RegisteredEffect>> {
552 self.entries.get(id).cloned()
553 }
554
555 pub(crate) fn len(&self) -> usize {
556 self.entries.len()
557 }
558
559 pub(crate) fn mark_builtin(&mut self, id: EffectId) {
560 debug_assert!(self.entries.contains_key(&id));
561 self.builtins.insert(id);
562 }
563
564 pub(crate) fn mark_internal(&mut self, id: EffectId) {
565 debug_assert!(self.entries.contains_key(&id));
566 self.internal.insert(id);
567 }
568}
569
570pub(crate) fn registered_effect(definition: EffectDef) -> RegisteredEffect {
572 RegisteredEffect {
573 uniform_layout: uniform_layout(&definition.params),
574 reads_time: body_reads_time(&definition.wgsl_body),
575 cost: crate::effect_cost::invocation_cost(&blank_comments(&definition.wgsl_body)),
576 definition: Arc::new(definition),
577 pipeline: std::sync::OnceLock::new(),
578 }
579}
580
581fn effect_shader(device: &wgpu::Device, definition: &EffectDef) -> wgpu::ShaderModule {
582 device.create_shader_module(wgpu::ShaderModuleDescriptor {
583 label: Some(&definition.id),
584 source: wgpu::ShaderSource::Wgsl(build_shader(definition).into()),
585 })
586}
587
588fn effect_pipeline(
589 device: &wgpu::Device,
590 definition: &EffectDef,
591 shader: wgpu::ShaderModule,
592 format: wgpu::TextureFormat,
593) -> EffectPipeline {
594 let bind_group_layout = runtime_bind_group_layout(
595 device,
596 &definition.params,
597 &definition.resources,
598 &definition.inputs,
599 );
600 let pipeline = runtime_pipeline(device, &bind_group_layout, &shader, format);
601 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
602 label: Some("alpha2 runtime effect sampler"),
603 address_mode_u: wgpu::AddressMode::ClampToEdge,
604 address_mode_v: wgpu::AddressMode::ClampToEdge,
605 mag_filter: wgpu::FilterMode::Linear,
606 min_filter: wgpu::FilterMode::Linear,
607 ..Default::default()
608 });
609 EffectPipeline {
610 _shader: shader,
611 bind_group_layout,
612 pipeline,
613 sampler,
614 }
615}
616
617fn runtime_bind_group_layout(
618 device: &wgpu::Device,
619 params: &[ParamSpec],
620 resources: &[ResourceSpec],
621 inputs: &[InputSpec],
622) -> wgpu::BindGroupLayout {
623 let mut entries = vec![
624 runtime_texture_entry(0, wgpu::TextureViewDimension::D2),
625 runtime_texture_entry(1, wgpu::TextureViewDimension::D2),
626 wgpu::BindGroupLayoutEntry {
627 binding: 2,
628 visibility: wgpu::ShaderStages::FRAGMENT,
629 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
630 count: None,
631 },
632 runtime_uniform_entry(3, param_uniform_bytes(params.len())),
635 runtime_uniform_entry(4, RUNTIME_UNIFORM_WORDS * size_of::<f32>()),
636 ];
637 for (index, resource) in resources.iter().enumerate() {
638 let binding = u32::try_from(index).unwrap_or(0) * 2 + 5;
639 let dimension = match resource.kind {
640 EffectResourceKind::Lut3d => wgpu::TextureViewDimension::D3,
641 };
642 entries.push(runtime_texture_entry(binding, dimension));
643 entries.push(runtime_uniform_entry(binding + 1, RESOURCE_METADATA_BYTES));
644 }
645 for index in 0..inputs.len() {
646 entries.push(runtime_texture_entry(
647 input_binding(index),
648 wgpu::TextureViewDimension::D2,
649 ));
650 }
651 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
652 label: Some("alpha2 runtime effect layout"),
653 entries: &entries,
654 })
655}
656
657pub(crate) fn input_binding(index: usize) -> u32 {
658 INPUT_BINDING_BASE + u32::try_from(index).unwrap_or(0)
659}
660
661fn runtime_texture_entry(
662 binding: u32,
663 view_dimension: wgpu::TextureViewDimension,
664) -> wgpu::BindGroupLayoutEntry {
665 wgpu::BindGroupLayoutEntry {
666 binding,
667 visibility: wgpu::ShaderStages::FRAGMENT,
668 ty: wgpu::BindingType::Texture {
669 sample_type: wgpu::TextureSampleType::Float { filterable: true },
670 view_dimension,
671 multisampled: false,
672 },
673 count: None,
674 }
675}
676
677fn runtime_uniform_entry(binding: u32, bytes: usize) -> wgpu::BindGroupLayoutEntry {
678 wgpu::BindGroupLayoutEntry {
679 binding,
680 visibility: wgpu::ShaderStages::FRAGMENT,
681 ty: wgpu::BindingType::Buffer {
682 ty: wgpu::BufferBindingType::Uniform,
683 has_dynamic_offset: false,
684 min_binding_size: u64::try_from(bytes)
685 .ok()
686 .and_then(std::num::NonZeroU64::new),
687 },
688 count: None,
689 }
690}
691
692fn runtime_pipeline(
693 device: &wgpu::Device,
694 bind_group_layout: &wgpu::BindGroupLayout,
695 shader: &wgpu::ShaderModule,
696 format: wgpu::TextureFormat,
697) -> wgpu::RenderPipeline {
698 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
699 label: Some("alpha2 runtime effect pipeline layout"),
700 bind_group_layouts: &[Some(bind_group_layout)],
701 immediate_size: 0,
702 });
703 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
704 label: Some("alpha2 runtime effect pipeline"),
705 layout: Some(&layout),
706 vertex: wgpu::VertexState {
707 module: shader,
708 entry_point: Some("alpha2_vs"),
709 buffers: &[],
710 compilation_options: wgpu::PipelineCompilationOptions::default(),
711 },
712 fragment: Some(wgpu::FragmentState {
713 module: shader,
714 entry_point: Some("alpha2_fs"),
715 targets: &[Some(format.into())],
716 compilation_options: wgpu::PipelineCompilationOptions::default(),
717 }),
718 primitive: wgpu::PrimitiveState::default(),
719 depth_stencil: None,
720 multisample: wgpu::MultisampleState::default(),
721 multiview_mask: None,
722 cache: None,
723 })
724}
725
726pub(crate) fn uniform_layout(params: &[ParamSpec]) -> UniformLayout {
727 let fields = params
728 .iter()
729 .enumerate()
730 .map(|(index, param)| UniformField {
731 name: param.name.clone(),
732 offset: u32::try_from(index).expect("parameter count fits u32") * 16,
733 size: 16,
734 })
735 .collect::<Vec<_>>();
736 UniformLayout {
737 size: u32::try_from(param_uniform_bytes(params.len())).expect("parameter uniform fits u32"),
738 fields,
739 }
740}
741
742pub(crate) fn body_reads_time(body: &str) -> bool {
749 body.split(|character: char| !(character.is_alphanumeric() || character == '_'))
750 .any(|word| matches!(word, "time" | "time_ticks" | "runtime"))
751}
752
753pub(crate) fn build_shader(definition: &EffectDef) -> String {
754 let param_fields = if definition.params.is_empty() {
755 " _padding: vec4f,\n".to_owned()
756 } else {
757 definition
758 .params
759 .iter()
760 .fold(String::new(), |mut output, param| {
761 writeln!(
762 output,
763 " {}: {},",
764 param.name,
765 wgsl_type(param.param_type)
766 )
767 .expect("writing to a String cannot fail");
768 output
769 })
770 };
771 let uniform_fields =
772 (0..definition.params.len().max(1)).fold(String::new(), |mut output, index| {
773 writeln!(output, " slot_{index}: vec4u,").expect("writing to a String cannot fail");
774 output
775 });
776 let param_values = if definition.params.is_empty() {
777 "vec4f(0.0)".to_owned()
778 } else {
779 definition
780 .params
781 .iter()
782 .enumerate()
783 .map(|(index, param)| uniform_value(index, param.param_type))
784 .collect::<Vec<_>>()
785 .join(", ")
786 };
787 let call = match definition.kind {
788 EffectKind::Effect => "effect(input.uv, sample_src(input.uv))",
789 EffectKind::Transition => "alpha2_transition(input.uv)",
790 EffectKind::Generator => "generate(input.uv)",
791 };
792 let transition_wrapper = match definition.kind {
793 EffectKind::Effect | EffectKind::Generator => "",
794 EffectKind::Transition => {
795 r"fn alpha2_transition(uv: vec2f) -> vec4f {
796 if (progress() <= 0.0) { return from_color(uv); }
797 if (progress() >= 1.0) { return to_color(uv); }
798 return transition(uv);
799}"
800 }
801 };
802 let resource_declarations = resource_declarations(&definition.resources);
803 let input_declarations = input_declarations(&definition.inputs);
804 format!(
805 r"@group(0) @binding(0) var source_a: texture_2d<f32>;
806@group(0) @binding(1) var source_b: texture_2d<f32>;
807@group(0) @binding(2) var source_sampler: sampler;
808struct EffectParams {{
809{param_fields}}};
810struct EffectParamUniforms {{
811{uniform_fields}}};
812@group(0) @binding(3) var<uniform> param_uniforms: EffectParamUniforms;
813var<private> params: EffectParams;
814var<private> {BUDGET}: u32;
815struct RuntimeValues {{ resolution_time: vec4f, transition: vec4f, ticks: vec4u, }};
816@group(0) @binding(4) var<uniform> runtime: RuntimeValues;
817{resource_declarations}{input_declarations}
818
819fn sample_src(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
820fn from_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
821fn to_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_b, source_sampler, uv, 0.0); }}
822fn resolution() -> vec2f {{ return runtime.resolution_time.xy; }}
823fn time() -> f32 {{ return runtime.resolution_time.z; }}
824fn time_ticks() -> vec2u {{ return runtime.ticks.xy; }}
825fn progress() -> f32 {{ return runtime.transition.x; }}
826fn ratio() -> f32 {{ return runtime.transition.y; }}
827fn render_scale() -> f32 {{ return runtime.resolution_time.w; }}
828fn render_scale_fixed() -> u32 {{ return runtime.ticks.z; }}
829fn max_filter_samples() -> f32 {{ return runtime.transition.z; }}
830fn load_params() -> EffectParams {{ return EffectParams({param_values}); }}
831
832{body}
833
834{transition_wrapper}
835
836struct VertexOutput {{ @builtin(position) position: vec4f, @location(0) uv: vec2f, }};
837@vertex fn alpha2_vs(@builtin(vertex_index) index: u32) -> VertexOutput {{
838 var p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
839 var u = array<vec2f, 3>(vec2f(0.0, 1.0), vec2f(2.0, 1.0), vec2f(0.0, -1.0));
840 return VertexOutput(vec4f(p[index], 0.0, 1.0), u[index]);
841}}
842@fragment fn alpha2_fs(input: VertexOutput) -> @location(0) vec4f {{
843 params = load_params();
844 {BUDGET} = {MAX_LOOP_ITERATIONS}u;
845 return {call};
846}}
847",
848 body =
850 bound_for_loops(&definition.wgsl_body).unwrap_or_else(|_| definition.wgsl_body.clone()),
851 resource_declarations = resource_declarations,
852 input_declarations = input_declarations,
853 transition_wrapper = transition_wrapper,
854 )
855}
856
857fn resource_declarations(resources: &[ResourceSpec]) -> String {
858 resources
859 .iter()
860 .enumerate()
861 .map(|(index, resource)| match resource.kind {
862 EffectResourceKind::Lut3d => format!(
863 "struct ResourceMetadata_{} {{ domain_min: vec4f, domain_max: vec4f, }};\n\
864 @group(0) @binding({}) var resource_{}: texture_3d<f32>;\n\
865 @group(0) @binding({}) var<uniform> resource_{}_metadata: ResourceMetadata_{};\n\
866 fn sample_{}(rgb: vec3f) -> vec3f {{\n\
867 let edge = f32(textureDimensions(resource_{}).x);\n\
868 let normalized = clamp((rgb - resource_{}_metadata.domain_min.xyz) /\n\
869 (resource_{}_metadata.domain_max.xyz - resource_{}_metadata.domain_min.xyz),\n\
870 vec3f(0.0), vec3f(1.0));\n\
871 let coord = (normalized * (edge - 1.0) + 0.5) / edge;\n\
872 return textureSampleLevel(resource_{}, source_sampler, coord, 0.0).rgb;\n\
873 }}",
874 resource.name,
875 index * 2 + 5,
876 resource.name,
877 index * 2 + 6,
878 resource.name,
879 resource.name,
880 resource.name,
881 resource.name,
882 resource.name,
883 resource.name,
884 resource.name,
885 resource.name,
886 ),
887 })
888 .collect::<Vec<_>>()
889 .join("\n")
890}
891
892fn input_declarations(inputs: &[InputSpec]) -> String {
894 inputs
895 .iter()
896 .enumerate()
897 .fold(String::new(), |mut output, (index, input)| {
898 let name = &input.name;
899 write!(
900 output,
901 "\n@group(0) @binding({binding}) var input_{name}: texture_2d<f32>;\n\
902 fn sample_{name}(uv: vec2f) -> vec4f {{ return textureSampleLevel(input_{name}, source_sampler, uv, 0.0); }}\n\
903 fn size_{name}() -> vec2f {{ return vec2f(textureDimensions(input_{name})); }}",
904 binding = input_binding(index),
905 )
906 .expect("writing to a String cannot fail");
907 output
908 })
909}
910
911fn uniform_value(index: usize, param_type: ParamType) -> String {
912 match param_type {
913 ParamType::Float => format!("bitcast<f32>(param_uniforms.slot_{index}.x)"),
914 ParamType::Vec2 => format!("bitcast<vec2f>(param_uniforms.slot_{index}.xy)"),
915 ParamType::Vec4 | ParamType::Color => {
916 format!("bitcast<vec4f>(param_uniforms.slot_{index})")
917 }
918 ParamType::Enum | ParamType::Bool => format!("param_uniforms.slot_{index}.x"),
919 }
920}
921
922fn wgsl_type(param_type: ParamType) -> &'static str {
923 match param_type {
924 ParamType::Float => "f32",
925 ParamType::Vec2 => "vec2f",
926 ParamType::Vec4 | ParamType::Color => "vec4f",
927 ParamType::Enum | ParamType::Bool => "u32",
928 }
929}
930
931#[derive(Clone, Debug, PartialEq, Eq)]
933pub struct CheckedEffect {
934 pub module: String,
936 pub functions: usize,
938 pub calls: u64,
940 pub cost_units: u64,
942}
943
944pub fn check_effect(definition: &EffectDef) -> Result<CheckedEffect, ShaderDiagnostics> {
951 validate_definition(definition)?;
952 let code = blank_comments(&definition.wgsl_body);
953 let (calls, _) = crate::call_budget::invocation_calls(&code)?;
954 Ok(CheckedEffect {
955 module: build_shader(definition),
956 functions: crate::call_budget::declarations(&code).len(),
957 calls,
958 cost_units: crate::effect_cost::invocation_cost(&code).units(),
959 })
960}
961
962fn validate_definition(definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
963 if !valid_identifier(&definition.id) {
964 return Err(ShaderDiagnostics::error(
965 "effect id must contain only ASCII letters, digits, '-', '_', or '.'",
966 ));
967 }
968 if definition.version == 0 {
969 return Err(ShaderDiagnostics::error("effect version must be non-zero"));
970 }
971 validate_wgsl_body(&definition.wgsl_body)?;
972 if !definition.inputs.is_empty() && definition.kind != EffectKind::Effect {
973 return Err(ShaderDiagnostics::error(
974 "only effects declare named inputs; a transition samples from and to",
975 ));
976 }
977 if definition.inputs.len() > MAX_EFFECT_INPUTS {
978 return Err(ShaderDiagnostics::error(format!(
979 "effect declares more than {MAX_EFFECT_INPUTS} named inputs"
980 )));
981 }
982 let mut names = std::collections::HashSet::new();
983 for param in &definition.params {
984 validate_param(param)?;
985 if !names.insert(param.name.as_str()) {
986 return Err(ShaderDiagnostics::error(format!(
987 "duplicate parameter name {}",
988 param.name
989 )));
990 }
991 }
992 if definition.resources.len() > MAX_EFFECT_RESOURCES {
993 return Err(ShaderDiagnostics::error(format!(
994 "effect declares more than {MAX_EFFECT_RESOURCES} resources"
995 )));
996 }
997 let mut resource_names = std::collections::HashSet::new();
998 let mut declared = std::collections::HashSet::new();
1000 for resource in &definition.resources {
1001 let generated = resource_declarations_of(&resource.name);
1002 if !valid_wgsl_identifier(&resource.name)
1003 || names.contains(resource.name.as_str())
1004 || !resource_names.insert(resource.name.as_str())
1005 || !generated
1006 .iter()
1007 .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1008 {
1009 return Err(ShaderDiagnostics::error(format!(
1010 "invalid or duplicate effect resource name {}",
1011 resource.name
1012 )));
1013 }
1014 }
1015 let mut input_names = std::collections::HashSet::new();
1017 for input in &definition.inputs {
1018 let generated = input_declarations_of(&input.name);
1019 if !valid_wgsl_identifier(&input.name)
1020 || names.contains(input.name.as_str())
1021 || resource_names.contains(input.name.as_str())
1022 || !input_names.insert(input.name.as_str())
1023 || !generated
1024 .iter()
1025 .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1026 {
1027 return Err(ShaderDiagnostics::error(format!(
1028 "invalid or duplicate effect input name {}",
1029 input.name
1030 )));
1031 }
1032 }
1033 Ok(())
1034}
1035
1036fn input_declarations_of(name: &str) -> [String; 3] {
1039 [
1040 format!("input_{name}"),
1041 format!("sample_{name}"),
1042 format!("size_{name}"),
1043 ]
1044}
1045
1046fn resource_declarations_of(name: &str) -> [String; 4] {
1048 [
1049 format!("resource_{name}"),
1050 format!("resource_{name}_metadata"),
1051 format!("sample_{name}"),
1052 format!("ResourceMetadata_{name}"),
1053 ]
1054}
1055
1056fn validate_wgsl_body(body: &str) -> Result<(), ShaderDiagnostics> {
1057 if body.len() > MAX_WGSL_BODY_BYTES {
1058 return Err(ShaderDiagnostics::error(format!(
1059 "WGSL body exceeds {MAX_WGSL_BODY_BYTES} bytes"
1060 )));
1061 }
1062 if body
1063 .chars()
1064 .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'))
1065 {
1066 return Err(ShaderDiagnostics::error(
1067 "WGSL body contains unsupported control characters",
1068 ));
1069 }
1070 let code = blank_comments(body);
1072 if !code.is_ascii() {
1074 return Err(ShaderDiagnostics::error(
1075 "a runtime effect's code is ASCII; comments may hold any text",
1076 ));
1077 }
1078 if let Some(identifier) = identifiers(&code).find(|word| word.starts_with(RESERVED_PREFIX)) {
1079 return Err(ShaderDiagnostics::error(format!(
1080 "WGSL identifier {identifier} is reserved: names starting with {RESERVED_PREFIX} belong to the generated wrapper"
1081 )));
1082 }
1083 if code.split([';', '{', '}']).any(|statement| {
1084 statement.bytes().filter(|byte| is_operator(*byte)).count() > MAX_WGSL_STATEMENT_OPERATORS
1085 }) {
1086 return Err(ShaderDiagnostics::error(format!(
1087 "a WGSL statement has more than {MAX_WGSL_STATEMENT_OPERATORS} operators; split it with `let`"
1088 )));
1089 }
1090 check_nesting(&code)?;
1091 check_arrays(&code)?;
1092
1093 let forbidden = [
1094 "@binding",
1095 "@compute",
1096 "@group",
1097 "atomic",
1098 "enable",
1099 "loop",
1100 "override",
1101 "var<storage",
1102 "var<uniform",
1103 "var<workgroup",
1104 "while",
1105 ];
1106 for token in code.split(|character: char| {
1107 !(character.is_ascii_alphanumeric() || matches!(character, '_' | '@' | '<'))
1108 }) {
1109 if forbidden.contains(&token) {
1110 return Err(ShaderDiagnostics::error(format!(
1111 "WGSL token {token} is not allowed in a runtime effect"
1112 )));
1113 }
1114 }
1115 bound_for_loops(body)?;
1116 crate::call_budget::check_invocation_calls(&code)?;
1117 crate::effect_cost::check_invocation_cost(&code).map(drop)
1118}
1119
1120fn check_arrays(code: &str) -> Result<(), ShaderDiagnostics> {
1123 let arrays = crate::effect_cost::array_types(code);
1124 if arrays.len() > MAX_ARRAY_TYPES {
1125 return Err(ShaderDiagnostics::error(format!(
1126 "a runtime effect writes at most {MAX_ARRAY_TYPES} array types"
1127 )));
1128 }
1129 for array in arrays {
1130 let text = &code[array.span.clone()];
1131 if !array.templated {
1132 return Err(ShaderDiagnostics::error(
1133 "write a runtime effect's arrays with their element type and count, as \
1134 `array<T, N>(...)`",
1135 ));
1136 }
1137 let Some(slots) = array.slots else {
1138 return Err(ShaderDiagnostics::error(format!(
1139 "`{text}` needs an integer literal count and elements that are scalars, \
1140 vectors, matrices or arrays"
1141 )));
1142 };
1143 if slots > MAX_ARRAY_SLOTS {
1144 return Err(ShaderDiagnostics::error(format!(
1145 "`{text}` holds more than {MAX_ARRAY_SLOTS} vectors; put a large table in a \
1146 resource texture"
1147 )));
1148 }
1149 }
1150 Ok(())
1151}
1152
1153fn check_nesting(code: &str) -> Result<(), ShaderDiagnostics> {
1156 let unbalanced = || ShaderDiagnostics::error("WGSL body has unbalanced delimiters");
1157 let too_deep = |chained: bool| {
1158 ShaderDiagnostics::error(if chained {
1159 format!(
1160 "an `else if` chain nests past {MAX_WGSL_NESTING} levels; use `switch` or \
1161 early returns"
1162 )
1163 } else {
1164 format!("WGSL nesting exceeds {MAX_WGSL_NESTING} levels")
1165 })
1166 };
1167 let mut open: Vec<(u8, usize, Option<usize>)> = Vec::new();
1169 let mut pending_if: Option<(usize, usize)> = None;
1171 let mut closed_chain: Option<usize> = None;
1173 let mut after_else = false;
1174 let bytes = code.as_bytes();
1175 let mut index = 0;
1176 while index < bytes.len() {
1177 let byte = bytes[index];
1178 if byte.is_ascii_whitespace() {
1179 index += 1;
1180 continue;
1181 }
1182 if crate::loop_bound::is_identifier_byte(byte) {
1183 let end = index
1184 + bytes[index..]
1185 .iter()
1186 .take_while(|byte| crate::loop_bound::is_identifier_byte(**byte))
1187 .count();
1188 let word = &code[index..end];
1189 index = end;
1190 if word == "else" && closed_chain.is_some() && !after_else {
1191 after_else = true;
1192 continue;
1193 }
1194 if word == "if" {
1195 let chain = if after_else {
1196 closed_chain.map_or(1, |chain| chain + 1)
1197 } else {
1198 1
1199 };
1200 pending_if = Some((open.len(), chain));
1201 }
1202 closed_chain = None;
1203 after_else = false;
1204 continue;
1205 }
1206 closed_chain = None;
1207 after_else = false;
1208 index += 1;
1209 match byte {
1210 b'{' | b'(' | b'[' => {
1211 let chain = pending_if
1212 .filter(|(at, _)| byte == b'{' && *at == open.len())
1213 .map(|(_, chain)| chain);
1214 if chain.is_some() {
1215 pending_if = None;
1216 }
1217 let depth = open.last().map_or(0, |(_, depth, _)| *depth) + chain.unwrap_or(1);
1218 if depth > MAX_WGSL_NESTING {
1219 return Err(too_deep(chain.is_some_and(|chain| chain > 1)));
1220 }
1221 open.push((byte, depth, chain));
1222 }
1223 b'}' | b')' | b']' => {
1224 let Some((opened, _, chain)) = open.pop() else {
1225 return Err(unbalanced());
1226 };
1227 if !matches!((opened, byte), (b'{', b'}') | (b'(', b')') | (b'[', b']')) {
1228 return Err(unbalanced());
1229 }
1230 closed_chain = chain;
1231 }
1232 _ => {}
1233 }
1234 }
1235 if open.is_empty() {
1236 Ok(())
1237 } else {
1238 Err(unbalanced())
1239 }
1240}
1241
1242fn identifiers(code: &str) -> impl Iterator<Item = &str> {
1244 code.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
1245 .filter(|word| word.starts_with(|first: char| first.is_ascii_alphabetic() || first == '_'))
1246}
1247
1248const fn is_operator(byte: u8) -> bool {
1251 matches!(
1252 byte,
1253 b'+' | b'-'
1254 | b'*'
1255 | b'/'
1256 | b'%'
1257 | b'&'
1258 | b'|'
1259 | b'^'
1260 | b'!'
1261 | b'~'
1262 | b'<'
1263 | b'>'
1264 | b'='
1265 | b'.'
1266 | b'['
1267 )
1268}
1269
1270fn validate_param(param: &ParamSpec) -> Result<(), ShaderDiagnostics> {
1271 if !valid_wgsl_identifier(¶m.name) {
1272 return Err(ShaderDiagnostics::error(format!(
1273 "invalid WGSL parameter name {}",
1274 param.name
1275 )));
1276 }
1277 let compatible = matches!(
1278 (¶m.param_type, ¶m.default, ¶m.unit),
1279 (
1280 ParamType::Float,
1281 ParamValue::Float(_),
1282 ParamUnit::Normalized | ParamUnit::Degrees
1283 ) | (ParamType::Vec2, ParamValue::Vec2(_), ParamUnit::Normalized)
1284 | (ParamType::Vec4, ParamValue::Vec4(_), ParamUnit::Normalized)
1285 | (ParamType::Color, ParamValue::Color(_), ParamUnit::Color)
1286 | (ParamType::Enum, ParamValue::Enum(_), ParamUnit::Enum)
1287 | (ParamType::Bool, ParamValue::Bool(_), ParamUnit::Bool)
1288 );
1289 if !compatible {
1290 return Err(ShaderDiagnostics::error(format!(
1291 "parameter {} has incompatible type, default, and unit",
1292 param.name
1293 )));
1294 }
1295 if !finite_value(¶m.default)
1296 || param.min.is_some_and(|value| !value.is_finite())
1297 || param.max.is_some_and(|value| !value.is_finite())
1298 || param
1299 .step
1300 .is_some_and(|value| !value.is_finite() || value <= 0.0)
1301 || matches!((param.min, param.max), (Some(min), Some(max)) if min > max)
1302 {
1303 return Err(ShaderDiagnostics::error(format!(
1304 "parameter {} has an invalid numeric range",
1305 param.name
1306 )));
1307 }
1308 if !matches!(
1309 param.param_type,
1310 ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1311 ) && (param.min.is_some() || param.max.is_some() || param.step.is_some())
1312 {
1313 return Err(ShaderDiagnostics::error(format!(
1314 "only float, vec2, or vec4 parameter {} may declare a numeric range",
1315 param.name
1316 )));
1317 }
1318 if matches!(
1319 param.param_type,
1320 ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1321 ) && !value_in_range(¶m.default, param.min, param.max)
1322 {
1323 return Err(ShaderDiagnostics::error(format!(
1324 "parameter {} default is outside its numeric range",
1325 param.name
1326 )));
1327 }
1328 if let ParamValue::Color(values) = ¶m.default
1329 && !values.iter().all(|value| (0.0..=1.0).contains(value))
1330 {
1331 return Err(ShaderDiagnostics::error(format!(
1332 "color parameter {} default must be inside 0..=1",
1333 param.name
1334 )));
1335 }
1336 if param.param_type == ParamType::Enum && param.enum_values.is_empty() {
1337 return Err(ShaderDiagnostics::error(format!(
1338 "enum parameter {} requires named values",
1339 param.name
1340 )));
1341 }
1342 if let ParamValue::Enum(value) = ¶m.default
1343 && usize::try_from(*value).map_or(true, |index| index >= param.enum_values.len())
1344 {
1345 return Err(ShaderDiagnostics::error(format!(
1346 "enum parameter {} default is out of range",
1347 param.name
1348 )));
1349 }
1350 Ok(())
1351}
1352
1353fn value_in_range(value: &ParamValue, min: Option<f32>, max: Option<f32>) -> bool {
1354 let in_range = |value: &f32| {
1355 min.is_none_or(|minimum| *value >= minimum) && max.is_none_or(|maximum| *value <= maximum)
1356 };
1357 match value {
1358 ParamValue::Float(value) => in_range(value),
1359 ParamValue::Vec2(values) => values.iter().all(in_range),
1360 ParamValue::Vec4(values) => values.iter().all(in_range),
1361 _ => true,
1362 }
1363}
1364
1365fn finite_value(value: &ParamValue) -> bool {
1366 match value {
1367 ParamValue::Float(value) => value.is_finite(),
1368 ParamValue::Vec2(values) => values.iter().all(|value| value.is_finite()),
1369 ParamValue::Vec4(values) | ParamValue::Color(values) => {
1370 values.iter().all(|value| value.is_finite())
1371 }
1372 ParamValue::Enum(_) | ParamValue::Bool(_) => true,
1373 }
1374}
1375
1376fn valid_identifier(value: &str) -> bool {
1377 !value.is_empty()
1378 && value
1379 .bytes()
1380 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
1381}
1382
1383fn valid_wgsl_identifier(value: &str) -> bool {
1384 let mut bytes = value.bytes();
1385 bytes
1386 .next()
1387 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
1388 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1389 && !value.starts_with(RESERVED_PREFIX)
1390 && !matches!(
1391 value,
1392 "params"
1393 | "resolution"
1394 | "time"
1395 | "time_ticks"
1396 | "progress"
1397 | "ratio"
1398 | "render_scale"
1399 | "render_scale_fixed"
1400 | "sample_src"
1401 | "from_color"
1402 | "to_color"
1403 | "load_params"
1404 | "max_filter_samples"
1405 | "source_a"
1406 | "source_b"
1407 | "source_sampler"
1408 | "param_uniforms"
1409 | "runtime"
1410 | "EffectParams"
1411 )
1412}
1413
1414fn compilation_diagnostics(info: wgpu::CompilationInfo) -> ShaderDiagnostics {
1415 ShaderDiagnostics {
1416 messages: info
1417 .messages
1418 .into_iter()
1419 .map(|message| {
1420 let severity = match message.message_type {
1421 wgpu::CompilationMessageType::Error => DiagnosticSeverity::Error,
1422 wgpu::CompilationMessageType::Warning => DiagnosticSeverity::Warning,
1423 wgpu::CompilationMessageType::Info => DiagnosticSeverity::Info,
1424 };
1425 ShaderDiagnostic {
1426 severity,
1427 message: message.message,
1428 line: message.location.map(|location| location.line_number),
1429 column: message.location.map(|location| location.line_position),
1430 }
1431 })
1432 .collect(),
1433 }
1434}
1435
1436#[cfg(test)]
1437#[path = "registry_tests.rs"]
1438mod tests;