Skip to main content

alpha2_render/
registry.rs

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
18/// Effects a host may register; built-ins do not count.
19const MAX_REGISTERED_EFFECTS: usize = 256;
20const MAX_WGSL_BODY_BYTES: usize = 32 * 1024;
21const MAX_WGSL_NESTING: usize = 64;
22/// Most `vec4f`-sized elements one array may hold, counts multiplied through nested arrays.
23/// Software adapters compile a dynamically indexed array in time that grows faster than its size,
24/// and this one compiles and draws in under a second there.
25const MAX_ARRAY_SLOTS: u64 = 128;
26/// Most array types a body may write.
27const MAX_ARRAY_TYPES: usize = 32;
28/// Operator characters one statement may hold.
29///
30/// naga recurses once per operand of a flat chain like `x+x+...+x`; about 2,500 operands
31/// overflow a 1 MiB stack (Windows main thread, wasm32) and abort the process. Engine bodies
32/// stay under 32. DXC needs more at this limit, hence `COMPILE_STACK`.
33const MAX_WGSL_STATEMENT_OPERATORS: usize = 256;
34/// Identifier prefix of everything the generated wrapper declares.
35const RESERVED_PREFIX: &str = "alpha2_";
36const MAX_EFFECT_RESOURCES: usize = 8;
37/// Most named inputs an effect declares. Source pair, resources and inputs must also fit the
38/// device's sampled textures per stage (16 on WebGL2-class limits), checked at registration.
39pub const MAX_EFFECT_INPUTS: usize = 8;
40/// First named input's binding, after every possible resource slot so inputs never shift other
41/// bindings.
42#[allow(clippy::cast_possible_truncation)]
43const INPUT_BINDING_BASE: u32 = 5 + 2 * MAX_EFFECT_RESOURCES as u32;
44/// `ResourceMetadata_<name>`: `domain_min` and `domain_max`, two `vec4f`.
45const RESOURCE_METADATA_BYTES: usize = 32;
46
47/// Stack size for effect shader and pipeline compiles. naga recurses per nested statement and
48/// DXC per operand, which needs about 1.5 MiB at [`MAX_WGSL_STATEMENT_OPERATORS`]; a caller's
49/// thread may have 1 MiB or less.
50#[cfg(not(target_arch = "wasm32"))]
51const COMPILE_STACK: usize = 8 << 20;
52
53/// Runs `make` on a thread of [`COMPILE_STACK`] bytes. Error scopes are per thread, so `make`
54/// pushes and pops its own.
55#[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
74/// A runtime effect created on the device, awaiting the device's verdict.
75///
76/// Made by [`Renderer::compile_effect`], awaited with [`PendingEffect::compiled`], added by
77/// [`Renderer::register_compiled`]. It borrows nothing from the renderer, so the renderer stays
78/// usable while a browser's shader compiler answers.
79pub 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    /// Waits for the device's verdict on the shader and pipeline.
97    ///
98    /// # Errors
99    /// The shader's diagnostics if it failed, else the pipeline creation errors.
100    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        // A pipeline from a failed shader fails too; report the shader's diagnostics.
111        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
136/// A compiled runtime effect, ready for [`Renderer::register_compiled`] on the same renderer.
137pub 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    /// The identity the effect registers under.
154    #[must_use]
155    pub const fn id(&self) -> &EffectId {
156        &self.id
157    }
158}
159
160/// Entries are shared so a frame keeps drawing with an effect another thread unregisters.
161#[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    /// Refuses `id` when already registered or the host's share is full. Built-ins do not count.
170    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    /// Worst-case per-pixel cost of one invocation.
193    pub(crate) cost: crate::effect_cost::EffectCost,
194    pub(crate) pass_id: u64,
195    /// Created at registration for host effects, and on first draw or warmup for built-ins.
196    pipeline: std::sync::OnceLock<EffectPipeline>,
197}
198
199#[derive(Debug)]
200pub(crate) struct EffectPipeline {
201    _shader: wgpu::ShaderModule,
202    pub(crate) bind_group_layout: wgpu::BindGroupLayout,
203    pub(crate) pipeline: wgpu::RenderPipeline,
204    pub(crate) sampler: wgpu::Sampler,
205}
206
207impl Renderer {
208    /// Validates, compiles and registers a runtime effect: [`Self::compile_effect`],
209    /// [`PendingEffect::compiled`], then [`Self::register_compiled`].
210    ///
211    /// Holds the renderer until the device answers; a host that needs the renderer meanwhile calls
212    /// the three steps itself.
213    ///
214    /// # Errors
215    /// Returns schema or WGSL diagnostics without mutating the registry.
216    pub async fn register_effect(
217        &self,
218        definition: EffectDef,
219    ) -> Result<EffectId, ShaderDiagnostics> {
220        let compiled = self.compile_effect(definition)?.compiled().await?;
221        self.register_compiled(compiled)
222    }
223
224    /// Validates a runtime effect and creates its shader module and pipeline without waiting for
225    /// the verdict.
226    ///
227    /// All error scopes open and close within this call, so overlapping registrations never share
228    /// one.
229    ///
230    /// # Errors
231    /// Schema diagnostics, a duplicate id or a full registry, without touching the device.
232    pub fn compile_effect(
233        &self,
234        definition: EffectDef,
235    ) -> Result<PendingEffect, ShaderDiagnostics> {
236        let id = self.check_registration(&definition)?;
237        let device = self.gpu.device();
238        let format = self.intermediate_format();
239        let (compilation, shader_errors, pipeline, pipeline_errors) = on_compile_stack(|| {
240            let shader_scope = CreationErrorScopes::push(device);
241            let shader = effect_shader(device, &definition);
242            let compilation: Answer<wgpu::CompilationInfo> =
243                Box::pin(shader.get_compilation_info());
244            let shader_errors = shader_scope.pop();
245            let pipeline_scope = CreationErrorScopes::push(device);
246            let pipeline = effect_pipeline(device, &definition, shader, format);
247            (compilation, shader_errors, pipeline, pipeline_scope.pop())
248        });
249        Ok(PendingEffect {
250            compiled: CompiledEffect {
251                device: device.clone(),
252                id,
253                effect: RegisteredEffect {
254                    pipeline: std::sync::OnceLock::from(pipeline),
255                    ..registered_effect(definition)
256                },
257            },
258            compilation,
259            shader_errors,
260            pipeline_errors,
261        })
262    }
263
264    /// Validates and registers a built-in without touching the device; its pipeline is made on
265    /// first draw or [`Self::warmup`]. Compiling every built-in up front costs seconds on a
266    /// software adapter.
267    ///
268    /// # Errors
269    /// Schema diagnostics, a duplicate id or a full registry.
270    pub(crate) fn register_lazily(
271        &self,
272        definition: EffectDef,
273    ) -> Result<EffectId, ShaderDiagnostics> {
274        let id = self.check_registration(&definition)?;
275        let mut effects = self.effects_mut();
276        effects.check_room(&id)?;
277        effects.entries.insert(
278            id.clone(),
279            crate::Shared::new(registered_effect(definition)),
280        );
281        Ok(id)
282    }
283
284    /// The registry, read; registration and removal take it briefly to write.
285    pub(crate) fn effects(&self) -> RwLockReadGuard<'_, EffectRegistry> {
286        self.effects.read().unwrap_or_else(PoisonError::into_inner)
287    }
288
289    pub(crate) fn effects_mut(&self) -> RwLockWriteGuard<'_, EffectRegistry> {
290        self.effects.write().unwrap_or_else(PoisonError::into_inner)
291    }
292
293    /// Pre-device registration checks; returns the identity to register under.
294    fn check_registration(&self, definition: &EffectDef) -> Result<EffectId, ShaderDiagnostics> {
295        validate_definition(definition)?;
296        self.validate_parameter_uniform(definition)?;
297        self.validate_texture_bindings(definition)?;
298        if definition.tier_min == CapabilityTier::TierA
299            && self.gpu.capabilities().tier == CapabilityTier::TierB
300        {
301            return Err(ShaderDiagnostics::error(
302                "effect requires capability tier A on a tier B adapter",
303            ));
304        }
305        let id = EffectId::new(definition.id.clone(), definition.version);
306        self.effects().check_room(&id)?;
307        Ok(id)
308    }
309
310    /// The effect's pipeline, created now if needed; a failed creation is not kept.
311    ///
312    /// # Errors
313    /// [`crate::RenderError::Gpu`] with the class of the creation's error.
314    pub(crate) fn effect_pipeline<'a>(
315        &self,
316        effect: &'a RegisteredEffect,
317    ) -> Result<&'a EffectPipeline, crate::RenderError> {
318        if let Some(pipeline) = effect.pipeline.get() {
319            return Ok(pipeline);
320        }
321        let created = crate::diagnostics::timed_pipeline_creation(
322            &self.diagnostics,
323            || effect.definition.id.as_str().to_owned(),
324            || {
325                let device = self.gpu.device();
326                let format = self.intermediate_format();
327                // Scopes are per thread, so the compile thread pushes its own.
328                on_compile_stack(|| {
329                    let shader = create_checked(device, || self.lazy_effect_shader(effect))?;
330                    create_checked(device, || {
331                        effect_pipeline(device, &effect.definition, shader, format)
332                    })
333                })
334            },
335        )
336        .map_err(|kind| crate::RenderError::Gpu { kind })?;
337        Ok(effect.pipeline.get_or_init(|| created))
338    }
339
340    fn lazy_effect_shader(&self, effect: &RegisteredEffect) -> wgpu::ShaderModule {
341        let device = self.gpu.device();
342        #[cfg(test)]
343        if self
344            .fail_next_pipeline
345            .swap(false, std::sync::atomic::Ordering::Relaxed)
346        {
347            // A module without the entry points the pipeline names.
348            return device.create_shader_module(wgpu::ShaderModuleDescriptor {
349                label: Some("alpha2 test module without entry points"),
350                source: wgpu::ShaderSource::Wgsl("fn unused() {}".into()),
351            });
352        }
353        effect_shader(device, &effect.definition)
354    }
355
356    /// Adds an effect this renderer compiled.
357    ///
358    /// # Errors
359    /// Refuses an effect from another device, one registered meanwhile, or a full registry.
360    pub fn register_compiled(
361        &self,
362        compiled: CompiledEffect,
363    ) -> Result<EffectId, ShaderDiagnostics> {
364        if compiled.device != *self.gpu.device() {
365            return Err(ShaderDiagnostics::error(format!(
366                "effect {} version {} was compiled on another GPU device",
367                compiled.id.as_str(),
368                compiled.id.version()
369            )));
370        }
371        let mut effects = self.effects_mut();
372        effects.check_room(&compiled.id)?;
373        effects
374            .entries
375            .insert(compiled.id.clone(), crate::Shared::new(compiled.effect));
376        Ok(compiled.id)
377    }
378
379    /// Refuses parameter uniforms some alpha2 runtime cannot bind.
380    ///
381    /// Each parameter is one 16-byte slot. The cap is the WebGL2 limit every alpha2 device
382    /// requests, so an effect that registers anywhere registers everywhere. Past it the pipeline
383    /// still compiles but every frame's bind group fails.
384    fn validate_parameter_uniform(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
385        let limit = self
386            .limits
387            .max_uniform_buffer_binding_size
388            .min(wgpu::Limits::downlevel_webgl2_defaults().max_uniform_buffer_binding_size);
389        let bytes = u64::try_from(param_uniform_bytes(definition.params.len())).unwrap_or(u64::MAX);
390        if bytes > limit {
391            let most = limit / u64::try_from(PARAM_SLOT_BYTES).unwrap_or(u64::MAX);
392            return Err(ShaderDiagnostics::error(format!(
393                "effect declares {} parameters, a {bytes}-byte uniform past the {limit}-byte \
394                 limit every alpha2 runtime binds (at most {most} parameters)",
395                definition.params.len()
396            )));
397        }
398        Ok(())
399    }
400
401    /// Refuses definitions needing more sampled textures per stage than the WebGL2 limit (16) every
402    /// alpha2 device requests: source pair, each resource and each named input take one.
403    fn validate_texture_bindings(&self, definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
404        let textures = 2 + definition.resources.len() + definition.inputs.len();
405        let limit =
406            usize::try_from(self.limits.max_sampled_textures_per_shader_stage.min(
407                wgpu::Limits::downlevel_webgl2_defaults().max_sampled_textures_per_shader_stage,
408            ))
409            .unwrap_or(usize::MAX);
410        if textures > limit {
411            return Err(ShaderDiagnostics::error(format!(
412                "effect samples {textures} textures (its source pair, {} resources, and {} \
413                 named inputs), past this device's {limit} per shader stage",
414                definition.resources.len(),
415                definition.inputs.len()
416            )));
417        }
418        Ok(())
419    }
420
421    /// The generated host uniform layout of a registered effect.
422    #[must_use]
423    pub fn effect_uniform_layout(&self, id: &EffectId) -> Option<UniformLayout> {
424        self.effects()
425            .entries
426            .get(id)
427            .map(|entry| entry.uniform_layout.clone())
428    }
429
430    /// The definition of a registered effect.
431    #[must_use]
432    pub fn effect_definition(&self, id: &EffectId) -> Option<Arc<EffectDef>> {
433        self.effects()
434            .entries
435            .get(id)
436            .map(|entry| Arc::clone(&entry.definition))
437    }
438
439    /// Whether `id`'s output can change with frame time alone; `true` for unknown effects.
440    ///
441    /// Derived from the WGSL of every pass: a body that never names `time`, `time_ticks` or
442    /// `runtime` cannot read it. Callers may pass any time to an effect answering `false`, so its
443    /// result can be reused across frames.
444    #[must_use]
445    pub fn effect_reads_time(&self, id: &EffectId) -> bool {
446        if let Some(passes) = crate::gaussian_blur::expanded_passes(id.as_str()) {
447            return passes
448                .iter()
449                .any(|pass| self.effect_reads_time(&EffectId::from_static(pass, 1)));
450        }
451        self.effects()
452            .entries
453            .get(id)
454            .is_none_or(|entry| entry.reads_time)
455    }
456
457    /// Whether an exact effect version is registered.
458    #[must_use]
459    pub fn is_effect_registered(&self, id: &EffectId) -> bool {
460        self.effects().entries.contains_key(id)
461    }
462
463    /// Whether a project document may reference the effect.
464    #[must_use]
465    pub fn is_effect_project_visible(&self, id: &EffectId) -> bool {
466        let effects = self.effects();
467        effects.entries.contains_key(id) && !effects.internal.contains(id)
468    }
469
470    /// The registered identity a project reference to `id`@`version` draws with, if the project
471    /// may reference it.
472    #[must_use]
473    pub fn project_effect_id(&self, id: &str, version: u32) -> Option<EffectId> {
474        let key: &dyn EffectKey = &(id, version);
475        let effects = self.effects();
476        effects
477            .entries
478            .get_key_value(key)
479            .map(|(id, _)| id)
480            .filter(|id| !effects.internal.contains(*id))
481            .cloned()
482    }
483
484    /// Whether `id` is an engine built-in rather than a host-registered runtime effect.
485    #[must_use]
486    pub fn is_builtin_effect(&self, id: &EffectId) -> bool {
487        self.effects().builtins.contains(id)
488    }
489
490    /// Removes one runtime effect and releases its GPU resources once no frame draws with it.
491    pub fn unregister_effect(&self, id: &EffectId) -> bool {
492        let removed = {
493            let mut effects = self.effects_mut();
494            !effects.builtins.contains(id) && effects.entries.remove(id).is_some()
495        };
496        if removed {
497            self.clear_result_cache_for(crate::CacheInvalidation::Effects);
498        }
499        removed
500    }
501
502    /// Removes every host-registered runtime effect.
503    pub fn clear_effects(&self) {
504        {
505            let mut effects = self.effects_mut();
506            let EffectRegistry {
507                entries, builtins, ..
508            } = &mut *effects;
509            entries.retain(|id, _| builtins.contains(id));
510        }
511        self.clear_result_cache_for(crate::CacheInvalidation::Effects);
512    }
513
514    /// Confirms the effects are registered and creates pending built-in pipelines (including their
515    /// passes) so the first frame does not wait on the compiler.
516    ///
517    /// # Errors
518    /// Names the first unregistered effect, or the first pipeline whose creation failed.
519    pub fn warmup(&self, effects: &[EffectId]) -> Result<(), ShaderDiagnostics> {
520        let create = |effect: &EffectId, registered: &RegisteredEffect| {
521            self.effect_pipeline(registered)
522                .map(|_| ())
523                .map_err(|error| {
524                    ShaderDiagnostics::error(format!(
525                        "effect {} version {}: {error}",
526                        effect.as_str(),
527                        effect.version()
528                    ))
529                })
530        };
531        for effect in effects {
532            let Some(registered) = self.effects().get(effect) else {
533                return Err(ShaderDiagnostics::error(format!(
534                    "effect {} version {} is not registered",
535                    effect.as_str(),
536                    effect.version()
537                )));
538            };
539            create(effect, &registered)?;
540            for pass in crate::gaussian_blur::expanded_passes(effect.as_str()).unwrap_or_default() {
541                let pass = EffectId::from_static(pass, 1);
542                if let Some(registered) = self.effects().get(&pass) {
543                    create(&pass, &registered)?;
544                }
545            }
546        }
547        Ok(())
548    }
549}
550
551impl EffectRegistry {
552    pub(crate) fn get(&self, id: &EffectId) -> Option<crate::Shared<RegisteredEffect>> {
553        self.entries.get(id).cloned()
554    }
555
556    pub(crate) fn len(&self) -> usize {
557        self.entries.len()
558    }
559
560    pub(crate) fn mark_builtin(&mut self, id: EffectId) {
561        debug_assert!(self.entries.contains_key(&id));
562        self.builtins.insert(id);
563    }
564
565    pub(crate) fn mark_internal(&mut self, id: EffectId) {
566        debug_assert!(self.entries.contains_key(&id));
567        self.internal.insert(id);
568    }
569}
570
571/// A registry entry for `definition`, pipeline not yet created.
572pub(crate) fn registered_effect(definition: EffectDef) -> RegisteredEffect {
573    RegisteredEffect {
574        uniform_layout: uniform_layout(&definition.params),
575        reads_time: body_reads_time(&definition.wgsl_body),
576        cost: crate::effect_cost::invocation_cost(&blank_comments(&definition.wgsl_body)),
577        pass_id: pass_id(&definition),
578        definition: Arc::new(definition),
579        pipeline: std::sync::OnceLock::new(),
580    }
581}
582
583fn pass_id(definition: &EffectDef) -> u64 {
584    use std::hash::{Hash, Hasher};
585    let mut hasher = std::hash::DefaultHasher::new();
586    definition.id.hash(&mut hasher);
587    definition.version.hash(&mut hasher);
588    definition.wgsl_body.hash(&mut hasher);
589    hasher.finish()
590}
591
592fn effect_shader(device: &wgpu::Device, definition: &EffectDef) -> wgpu::ShaderModule {
593    device.create_shader_module(wgpu::ShaderModuleDescriptor {
594        label: Some(&definition.id),
595        source: wgpu::ShaderSource::Wgsl(build_shader(definition).into()),
596    })
597}
598
599fn effect_pipeline(
600    device: &wgpu::Device,
601    definition: &EffectDef,
602    shader: wgpu::ShaderModule,
603    format: wgpu::TextureFormat,
604) -> EffectPipeline {
605    let bind_group_layout = runtime_bind_group_layout(
606        device,
607        &definition.params,
608        &definition.resources,
609        &definition.inputs,
610    );
611    let pipeline = runtime_pipeline(device, &bind_group_layout, &shader, format);
612    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
613        label: Some("alpha2 runtime effect sampler"),
614        address_mode_u: wgpu::AddressMode::ClampToEdge,
615        address_mode_v: wgpu::AddressMode::ClampToEdge,
616        mag_filter: wgpu::FilterMode::Linear,
617        min_filter: wgpu::FilterMode::Linear,
618        ..Default::default()
619    });
620    EffectPipeline {
621        _shader: shader,
622        bind_group_layout,
623        pipeline,
624        sampler,
625    }
626}
627
628fn runtime_bind_group_layout(
629    device: &wgpu::Device,
630    params: &[ParamSpec],
631    resources: &[ResourceSpec],
632    inputs: &[InputSpec],
633) -> wgpu::BindGroupLayout {
634    let mut entries = vec![
635        runtime_texture_entry(0, wgpu::TextureViewDimension::D2),
636        runtime_texture_entry(1, wgpu::TextureViewDimension::D2),
637        wgpu::BindGroupLayoutEntry {
638            binding: 2,
639            visibility: wgpu::ShaderStages::FRAGMENT,
640            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
641            count: None,
642        },
643        // Bind at exact struct sizes so a shader reading past them fails to compile instead of
644        // reading the next arena slot.
645        runtime_uniform_entry(3, param_uniform_bytes(params.len())),
646        runtime_uniform_entry(4, RUNTIME_UNIFORM_WORDS * size_of::<f32>()),
647    ];
648    for (index, resource) in resources.iter().enumerate() {
649        let binding = u32::try_from(index).unwrap_or(0) * 2 + 5;
650        let dimension = match resource.kind {
651            EffectResourceKind::Lut3d => wgpu::TextureViewDimension::D3,
652        };
653        entries.push(runtime_texture_entry(binding, dimension));
654        entries.push(runtime_uniform_entry(binding + 1, RESOURCE_METADATA_BYTES));
655    }
656    for index in 0..inputs.len() {
657        entries.push(runtime_texture_entry(
658            input_binding(index),
659            wgpu::TextureViewDimension::D2,
660        ));
661    }
662    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
663        label: Some("alpha2 runtime effect layout"),
664        entries: &entries,
665    })
666}
667
668pub(crate) fn input_binding(index: usize) -> u32 {
669    INPUT_BINDING_BASE + u32::try_from(index).unwrap_or(0)
670}
671
672fn runtime_texture_entry(
673    binding: u32,
674    view_dimension: wgpu::TextureViewDimension,
675) -> wgpu::BindGroupLayoutEntry {
676    wgpu::BindGroupLayoutEntry {
677        binding,
678        visibility: wgpu::ShaderStages::FRAGMENT,
679        ty: wgpu::BindingType::Texture {
680            sample_type: wgpu::TextureSampleType::Float { filterable: true },
681            view_dimension,
682            multisampled: false,
683        },
684        count: None,
685    }
686}
687
688fn runtime_uniform_entry(binding: u32, bytes: usize) -> wgpu::BindGroupLayoutEntry {
689    wgpu::BindGroupLayoutEntry {
690        binding,
691        visibility: wgpu::ShaderStages::FRAGMENT,
692        ty: wgpu::BindingType::Buffer {
693            ty: wgpu::BufferBindingType::Uniform,
694            has_dynamic_offset: false,
695            min_binding_size: u64::try_from(bytes)
696                .ok()
697                .and_then(std::num::NonZeroU64::new),
698        },
699        count: None,
700    }
701}
702
703fn runtime_pipeline(
704    device: &wgpu::Device,
705    bind_group_layout: &wgpu::BindGroupLayout,
706    shader: &wgpu::ShaderModule,
707    format: wgpu::TextureFormat,
708) -> wgpu::RenderPipeline {
709    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
710        label: Some("alpha2 runtime effect pipeline layout"),
711        bind_group_layouts: &[Some(bind_group_layout)],
712        immediate_size: 0,
713    });
714    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
715        label: Some("alpha2 runtime effect pipeline"),
716        layout: Some(&layout),
717        vertex: wgpu::VertexState {
718            module: shader,
719            entry_point: Some("alpha2_vs"),
720            buffers: &[],
721            compilation_options: wgpu::PipelineCompilationOptions::default(),
722        },
723        fragment: Some(wgpu::FragmentState {
724            module: shader,
725            entry_point: Some("alpha2_fs"),
726            targets: &[Some(format.into())],
727            compilation_options: wgpu::PipelineCompilationOptions::default(),
728        }),
729        primitive: wgpu::PrimitiveState::default(),
730        depth_stencil: None,
731        multisample: wgpu::MultisampleState::default(),
732        multiview_mask: None,
733        cache: None,
734    })
735}
736
737pub(crate) fn uniform_layout(params: &[ParamSpec]) -> UniformLayout {
738    let fields = params
739        .iter()
740        .enumerate()
741        .map(|(index, param)| UniformField {
742            name: param.name.clone(),
743            offset: u32::try_from(index).expect("parameter count fits u32") * 16,
744            size: 16,
745        })
746        .collect::<Vec<_>>();
747    UniformLayout {
748        size: u32::try_from(param_uniform_bytes(params.len())).expect("parameter uniform fits u32"),
749        fields,
750    }
751}
752
753/// Whether an effect body can read the frame time.
754///
755/// `time()` and `time_ticks()` read the `runtime` uniform, and WGSL can reach none of them
756/// without naming it, so a body lacking all three as words cannot. Anything else counts as
757/// reading it (comments and shadowing included): a false `true` only redraws. A word is a run
758/// of letters, digits and underscores.
759pub(crate) fn body_reads_time(body: &str) -> bool {
760    body.split(|character: char| !(character.is_alphanumeric() || character == '_'))
761        .any(|word| matches!(word, "time" | "time_ticks" | "runtime"))
762}
763
764pub(crate) fn build_shader(definition: &EffectDef) -> String {
765    let param_fields = if definition.params.is_empty() {
766        "    _padding: vec4f,\n".to_owned()
767    } else {
768        definition
769            .params
770            .iter()
771            .fold(String::new(), |mut output, param| {
772                writeln!(
773                    output,
774                    "    {}: {},",
775                    param.name,
776                    wgsl_type(param.param_type)
777                )
778                .expect("writing to a String cannot fail");
779                output
780            })
781    };
782    let uniform_fields =
783        (0..definition.params.len().max(1)).fold(String::new(), |mut output, index| {
784            writeln!(output, "    slot_{index}: vec4u,").expect("writing to a String cannot fail");
785            output
786        });
787    let param_values = if definition.params.is_empty() {
788        "vec4f(0.0)".to_owned()
789    } else {
790        definition
791            .params
792            .iter()
793            .enumerate()
794            .map(|(index, param)| uniform_value(index, param.param_type))
795            .collect::<Vec<_>>()
796            .join(", ")
797    };
798    let call = match definition.kind {
799        EffectKind::Effect => "effect(input.uv, sample_src(input.uv))",
800        EffectKind::Transition => "alpha2_transition(input.uv)",
801        EffectKind::Generator => "generate(input.uv)",
802    };
803    let transition_wrapper = match definition.kind {
804        EffectKind::Effect | EffectKind::Generator => "",
805        EffectKind::Transition => {
806            r"fn alpha2_transition(uv: vec2f) -> vec4f {
807    if (progress() <= 0.0) { return from_color(uv); }
808    if (progress() >= 1.0) { return to_color(uv); }
809    return transition(uv);
810}"
811        }
812    };
813    let resource_declarations = resource_declarations(&definition.resources);
814    let input_declarations = input_declarations(&definition.inputs);
815    format!(
816        r"@group(0) @binding(0) var source_a: texture_2d<f32>;
817@group(0) @binding(1) var source_b: texture_2d<f32>;
818@group(0) @binding(2) var source_sampler: sampler;
819struct EffectParams {{
820{param_fields}}};
821struct EffectParamUniforms {{
822{uniform_fields}}};
823@group(0) @binding(3) var<uniform> param_uniforms: EffectParamUniforms;
824var<private> params: EffectParams;
825var<private> {BUDGET}: u32;
826struct RuntimeValues {{ resolution_time: vec4f, transition: vec4f, ticks: vec4u, }};
827@group(0) @binding(4) var<uniform> runtime: RuntimeValues;
828{resource_declarations}{input_declarations}
829
830fn sample_src(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
831fn from_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_a, source_sampler, uv, 0.0); }}
832fn to_color(uv: vec2f) -> vec4f {{ return textureSampleLevel(source_b, source_sampler, uv, 0.0); }}
833fn resolution() -> vec2f {{ return runtime.resolution_time.xy; }}
834fn time() -> f32 {{ return runtime.resolution_time.z; }}
835fn time_ticks() -> vec2u {{ return runtime.ticks.xy; }}
836fn progress() -> f32 {{ return runtime.transition.x; }}
837fn ratio() -> f32 {{ return runtime.transition.y; }}
838fn render_scale() -> f32 {{ return runtime.resolution_time.w; }}
839fn render_scale_fixed() -> u32 {{ return runtime.ticks.z; }}
840fn max_filter_samples() -> f32 {{ return runtime.transition.z; }}
841fn load_params() -> EffectParams {{ return EffectParams({param_values}); }}
842
843{body}
844
845{transition_wrapper}
846
847struct VertexOutput {{ @builtin(position) position: vec4f, @location(0) uv: vec2f, }};
848@vertex fn alpha2_vs(@builtin(vertex_index) index: u32) -> VertexOutput {{
849    var p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
850    var u = array<vec2f, 3>(vec2f(0.0, 1.0), vec2f(2.0, 1.0), vec2f(0.0, -1.0));
851    return VertexOutput(vec4f(p[index], 0.0, 1.0), u[index]);
852}}
853@fragment fn alpha2_fs(input: VertexOutput) -> @location(0) vec4f {{
854    params = load_params();
855    {BUDGET} = {MAX_LOOP_ITERATIONS}u;
856    return {call};
857}}
858",
859        // Registration already delimited loops; this covers definitions that skipped it.
860        body =
861            bound_for_loops(&definition.wgsl_body).unwrap_or_else(|_| definition.wgsl_body.clone()),
862        resource_declarations = resource_declarations,
863        input_declarations = input_declarations,
864        transition_wrapper = transition_wrapper,
865    )
866}
867
868fn resource_declarations(resources: &[ResourceSpec]) -> String {
869    resources
870        .iter()
871        .enumerate()
872        .map(|(index, resource)| match resource.kind {
873            EffectResourceKind::Lut3d => format!(
874                "struct ResourceMetadata_{} {{ domain_min: vec4f, domain_max: vec4f, }};\n\
875                 @group(0) @binding({}) var resource_{}: texture_3d<f32>;\n\
876                 @group(0) @binding({}) var<uniform> resource_{}_metadata: ResourceMetadata_{};\n\
877                 fn sample_{}(rgb: vec3f) -> vec3f {{\n\
878                     let edge = f32(textureDimensions(resource_{}).x);\n\
879                     let normalized = clamp((rgb - resource_{}_metadata.domain_min.xyz) /\n\
880                         (resource_{}_metadata.domain_max.xyz - resource_{}_metadata.domain_min.xyz),\n\
881                         vec3f(0.0), vec3f(1.0));\n\
882                     let coord = (normalized * (edge - 1.0) + 0.5) / edge;\n\
883                     return textureSampleLevel(resource_{}, source_sampler, coord, 0.0).rgb;\n\
884                 }}",
885                resource.name,
886                index * 2 + 5,
887                resource.name,
888                index * 2 + 6,
889                resource.name,
890                resource.name,
891                resource.name,
892                resource.name,
893                resource.name,
894                resource.name,
895                resource.name,
896                resource.name,
897            ),
898        })
899        .collect::<Vec<_>>()
900        .join("\n")
901}
902
903/// Per-input wrapper declarations: texture, sampling helper and size. Empty without inputs.
904fn input_declarations(inputs: &[InputSpec]) -> String {
905    inputs
906        .iter()
907        .enumerate()
908        .fold(String::new(), |mut output, (index, input)| {
909            let name = &input.name;
910            write!(
911                output,
912                "\n@group(0) @binding({binding}) var input_{name}: texture_2d<f32>;\n\
913                 fn sample_{name}(uv: vec2f) -> vec4f {{ return textureSampleLevel(input_{name}, source_sampler, uv, 0.0); }}\n\
914                 fn size_{name}() -> vec2f {{ return vec2f(textureDimensions(input_{name})); }}",
915                binding = input_binding(index),
916            )
917            .expect("writing to a String cannot fail");
918            output
919        })
920}
921
922fn uniform_value(index: usize, param_type: ParamType) -> String {
923    match param_type {
924        ParamType::Float => format!("bitcast<f32>(param_uniforms.slot_{index}.x)"),
925        ParamType::Vec2 => format!("bitcast<vec2f>(param_uniforms.slot_{index}.xy)"),
926        ParamType::Vec4 | ParamType::Color => {
927            format!("bitcast<vec4f>(param_uniforms.slot_{index})")
928        }
929        ParamType::Enum | ParamType::Bool => format!("param_uniforms.slot_{index}.x"),
930    }
931}
932
933fn wgsl_type(param_type: ParamType) -> &'static str {
934    match param_type {
935        ParamType::Float => "f32",
936        ParamType::Vec2 => "vec2f",
937        ParamType::Vec4 | ParamType::Color => "vec4f",
938        ParamType::Enum | ParamType::Bool => "u32",
939    }
940}
941
942/// What registration learns about a runtime effect before any device sees it.
943#[derive(Clone, Debug, PartialEq, Eq)]
944pub struct CheckedEffect {
945    /// The WGSL module the device would compile: the body, its loops bounded, in the wrapper.
946    pub module: String,
947    /// Functions the body declares.
948    pub functions: usize,
949    /// The most function bodies one invocation of any of them runs once calls are inlined.
950    pub calls: u64,
951    /// The invocation's cost in units of the registration cap.
952    pub cost_units: u64,
953}
954
955/// Checks `definition` as registration does before the device compiles it: the schema, the
956/// lexical rules of the body, its calls and its cost. Device limits (uniform size, texture
957/// bindings) and the compile itself are not checked.
958///
959/// # Errors
960/// The diagnostics registration would return.
961pub fn check_effect(definition: &EffectDef) -> Result<CheckedEffect, ShaderDiagnostics> {
962    validate_definition(definition)?;
963    let code = blank_comments(&definition.wgsl_body);
964    let (calls, _) = crate::call_budget::invocation_calls(&code)?;
965    Ok(CheckedEffect {
966        module: build_shader(definition),
967        functions: crate::call_budget::declarations(&code).len(),
968        calls,
969        cost_units: crate::effect_cost::invocation_cost(&code).units(),
970    })
971}
972
973fn validate_definition(definition: &EffectDef) -> Result<(), ShaderDiagnostics> {
974    if !valid_identifier(&definition.id) {
975        return Err(ShaderDiagnostics::error(
976            "effect id must contain only ASCII letters, digits, '-', '_', or '.'",
977        ));
978    }
979    if definition.version == 0 {
980        return Err(ShaderDiagnostics::error("effect version must be non-zero"));
981    }
982    validate_wgsl_body(&definition.wgsl_body)?;
983    if !definition.inputs.is_empty() && definition.kind != EffectKind::Effect {
984        return Err(ShaderDiagnostics::error(
985            "only effects declare named inputs; a transition samples from and to",
986        ));
987    }
988    if definition.inputs.len() > MAX_EFFECT_INPUTS {
989        return Err(ShaderDiagnostics::error(format!(
990            "effect declares more than {MAX_EFFECT_INPUTS} named inputs"
991        )));
992    }
993    let mut names = std::collections::HashSet::new();
994    for param in &definition.params {
995        validate_param(param)?;
996        if !names.insert(param.name.as_str()) {
997            return Err(ShaderDiagnostics::error(format!(
998                "duplicate parameter name {}",
999                param.name
1000            )));
1001        }
1002    }
1003    if definition.resources.len() > MAX_EFFECT_RESOURCES {
1004        return Err(ShaderDiagnostics::error(format!(
1005            "effect declares more than {MAX_EFFECT_RESOURCES} resources"
1006        )));
1007    }
1008    let mut resource_names = std::collections::HashSet::new();
1009    // Resource declarations share module scope with the wrapper's names and each other.
1010    let mut declared = std::collections::HashSet::new();
1011    for resource in &definition.resources {
1012        let generated = resource_declarations_of(&resource.name);
1013        if !valid_wgsl_identifier(&resource.name)
1014            || names.contains(resource.name.as_str())
1015            || !resource_names.insert(resource.name.as_str())
1016            || !generated
1017                .iter()
1018                .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1019        {
1020            return Err(ShaderDiagnostics::error(format!(
1021                "invalid or duplicate effect resource name {}",
1022                resource.name
1023            )));
1024        }
1025    }
1026    // An input's names share the module scope with the resources'.
1027    let mut input_names = std::collections::HashSet::new();
1028    for input in &definition.inputs {
1029        let generated = input_declarations_of(&input.name);
1030        if !valid_wgsl_identifier(&input.name)
1031            || names.contains(input.name.as_str())
1032            || resource_names.contains(input.name.as_str())
1033            || !input_names.insert(input.name.as_str())
1034            || !generated
1035                .iter()
1036                .all(|name| valid_wgsl_identifier(name) && declared.insert(name.clone()))
1037        {
1038            return Err(ShaderDiagnostics::error(format!(
1039                "invalid or duplicate effect input name {}",
1040                input.name
1041            )));
1042        }
1043    }
1044    Ok(())
1045}
1046
1047/// Module-scope names [`build_shader`] declares for input `name`. This is also what refuses
1048/// `src`, since `sample_src` is the prelude's.
1049fn input_declarations_of(name: &str) -> [String; 3] {
1050    [
1051        format!("input_{name}"),
1052        format!("sample_{name}"),
1053        format!("size_{name}"),
1054    ]
1055}
1056
1057/// Module-scope names [`build_shader`] declares for resource `name`.
1058fn resource_declarations_of(name: &str) -> [String; 4] {
1059    [
1060        format!("resource_{name}"),
1061        format!("resource_{name}_metadata"),
1062        format!("sample_{name}"),
1063        format!("ResourceMetadata_{name}"),
1064    ]
1065}
1066
1067fn validate_wgsl_body(body: &str) -> Result<(), ShaderDiagnostics> {
1068    if body.len() > MAX_WGSL_BODY_BYTES {
1069        return Err(ShaderDiagnostics::error(format!(
1070            "WGSL body exceeds {MAX_WGSL_BODY_BYTES} bytes"
1071        )));
1072    }
1073    if body
1074        .chars()
1075        .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'))
1076    {
1077        return Err(ShaderDiagnostics::error(
1078            "WGSL body contains unsupported control characters",
1079        ));
1080    }
1081    // Only code is checked; comments may contain anything.
1082    let code = blank_comments(body);
1083    // The cost analysis reads ASCII identifiers and blankspace only.
1084    if !code.is_ascii() {
1085        return Err(ShaderDiagnostics::error(
1086            "a runtime effect's code is ASCII; comments may hold any text",
1087        ));
1088    }
1089    if let Some(identifier) = identifiers(&code).find(|word| word.starts_with(RESERVED_PREFIX)) {
1090        return Err(ShaderDiagnostics::error(format!(
1091            "WGSL identifier {identifier} is reserved: names starting with {RESERVED_PREFIX} belong to the generated wrapper"
1092        )));
1093    }
1094    if code.split([';', '{', '}']).any(|statement| {
1095        statement.bytes().filter(|byte| is_operator(*byte)).count() > MAX_WGSL_STATEMENT_OPERATORS
1096    }) {
1097        return Err(ShaderDiagnostics::error(format!(
1098            "a WGSL statement has more than {MAX_WGSL_STATEMENT_OPERATORS} operators; split it with `let`"
1099        )));
1100    }
1101    check_nesting(&code)?;
1102    check_arrays(&code)?;
1103
1104    let forbidden = [
1105        "@binding",
1106        "@compute",
1107        "@group",
1108        "atomic",
1109        "enable",
1110        "loop",
1111        "override",
1112        "var<storage",
1113        "var<uniform",
1114        "var<workgroup",
1115        "while",
1116    ];
1117    for token in code.split(|character: char| {
1118        !(character.is_ascii_alphanumeric() || matches!(character, '_' | '@' | '<'))
1119    }) {
1120        if forbidden.contains(&token) {
1121            return Err(ShaderDiagnostics::error(format!(
1122                "WGSL token {token} is not allowed in a runtime effect"
1123            )));
1124        }
1125    }
1126    bound_for_loops(body)?;
1127    crate::call_budget::check_invocation_calls(&code)?;
1128    crate::effect_cost::check_invocation_cost(&code).map(drop)
1129}
1130
1131/// Refuses an array without a literal count, of elements other than scalars, vectors, matrices
1132/// and arrays, past [`MAX_ARRAY_SLOTS`] elements, or one array type too many.
1133fn check_arrays(code: &str) -> Result<(), ShaderDiagnostics> {
1134    let arrays = crate::effect_cost::array_types(code);
1135    if arrays.len() > MAX_ARRAY_TYPES {
1136        return Err(ShaderDiagnostics::error(format!(
1137            "a runtime effect writes at most {MAX_ARRAY_TYPES} array types"
1138        )));
1139    }
1140    for array in arrays {
1141        let text = &code[array.span.clone()];
1142        if !array.templated {
1143            return Err(ShaderDiagnostics::error(
1144                "write a runtime effect's arrays with their element type and count, as \
1145                 `array<T, N>(...)`",
1146            ));
1147        }
1148        let Some(slots) = array.slots else {
1149            return Err(ShaderDiagnostics::error(format!(
1150                "`{text}` needs an integer literal count and elements that are scalars, \
1151                 vectors, matrices or arrays"
1152            )));
1153        };
1154        if slots > MAX_ARRAY_SLOTS {
1155            return Err(ShaderDiagnostics::error(format!(
1156                "`{text}` holds more than {MAX_ARRAY_SLOTS} vectors; put a large table in a \
1157                 resource texture"
1158            )));
1159        }
1160    }
1161    Ok(())
1162}
1163
1164/// Refuses unbalanced delimiters and nesting past [`MAX_WGSL_NESTING`], where each arm of an
1165/// `else if` chain nests one level deeper than the one before, as naga lowers it.
1166fn check_nesting(code: &str) -> Result<(), ShaderDiagnostics> {
1167    let unbalanced = || ShaderDiagnostics::error("WGSL body has unbalanced delimiters");
1168    let too_deep = |chained: bool| {
1169        ShaderDiagnostics::error(if chained {
1170            format!(
1171                "an `else if` chain nests past {MAX_WGSL_NESTING} levels; use `switch` or \
1172                 early returns"
1173            )
1174        } else {
1175            format!("WGSL nesting exceeds {MAX_WGSL_NESTING} levels")
1176        })
1177    };
1178    // Open delimiters with their depth, and the chain length of an `if` body.
1179    let mut open: Vec<(u8, usize, Option<usize>)> = Vec::new();
1180    // An `if` whose body opens at this delimiter count, and its chain length.
1181    let mut pending_if: Option<(usize, usize)> = None;
1182    // The chain length of the `if` body that closed last, while only `else` may follow it.
1183    let mut closed_chain: Option<usize> = None;
1184    let mut after_else = false;
1185    let bytes = code.as_bytes();
1186    let mut index = 0;
1187    while index < bytes.len() {
1188        let byte = bytes[index];
1189        if byte.is_ascii_whitespace() {
1190            index += 1;
1191            continue;
1192        }
1193        if crate::loop_bound::is_identifier_byte(byte) {
1194            let end = index
1195                + bytes[index..]
1196                    .iter()
1197                    .take_while(|byte| crate::loop_bound::is_identifier_byte(**byte))
1198                    .count();
1199            let word = &code[index..end];
1200            index = end;
1201            if word == "else" && closed_chain.is_some() && !after_else {
1202                after_else = true;
1203                continue;
1204            }
1205            if word == "if" {
1206                let chain = if after_else {
1207                    closed_chain.map_or(1, |chain| chain + 1)
1208                } else {
1209                    1
1210                };
1211                pending_if = Some((open.len(), chain));
1212            }
1213            closed_chain = None;
1214            after_else = false;
1215            continue;
1216        }
1217        closed_chain = None;
1218        after_else = false;
1219        index += 1;
1220        match byte {
1221            b'{' | b'(' | b'[' => {
1222                let chain = pending_if
1223                    .filter(|(at, _)| byte == b'{' && *at == open.len())
1224                    .map(|(_, chain)| chain);
1225                if chain.is_some() {
1226                    pending_if = None;
1227                }
1228                let depth = open.last().map_or(0, |(_, depth, _)| *depth) + chain.unwrap_or(1);
1229                if depth > MAX_WGSL_NESTING {
1230                    return Err(too_deep(chain.is_some_and(|chain| chain > 1)));
1231                }
1232                open.push((byte, depth, chain));
1233            }
1234            b'}' | b')' | b']' => {
1235                let Some((opened, _, chain)) = open.pop() else {
1236                    return Err(unbalanced());
1237                };
1238                if !matches!((opened, byte), (b'{', b'}') | (b'(', b')') | (b'[', b']')) {
1239                    return Err(unbalanced());
1240                }
1241                closed_chain = chain;
1242            }
1243            _ => {}
1244        }
1245    }
1246    if open.is_empty() {
1247        Ok(())
1248    } else {
1249        Err(unbalanced())
1250    }
1251}
1252
1253/// Identifiers in `code`; words starting with a letter or `_`, so number suffixes are excluded.
1254fn identifiers(code: &str) -> impl Iterator<Item = &str> {
1255    code.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
1256        .filter(|word| word.starts_with(|first: char| first.is_ascii_alphabetic() || first == '_'))
1257}
1258
1259/// Characters that can deepen an expression. Overcounts (`1.0`, `vec4<f32>`), which only
1260/// lowers the effective limit.
1261const fn is_operator(byte: u8) -> bool {
1262    matches!(
1263        byte,
1264        b'+' | b'-'
1265            | b'*'
1266            | b'/'
1267            | b'%'
1268            | b'&'
1269            | b'|'
1270            | b'^'
1271            | b'!'
1272            | b'~'
1273            | b'<'
1274            | b'>'
1275            | b'='
1276            | b'.'
1277            | b'['
1278    )
1279}
1280
1281fn validate_param(param: &ParamSpec) -> Result<(), ShaderDiagnostics> {
1282    if !valid_wgsl_identifier(&param.name) {
1283        return Err(ShaderDiagnostics::error(format!(
1284            "invalid WGSL parameter name {}",
1285            param.name
1286        )));
1287    }
1288    let compatible = matches!(
1289        (&param.param_type, &param.default, &param.unit),
1290        (
1291            ParamType::Float,
1292            ParamValue::Float(_),
1293            ParamUnit::Normalized | ParamUnit::Degrees
1294        ) | (ParamType::Vec2, ParamValue::Vec2(_), ParamUnit::Normalized)
1295            | (ParamType::Vec4, ParamValue::Vec4(_), ParamUnit::Normalized)
1296            | (ParamType::Color, ParamValue::Color(_), ParamUnit::Color)
1297            | (ParamType::Enum, ParamValue::Enum(_), ParamUnit::Enum)
1298            | (ParamType::Bool, ParamValue::Bool(_), ParamUnit::Bool)
1299    );
1300    if !compatible {
1301        return Err(ShaderDiagnostics::error(format!(
1302            "parameter {} has incompatible type, default, and unit",
1303            param.name
1304        )));
1305    }
1306    if !finite_value(&param.default)
1307        || param.min.is_some_and(|value| !value.is_finite())
1308        || param.max.is_some_and(|value| !value.is_finite())
1309        || param
1310            .step
1311            .is_some_and(|value| !value.is_finite() || value <= 0.0)
1312        || matches!((param.min, param.max), (Some(min), Some(max)) if min > max)
1313    {
1314        return Err(ShaderDiagnostics::error(format!(
1315            "parameter {} has an invalid numeric range",
1316            param.name
1317        )));
1318    }
1319    if !matches!(
1320        param.param_type,
1321        ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1322    ) && (param.min.is_some() || param.max.is_some() || param.step.is_some())
1323    {
1324        return Err(ShaderDiagnostics::error(format!(
1325            "only float, vec2, or vec4 parameter {} may declare a numeric range",
1326            param.name
1327        )));
1328    }
1329    if matches!(
1330        param.param_type,
1331        ParamType::Float | ParamType::Vec2 | ParamType::Vec4
1332    ) && !value_in_range(&param.default, param.min, param.max)
1333    {
1334        return Err(ShaderDiagnostics::error(format!(
1335            "parameter {} default is outside its numeric range",
1336            param.name
1337        )));
1338    }
1339    if let ParamValue::Color(values) = &param.default
1340        && !values.iter().all(|value| (0.0..=1.0).contains(value))
1341    {
1342        return Err(ShaderDiagnostics::error(format!(
1343            "color parameter {} default must be inside 0..=1",
1344            param.name
1345        )));
1346    }
1347    if param.param_type == ParamType::Enum && param.enum_values.is_empty() {
1348        return Err(ShaderDiagnostics::error(format!(
1349            "enum parameter {} requires named values",
1350            param.name
1351        )));
1352    }
1353    if let ParamValue::Enum(value) = &param.default
1354        && usize::try_from(*value).map_or(true, |index| index >= param.enum_values.len())
1355    {
1356        return Err(ShaderDiagnostics::error(format!(
1357            "enum parameter {} default is out of range",
1358            param.name
1359        )));
1360    }
1361    Ok(())
1362}
1363
1364fn value_in_range(value: &ParamValue, min: Option<f32>, max: Option<f32>) -> bool {
1365    let in_range = |value: &f32| {
1366        min.is_none_or(|minimum| *value >= minimum) && max.is_none_or(|maximum| *value <= maximum)
1367    };
1368    match value {
1369        ParamValue::Float(value) => in_range(value),
1370        ParamValue::Vec2(values) => values.iter().all(in_range),
1371        ParamValue::Vec4(values) => values.iter().all(in_range),
1372        _ => true,
1373    }
1374}
1375
1376fn finite_value(value: &ParamValue) -> bool {
1377    match value {
1378        ParamValue::Float(value) => value.is_finite(),
1379        ParamValue::Vec2(values) => values.iter().all(|value| value.is_finite()),
1380        ParamValue::Vec4(values) | ParamValue::Color(values) => {
1381            values.iter().all(|value| value.is_finite())
1382        }
1383        ParamValue::Enum(_) | ParamValue::Bool(_) => true,
1384    }
1385}
1386
1387fn valid_identifier(value: &str) -> bool {
1388    !value.is_empty()
1389        && value
1390            .bytes()
1391            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
1392}
1393
1394fn valid_wgsl_identifier(value: &str) -> bool {
1395    let mut bytes = value.bytes();
1396    bytes
1397        .next()
1398        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
1399        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1400        && !value.starts_with(RESERVED_PREFIX)
1401        && !matches!(
1402            value,
1403            "params"
1404                | "resolution"
1405                | "time"
1406                | "time_ticks"
1407                | "progress"
1408                | "ratio"
1409                | "render_scale"
1410                | "render_scale_fixed"
1411                | "sample_src"
1412                | "from_color"
1413                | "to_color"
1414                | "load_params"
1415                | "max_filter_samples"
1416                | "source_a"
1417                | "source_b"
1418                | "source_sampler"
1419                | "param_uniforms"
1420                | "runtime"
1421                | "EffectParams"
1422        )
1423}
1424
1425fn compilation_diagnostics(info: wgpu::CompilationInfo) -> ShaderDiagnostics {
1426    ShaderDiagnostics {
1427        messages: info
1428            .messages
1429            .into_iter()
1430            .map(|message| {
1431                let severity = match message.message_type {
1432                    wgpu::CompilationMessageType::Error => DiagnosticSeverity::Error,
1433                    wgpu::CompilationMessageType::Warning => DiagnosticSeverity::Warning,
1434                    wgpu::CompilationMessageType::Info => DiagnosticSeverity::Info,
1435                };
1436                ShaderDiagnostic {
1437                    severity,
1438                    message: message.message,
1439                    line: message.location.map(|location| location.line_number),
1440                    column: message.location.map(|location| location.line_position),
1441                }
1442            })
1443            .collect(),
1444    }
1445}
1446
1447#[cfg(test)]
1448#[path = "registry_tests.rs"]
1449mod tests;