1use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
12
13pub type CapabilitySchemaEntry = SchemaEntry;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum Effect {
19 Pure, Compute, Cold, Async, External,
20}
21
22impl Effect {
23 pub const fn as_str(&self) -> &'static str {
24 match self {
25 Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
26 Self::Async => "async", Self::External => "external",
27 }
28 }
29}
30
31pub type EffectTag = Effect;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum ExecutionClass { PureCpu, GpuComputeWorkgroup, AsyncHost }
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub enum DeterminismGuarantee { BitExactParity, PlatformAgnostic, DeterministicDigest }
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum SemanticUnit { Dimensionless, Meters, Radians, Degrees, Seconds, Bytes }
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum ValueType { F32, F64, U32, I32, Bool, Record, FieldRef }
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub enum StyleProfile { StandardWgsl, SubgroupMatrix, TiledSharedMem }
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum StyleSupportLevel { Core, Optional, Emulated }
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum ParamType {
61 F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
62}
63
64impl ParamType {
65 pub const fn as_str(&self) -> &'static str {
66 match self {
67 Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64", Self::Bool => "bool",
68 Self::Str => "string", Self::Record => "Record", Self::List => "List",
69 Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct ParamSchema {
77 pub name: &'static str,
78 pub param_type: ParamType,
79 pub required: bool,
80 pub description: &'static str,
81}
82
83const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
84 ParamSchema { name, param_type: ty, required: req, description: desc }
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct GeoWgslForgeSpec {
90 pub invoke_id: &'static str,
91 pub call_path: &'static str,
92 pub effect: Effect,
93 pub params: &'static [ParamSchema],
94 pub returns: &'static str,
95 pub description: &'static str,
96}
97
98const fn spec(
99 invoke_id: &'static str, call_path: &'static str, effect: Effect,
100 returns: &'static str, description: &'static str, params: &'static [ParamSchema],
101) -> GeoWgslForgeSpec {
102 GeoWgslForgeSpec { invoke_id, call_path, effect, params, returns, description }
103}
104
105#[derive(Debug, Clone, PartialEq)]
107pub struct ComplexDecl {
108 pub name: String,
109 pub complex_id: String,
110 pub states: Vec<String>,
111 pub transitions: Vec<String>,
112 pub invariants: Vec<String>,
113 pub initial_state: String,
114 pub target_state: String,
115}
116
117impl ComplexDecl {
118 pub fn new(
119 name: impl Into<String>, complex_id: impl Into<String>, states: Vec<String>,
120 transitions: Vec<String>, invariants: Vec<String>,
121 initial_state: impl Into<String>, target_state: impl Into<String>,
122 ) -> Self {
123 Self {
124 name: name.into(), complex_id: complex_id.into(), states, transitions,
125 invariants, initial_state: initial_state.into(), target_state: target_state.into(),
126 }
127 }
128
129 pub fn validate(&self) -> Result<(), &'static str> {
130 if self.name.is_empty() { return Err("name must not be empty"); }
131 if self.complex_id.is_empty() { return Err("complex_id must not be empty"); }
132 if self.states.is_empty() { return Err("states must not be empty"); }
133 if self.transitions.is_empty() { return Err("transitions must not be empty"); }
134 if !self.states.contains(&self.initial_state) { return Err("initial_state not in states"); }
135 if !self.states.contains(&self.target_state) { return Err("target_state not in states"); }
136 Ok(())
137 }
138}
139
140pub type WgslGeoKernelComplexDecl = ComplexDecl;
142
143pub fn wgsl_geo_kernel_complex_decl() -> ComplexDecl {
145 ComplexDecl::new(
146 "WgslGeoKernelComplex",
147 "urn:qualia:topology:wgsl-geo-kernel",
148 vec![
149 "AstCellProgram".into(),
150 "WgslSourceEmitted".into(),
151 "NagaAndHashCertified".into(),
152 "CpuOracleVerified".into(),
153 "GpuDispatched".into(),
154 ],
155 vec![
156 "emit_wgsl_kernel".into(),
157 "certify_shader_hash".into(),
158 "verify_cpu_oracle_parity".into(),
159 "dispatch_gpu_workgroups".into(),
160 ],
161 vec![
162 "DeterministicShaderDigest".into(),
163 "ZeroHeapWorkgroupDispatch".into(),
164 "CpuGpuOracleParity".into(),
165 "NagaAstValidationCertified".into(),
166 ],
167 "AstCellProgram",
168 "GpuDispatched",
169 )
170}
171
172pub const GEO_WGSL_FORGE_INVOKE_IDS: &[&str] = &[
174 "WgslForge.geo_emit_824_pipe_erosion",
175 "WgslForge.geo_emit_6layer_strata_erosion",
176 "WgslForge.geo_emit_d8_dinfinity_flow",
177 "WgslForge.geo_emit_multifractal_noise",
178 "WgslForge.geo_emit_landform_filters",
179 "WgslForge.geo_emit_sentinel2_biome_splat",
180 "WgslForge.geo_compile_cell_map_algebra",
181 "WgslForge.geo_emit_viewshed_hillshade",
182 "WgslForge.geo_emit_horn_twi_geomorphons",
183 "WgslForge.geo_certify_and_dispatch",
184];
185
186pub const GEO_WGSL_FORGE_RAW: &[GeoWgslForgeSpec] = &[
188 spec("WgslForge.geo_emit_824_pipe_erosion", "wgsl_forge.geo_emit_824_pipe_erosion", Effect::Cold, "Record",
190 "Emits WGSL compute shader for 8-pipe shallow-water hydrodynamic erosion and sediment transport (Q8.24 fixed-point / f32).", &[
191 p("grid_resolution", ParamType::Record, true, "Grid width, height, and cell size dx in meters"),
192 p("workgroup_size", ParamType::Record, true, "Workgroup dimensions (x, y)"),
193 p("pipe_mode", ParamType::Str, true, "Pipe discretization mode: q8_24_fixed or f32_float"),
194 ]),
195 spec("WgslForge.geo_emit_6layer_strata_erosion", "wgsl_forge.geo_emit_6layer_strata_erosion", Effect::Cold, "Record",
197 "Emits WGSL compute shader for 6-layer stratigraphic regolith column erosion and bedrock differential weathering.", &[
198 p("grid_resolution", ParamType::Record, true, "Raster domain dimensions (width, height)"),
199 p("workgroup_size", ParamType::Record, true, "Workgroup dispatch size (x, y)"),
200 p("layer_count", ParamType::U64, true, "Number of stratigraphic geological layers (default 6)"),
201 ]),
202 spec("WgslForge.geo_emit_d8_dinfinity_flow", "wgsl_forge.geo_emit_d8_dinfinity_flow", Effect::Cold, "Record",
204 "Emits WGSL compute shader for D8 and Tarboton D-infinity flow direction, slope steepest descent, and upslope contributing area.", &[
205 p("grid_resolution", ParamType::Record, true, "Elevation grid extent and resolution"),
206 p("workgroup_size", ParamType::Record, true, "Workgroup dimensions (x, y)"),
207 p("flow_model", ParamType::Str, true, "Hydrological routing algorithm: d8 or d_infinity"),
208 ]),
209 spec("WgslForge.geo_emit_multifractal_noise", "wgsl_forge.geo_emit_multifractal_noise", Effect::Cold, "Record",
211 "Emits WGSL compute shader for procedural multifractal terrain cascades (RidgedMulti, FBM, Jordan, Simplex3D domain warp).", &[
212 p("workgroup_size", ParamType::Record, true, "Compute workgroup tiling (x, y)"),
213 p("octaves", ParamType::U64, true, "Number of harmonic fractal noise octaves"),
214 p("warp_enabled", ParamType::Bool, true, "Enable non-linear Simplex domain warping"),
215 ]),
216 spec("WgslForge.geo_emit_landform_filters", "wgsl_forge.geo_emit_landform_filters", Effect::Cold, "Record",
218 "Emits WGSL compute shader for non-linear morphological landform filters (hydraulic talus deposition, thermal terracing, plateau clamping).", &[
219 p("workgroup_size", ParamType::Record, true, "Compute workgroup size (x, y)"),
220 p("filter_type", ParamType::Str, true, "Morphological operator: hydraulic_talus, thermal_terrace, or plateau_clamp"),
221 p("terrace_steps", ParamType::F64, false, "Number of quantized elevation terrace steps"),
222 ]),
223 spec("WgslForge.geo_emit_sentinel2_biome_splat", "wgsl_forge.geo_emit_sentinel2_biome_splat", Effect::Cold, "Record",
225 "Emits WGSL compute shader for 323-biome Sentinel-2 spectral surface reflectance splatting and Whittaker biome classification.", &[
226 p("workgroup_size", ParamType::Record, true, "Workgroup tiling dimensions (x, y)"),
227 p("biome_lut_count", ParamType::U64, true, "Size of spectral reflectance LUT table (default 323)"),
228 p("elevation_lapse_rate", ParamType::F64, false, "Temperature lapse rate per 1000m elevation"),
229 ]),
230 spec("WgslForge.geo_compile_cell_map_algebra", "wgsl_forge.geo_compile_cell_map_algebra", Effect::Pure, "Record",
232 "Compiles a pure VibeScript cell mathematical formula or AST into an optimized, zero-heap WGSL compute kernel.", &[
233 p("formula", ParamType::Str, true, "Pure mathematical formula or cell AST expression"),
234 p("raster_inputs", ParamType::Record, true, "Named dictionary of input raster bind groups"),
235 p("target_format", ParamType::Str, true, "Target output backend: wgsl or naga_ir"),
236 ]),
237 spec("WgslForge.geo_emit_viewshed_hillshade", "wgsl_forge.geo_emit_viewshed_hillshade", Effect::Cold, "Record",
239 "Emits WGSL compute shader for multi-directional analytical hillshading, slope/aspect, and radial line-of-sight viewshed visibility.", &[
240 p("workgroup_size", ParamType::Record, true, "Workgroup tiling layout (x, y)"),
241 p("azimuth_deg", ParamType::F64, true, "Sun illumination azimuth angle in degrees"),
242 p("altitude_deg", ParamType::F64, true, "Sun illumination solar altitude elevation angle in degrees"),
243 p("shading_mode", ParamType::Str, true, "Shading algorithm: hillshade, viewshed, or combined"),
244 ]),
245 spec("WgslForge.geo_emit_horn_twi_geomorphons", "wgsl_forge.geo_emit_horn_twi_geomorphons", Effect::Cold, "Record",
247 "Emits WGSL compute shader for Horn's 3x3 finite-difference slope/aspect, Topographic Wetness Index (TWI), and 10 Geomorphon landforms.", &[
248 p("workgroup_size", ParamType::Record, true, "Workgroup dispatch size (x, y)"),
249 p("cell_size_m", ParamType::F64, true, "DEM horizontal spatial resolution in meters"),
250 p("flatness_threshold_deg", ParamType::F64, true, "Geomorphon zenith/nadir angle threshold in degrees"),
251 ]),
252 spec("WgslForge.geo_certify_and_dispatch", "wgsl_forge.geo_certify_and_dispatch", Effect::Compute, "Record",
254 "Certifies WGSL shader via Naga AST validation and SHA-256 digest, verifies against CPU oracle, and dispatches GPU workgroups.", &[
255 p("wgsl_source", ParamType::Str, true, "WGSL shader source text to validate and execute"),
256 p("entry_point", ParamType::Str, true, "Compute shader entry point function name"),
257 p("workgroup_dispatch", ParamType::Record, true, "Grid dispatch counts (x, y, z)"),
258 p("expected_hash", ParamType::U64, true, "Expected FNV-1a / SHA-256 shader source hash digest"),
259 p("verify_oracle", ParamType::Bool, false, "Verify execution parity against pure CPU oracle if true"),
260 ]),
261];
262
263pub fn geo_wgsl_forge_entries() -> Vec<CapabilitySchemaEntry> {
265 GEO_WGSL_FORGE_RAW.iter().map(|s| {
266 let effect_class = match s.effect {
267 Effect::Pure => EffectClass::Pure,
268 Effect::Compute | Effect::Cold => EffectClass::Read,
269 Effect::Async | Effect::External => EffectClass::External,
270 };
271 let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
272 .with_description(s.description);
273 for p in s.params {
274 entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
275 }
276 entry
277 }).collect()
278}
279
280pub fn entries() -> Vec<SchemaEntry> {
282 geo_wgsl_forge_entries()
283}
284
285pub fn lookup_geo_wgsl_forge_entry(call_path: &str) -> Option<CapabilitySchemaEntry> {
287 let s = GEO_WGSL_FORGE_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)?;
288 let effect_class = match s.effect {
289 Effect::Pure => EffectClass::Pure,
290 Effect::Compute | Effect::Cold => EffectClass::Read,
291 Effect::Async | Effect::External => EffectClass::External,
292 };
293 let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
294 .with_description(s.description);
295 for p in s.params {
296 entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
297 }
298 Some(entry)
299}
300
301pub fn lookup_geo_wgsl_forge_spec(call_path: &str) -> Option<&'static GeoWgslForgeSpec> {
303 GEO_WGSL_FORGE_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn test_geo_wgsl_forge_count_and_uniqueness() {
312 assert_eq!(GEO_WGSL_FORGE_RAW.len(), 10);
313 assert_eq!(GEO_WGSL_FORGE_INVOKE_IDS.len(), 10);
314 for (i, spec) in GEO_WGSL_FORGE_RAW.iter().enumerate() {
315 assert_eq!(spec.invoke_id, GEO_WGSL_FORGE_INVOKE_IDS[i]);
316 assert!(spec.invoke_id.starts_with("WgslForge."));
317 assert!(spec.call_path.starts_with("wgsl_forge."));
318 assert!(!spec.returns.is_empty());
319 assert!(!spec.description.is_empty());
320 }
321 let mut ids: Vec<&str> = GEO_WGSL_FORGE_INVOKE_IDS.to_vec();
322 ids.sort();
323 ids.dedup();
324 assert_eq!(ids.len(), 10, "All 10 invoke IDs must be unique");
325
326 let mut paths: Vec<&str> = GEO_WGSL_FORGE_RAW.iter().map(|s| s.call_path).collect();
327 paths.sort();
328 paths.dedup();
329 assert_eq!(paths.len(), 10, "All 10 call paths must be unique");
330 }
331
332 #[test]
333 fn test_entries_conversion_and_lookup() {
334 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_824_pipe_erosion").is_some());
335 assert!(lookup_geo_wgsl_forge_entry("wgsl_forge.geo_emit_824_pipe_erosion").is_some());
336 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_6layer_strata_erosion").is_some());
337 assert!(lookup_geo_wgsl_forge_entry("wgsl_forge.geo_emit_6layer_strata_erosion").is_some());
338 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_d8_dinfinity_flow").is_some());
339 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_multifractal_noise").is_some());
340 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_landform_filters").is_some());
341 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_sentinel2_biome_splat").is_some());
342 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_compile_cell_map_algebra").is_some());
343 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_viewshed_hillshade").is_some());
344 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_emit_horn_twi_geomorphons").is_some());
345 assert!(lookup_geo_wgsl_forge_entry("WgslForge.geo_certify_and_dispatch").is_some());
346 assert!(lookup_geo_wgsl_forge_entry("WgslForge.unknown_call").is_none());
347
348 let converted = geo_wgsl_forge_entries();
349 assert_eq!(converted.len(), 10);
350 for (i, entry) in converted.iter().enumerate() {
351 assert_eq!(entry.id, GEO_WGSL_FORGE_INVOKE_IDS[i]);
352 assert_eq!(entry.honesty, HonestyLabel::Always);
353 }
354
355 let alias_entries = entries();
356 assert_eq!(alias_entries.len(), 10);
357 }
358
359 #[test]
360 fn test_wgsl_geo_kernel_complex_decl_validation() {
361 let decl = wgsl_geo_kernel_complex_decl();
362 assert!(decl.validate().is_ok());
363 assert_eq!(decl.name, "WgslGeoKernelComplex");
364 assert_eq!(decl.complex_id, "urn:qualia:topology:wgsl-geo-kernel");
365 assert_eq!(decl.states.len(), 5);
366 assert_eq!(decl.transitions.len(), 4);
367 assert_eq!(decl.invariants.len(), 4);
368 assert_eq!(decl.initial_state, "AstCellProgram");
369 assert_eq!(decl.target_state, "GpuDispatched");
370
371 let bad_initial = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "NonExistent", "A");
372 assert!(bad_initial.validate().is_err());
373
374 let bad_target = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "NonExistent");
375 assert!(bad_target.validate().is_err());
376
377 let empty_name = ComplexDecl::new("", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "A");
378 assert!(empty_name.validate().is_err());
379 }
380
381 #[test]
382 fn test_wgsl_forge_terrain_gpu_fixture_exists() {
383 let manifest_dir = env!("CARGO_MANIFEST_DIR");
384 let fixture_path = std::path::Path::new(manifest_dir)
385 .join("fixtures")
386 .join("geography")
387 .join("wgsl_forge_terrain_gpu.vibe");
388 assert!(
389 fixture_path.exists(),
390 "Fixture wgsl_forge_terrain_gpu.vibe must exist at {:?}",
391 fixture_path
392 );
393 }
394}