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    /// Created at registration for host effects, and on first draw or warmup for built-ins.
195    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    /// Validates, compiles and registers a runtime effect: [`Self::compile_effect`],
208    /// [`PendingEffect::compiled`], then [`Self::register_compiled`].
209    ///
210    /// Holds the renderer until the device answers; a host that needs the renderer meanwhile calls
211    /// the three steps itself.
212    ///
213    /// # Errors
214    /// Returns schema or WGSL diagnostics without mutating the registry.
215    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    /// Validates a runtime effect and creates its shader module and pipeline without waiting for
224    /// the verdict.
225    ///
226    /// All error scopes open and close within this call, so overlapping registrations never share
227    /// one.
228    ///
229    /// # Errors
230    /// Schema diagnostics, a duplicate id or a full registry, without touching the device.
231    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    /// Validates and registers a built-in without touching the device; its pipeline is made on
264    /// first draw or [`Self::warmup`]. Compiling every built-in up front costs seconds on a
265    /// software adapter.
266    ///
267    /// # Errors
268    /// Schema diagnostics, a duplicate id or a full registry.
269    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    /// The registry, read; registration and removal take it briefly to write.
284    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    /// Pre-device registration checks; returns the identity to register under.
293    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    /// The effect's pipeline, created now if needed; a failed creation is not kept.
310    ///
311    /// # Errors
312    /// [`crate::RenderError::Gpu`] with the class of the creation's error.
313    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                // Scopes are per thread, so the compile thread pushes its own.
327                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            // A module without the entry points the pipeline names.
347            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    /// Adds an effect this renderer compiled.
356    ///
357    /// # Errors
358    /// Refuses an effect from another device, one registered meanwhile, or a full registry.
359    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    /// Refuses parameter uniforms some alpha2 runtime cannot bind.
379    ///
380    /// Each parameter is one 16-byte slot. The cap is the WebGL2 limit every alpha2 device
381    /// requests, so an effect that registers anywhere registers everywhere. Past it the pipeline
382    /// still compiles but every frame's bind group fails.
383    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    /// Refuses definitions needing more sampled textures per stage than the WebGL2 limit (16) every
401    /// alpha2 device requests: source pair, each resource and each named input take one.
402    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    /// The generated host uniform layout of a registered effect.
421    #[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    /// The definition of a registered effect.
430    #[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    /// Whether `id`'s output can change with frame time alone; `true` for unknown effects.
439    ///
440    /// Derived from the WGSL of every pass: a body that never names `time`, `time_ticks` or
441    /// `runtime` cannot read it. Callers may pass any time to an effect answering `false`, so its
442    /// result can be reused across frames.
443    #[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    /// Whether an exact effect version is registered.
457    #[must_use]
458    pub fn is_effect_registered(&self, id: &EffectId) -> bool {
459        self.effects().entries.contains_key(id)
460    }
461
462    /// Whether a project document may reference the effect.
463    #[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    /// The registered identity a project reference to `id`@`version` draws with, if the project
470    /// may reference it.
471    #[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    /// Whether `id` is an engine built-in rather than a host-registered runtime effect.
484    #[must_use]
485    pub fn is_builtin_effect(&self, id: &EffectId) -> bool {
486        self.effects().builtins.contains(id)
487    }
488
489    /// Removes one runtime effect and releases its GPU resources once no frame draws with it.
490    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    /// Removes every host-registered runtime effect.
502    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    /// Confirms the effects are registered and creates pending built-in pipelines (including their
514    /// passes) so the first frame does not wait on the compiler.
515    ///
516    /// # Errors
517    /// Names the first unregistered effect, or the first pipeline whose creation failed.
518    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, &registered)?;
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, &registered)?;
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
570/// A registry entry for `definition`, pipeline not yet created.
571pub(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        // Bind at exact struct sizes so a shader reading past them fails to compile instead of
633        // reading the next arena slot.
634        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
742/// Whether an effect body can read the frame time.
743///
744/// `time()` and `time_ticks()` read the `runtime` uniform, and WGSL can reach none of them
745/// without naming it, so a body lacking all three as words cannot. Anything else counts as
746/// reading it (comments and shadowing included): a false `true` only redraws. A word is a run
747/// of letters, digits and underscores.
748pub(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        // Registration already delimited loops; this covers definitions that skipped it.
849        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
892/// Per-input wrapper declarations: texture, sampling helper and size. Empty without inputs.
893fn 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/// What registration learns about a runtime effect before any device sees it.
932#[derive(Clone, Debug, PartialEq, Eq)]
933pub struct CheckedEffect {
934    /// The WGSL module the device would compile: the body, its loops bounded, in the wrapper.
935    pub module: String,
936    /// Functions the body declares.
937    pub functions: usize,
938    /// The most function bodies one invocation of any of them runs once calls are inlined.
939    pub calls: u64,
940    /// The invocation's cost in units of the registration cap.
941    pub cost_units: u64,
942}
943
944/// Checks `definition` as registration does before the device compiles it: the schema, the
945/// lexical rules of the body, its calls and its cost. Device limits (uniform size, texture
946/// bindings) and the compile itself are not checked.
947///
948/// # Errors
949/// The diagnostics registration would return.
950pub 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    // Resource declarations share module scope with the wrapper's names and each other.
999    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    // An input's names share the module scope with the resources'.
1016    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
1036/// Module-scope names [`build_shader`] declares for input `name`. This is also what refuses
1037/// `src`, since `sample_src` is the prelude's.
1038fn input_declarations_of(name: &str) -> [String; 3] {
1039    [
1040        format!("input_{name}"),
1041        format!("sample_{name}"),
1042        format!("size_{name}"),
1043    ]
1044}
1045
1046/// Module-scope names [`build_shader`] declares for resource `name`.
1047fn 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    // Only code is checked; comments may contain anything.
1071    let code = blank_comments(body);
1072    // The cost analysis reads ASCII identifiers and blankspace only.
1073    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
1120/// Refuses an array without a literal count, of elements other than scalars, vectors, matrices
1121/// and arrays, past [`MAX_ARRAY_SLOTS`] elements, or one array type too many.
1122fn 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
1153/// Refuses unbalanced delimiters and nesting past [`MAX_WGSL_NESTING`], where each arm of an
1154/// `else if` chain nests one level deeper than the one before, as naga lowers it.
1155fn 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    // Open delimiters with their depth, and the chain length of an `if` body.
1168    let mut open: Vec<(u8, usize, Option<usize>)> = Vec::new();
1169    // An `if` whose body opens at this delimiter count, and its chain length.
1170    let mut pending_if: Option<(usize, usize)> = None;
1171    // The chain length of the `if` body that closed last, while only `else` may follow it.
1172    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
1242/// Identifiers in `code`; words starting with a letter or `_`, so number suffixes are excluded.
1243fn 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
1248/// Characters that can deepen an expression. Overcounts (`1.0`, `vec4<f32>`), which only
1249/// lowers the effective limit.
1250const 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(&param.name) {
1272        return Err(ShaderDiagnostics::error(format!(
1273            "invalid WGSL parameter name {}",
1274            param.name
1275        )));
1276    }
1277    let compatible = matches!(
1278        (&param.param_type, &param.default, &param.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(&param.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(&param.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) = &param.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) = &param.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;