Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

5.3 KB
Raw Blame
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
use super::R;
use serde_json::Value;
use std::path::Path;

/// One composition the game registers
pub struct Comp {
    pub id: String,
    pub width: u32,
    pub height: u32,
    pub fps: f64,
    pub frames: u64,
}

/// What the lint found: refusals stop the export, notes don't
pub struct Found {
    pub comps: Vec<Comp>,
    pub kinds: Vec<String>,
    pub notes: Vec<String>,
    pub refusals: Vec<String>,
}

const SOURCE_RULES: &[(&str, &str)] = &[
    (r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
    (r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
    (r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
    (r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
    (r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
];

/// The game's source and its compositions, judged
pub fn lint(game: &Path) -> R<Found> {
    let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
    let mut refusals = Vec::new();
    let mut notes = Vec::new();
    // a URL the SVG namespace names is a name, not a request
    let src_no_ns = src.replace("http://www.w3.org", "");
    for (re, why) in SOURCE_RULES {
        if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
            refusals.push(why.to_string());
        }
    }
    if !src.contains("raea/playable") {
        notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
    }
    let walked = match walk(game) {
        Ok(w) => w,
        // what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
        Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
        Err(e) => return Err(e),
    };
    let comps: Vec<Comp> = walked["comps"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|c| Comp {
            id: c["id"].as_str().unwrap_or("").into(),
            width: c["width"].as_u64().unwrap_or(0) as u32,
            height: c["height"].as_u64().unwrap_or(0) as u32,
            fps: c["fps"].as_f64().unwrap_or(30.0),
            frames: c["frames"].as_u64().unwrap_or(0),
        })
        .collect();
    let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
    if comps.is_empty() {
        refusals.push("no composition registered (registerRoot)".into());
    }
    if comps.len() == 1 {
        notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
    }
    for k in strings("refused") {
        refusals.push(format!("3D kind {k} isn't drawn in a playable"));
    }
    Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
}

/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
/// out of this one; its answer is the JSON it prints
fn walk(game: &Path) -> R<Value> {
    let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
    if !walk.is_file() {
        return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
    }
    let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
    std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
    let entry = work.join("lint.ts");
    std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
    let _ = std::fs::remove_dir_all(&work);
    let run = run?;
    let out = String::from_utf8_lossy(&run.stdout);
    if !run.status.success() {
        let err = String::from_utf8_lossy(&run.stderr);
        let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
        // the line that names the error, else the last one ("… ended with exit 1" says nothing)
        let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
        return Err(format!("the game didn't render for the lint: {why}"));
    }
    let at = out.find('{').ok_or("the lint's walk printed no answer")?;
    serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
}