1use std::rc::Rc;
13
14use super::node::{NodeRef, Type};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum ParamKind {
19 Value(Type),
21 Texture,
24 Sampler,
27}
28
29#[derive(Debug)]
31pub struct CodeDef {
32 pub name: String,
34 pub code: String,
37 pub(crate) params: Vec<(String, ParamKind)>,
39 pub(crate) ret: Type,
41 pub includes: Vec<NodeRef>,
49}
50
51pub fn wgsl_fn(source: &str, includes: Vec<NodeRef>) -> Rc<CodeDef> {
60 let parsed = parse(source);
61 let output = if parsed.output_type == "void" {
62 String::new()
63 } else {
64 format!("-> {}", parsed.output_type)
65 };
66 let code = format!(
70 "fn {} ( {} ) {}{}",
71 parsed.name,
72 parsed.inputs_code.trim(),
73 output,
74 parsed.block_code
75 );
76 Rc::new(CodeDef {
77 name: parsed.name,
78 code,
79 params: parsed.params,
80 ret: param_type(&parsed.output_type)
81 .unwrap_or_else(|| panic!("three-rs: wgslFn returns an unmodelled type")),
82 includes,
83 })
84}
85
86struct Parsed {
87 name: String,
88 inputs_code: String,
89 block_code: String,
90 output_type: String,
91 params: Vec<(String, ParamKind)>,
92}
93
94fn is_ident(c: char) -> bool {
95 c.is_ascii_alphanumeric() || c == '_'
96}
97
98fn parse(source: &str) -> Parsed {
104 let source = strip_leading(source);
105 let bytes: Vec<char> = source.chars().collect();
106 let mut i = 0;
107 let at = |i: usize| bytes.get(i).copied().unwrap_or('\0');
108
109 while matches!(at(i), 'f' | 'n') {
111 i += 1;
112 }
113 while at(i).is_whitespace() {
114 i += 1;
115 }
116 let name_start = i;
117 while is_ident(at(i)) {
118 i += 1;
119 }
120 let name: String = bytes[name_start..i].iter().collect();
121 while at(i).is_whitespace() {
122 i += 1;
123 }
124 assert_eq!(at(i), '(', "three-rs: wgslFn source is not a WGSL function");
125 i += 1;
126 let inputs_start = i;
127 while at(i) != ')' {
128 assert!(i < bytes.len(), "three-rs: wgslFn declaration has no `)`");
129 i += 1;
130 }
131 let inputs_code: String = bytes[inputs_start..i].iter().collect();
132 i += 1;
133 while at(i).is_whitespace() {
134 i += 1;
135 }
136 while matches!(at(i), '-' | '>') {
137 i += 1;
138 }
139 while at(i).is_whitespace() {
140 i += 1;
141 }
142 let out_start = i;
143 while is_ident(at(i)) {
144 i += 1;
145 }
146 if at(i) == '<' {
147 while at(i) != '>' {
148 assert!(i < bytes.len(), "three-rs: wgslFn return type has no `>`");
149 i += 1;
150 }
151 i += 1;
152 }
153 let output_type: String = bytes[out_start..i].iter().collect();
154 let block_code: String = bytes[i..].iter().collect();
155
156 Parsed {
157 params: parse_params(&inputs_code),
158 name,
159 inputs_code,
160 block_code,
161 output_type,
162 }
163}
164
165fn strip_leading(source: &str) -> &str {
167 let mut rest = source.trim_start();
168 loop {
169 if let Some(after) = rest.strip_prefix("//") {
170 rest = after
171 .find(['\r', '\n'])
172 .map_or("", |at| &after[at..])
173 .trim_start();
174 } else if let Some(after) = rest.strip_prefix("/*") {
175 rest = after
176 .find("*/")
177 .map_or("", |at| &after[at + 2..])
178 .trim_start();
179 } else {
180 return rest;
181 }
182 }
183}
184
185fn parse_params(inputs_code: &str) -> Vec<(String, ParamKind)> {
187 let chars: Vec<char> = inputs_code.chars().collect();
188 let at = |i: usize| chars.get(i).copied().unwrap_or('\0');
189 let mut params = Vec::new();
190 let mut i = 0;
191 while i < chars.len() {
192 if !is_ident(at(i)) {
193 i += 1;
194 continue;
195 }
196 let start = i;
197 while is_ident(at(i)) {
198 i += 1;
199 }
200 let name: String = chars[start..i].iter().collect();
201 let mut j = i;
202 while at(j).is_whitespace() {
203 j += 1;
204 }
205 if at(j) != ':' {
206 continue;
208 }
209 j += 1;
210 while at(j).is_whitespace() {
211 j += 1;
212 }
213 let type_start = j;
214 while is_ident(at(j)) {
215 j += 1;
216 }
217 if at(j) == '<' {
218 while j < chars.len() && at(j) != '>' {
219 j += 1;
220 }
221 j += 1;
222 }
223 let ty: String = chars[type_start..j].iter().collect();
224 params.push((name, param_kind(&ty)));
225 i = j;
226 }
227 params
228}
229
230fn param_kind(ty: &str) -> ParamKind {
231 if ty == "sampler" {
232 ParamKind::Sampler
233 } else if ty.starts_with("texture") {
234 ParamKind::Texture
235 } else {
236 ParamKind::Value(
237 param_type(ty).unwrap_or_else(|| panic!("three-rs: wgslFn parameter type `{ty}`")),
238 )
239 }
240}
241
242fn param_type(ty: &str) -> Option<Type> {
244 Some(match ty {
245 "f32" => Type::F32,
246 "i32" => Type::I32,
247 "u32" => Type::U32,
248 "bool" => Type::Bool,
249 "vec2<f32>" | "vec2f" => Type::Vec2,
250 "vec3<f32>" | "vec3f" => Type::Vec3,
251 "vec4<f32>" | "vec4f" => Type::Vec4,
252 "vec2<u32>" | "vec2u" => Type::UVec2,
253 "vec2<i32>" | "vec2i" => Type::IVec2,
254 "vec3<u32>" | "vec3u" => Type::UVec3,
255 "vec3<bool>" | "vec3b" => Type::BVec3,
256 "mat2x2<f32>" | "mat2x2f" => Type::Mat2,
257 "mat3x3<f32>" | "mat3x3f" => Type::Mat3,
258 "mat4x4<f32>" | "mat4x4f" => Type::Mat4,
259 _ => return None,
260 })
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 const DESATURATE: &str = "
268\t\t\t\t\tfn desaturate( color:vec3<f32> ) -> vec3<f32> {
269
270\t\t\t\t\t\treturn vec3<f32>( dot( lum, color ) );
271
272\t\t\t\t\t}
273\t\t\t\t";
274
275 #[test]
280 fn the_body_is_copied_through_verbatim() {
281 let def = wgsl_fn(DESATURATE, vec![]);
282 assert_eq!(def.name, "desaturate");
283 assert_eq!(def.ret, Type::Vec3);
284 assert_eq!(
285 def.params,
286 vec![("color".to_string(), ParamKind::Value(Type::Vec3))]
287 );
288 assert_eq!(
289 def.code,
290 "fn desaturate ( color:vec3<f32> ) -> vec3<f32> {\n\n\t\t\t\t\t\treturn vec3<f32>( dot( lum, color ) );\n\n\t\t\t\t\t}\n\t\t\t\t"
291 );
292 }
293
294 #[test]
297 fn texture_and_sampler_parameters_are_bindings() {
298 let def = wgsl_fn(
299 "fn f( tex: texture_2d<f32>, tex_sampler: sampler, uv:vec2<f32> ) -> vec4<f32> { }",
300 vec![],
301 );
302 let kinds: Vec<ParamKind> = def.params.iter().map(|(_, k)| *k).collect();
303 assert_eq!(
304 kinds,
305 vec![
306 ParamKind::Texture,
307 ParamKind::Sampler,
308 ParamKind::Value(Type::Vec2)
309 ]
310 );
311 }
312
313 #[test]
316 fn leading_comments_are_stripped() {
317 let def = wgsl_fn(
318 "// a note\n/* and another */\nfn f( x:f32 ) -> f32 { return x; }",
319 vec![],
320 );
321 assert_eq!(def.name, "f");
322 assert_eq!(def.code, "fn f ( x:f32 ) -> f32 { return x; }");
323 }
324}