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