Skip to main content

rayengine_core/
manifest.rs

1//! Versioned, optional project descriptions shared by tools and the runtime.
2//!
3//! Loading performs CPU/file-system work only. Native resources must still be
4//! loaded explicitly on their owning render/audio thread.
5
6use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::BTreeMap,
10    fmt, fs,
11    path::{Component, Path, PathBuf},
12};
13
14/// Current project schema version, independent of the SDK/crate version.
15pub const SCHEMA_VERSION: u32 = 1;
16/// Conventional manifest filename.
17pub const FILE_NAME: &str = "rayengine.toml";
18/// Open TOML namespace; games and plugins deserialize and validate their own data.
19pub type Table = toml::Table;
20
21/// Actionable project error, including the manifest path when loading a file.
22#[derive(Debug)]
23pub struct ManifestError(pub String);
24impl fmt::Display for ManifestError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.write_str(&self.0)
27    }
28}
29impl std::error::Error for ManifestError {}
30type Result<T> = std::result::Result<T, ManifestError>;
31fn error(message: impl Into<String>) -> ManifestError {
32    ManifestError(message.into())
33}
34
35/// Project identity. Cargo still controls Rust packages and builds.
36#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
37#[serde(default, deny_unknown_fields)]
38pub struct Project {
39    /// Optional display/project name.
40    pub name: Option<String>,
41    /// Default Cargo binary target for `rayengine run`.
42    pub executable: Option<String>,
43}
44
45/// Discovery roots, searched in declaration order; paths are manifest-relative.
46#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
47#[serde(default, deny_unknown_fields)]
48pub struct AssetSettings {
49    /// Directories containing assets. Defaults to `["assets"]`; `[]` disables discovery.
50    pub roots: Vec<PathBuf>,
51    /// Case-sensitive globs relative to each root; `*` cannot cross `/`, `**` can.
52    pub exclude: Vec<String>,
53}
54impl Default for AssetSettings {
55    fn default() -> Self {
56        Self {
57            roots: vec!["assets".into()],
58            exclude: vec![],
59        }
60    }
61}
62
63/// Initial window settings.
64#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
65#[serde(default, deny_unknown_fields)]
66pub struct WindowSettings {
67    /// Window title, without NUL.
68    pub title: String,
69    /// Logical dimensions, each in `1..=8192`.
70    pub size: [u32; 2],
71}
72impl Default for WindowSettings {
73    fn default() -> Self {
74        Self {
75            title: "rayengine game".into(),
76            size: [1280, 720],
77        }
78    }
79}
80
81/// Content scaling policy, matching the runtime viewport policies.
82#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
83#[serde(rename_all = "snake_case")]
84pub enum ScaleMode {
85    /// Preserve reference aspect ratio with bars.
86    #[default]
87    Fit,
88    /// Expand the view to fill the window.
89    Expand,
90    /// Render at reference resolution and use integer scaling.
91    IntegerFit,
92}
93/// Renderer defaults and supported offscreen world quality settings.
94#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
95#[serde(default, deny_unknown_fields)]
96pub struct RenderSettings {
97    /// Logical reference size, each finite and in `1..=8192`.
98    pub reference_size: [f32; 2],
99    /// Fit, expand, or integer-fit scaling.
100    pub scale_mode: ScaleMode,
101    /// World pixels per native content pixel in each dimension: 1 or 2.
102    pub render_scale: f32,
103    /// Offscreen world edge filter; native UI is composed afterwards.
104    pub anti_aliasing: crate::quality::AntiAliasing,
105    /// Framerate cap, `0..=1000`; zero is uncapped.
106    pub target_fps: u32,
107    /// Request driver display synchronization.
108    pub vsync: bool,
109    /// RGBA color outside the content viewport.
110    pub bar_color: [u8; 4],
111}
112impl Default for RenderSettings {
113    fn default() -> Self {
114        Self {
115            reference_size: [960.0, 540.0],
116            scale_mode: ScaleMode::Fit,
117            render_scale: 1.0,
118            anti_aliasing: crate::quality::AntiAliasing::None,
119            target_fps: 120,
120            vsync: true,
121            bar_color: [9, 14, 24, 255],
122        }
123    }
124}
125/// Simulation/audio defaults.
126#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
127#[serde(default, deny_unknown_fields)]
128pub struct RuntimeSettings {
129    /// Fixed updates per second, `1..=1000`.
130    pub fixed_hz: u32,
131    /// Maximum simulation steps before rendering, `1..=1000`.
132    pub max_catch_up: u32,
133    /// Initialize audio before game initialization.
134    pub audio: bool,
135}
136impl Default for RuntimeSettings {
137    fn default() -> Self {
138        Self {
139            fixed_hz: 120,
140            max_catch_up: 8,
141            audio: false,
142        }
143    }
144}
145/// Font atlas sampling policy, shared with the custom-font integration.
146#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
147#[serde(rename_all = "snake_case")]
148pub enum FontFilter {
149    /// Smooth UI text.
150    #[default]
151    Linear,
152    /// Intentional pixel-style text.
153    Nearest,
154}
155/// Font atlas resolution policy, shared with the runtime font loader.
156#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, Hash)]
157#[serde(rename_all = "snake_case")]
158pub enum FontRasterization {
159    /// Grow cached atlases to match text size in actual render-target pixels.
160    #[default]
161    Adaptive,
162    /// Preserve the declared raster size, including intentional pixel enlargement.
163    Fixed,
164}
165/// Named font declaration. This describes a resource; it does not load an atlas.
166#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
167#[serde(deny_unknown_fields)]
168pub struct FontDeclaration {
169    /// Font file, resolved relative to the manifest, independently of asset roots.
170    pub path: PathBuf,
171    /// Base rasterization size, `1..=512`; default 32. DPI policy belongs to the font loader.
172    #[serde(default = "font_size")]
173    pub raster_size: u32,
174    /// Atlas filtering; defaults to linear.
175    #[serde(default)]
176    pub filter: FontFilter,
177    /// Resolution policy; defaults to adaptive. Use fixed with nearest for pixel text.
178    #[serde(default)]
179    pub rasterization: FontRasterization,
180    /// Optional Unicode scalar values; omitted means the loader's default coverage.
181    pub glyphs: Option<Vec<u32>>,
182}
183fn font_size() -> u32 {
184    32
185}
186
187/// Fully defaulted, validated settings for the base plus one selected profile.
188#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
189#[serde(default, deny_unknown_fields)]
190pub struct Settings {
191    /// Project identity and default Cargo target.
192    pub project: Project,
193    /// Asset selection rules.
194    pub assets: AssetSettings,
195    /// Window defaults.
196    pub window: WindowSettings,
197    /// Rendering defaults.
198    pub render: RenderSettings,
199    /// Simulation/audio defaults.
200    pub runtime: RuntimeSettings,
201    /// Font names map to declarations. Native loading remains explicit.
202    pub fonts: BTreeMap<String, FontDeclaration>,
203    /// Reserved packaging namespace; stored without acting on it.
204    pub package: Table,
205    /// Game-owned settings; the game validates these.
206    pub game: Table,
207    /// Explicit plugin namespaces, without a mandatory registry.
208    pub plugins: BTreeMap<String, Table>,
209}
210
211/// Parsed manifest, with its canonical file location and validated profiles.
212#[derive(Clone, Debug)]
213pub struct ProjectManifest {
214    path: PathBuf,
215    base: Table,
216    profiles: BTreeMap<String, Table>,
217}
218/// Resolved project description suitable for CLI inspection and runtime use.
219#[derive(Clone, Debug, Serialize)]
220pub struct ResolvedManifest {
221    /// Version of the project schema.
222    pub schema_version: u32,
223    /// Canonical manifest path.
224    pub path: PathBuf,
225    /// Selected named profile, or `None` for the base.
226    pub profile: Option<String>,
227    /// Validated settings, including defaults and absolute asset/font paths.
228    pub settings: Settings,
229    #[serde(skip)]
230    declared: Table,
231}
232
233impl ProjectManifest {
234    /// Loads an explicitly named file; absence, invalid syntax and invalid profiles fail.
235    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
236        let requested = path.as_ref();
237        let path = requested
238            .canonicalize()
239            .map_err(|e| error(format!("{}: {e}", requested.display())))?;
240        let source =
241            fs::read_to_string(&path).map_err(|e| error(format!("{}: {e}", path.display())))?;
242        Self::parse_at(&source, path)
243    }
244
245    /// Loads a sibling `rayengine.toml` for a directory or Cargo manifest.
246    /// An explicit `rayengine.toml` must exist. No upward search is performed.
247    /// Only a missing optional sibling yields `None`; other I/O errors fail.
248    pub fn load_optional(path: impl AsRef<Path>) -> Result<Option<Self>> {
249        let path = path.as_ref();
250        if path.file_name().is_some_and(|name| name == FILE_NAME) {
251            return Self::load(path).map(Some);
252        }
253        if path.file_name().is_none_or(|name| name != "Cargo.toml") && !path.is_dir() {
254            return Err(error(format!(
255                "{}: expected a project directory, Cargo.toml, or rayengine.toml",
256                path.display()
257            )));
258        }
259        let manifest = if path.is_dir() {
260            path.join(FILE_NAME)
261        } else {
262            path.parent().unwrap_or(Path::new(".")).join(FILE_NAME)
263        };
264        match fs::symlink_metadata(&manifest) {
265            Ok(_) => Self::load(manifest).map(Some),
266            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
267            Err(e) => Err(error(format!("{}: {e}", manifest.display()))),
268        }
269    }
270
271    fn parse_at(source: &str, path: PathBuf) -> Result<Self> {
272        let parse = || -> Result<Self> {
273            let mut base: Table = toml::from_str(source).map_err(|e| error(e.to_string()))?;
274            let version = base.remove("schema_version").and_then(|v| v.as_integer());
275            if version != Some(i64::from(SCHEMA_VERSION)) {
276                return Err(error(format!(
277                    "unsupported or missing schema_version; expected {SCHEMA_VERSION}, got {version:?}"
278                )));
279            }
280            let profiles = match base.remove("profiles") {
281                None => BTreeMap::new(),
282                Some(value) => value
283                    .try_into::<BTreeMap<String, Table>>()
284                    .map_err(|e| error(format!("profiles: {e}")))?,
285            };
286            let manifest = Self {
287                path: path.clone(),
288                base,
289                profiles,
290            };
291            manifest.resolve_inner(None)?;
292            for name in manifest.profiles.keys() {
293                validate_name(name, "profile")?;
294                let table = &manifest.profiles[name];
295                if table.contains_key("project") {
296                    return Err(error(format!(
297                        "profiles.{name}.project: project identity cannot be overridden"
298                    )));
299                }
300                manifest
301                    .resolve_inner(Some(name))
302                    .map_err(|e| error(format!("profiles.{name}: {e}")))?;
303            }
304            Ok(manifest)
305        };
306        parse().map_err(|e| error(format!("{}: {e}", path.display())))
307    }
308
309    /// Applies one profile over the shared base. Tables merge recursively;
310    /// scalars and arrays replace. Profiles do not inherit from one another.
311    pub fn resolve(&self, profile: Option<&str>) -> Result<ResolvedManifest> {
312        self.resolve_inner(profile)
313            .map_err(|e| error(format!("{}: {e}", self.path.display())))
314    }
315    fn resolve_inner(&self, profile: Option<&str>) -> Result<ResolvedManifest> {
316        let mut declared = self.base.clone();
317        if let Some(name) = profile {
318            let overlay = self.profiles.get(name).ok_or_else(|| {
319                error(format!(
320                    "unknown profile `{name}`; available: {}",
321                    self.profiles.keys().cloned().collect::<Vec<_>>().join(", ")
322                ))
323            })?;
324            merge(&mut declared, overlay);
325        }
326        let mut settings: Settings = toml::Value::Table(declared.clone())
327            .try_into()
328            .map_err(|e| error(e.to_string()))?;
329        validate(&settings)?;
330        let root = self.path.parent().expect("canonical manifest has parent");
331        for path in &mut settings.assets.roots {
332            *path = resolve_path(root, path);
333        }
334        for font in settings.fonts.values_mut() {
335            font.path = resolve_path(root, &font.path);
336        }
337        Ok(ResolvedManifest {
338            schema_version: SCHEMA_VERSION,
339            path: self.path.clone(),
340            profile: profile.map(str::to_owned),
341            settings,
342            declared,
343        })
344    }
345    /// Lists profile names in deterministic order.
346    pub fn profiles(&self) -> impl Iterator<Item = &str> {
347        self.profiles.keys().map(String::as_str)
348    }
349}
350fn merge(base: &mut Table, overlay: &Table) {
351    for (key, value) in overlay {
352        match (base.get_mut(key), value) {
353            (Some(toml::Value::Table(base)), toml::Value::Table(overlay)) => merge(base, overlay),
354            _ => {
355                base.insert(key.clone(), value.clone());
356            }
357        }
358    }
359}
360fn resolve_path(root: &Path, path: &Path) -> PathBuf {
361    // Do not canonicalize optional assets: declarations can precede file creation.
362    // Preserve `..` so OS symlink traversal semantics are not changed.
363    if path.is_absolute() {
364        path.to_owned()
365    } else {
366        root.join(path)
367    }
368}
369fn validate_name(name: &str, kind: &str) -> Result<()> {
370    if name.is_empty()
371        || !name
372            .bytes()
373            .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
374    {
375        return Err(error(format!(
376            "{kind} name `{name}` must contain ASCII letters, digits, '-' or '_'"
377        )));
378    }
379    Ok(())
380}
381fn validate_path(path: &Path, field: &str) -> Result<()> {
382    if path.as_os_str().is_empty() || path.to_str().is_none_or(|s| s.contains('\0')) {
383        return Err(error(format!(
384            "{field}: expected a nonempty UTF-8 path without NUL"
385        )));
386    }
387    Ok(())
388}
389fn exclusions(patterns: &[String]) -> Result<GlobSet> {
390    let mut builder = GlobSetBuilder::new();
391    for pattern in patterns {
392        if pattern.is_empty()
393            || pattern.contains('\0')
394            || pattern.contains('\\')
395            || Path::new(pattern).is_absolute()
396            || pattern.split('/').any(|part| part == "..")
397        {
398            return Err(error(format!(
399                "assets.exclude `{pattern}`: expected a nonempty root-relative glob using '/'"
400            )));
401        }
402        builder.add(
403            GlobBuilder::new(pattern)
404                .literal_separator(true)
405                .backslash_escape(false)
406                .build()
407                .map_err(|e| error(format!("assets.exclude `{pattern}`: {e}")))?,
408        );
409    }
410    builder
411        .build()
412        .map_err(|e| error(format!("assets.exclude: {e}")))
413}
414fn validate(settings: &Settings) -> Result<()> {
415    if let Some(name) = &settings.project.name
416        && (name.trim().is_empty() || name.contains('\0'))
417    {
418        return Err(error(
419            "project.name must be nonempty and cannot contain NUL",
420        ));
421    }
422    if let Some(target) = &settings.project.executable {
423        validate_name(target, "project.executable")?;
424    }
425    if settings.window.title.contains('\0') {
426        return Err(error("window.title cannot contain NUL"));
427    }
428    if settings.window.size.iter().any(|n| !(1..=8192).contains(n)) {
429        return Err(error("window.size dimensions must be between 1 and 8192"));
430    }
431    if settings
432        .render
433        .reference_size
434        .iter()
435        .any(|n| !n.is_finite() || !(1.0..=8192.0).contains(n))
436    {
437        return Err(error(
438            "render.reference_size dimensions must be finite and between 1 and 8192",
439        ));
440    }
441    let mode = match settings.render.scale_mode {
442        ScaleMode::Fit => crate::viewport::ScaleMode::Fit,
443        ScaleMode::Expand => crate::viewport::ScaleMode::Expand,
444        ScaleMode::IntegerFit => crate::viewport::ScaleMode::IntegerFit,
445    };
446    let view = crate::viewport::Viewport::new(
447        glam::Vec2::new(
448            settings.window.size[0] as f32,
449            settings.window.size[1] as f32,
450        ),
451        glam::Vec2::from_array(settings.render.reference_size),
452        mode,
453    )
454    .expect("validated sizes");
455    crate::quality::RenderQuality {
456        render_scale: settings.render.render_scale,
457        anti_aliasing: settings.render.anti_aliasing,
458    }
459    .plan(&view, glam::Vec2::ONE, mode)
460    .map_err(|e| error(format!("render: {e}")))?;
461    if settings.render.target_fps > 1000 {
462        return Err(error("render.target_fps must be 0..=1000"));
463    }
464    if !(1..=1000).contains(&settings.runtime.fixed_hz)
465        || !(1..=1000).contains(&settings.runtime.max_catch_up)
466    {
467        return Err(error(
468            "runtime.fixed_hz and runtime.max_catch_up must be between 1 and 1000",
469        ));
470    }
471    for path in &settings.assets.roots {
472        validate_path(path, "assets.roots")?;
473    }
474    exclusions(&settings.assets.exclude)?;
475    for (name, font) in &settings.fonts {
476        validate_name(name, "font")?;
477        validate_path(&font.path, &format!("fonts.{name}.path"))?;
478        if !(1..=512).contains(&font.raster_size) {
479            return Err(error(format!(
480                "fonts.{name}.raster_size must be between 1 and 512"
481            )));
482        }
483        if let Some(glyphs) = &font.glyphs {
484            let coverage: std::collections::BTreeSet<_> =
485                glyphs.iter().copied().chain([32, 63]).collect();
486            if glyphs.is_empty()
487                || coverage.len() > 1024
488                || coverage
489                    .iter()
490                    .any(|&value| char::from_u32(value).is_none_or(char::is_control))
491            {
492                return Err(error(format!(
493                    "fonts.{name}.glyphs must be a nonempty array of printable Unicode scalar values, at most 1024 unique including space and '?'"
494                )));
495            }
496        }
497    }
498    for name in settings.plugins.keys() {
499        validate_name(name, "plugin")?;
500    }
501    Ok(())
502}
503
504impl ResolvedManifest {
505    /// Whether a field was explicitly supplied by the base/profile. Runtime
506    /// adapters apply only declared fields over caller-supplied Rust defaults.
507    pub fn is_declared(&self, section: &str, field: &str) -> bool {
508        self.declared
509            .get(section)
510            .and_then(toml::Value::as_table)
511            .is_some_and(|table| table.contains_key(field))
512    }
513    /// Finds the first matching regular file in root order. Exclusions also
514    /// apply to lookup. Absolute/traversal names and symlinks are rejected.
515    pub fn asset(&self, name: impl AsRef<Path>) -> Result<PathBuf> {
516        let name = name.as_ref();
517        validate_path(name, "asset name")?;
518        if name
519            .components()
520            .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
521        {
522            return Err(error("asset name must be root-relative without '..'"));
523        }
524        // Match and open the same logical spelling. Path::components removes
525        // internal '.' and repeated separators; raw spellings could otherwise
526        // bypass exclusions even though the OS opens the same file.
527        let normalized: PathBuf = name
528            .components()
529            .filter(|c| !matches!(c, Component::CurDir))
530            .collect();
531        validate_path(&normalized, "asset name")?;
532        let name = normalized.as_path();
533        let excluded = exclusions(&self.settings.assets.exclude)?;
534        if is_excluded(&excluded, name) {
535            return Err(error(format!("asset `{}` is excluded", name.display())));
536        }
537        for root in &self.settings.assets.roots {
538            let candidate = root.join(name);
539            let mut path = root.clone();
540            let mut found = true;
541            let mut components = name.components().peekable();
542            while let Some(component) = components.next() {
543                path.push(component);
544                match fs::symlink_metadata(&path) {
545                    Ok(metadata)
546                        if metadata.file_type().is_symlink()
547                            || (components.peek().is_some() && !metadata.is_dir())
548                            || (components.peek().is_none() && !metadata.is_file()) =>
549                    {
550                        found = false;
551                        break;
552                    }
553                    Ok(_) => (),
554                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
555                        found = false;
556                        break;
557                    }
558                    Err(e) => return Err(error(format!("{}: {e}", path.display()))),
559                }
560            }
561            if found {
562                return Ok(candidate);
563            }
564        }
565        Err(error(format!(
566            "asset `{}` not found in declared roots (symlinks are skipped)",
567            name.display()
568        )))
569    }
570    /// Discovers regular files in root order, sorted within each root. Missing
571    /// roots are allowed; links are skipped; duplicate logical names use the
572    /// first root, matching [`Self::asset`]. No native resources are loaded.
573    pub fn discover_assets(&self) -> Result<Vec<PathBuf>> {
574        let excluded = exclusions(&self.settings.assets.exclude)?;
575        let mut selected = BTreeMap::new();
576        let mut output = vec![];
577        for root in &self.settings.assets.roots {
578            match fs::metadata(root) {
579                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
580                Err(e) => return Err(error(format!("{}: {e}", root.display()))),
581                Ok(m) if !m.is_dir() => {
582                    return Err(error(format!(
583                        "asset root {} is not a directory",
584                        root.display()
585                    )));
586                }
587                Ok(_) => (),
588            }
589            let mut files = vec![];
590            collect_files(root, root, &excluded, &mut files)?;
591            files.sort();
592            for file in files {
593                let relative = file
594                    .strip_prefix(root)
595                    .expect("discovered below root")
596                    .to_owned();
597                if selected.insert(relative, ()).is_none() {
598                    output.push(file);
599                }
600            }
601        }
602        Ok(output)
603    }
604}
605fn is_excluded(excluded: &GlobSet, path: &Path) -> bool {
606    // An excluded directory excludes its entire subtree as well.
607    path.ancestors()
608        .filter(|p| !p.as_os_str().is_empty())
609        .any(|p| excluded.is_match(p))
610}
611fn collect_files(
612    root: &Path,
613    dir: &Path,
614    excluded: &GlobSet,
615    output: &mut Vec<PathBuf>,
616) -> Result<()> {
617    let entries = fs::read_dir(dir).map_err(|e| error(format!("{}: {e}", dir.display())))?;
618    for entry in entries {
619        let entry = entry.map_err(|e| error(format!("{}: {e}", dir.display())))?;
620        let path = entry.path();
621        if is_excluded(excluded, path.strip_prefix(root).expect("entry below root")) {
622            continue;
623        }
624        let kind = entry
625            .file_type()
626            .map_err(|e| error(format!("{}: {e}", path.display())))?;
627        if kind.is_dir() {
628            collect_files(root, &path, excluded, output)?;
629        } else if kind.is_file() {
630            output.push(path);
631        }
632    }
633    Ok(())
634}
635
636#[cfg(test)]
637mod tests;