Skip to main content

ultrafast_render/
tables.rs

1//! Big constant tables in agent shader code, read from the params instead.
2//!
3//! On Vulkan a `static const float ENV[3863] = {...};` in a shader is an
4//! array in every GPU thread's own memory (SPIR-V has no constant address
5//! space for it). When NVIDIA's compiler does not move it to its constant
6//! bank, every pixel fills its copy before reading from it: one 1080p frame
7//! of a production film took more than two seconds and Windows reset the
8//! GPU. So tables of at least [`MIN_FLOATS`] floats move into the node's
9//! params, uploaded with its other params, and `ENV[i]` reads them through
10//! a subscript. Their values are then no longer in the kernel, so editing
11//! them compiles nothing.
12
13use std::sync::Arc;
14
15/// Tables smaller than this stay in the code, where the compiler keeps
16/// them in registers or folds their reads.
17pub const MIN_FLOATS: usize = 64;
18
19/// The param offset the rewritten code reads its tables from. The code
20/// that hosts it defines it ([`declare_base`]).
21pub const BASE: &str = "ULTRAFAST_TABLES";
22
23/// Declares [`BASE`]: the tables start at param `at`.
24pub fn declare_base(at: usize) -> String {
25    format!("static const uint {BASE} = {at};\n")
26}
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct Hoisted {
30    /// The code with each moved table replaced by an accessor of the same
31    /// name, on as many lines as the table took (errors keep their lines).
32    pub code: String,
33    /// The tables' values, one table after another.
34    pub data: Arc<[f32]>,
35}
36
37/// Moves the big constant tables out of `code`; None when it has none.
38pub fn hoist(code: &str) -> Option<Hoisted> {
39    let toks = lex(code);
40    let mut found: Vec<Table> = Vec::new();
41    let mut depth = 0i32;
42    let mut i = 0;
43    while i < toks.len() {
44        match toks[i].tok {
45            Tok::Punct(b'{') => depth += 1,
46            Tok::Punct(b'}') => depth -= 1,
47            _ if depth == 0 => {
48                if let Some(t) = table_at(&toks, i) {
49                    i = t.last + 1;
50                    found.push(t);
51                    continue;
52                }
53            }
54            _ => {}
55        }
56        i += 1;
57    }
58    found.retain(|t| t.values.len() >= MIN_FLOATS && only_indexed(&toks, t));
59    if found.is_empty() {
60        return None;
61    }
62    let mut out = String::with_capacity(code.len());
63    let mut data = Vec::new();
64    let mut from = 0;
65    for t in &found {
66        let (start, end) = (toks[t.first].start, toks[t.last].end);
67        out += &code[from..start];
68        out += &accessor(t, data.len());
69        out.extend(std::iter::repeat_n('\n', code[start..end].matches('\n').count()));
70        data.extend_from_slice(&t.values);
71        from = end;
72    }
73    out += &code[from..];
74    Some(Hoisted {
75        code: out,
76        data: data.into(),
77    })
78}
79
80/// A `static const` array declaration at the top level of the code.
81struct Table {
82    name: String,
83    /// Scalar type of its elements and how many each has (float3: 3).
84    scalar: &'static str,
85    width: usize,
86    count: usize,
87    values: Vec<f32>,
88    /// Its tokens, `static` to `;`.
89    first: usize,
90    last: usize,
91}
92
93const SCALARS: [&str; 4] = ["float", "half", "int", "uint"];
94
95fn element_type(name: &str) -> Option<(&'static str, usize)> {
96    let scalar = SCALARS.iter().find(|s| name.starts_with(**s))?;
97    match &name[scalar.len()..] {
98        "" => Some((scalar, 1)),
99        w @ ("2" | "3" | "4") => Some((scalar, w.parse().unwrap())),
100        _ => None,
101    }
102}
103
104/// The table declared at token `i`, if one is: `static const T NAME[N] =
105/// { numbers };`, N a number, a constant or left out, the numbers plain
106/// literals (constructors like `float2(1, 2)` and nested braces are fine).
107fn table_at(toks: &[Token], i: usize) -> Option<Table> {
108    let ident = |k: usize| match toks.get(k)?.tok {
109        Tok::Ident(s) => Some(s),
110        _ => None,
111    };
112    let punct = |k: usize, c: u8| toks.get(k).is_some_and(|t| t.tok == Tok::Punct(c));
113    let mut k = i;
114    match (ident(k)?, ident(k + 1)?) {
115        ("static", "const") | ("const", "static") => k += 2,
116        _ => return None,
117    }
118    let (scalar, width) = element_type(ident(k)?)?;
119    let name = ident(k + 1)?;
120    k += 2;
121    if !punct(k, b'[') {
122        return None;
123    }
124    let size = match toks.get(k + 1)?.tok {
125        Tok::Punct(b']') => {
126            k += 2;
127            None
128        }
129        Tok::Num(n) if punct(k + 2, b']') => {
130            k += 3;
131            Some(parse_int(n)?)
132        }
133        Tok::Ident(c) if punct(k + 2, b']') => {
134            k += 3;
135            constant(toks, c)
136        }
137        _ => return None,
138    };
139    if !punct(k, b'=') || !punct(k + 1, b'{') {
140        return None;
141    }
142    k += 1;
143    // The initializer: numbers, commas, signs, braces, constructors.
144    let mut values = Vec::new();
145    let mut nest: Vec<u8> = Vec::new();
146    let mut sign = 1.0f64;
147    loop {
148        let t = toks.get(k)?;
149        match t.tok {
150            Tok::Punct(c @ (b'{' | b'(')) => nest.push(c),
151            Tok::Punct(b'}') => {
152                if nest.pop()? != b'{' {
153                    return None;
154                }
155                if nest.is_empty() {
156                    break;
157                }
158            }
159            Tok::Punct(b')') => {
160                if nest.pop()? != b'(' {
161                    return None;
162                }
163            }
164            Tok::Punct(b',') => {}
165            // Signs, only on numbers.
166            Tok::Punct(c @ (b'-' | b'+')) => {
167                if !matches!(toks.get(k + 1)?.tok, Tok::Num(_) | Tok::Punct(b'-' | b'+')) {
168                    return None;
169                }
170                if c == b'-' {
171                    sign = -sign;
172                }
173                k += 1;
174                continue;
175            }
176            // A constructor: `float2(`.
177            Tok::Ident(s) if element_type(s).is_some() && punct(k + 1, b'(') => {}
178            Tok::Num(n) => values.push(number(n, scalar, sign)?),
179            _ => return None,
180        }
181        sign = 1.0;
182        k += 1;
183    }
184    if !punct(k + 1, b';') {
185        return None;
186    }
187    let count = size.unwrap_or(values.len() / width);
188    if count == 0 || values.len() != count * width {
189        return None;
190    }
191    Some(Table {
192        name: name.to_string(),
193        scalar,
194        width,
195        count,
196        values,
197        first: i,
198        last: k + 1,
199    })
200}
201
202/// A literal as the table's scalar type holds it: floats as f32 (rounded
203/// once, as the shader compiler would), integers exactly or not at all.
204fn number(lit: &str, scalar: &str, sign: f64) -> Option<f32> {
205    if scalar == "float" || scalar == "half" {
206        if lit.starts_with("0x") || lit.starts_with("0X") {
207            return None;
208        }
209        let v: f32 = lit.trim_end_matches(['f', 'F', 'h', 'H', 'l', 'L']).parse().ok()?;
210        return Some(if sign < 0.0 { -v } else { v });
211    }
212    let v = parse_int(lit)? as f64 * sign;
213    // Every integer up to 2^24 is an f32 exactly.
214    (v.abs() <= (1u32 << 24) as f64 && (scalar == "int" || v >= 0.0)).then_some(v as f32)
215}
216
217fn parse_int(lit: &str) -> Option<usize> {
218    let s = lit.trim_end_matches(['u', 'U', 'l', 'L']);
219    match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
220        Some(hex) => usize::from_str_radix(hex, 16).ok(),
221        None => s.parse().ok(),
222    }
223}
224
225/// The value of `static const int NAME = 123;` at the top level.
226fn constant(toks: &[Token], name: &str) -> Option<usize> {
227    toks.windows(7).find_map(|w| {
228        let is = |k: usize, s: &str| w[k].tok == Tok::Ident(s);
229        let ok = is(0, "static")
230            && is(1, "const")
231            && (is(2, "int") || is(2, "uint"))
232            && is(3, name)
233            && w[4].tok == Tok::Punct(b'=')
234            && w[6].tok == Tok::Punct(b';');
235        match w[5].tok {
236            Tok::Num(n) if ok => parse_int(n),
237            _ => None,
238        }
239    })
240}
241
242/// Whether every use of the table outside its declaration indexes it inside
243/// a function. A table passed whole to a function, a name used for
244/// something else, or a global initialized from the table (which must be a
245/// compile-time constant) keeps the table in the code.
246fn only_indexed(toks: &[Token], t: &Table) -> bool {
247    // Open braces, true for an initializer list (`= {`).
248    let mut open: Vec<bool> = Vec::new();
249    for (k, tok) in toks.iter().enumerate() {
250        match tok.tok {
251            Tok::Punct(b'{') => open.push(k > 0 && toks[k - 1].tok == Tok::Punct(b'=')),
252            Tok::Punct(b'}') => {
253                open.pop();
254            }
255            Tok::Ident(name) if name == t.name && !(t.first..=t.last).contains(&k) => {
256                let indexed = toks.get(k + 1).is_some_and(|n| n.tok == Tok::Punct(b'['));
257                if !indexed || open.first() != Some(&false) {
258                    return false;
259                }
260            }
261            _ => {}
262        }
263    }
264    true
265}
266
267/// A struct with the table's name whose subscript reads its values from
268/// the params, starting at float `at` of the node's tables.
269fn accessor(t: &Table, at: usize) -> String {
270    let (name, s, w, last) = (&t.name, t.scalar, t.width, t.count - 1);
271    let read = |k: usize| {
272        let p = if k == 0 {
273            "P[b]".to_string()
274        } else {
275            format!("P[b + {k}u]")
276        };
277        if s == "float" { p } else { format!("{s}({p})") }
278    };
279    let (ty, value) = if w == 1 {
280        (s.to_string(), read(0))
281    } else {
282        (
283            format!("{s}{w}"),
284            format!("{s}{w}({})", (0..w).map(read).collect::<Vec<_>>().join(", ")),
285        )
286    };
287    format!(
288        "struct UltrafastTable_{name} {{ __subscript(int i) -> {ty} {{ get {{ \
289         uint b = {BASE} + {at}u + {w}u * uint(clamp(i, 0, {last})); return {value}; }} }} }}; \
290         static const UltrafastTable_{name} {name} = {{}};"
291    )
292}
293
294#[derive(Clone, Copy, PartialEq, Debug)]
295enum Tok<'a> {
296    Ident(&'a str),
297    Num(&'a str),
298    Punct(u8),
299}
300
301struct Token<'a> {
302    tok: Tok<'a>,
303    start: usize,
304    end: usize,
305}
306
307/// Identifiers, numbers and punctuation, without comments, preprocessor
308/// lines and string literals.
309fn lex(code: &str) -> Vec<Token<'_>> {
310    let b = code.as_bytes();
311    let mut toks = Vec::new();
312    let mut i = 0;
313    let line_end = |i: usize| b[i..].iter().position(|&c| c == b'\n').map_or(b.len(), |p| i + p);
314    // Nothing but whitespace yet on this line (a `#` there starts a
315    // preprocessor line).
316    let mut line_start = true;
317    while i < b.len() {
318        let c = b[i];
319        let start = i;
320        if c.is_ascii_whitespace() {
321            line_start |= c == b'\n';
322            i += 1;
323            continue;
324        }
325        if b[i..].starts_with(b"//") || (c == b'#' && line_start) {
326            i = line_end(i);
327        } else if b[i..].starts_with(b"/*") {
328            i = code[i + 2..].find("*/").map_or(b.len(), |p| i + 2 + p + 2);
329        } else if c == b'"' {
330            i += 1;
331            while i < b.len() && b[i] != b'"' {
332                i += if b[i] == b'\\' { 2 } else { 1 };
333            }
334            i = (i + 1).min(b.len());
335            toks.push(Token {
336                tok: Tok::Punct(b'"'),
337                start,
338                end: i,
339            });
340        } else if c.is_ascii_alphabetic() || c == b'_' {
341            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
342                i += 1;
343            }
344            toks.push(Token {
345                tok: Tok::Ident(&code[start..i]),
346                start,
347                end: i,
348            });
349        } else if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) {
350            let hex = b[i..].starts_with(b"0x") || b[i..].starts_with(b"0X");
351            i += 1;
352            while i < b.len() {
353                let d = b[i];
354                let exp_sign = !hex && (d == b'+' || d == b'-') && matches!(b[i - 1], b'e' | b'E');
355                if d.is_ascii_alphanumeric() || d == b'.' || exp_sign {
356                    i += 1;
357                } else {
358                    break;
359                }
360            }
361            toks.push(Token {
362                tok: Tok::Num(&code[start..i]),
363                start,
364                end: i,
365            });
366        } else {
367            // One token per byte; a multi-byte character outside a comment
368            // is only ever punctuation here, never part of a table.
369            i += code[i..].chars().next().map_or(1, char::len_utf8);
370            toks.push(Token {
371                tok: Tok::Punct(c),
372                start,
373                end: i,
374            });
375        }
376        line_start = false;
377    }
378    toks
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    fn floats(n: usize) -> String {
386        (0..n)
387            .map(|i| format!("{:.3}", i as f32 / 8.0))
388            .collect::<Vec<_>>()
389            .join(", ")
390    }
391
392    #[test]
393    fn moves_a_big_table_and_keeps_lines() {
394        let code = format!(
395            "static const int ENV_N = 100;\n// The envelope.\nstatic const float ENV[100] = {{\n  {}\n}};\nstatic const float SEG[3] = {{1.0, 2.0, 3.0}};\nfloat4 shade(float2 pos, float px) {{\n  int i = int(pos.x);\n  return float4(ENV[i] + SEG[1], ENV [ min(i, ENV_N - 1) ], 0.0, 1.0);\n}}\n",
396            floats(100)
397        );
398        let h = hoist(&code).expect("hoisted");
399        assert_eq!(h.data.len(), 100);
400        assert_eq!(h.data[9], 9.0 / 8.0);
401        assert_eq!(h.code.lines().count(), code.lines().count());
402        assert!(h.code.contains("static const UltrafastTable_ENV ENV = {};"));
403        assert!(h.code.contains("uint(clamp(i, 0, 99))"));
404        // Small tables stay, and so does everything after the big one.
405        assert!(h.code.contains("static const float SEG[3] = {1.0, 2.0, 3.0};"));
406        assert!(h.code.contains("ENV [ min(i, ENV_N - 1) ]"));
407        assert!(!h.code.contains("12.375"));
408    }
409
410    #[test]
411    fn vectors_signs_comments_and_sizes() {
412        let pts: Vec<String> = (0..40).map(|i| format!("float2(-{i}.5, +{i}e1) /* p{i} */")).collect();
413        let code = format!(
414            "static const uint N = 40;\nstatic const float2 PTS[N] = {{ {} }};\nconst static int IDX[] = {{ {} }};\nfloat4 shade(float2 p, float px) {{ return float4(PTS[0], float(IDX[3]), 1.0); }}",
415            pts.join(",\n"),
416            (0..70).map(|i| format!("-{i}")).collect::<Vec<_>>().join(", ")
417        );
418        let h = hoist(&code).expect("hoisted");
419        assert_eq!(h.data.len(), 80 + 70);
420        assert_eq!(&h.data[..4], &[-0.5, 0.0, -1.5, 10.0]);
421        assert_eq!(h.data[80 + 3], -3.0);
422        assert!(h.code.contains("-> float2"));
423        assert!(h.code.contains("float2(P[b], P[b + 1u])"));
424        assert!(h.code.contains("ULTRAFAST_TABLES + 80u + 1u * uint(clamp(i, 0, 69))"));
425        assert!(h.code.contains("-> int { get"));
426        assert_eq!(h.code.lines().count(), code.lines().count());
427    }
428
429    #[test]
430    fn leaves_what_it_cannot_read() {
431        let big = floats(100);
432        for code in [
433            // Used whole, not indexed.
434            format!(
435                "static const float T[100] = {{{big}}};\nfloat f(float t[100]) {{ return t[0]; }}\nfloat g() {{ return f(T); }}"
436            ),
437            // An expression in the initializer.
438            format!(
439                "static const float PI2 = 6.28;\nstatic const float T[101] = {{PI2, {big}}};\nfloat g(int i) {{ return T[i]; }}"
440            ),
441            // Inside a function: the compiler's to place.
442            format!("float g(int i) {{ static const float T[100] = {{{big}}}; return T[i]; }}"),
443            // A global initialized from it.
444            format!(
445                "static const float T[100] = {{{big}}};\nstatic const float FIRST = T[0];\nfloat g(int i) {{ return T[i] + FIRST; }}"
446            ),
447            format!(
448                "static const float T[100] = {{{big}}};\nstatic const float2 AB[2] = {{ float2(T[0], 1.0), float2(T[1], 2.0) }};\nfloat g(int i) {{ return T[i]; }}"
449            ),
450            // Size and values disagree.
451            format!("static const float T[99] = {{{big}}};\nfloat g(int i) {{ return T[i]; }}"),
452            // Too small.
453            "static const float T[8] = {0, 1, 2, 3, 4, 5, 6, 7};\nfloat g(int i) { return T[i]; }".to_string(),
454            // An integer an f32 cannot hold exactly.
455            format!(
456                "static const uint T[65] = {{4294967295u, {}}};\nuint g(int i) {{ return T[i]; }}",
457                vec!["1"; 64].join(", ")
458            ),
459        ] {
460            assert_eq!(hoist(&code), None, "{code}");
461        }
462    }
463}