ferravex_play/authoring/
mod.rs

1//! First-party typed scene authoring, hierarchical prefab expansion and compact
2//! cooked data. Parsing/validation happens on load, never during scene traversal.
3mod cooked;
4mod expand;
5mod parser;
6mod schema;
7use crate::scene::{Matrix, NodeId, Scene, Transform};
8pub use cooked::CookedMetadata;
9pub use schema::*;
10use std::{collections::BTreeMap, fmt};
11pub const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024;
12pub const MAX_COOKED_BYTES: usize = 8 * 1024 * 1024;
13pub const MAX_NODES: usize = 4096;
14pub const MAX_PREFABS: usize = 256;
15pub const MAX_COMPONENTS: usize = 32;
16pub const MAX_FIELDS: usize = 64;
17pub const MAX_VALUES: usize = 65536;
18pub const MAX_STRING: usize = 1024;
19pub const MAX_PREFAB_DEPTH: usize = 16;
20pub const MAX_HIERARCHY_DEPTH: usize = 128;
21/// A source position: one-based line and Unicode scalar column, and a zero-based
22/// UTF-8 byte offset. A zero line denotes an error without a text location (for
23/// example, a cooked-data or schema-registration error).
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25pub struct SourceSpan {
26    pub line: usize,
27    pub column: usize,
28    pub offset: usize,
29}
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum ErrorKind {
32    Syntax,
33    Version,
34    Limit,
35    Duplicate,
36    UnknownPrefab,
37    PrefabCycle,
38    MissingNode,
39    ParentCycle,
40    InvalidTransform,
41    UnknownComponent,
42    UnknownField,
43    MissingField,
44    Type,
45    Range,
46    Reference,
47    Format,
48    Checksum,
49    Domain,
50}
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct ContentError {
53    pub kind: ErrorKind,
54    pub span: SourceSpan,
55    pub context: String,
56}
57impl ContentError {
58    /// Attach a source excerpt and offending token without changing this error.
59    /// Supply the original source; inconsistent or non-text positions produce no
60    /// excerpt. Tabs count as one column, as do individual Unicode scalars.
61    ///
62    /// ```
63    /// use ferravex_play::authoring::Document;
64    /// let source = "ferravex_scene 9;";
65    /// let error = Document::parse(source).unwrap_err();
66    /// let diagnostic = error.diagnostic(source);
67    /// assert_eq!(diagnostic.token.as_deref(), Some("9"));
68    /// assert_eq!(diagnostic.error, error);
69    /// assert!(diagnostic.to_string().contains("expected authoring version 1"));
70    /// ```
71    pub fn diagnostic(&self, source: &str) -> SceneDiagnostic {
72        parser::diagnostic(source, self.clone())
73    }
74
75    pub fn domain(context: impl Into<String>) -> Self {
76        Self {
77            kind: ErrorKind::Domain,
78            span: SourceSpan::default(),
79            context: context.into(),
80        }
81    }
82    pub(crate) fn new(kind: ErrorKind, span: SourceSpan, context: impl Into<String>) -> Self {
83        Self {
84            kind,
85            span,
86            context: context.into(),
87        }
88    }
89}
90impl fmt::Display for ContentError {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        if self.span.line > 0 {
93            write!(f, "{}:{}: ", self.span.line, self.span.column)?;
94        }
95        write!(f, "{:?}: {}", self.kind, self.context)
96    }
97}
98impl std::error::Error for ContentError {}
99
100/// An owned, source-aware view of the first scene error. Existing error kinds,
101/// contexts and positions remain available through `error`. Display includes a
102/// caret excerpt and any repair guidance, suitable for an editor or CLI.
103///
104/// ```
105/// use ferravex_play::authoring::Document;
106/// let error = Document::parse_with_diagnostics("ferravex_scene 2;").unwrap_err();
107/// assert_eq!(error.error.span.column, 16);
108/// assert_eq!(error.source_line.as_deref(), Some("ferravex_scene 2;"));
109/// println!("{error}");
110/// ```
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct SceneDiagnostic {
113    /// The unchanged error returned by the compatible parsing/loading API.
114    pub error: ContentError,
115    /// Raw source spelling, including quotes and escapes. None at end of input
116    /// or when the error has no matching source position. Malformed strings are
117    /// clipped at the first line break.
118    pub token: Option<Box<str>>,
119    /// The original line without its LF/CRLF terminator, if the position matches.
120    pub source_line: Option<Box<str>>,
121    /// A concrete repair hint, including schema requirements when available.
122    pub help: Option<Box<str>>,
123}
124impl fmt::Display for SceneDiagnostic {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        write!(f, "{}", self.error)?;
127        if let Some(token) = &self.token {
128            write!(f, "; found {token:?}")?;
129        } else if self.source_line.is_some() {
130            write!(f, "; found end of input")?;
131        }
132        if let Some(line) = &self.source_line {
133            let number = self.error.span.line;
134            let width = number.to_string().len();
135            write!(
136                f,
137                "\n{empty:width$} |\n{number} | {line}\n{empty:width$} | ",
138                empty = ""
139            )?;
140            for c in line.chars().take(self.error.span.column.saturating_sub(1)) {
141                f.write_str(if c == '\t' { "\t" } else { " " })?;
142            }
143            let width = self.token.as_ref().map_or(1, |t| t.chars().count().max(1));
144            for _ in 0..width {
145                f.write_str("^")?;
146            }
147        }
148        if let Some(help) = &self.help {
149            write!(f, "\nhelp: {help}")?;
150        }
151        Ok(())
152    }
153}
154impl std::error::Error for SceneDiagnostic {
155    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
156        Some(&self.error)
157    }
158}
159#[derive(Clone, Debug, PartialEq)]
160pub enum Value {
161    Bool(bool),
162    Integer(i64),
163    Number(f64),
164    Text(String),
165    Vec2([f32; 2]),
166    Vec3([f32; 3]),
167    Quaternion([f32; 4]),
168    Color([u8; 4]),
169    Reference(String),
170}
171impl Value {
172    pub fn boolean(&self) -> Option<bool> {
173        if let Self::Bool(v) = self {
174            Some(*v)
175        } else {
176            None
177        }
178    }
179    pub fn integer(&self) -> Option<i64> {
180        if let Self::Integer(v) = self {
181            Some(*v)
182        } else {
183            None
184        }
185    }
186    pub fn number(&self) -> Option<f64> {
187        if let Self::Number(v) = self {
188            Some(*v)
189        } else {
190            None
191        }
192    }
193    pub fn text(&self) -> Option<&str> {
194        if let Self::Text(v) = self {
195            Some(v)
196        } else {
197            None
198        }
199    }
200    pub fn vec2(&self) -> Option<[f32; 2]> {
201        if let Self::Vec2(v) = self {
202            Some(*v)
203        } else {
204            None
205        }
206    }
207    pub fn vec3(&self) -> Option<[f32; 3]> {
208        if let Self::Vec3(v) = self {
209            Some(*v)
210        } else {
211            None
212        }
213    }
214    pub fn quaternion(&self) -> Option<[f32; 4]> {
215        if let Self::Quaternion(v) = self {
216            Some(*v)
217        } else {
218            None
219        }
220    }
221    pub fn color(&self) -> Option<[u8; 4]> {
222        if let Self::Color(v) = self {
223            Some(*v)
224        } else {
225            None
226        }
227    }
228    pub fn reference(&self) -> Option<&str> {
229        if let Self::Reference(v) = self {
230            Some(v)
231        } else {
232            None
233        }
234    }
235    pub(crate) fn size(&self) -> usize {
236        match self {
237            Self::Bool(_) => 1,
238            Self::Integer(_) | Self::Number(_) => 8,
239            Self::Text(v) | Self::Reference(v) => v.len() + 2,
240            Self::Vec2(_) => 8,
241            Self::Vec3(_) => 12,
242            Self::Quaternion(_) => 16,
243            Self::Color(_) => 4,
244        }
245    }
246}
247#[derive(Clone, Debug)]
248pub struct Property {
249    pub value: Value,
250    pub span: SourceSpan,
251}
252#[derive(Clone, Debug, Default)]
253pub struct Component {
254    pub(crate) fields: BTreeMap<String, Property>,
255    pub(crate) span: SourceSpan,
256}
257impl Component {
258    pub fn get(&self, name: &str) -> Option<&Value> {
259        self.fields.get(name).map(|p| &p.value)
260    }
261    pub fn fields(&self) -> impl Iterator<Item = (&str, &Value)> {
262        self.fields.iter().map(|(k, v)| (k.as_str(), &v.value))
263    }
264    pub fn required(&self, name: &str) -> Result<&Value, ContentError> {
265        self.get(name)
266            .ok_or_else(|| ContentError::new(ErrorKind::MissingField, self.span, name))
267    }
268}
269#[derive(Clone, Debug)]
270pub(crate) struct NodeSpec {
271    pub id: String,
272    pub span: SourceSpan,
273    pub parent: Option<String>,
274    pub prefab: Option<String>,
275    pub local: Option<Transform>,
276    pub components: BTreeMap<String, Component>,
277    pub overrides: BTreeMap<String, NodeOverride>,
278}
279#[derive(Clone, Debug, Default)]
280pub(crate) struct NodeOverride {
281    pub local: Option<Transform>,
282    pub components: BTreeMap<String, Component>,
283}
284#[derive(Clone, Debug)]
285pub struct Document {
286    pub(crate) nodes: Vec<NodeSpec>,
287    pub(crate) prefabs: BTreeMap<String, Vec<NodeSpec>>,
288}
289impl Document {
290    pub fn parse(source: &str) -> Result<Self, ContentError> {
291        parser::parse(source)
292    }
293    /// Parse with an offending token, source excerpt and repair guidance.
294    /// Reports the same first error as [`Self::parse`]; schema validation requires
295    /// [`Self::load_with_diagnostics`]. No source is retained on success.
296    ///
297    /// ```
298    /// use ferravex_play::authoring::{Document, ErrorKind};
299    /// let source = "ferravex_scene 1;\nnode x { component body { mass number NaN; } }";
300    /// let error = Document::parse_with_diagnostics(source).unwrap_err();
301    /// assert_eq!(error.error.kind, ErrorKind::Range);
302    /// assert_eq!(error.error.span.line, 2);
303    /// assert_eq!(error.token.as_deref(), Some("NaN"));
304    /// ```
305    pub fn parse_with_diagnostics(source: &str) -> Result<Self, SceneDiagnostic> {
306        Self::parse(source).map_err(|error| parser::diagnostic(source, error))
307    }
308    pub fn compile(&self, schema: &Schema) -> Result<SceneData, ContentError> {
309        expand::compile(self, schema)
310    }
311    pub fn load(source: &str, schema: &Schema) -> Result<SceneData, ContentError> {
312        Self::parse(source)?.compile(schema)
313    }
314    /// Parse, expand and validate with source-aware diagnostics. In addition to
315    /// syntax hints, schema errors list allowed fields/components, required value
316    /// types and inclusive bounds. Reports the same first error as [`Self::load`]
317    /// and produces identical scene/cooked data on success.
318    ///
319    /// ```
320    /// use ferravex_play::authoring::{Document, FieldRule, Schema, ValueKind};
321    /// let mut schema = Schema::new();
322    /// schema.register("body", &[FieldRule::optional("mass", ValueKind::Number)])?;
323    /// let source = "ferravex_scene 1; node x { component body { mas number 1; } }";
324    /// let error = Document::load_with_diagnostics(source, &schema).err().unwrap();
325    /// assert_eq!(error.token.as_deref(), Some("mas"));
326    /// assert!(error.help.as_deref().unwrap().contains("mass"));
327    /// # Ok::<(), ferravex_play::authoring::ContentError>(())
328    /// ```
329    pub fn load_with_diagnostics(
330        source: &str,
331        schema: &Schema,
332    ) -> Result<SceneData, SceneDiagnostic> {
333        let document = Self::parse_with_diagnostics(source)?;
334        document
335            .compile(schema)
336            .map_err(|error| document.schema_diagnostic(source, schema, error))
337    }
338
339    fn schema_diagnostic(
340        &self,
341        source: &str,
342        schema: &Schema,
343        error: ContentError,
344    ) -> SceneDiagnostic {
345        let mut diagnostic = parser::diagnostic(source, error);
346        let error = &diagnostic.error;
347        if error.kind == ErrorKind::UnknownComponent {
348            diagnostic.help = Some(if schema.components.is_empty() {
349                "No components are registered; register this component before loading.".into()
350            } else {
351                format!(
352                    "Use a registered component: {}. Register custom components before loading.",
353                    schema
354                        .components
355                        .keys()
356                        .cloned()
357                        .collect::<Vec<_>>()
358                        .join(", ")
359                )
360                .into()
361            });
362        }
363        if error.span.line == 0 {
364            return diagnostic;
365        }
366        let components = self
367            .nodes
368            .iter()
369            .chain(self.prefabs.values().flatten())
370            .flat_map(|node| {
371                node.components.iter().chain(
372                    node.overrides
373                        .values()
374                        .flat_map(|patch| patch.components.iter()),
375                )
376            });
377        for (kind, component) in components {
378            let field = component.fields.iter().find(|(_, p)| p.span == error.span);
379            if field.is_none() && component.span != error.span {
380                continue;
381            }
382            let Some(rules) = schema.components.get(kind) else {
383                break;
384            };
385            if error.kind == ErrorKind::UnknownField {
386                diagnostic.help = Some(if rules.is_empty() {
387                    format!("Component `{kind}` accepts no fields; remove this field.").into()
388                } else {
389                    format!(
390                        "Component `{kind}` accepts these fields: {}. Rename or remove this field.",
391                        rules.keys().cloned().collect::<Vec<_>>().join(", ")
392                    )
393                    .into()
394                });
395            } else if matches!(
396                error.kind,
397                ErrorKind::Type | ErrorKind::Range | ErrorKind::MissingField | ErrorKind::Reference
398            ) {
399                let name = field.map_or_else(
400                    || error.context.rsplit('.').next().unwrap_or(&error.context),
401                    |(name, _)| name.as_str(),
402                );
403                if let Some(rule) = rules.get(name) {
404                    diagnostic.help = Some(field_help(kind, name, rule).into());
405                }
406            }
407            break;
408        }
409        diagnostic
410    }
411}
412
413fn field_help(component: &str, name: &str, rule: &FieldRule) -> String {
414    let expected = match rule.kind {
415        ValueKind::Bool => "bool true or bool false",
416        ValueKind::Integer => "int followed by a signed 64-bit integer",
417        ValueKind::Number => "number followed by a finite number",
418        ValueKind::Text => "text followed by a string without NUL characters",
419        ValueKind::Vec2 => "vec2 followed by two finite f32 numbers",
420        ValueKind::Vec3 => "vec3 followed by three finite f32 numbers",
421        ValueKind::Quaternion => {
422            "quat followed by four finite f32 numbers with squared length > 1e-20"
423        }
424        ValueKind::Color => "rgba followed by four integer channels in 0..255",
425        ValueKind::Reference => "ref followed by an existing node path",
426    };
427    let mut help = format!("Field `{component}.{name}` expects {expected}.");
428    if let Some((min, max)) = rule.bounds {
429        help.push_str(&format!(
430            " Each value must be in the inclusive range {min}..{max}."
431        ));
432    }
433    if let Some((min, max)) = rule.integer_bounds {
434        help.push_str(&format!(
435            " Use an integer in the inclusive range {min}..{max}."
436        ));
437    }
438    if let Some(target) = &rule.target {
439        help.push_str(&format!(" The target node must have component `{target}`."));
440    }
441    if rule.required {
442        help.push_str(" This field is required.");
443    }
444    help
445}
446#[derive(Clone, Debug)]
447pub struct DataNode {
448    pub id: String,
449    pub parent: Option<String>,
450    pub local: Transform,
451    pub world: Matrix,
452    pub(crate) components: BTreeMap<String, Component>,
453    pub(crate) span: SourceSpan,
454}
455impl DataNode {
456    pub fn component(&self, kind: &str) -> Option<&Component> {
457        self.components.get(kind)
458    }
459    pub fn components(&self) -> impl Iterator<Item = (&str, &Component)> {
460        self.components.iter().map(|(k, v)| (k.as_str(), v))
461    }
462    pub fn position(&self) -> [f32; 3] {
463        [self.world[12], self.world[13], self.world[14]]
464    }
465}
466/// Owns a scene hierarchy and validated typed data. Handles belong to this
467/// generation only; retain the owner while holding handles/components.
468pub struct SceneData {
469    nodes: Vec<DataNode>,
470    lookup: BTreeMap<String, usize>,
471    hierarchy: Scene,
472    handles: Vec<NodeId>,
473}
474impl SceneData {
475    pub fn nodes(&self) -> &[DataNode] {
476        &self.nodes
477    }
478    pub fn node(&self, id: &str) -> Option<&DataNode> {
479        self.lookup.get(id).map(|i| &self.nodes[*i])
480    }
481    pub fn of_kind<'a>(
482        &'a self,
483        kind: &'a str,
484    ) -> impl Iterator<Item = (&'a DataNode, &'a Component)> {
485        self.nodes
486            .iter()
487            .filter_map(move |n| n.component(kind).map(|c| (n, c)))
488    }
489    pub fn hierarchy(&self) -> &Scene {
490        &self.hierarchy
491    }
492    pub fn handle(&self, id: &str) -> Option<NodeId> {
493        self.lookup.get(id).map(|i| self.handles[*i])
494    }
495    pub fn encode(&self) -> Result<Vec<u8>, ContentError> {
496        cooked::encode(self)
497    }
498    pub fn decode(bytes: &[u8], schema: &Schema) -> Result<Self, ContentError> {
499        cooked::decode(bytes, schema)
500    }
501}
502pub(crate) fn identifier(id: &str) -> bool {
503    !id.is_empty()
504        && id.len() <= 64
505        && id
506            .bytes()
507            .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
508}
509pub(crate) fn path(id: &str) -> bool {
510    !id.is_empty() && id.len() <= 512 && id.split('/').all(identifier)
511}