Skip to main content

nadir/
reflected.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The engine's components that are reflected by hand, [`Sprite`],
16//! [`Collider`] and [`Animator`], the names of the game's collision layers
17//! that colliders are written with, and the reflect contexts the engine
18//! builds (ADR-0038, `docs/subsystems/scene.md`):
19//!
20//! - **`Sprite`** is an object of its fields: `texture` (its page's path),
21//!   `uv`, `size`, `pivot`, `rotation`, `color`, `layer`, `sort` (`"YSort"`
22//!   or `{"Fixed": n}`) and `flip` (`{"x": false, "y": false}`). Read, a
23//!   sprite may instead name a frame of a cooked atlas, `{"atlas":
24//!   "atlas/sprites.kbj", "sprite": "sprites/hero", "frame": 0}`, which
25//!   loads the atlas and gives the frame's page, region, size and pivot, as
26//!   [`Sprite::from_atlas`]; the other fields beside it apply over it. One
27//!   needs a `texture` or an `atlas`, and a `sprite` or `frame` without its
28//!   `atlas` is an error: a sprite keeps no atlas, so a layer that changes
29//!   the frame names the atlas and the sprite again. Hashed ([`ReflectContext::hashing`]),
30//!   it leaves out what `nadir::animate` writes: its texture, uv, size,
31//!   pivot and `flip.x`.
32//! - **`Collider`** is `{"shape": {"Aabb": {"half": [x, y]}}, "offset":
33//!   [x, y], "layer": [...], "mask": [...], "kind": "Solid"}`, with the
34//!   shape `{"Circle": {"radius": r}}` the other one. A layer mask is
35//!   `"all"`, or a list of the game's layer names
36//!   ([`App::collision_layers`](crate::App::collision_layers)) and bit
37//!   numbers for the bits with no name. Read, a collider needs its `shape`;
38//!   the rest default as [`Collider::solid`] has them.
39//! - **`Animator`** is `{"clip": "sprites/hero/walk"}`, its clip's name in
40//!   the [`Clips`]; its time and finished flag are left out, and a read one
41//!   starts its clip.
42
43use nadir_assets::{AssetServer, FinalizeCtx, Handle, Scope};
44use nadir_collision::{ColliderKind, LayerMask, Shape};
45use nadir_core::{Color, Vec2};
46use nadir_ecs::World;
47use nadir_render::{Atlas, Flip, SortMode, Texture};
48use nadir_scene::{
49    FieldInfo, FromValue, Reflect, ReflectContext, ReflectError, ReflectErrorKind, ReflectKind,
50    Value,
51};
52
53use crate::{Animator, Clips, Collider, Sprite};
54
55/// The names of the game's collision layers: the layer of bit `n` of a
56/// [`LayerMask`] is named by the `n`-th, so that prefabs and levels write
57/// `["World", "People"]` for a collider's layers. A resource of every
58/// [`App`](crate::App), with no names until
59/// [`App::collision_layers`](crate::App::collision_layers) gives them.
60#[derive(Clone, Debug, Default, PartialEq, Eq)]
61pub struct CollisionLayers {
62    names: Vec<String>,
63}
64
65impl CollisionLayers {
66    /// Layers named `names`: bit 0 the first, bit 1 the next, and so on.
67    ///
68    /// # Panics
69    ///
70    /// If there are more than 32 names, one is empty, or two are the same:
71    /// data could not tell them apart.
72    pub fn new(names: &[&str]) -> Self {
73        assert!(
74            names.len() <= 32,
75            "a layer mask has 32 bits, so there are at most 32 collision layers, not {}",
76            names.len()
77        );
78        for (index, name) in names.iter().enumerate() {
79            assert!(
80                !name.is_empty(),
81                "collision layer {index} has an empty name"
82            );
83            assert!(
84                !names[..index].contains(name),
85                "two collision layers are named `{name}`"
86            );
87        }
88        Self {
89            names: names.iter().map(|name| name.to_string()).collect(),
90        }
91    }
92
93    /// The names, by bit.
94    pub fn names(&self) -> &[String] {
95        &self.names
96    }
97
98    /// The bit of the layer named `name`.
99    pub fn bit(&self, name: &str) -> Option<u32> {
100        self.names
101            .iter()
102            .position(|known| known == name)
103            .and_then(|bit| u32::try_from(bit).ok())
104    }
105
106    /// The name of the layer of `bit`, if it has one.
107    pub fn name(&self, bit: u32) -> Option<&str> {
108        usize::try_from(bit)
109            .ok()
110            .and_then(|bit| self.names.get(bit))
111            .map(String::as_str)
112    }
113
114    /// The mask of the layers named `names`, if each is a layer here.
115    pub fn mask(&self, names: &[&str]) -> Option<LayerMask> {
116        names.iter().try_fold(LayerMask::NONE, |mask, name| {
117            self.bit(name)
118                .map(|bit| LayerMask(mask.0 | LayerMask::bit(bit).0))
119        })
120    }
121}
122
123/// Runs `f` with a [`ReflectContext`] for `source` that has what the
124/// engine's components need to be written: the [`AssetServer`], the
125/// [`Clips`] and the [`CollisionLayers`] of `world`, each if `world` has
126/// it. For writing values, such as a save's, or, with
127/// [`ReflectContext::hashing`], a hash's, as [`world_hash`](crate::world_hash)
128/// does; it never loads, so it cannot read a handle.
129///
130/// # Panics
131///
132/// If one of those resources is borrowed mutably elsewhere.
133pub fn reflect_context<R>(
134    world: &World,
135    source: &str,
136    f: impl FnOnce(ReflectContext<'_>) -> R,
137) -> R {
138    let server = world
139        .contains_resource::<AssetServer>()
140        .then(|| world.resource::<AssetServer>());
141    let clips = world
142        .contains_resource::<Clips>()
143        .then(|| world.resource::<Clips>());
144    let layers = world
145        .contains_resource::<CollisionLayers>()
146        .then(|| world.resource::<CollisionLayers>());
147    let mut cx = ReflectContext::new(source);
148    if let Some(server) = &server {
149        cx = cx.with_assets(server);
150    }
151    if let Some(clips) = &clips {
152        cx = cx.with_resource::<Clips>(clips);
153    }
154    if let Some(layers) = &layers {
155        cx = cx.with_resource::<CollisionLayers>(layers);
156    }
157    f(cx)
158}
159
160/// Runs `f` with a [`ReflectContext`] for `source` that reads the engine's
161/// components too: as [`reflect_context`], with the [`AssetServer`] to load
162/// each handle read in `scope` ([`ReflectContext::loading`]). For spawning
163/// prefabs and a level's entities
164/// ([`PrefabLibrary`](nadir_scene::PrefabLibrary)).
165///
166/// # Panics
167///
168/// If `world` has no [`AssetServer`] (every [`App`](crate::App)'s has
169/// one), or one of the resources is borrowed elsewhere.
170pub fn loading_context<R>(
171    world: &World,
172    source: &str,
173    scope: Scope,
174    f: impl FnOnce(ReflectContext<'_>) -> R,
175) -> R {
176    let mut server = world.resource_mut::<AssetServer>();
177    let clips = world
178        .contains_resource::<Clips>()
179        .then(|| world.resource::<Clips>());
180    let layers = world
181        .contains_resource::<CollisionLayers>()
182        .then(|| world.resource::<CollisionLayers>());
183    let mut cx = ReflectContext::new(source).loading(&mut server, scope);
184    if let Some(clips) = &clips {
185        cx = cx.with_resource::<Clips>(clips);
186    }
187    if let Some(layers) = &layers {
188        cx = cx.with_resource::<CollisionLayers>(layers);
189    }
190    f(cx)
191}
192
193/// The parts of [`Reflect`] that are the same for the types here: each is
194/// one value, read and written whole, with no fields to walk.
195macro_rules! opaque {
196    ($name:expr) => {
197        fn type_name(&self) -> &'static str {
198            $name
199        }
200
201        fn kind(&self) -> ReflectKind {
202            ReflectKind::Primitive
203        }
204
205        fn fields(&self) -> &'static [FieldInfo] {
206            &[]
207        }
208
209        fn field(&self, _index: usize) -> Option<&dyn Reflect> {
210            None
211        }
212
213        fn field_mut(&mut self, _index: usize) -> Option<&mut dyn Reflect> {
214            None
215        }
216    };
217}
218
219/// An object's members, or the error that it is not one.
220fn object<'v>(
221    value: &'v Value,
222    cx: &ReflectContext<'_>,
223    expected: &'static str,
224) -> Result<&'v [(String, Value)], ReflectError> {
225    value
226        .as_object()
227        .ok_or_else(|| cx.expected(expected, value))
228}
229
230/// The member `name` of `members`.
231fn member<'v>(members: &'v [(String, Value)], name: &str) -> Option<&'v Value> {
232    members
233        .iter()
234        .find(|(key, _)| key == name)
235        .map(|(_, value)| value)
236}
237
238/// A member of an object, by its owned name.
239fn pair(name: &str, value: Value) -> (String, Value) {
240    (name.to_string(), value)
241}
242
243fn sort_to_value(sort: SortMode) -> Value {
244    match sort {
245        SortMode::YSort => Value::String("YSort".to_string()),
246        SortMode::Fixed(depth) => Value::Object(vec![pair("Fixed", Value::Int(depth.into()))]),
247    }
248}
249
250fn sort_from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<SortMode, ReflectError> {
251    const VARIANTS: &[&str] = &["YSort", "Fixed"];
252    let unknown = |cx: &ReflectContext<'_>, found: &str| {
253        cx.error(ReflectErrorKind::UnknownVariant {
254            type_name: "SortMode",
255            found: found.to_string(),
256            variants: VARIANTS,
257        })
258    };
259    match value {
260        Value::String(name) if name == "YSort" => Ok(SortMode::YSort),
261        Value::String(name) => Err(unknown(cx, name)),
262        Value::Object(members) => match members.as_slice() {
263            [(name, depth)] if name == "Fixed" => {
264                let depth = cx.field("Fixed", |cx| u32::from_value(depth, cx))?;
265                Ok(SortMode::Fixed(depth))
266            }
267            [(name, _)] => Err(unknown(cx, name)),
268            _ => Err(cx.expected("`\"YSort\"` or `{\"Fixed\": depth}`", value)),
269        },
270        _ => Err(cx.expected("`\"YSort\"` or `{\"Fixed\": depth}`", value)),
271    }
272}
273
274fn apply_flip(
275    flip: &mut Flip,
276    value: &Value,
277    cx: &mut ReflectContext<'_>,
278) -> Result<(), ReflectError> {
279    for (key, member) in object(value, cx, "an object `{\"x\": false, \"y\": false}`")? {
280        match key.as_str() {
281            "x" => flip.x = cx.field("x", |cx| bool::from_value(member, cx))?,
282            "y" => flip.y = cx.field("y", |cx| bool::from_value(member, cx))?,
283            _ => cx.unknown_field("Flip", key),
284        }
285    }
286    Ok(())
287}
288
289/// The sprite of frame `frame` of the sprite `name` of the atlas at
290/// `path`, loaded with its pages through the context's server.
291fn sprite_from_atlas(
292    path: &Value,
293    name: &Value,
294    frame: usize,
295    cx: &mut ReflectContext<'_>,
296) -> Result<Sprite, ReflectError> {
297    let path = cx.field("atlas", |cx| {
298        path.as_str()
299            .ok_or_else(|| cx.expected("an atlas file's path", path))
300    })?;
301    let name = cx.field("sprite", |cx| {
302        name.as_str()
303            .ok_or_else(|| cx.expected("a sprite's name in the atlas", name))
304    })?;
305    let Some((server, scope)) = cx.assets_mut() else {
306        return Err(cx.error(ReflectErrorKind::NoContext {
307            needs: "the asset server, to load an atlas",
308        }));
309    };
310    let made = load_atlas_sprite(server, scope, path, name, frame);
311    made.map_err(|kind| cx.error(kind))
312}
313
314/// [`sprite_from_atlas`]'s loads, which hold the server.
315fn load_atlas_sprite(
316    server: &mut AssetServer,
317    scope: Scope,
318    path: &str,
319    name: &str,
320    frame: usize,
321) -> Result<Sprite, ReflectErrorKind> {
322    let loaded = server
323        .load_now_in::<Atlas>(path, scope, &mut FinalizeCtx::new())
324        .map_err(|error| ReflectErrorKind::BadAssetPath {
325            path: path.to_string(),
326            reason: error.to_string(),
327        })?;
328    let atlas = server
329        .get(loaded)
330        .cloned()
331        .ok_or_else(|| ReflectErrorKind::BadAssetPath {
332            path: path.to_string(),
333            reason: "the atlas did not load".to_string(),
334        })?;
335    let pages = atlas.load_pages(server, scope);
336    let unknown = |what: &'static str, name: String| ReflectErrorKind::UnknownName { what, name };
337    let sprite = atlas
338        .sprite(name)
339        .ok_or_else(|| unknown("sprite in the atlas", name.to_string()))?;
340    let page = sprite
341        .frame(frame)
342        .and_then(|frame| pages.get(frame.page()).copied())
343        .ok_or_else(|| unknown("frame of the sprite", format!("{name} {frame}")))?;
344    Sprite::from_atlas(page, sprite, frame)
345        .ok_or_else(|| unknown("sprite with a pivot, not a tile set,", name.to_string()))
346}
347
348impl Sprite {
349    /// Applies the members of a sprite's value but its atlas form's.
350    fn apply_members(
351        &mut self,
352        members: &[(String, Value)],
353        cx: &mut ReflectContext<'_>,
354    ) -> Result<(), ReflectError> {
355        for (key, member) in members {
356            match key.as_str() {
357                "atlas" | "sprite" | "frame" => {}
358                "texture" => {
359                    self.texture =
360                        cx.field("texture", |cx| Handle::<Texture>::from_value(member, cx))?;
361                }
362                "uv" => cx.field("uv", |cx| self.uv.apply_value(member, cx))?,
363                "size" => self.size = cx.field("size", |cx| Vec2::from_value(member, cx))?,
364                "pivot" => self.pivot = cx.field("pivot", |cx| Vec2::from_value(member, cx))?,
365                "rotation" => {
366                    self.rotation = cx.field("rotation", |cx| f32::from_value(member, cx))?;
367                }
368                "color" => self.color = cx.field("color", |cx| Color::from_value(member, cx))?,
369                "layer" => self.layer = cx.field("layer", |cx| u8::from_value(member, cx))?,
370                "sort" => self.sort = cx.field("sort", |cx| sort_from_value(member, cx))?,
371                "flip" => cx.field("flip", |cx| apply_flip(&mut self.flip, member, cx))?,
372                _ => cx.unknown_field("Sprite", key),
373            }
374        }
375        Ok(())
376    }
377
378    /// The sprite of its atlas form's members, if it has them.
379    fn atlas_form(
380        members: &[(String, Value)],
381        cx: &mut ReflectContext<'_>,
382    ) -> Result<Option<Sprite>, ReflectError> {
383        let Some(atlas) = member(members, "atlas") else {
384            // A frame or a sprite's name alone cannot be applied: a sprite
385            // keeps no atlas to look them up in.
386            if member(members, "sprite").is_some() || member(members, "frame").is_some() {
387                return Err(cx.error(ReflectErrorKind::MissingField { field: "atlas" }));
388            }
389            return Ok(None);
390        };
391        let name = member(members, "sprite")
392            .ok_or_else(|| cx.error(ReflectErrorKind::MissingField { field: "sprite" }))?;
393        let frame = match member(members, "frame") {
394            Some(frame) => cx.field("frame", |cx| usize::from_value(frame, cx))?,
395            None => 0,
396        };
397        sprite_from_atlas(atlas, name, frame, cx).map(Some)
398    }
399}
400
401impl Reflect for Sprite {
402    opaque!("Sprite");
403
404    fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
405        let mut members = Vec::with_capacity(9);
406        if !cx.is_hashing() {
407            let texture = cx.field("texture", |cx| self.texture.to_value(cx));
408            members.push(pair("texture", texture));
409            members.push(pair("uv", self.uv.to_value(cx)));
410            members.push(pair("size", self.size.to_value(cx)));
411            members.push(pair("pivot", self.pivot.to_value(cx)));
412        }
413        members.push(pair("rotation", self.rotation.to_value(cx)));
414        members.push(pair("color", self.color.to_value(cx)));
415        members.push(pair("layer", self.layer.to_value(cx)));
416        members.push(pair("sort", sort_to_value(self.sort)));
417        let mut flip = Vec::with_capacity(2);
418        if !cx.is_hashing() {
419            flip.push(pair("x", Value::Bool(self.flip.x)));
420        }
421        flip.push(pair("y", Value::Bool(self.flip.y)));
422        members.push(pair("flip", Value::Object(flip)));
423        Value::Object(members)
424    }
425
426    /// Sets the fields the value names; an atlas form sets the texture, uv,
427    /// size and pivot, and the fields beside it apply over it.
428    fn apply_value(
429        &mut self,
430        value: &Value,
431        cx: &mut ReflectContext<'_>,
432    ) -> Result<(), ReflectError> {
433        let members = object(value, cx, "an object of a sprite's fields")?;
434        if let Some(made) = Self::atlas_form(members, cx)? {
435            self.texture = made.texture;
436            self.uv = made.uv;
437            self.size = made.size;
438            self.pivot = made.pivot;
439        }
440        self.apply_members(members, cx)
441    }
442}
443
444impl FromValue for Sprite {
445    const TYPE_NAME: &'static str = "Sprite";
446
447    /// A sprite of its atlas form, or of its `texture`, with all of it as
448    /// its region and no size until the value gives one; then the other
449    /// fields the value names.
450    fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
451        let members = object(value, cx, "an object of a sprite's fields")?;
452        let mut sprite = match Self::atlas_form(members, cx)? {
453            Some(sprite) => sprite,
454            None => {
455                let texture = member(members, "texture")
456                    .ok_or_else(|| cx.error(ReflectErrorKind::MissingField { field: "texture" }))?;
457                let texture =
458                    cx.field("texture", |cx| Handle::<Texture>::from_value(texture, cx))?;
459                Sprite::new(texture, Vec2::ZERO)
460            }
461        };
462        sprite.apply_members(members, cx)?;
463        Ok(sprite)
464    }
465}
466
467fn shape_to_value(shape: Shape, cx: &mut ReflectContext<'_>) -> Value {
468    let (name, field, value) = match shape {
469        Shape::Aabb { half } => ("Aabb", "half", half.to_value(cx)),
470        Shape::Circle { radius } => ("Circle", "radius", radius.to_value(cx)),
471    };
472    Value::Object(vec![pair(name, Value::Object(vec![pair(field, value)]))])
473}
474
475fn shape_from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Shape, ReflectError> {
476    const VARIANTS: &[&str] = &["Aabb", "Circle"];
477    let expected = "a shape `{\"Aabb\": {\"half\": [x, y]}}` or `{\"Circle\": {\"radius\": r}}`";
478    let [(name, fields)] = object(value, cx, expected)? else {
479        return Err(cx.expected(expected, value));
480    };
481    let fields = cx.key(name, |cx| {
482        object(fields, cx, "an object of the shape's fields")
483    })?;
484    let field = |cx: &mut ReflectContext<'_>, field: &'static str| {
485        member(fields, field).ok_or_else(|| {
486            cx.key(name, |cx| {
487                cx.error(ReflectErrorKind::MissingField { field })
488            })
489        })
490    };
491    // Warns of the members a shape has not got, as every reader does.
492    let others = |cx: &mut ReflectContext<'_>, own: &str| {
493        cx.key(name, |cx| {
494            for (key, _) in fields {
495                if key != own {
496                    cx.unknown_field("Shape", key);
497                }
498            }
499        });
500    };
501    match name.as_str() {
502        "Aabb" => {
503            let half = field(cx, "half")?;
504            let half = cx.key(name, |cx| cx.field("half", |cx| Vec2::from_value(half, cx)))?;
505            others(cx, "half");
506            Ok(Shape::Aabb { half })
507        }
508        "Circle" => {
509            let radius = field(cx, "radius")?;
510            let radius = cx.key(name, |cx| {
511                cx.field("radius", |cx| f32::from_value(radius, cx))
512            })?;
513            others(cx, "radius");
514            Ok(Shape::Circle { radius })
515        }
516        _ => Err(cx.error(ReflectErrorKind::UnknownVariant {
517            type_name: "Shape",
518            found: name.clone(),
519            variants: VARIANTS,
520        })),
521    }
522}
523
524fn mask_to_value(mask: LayerMask, cx: &ReflectContext<'_>) -> Value {
525    if mask == LayerMask::ALL {
526        return Value::String("all".to_string());
527    }
528    let layers = cx.resource::<CollisionLayers>();
529    let bits = (0..32).filter(|bit| mask.0 & (1 << bit) != 0);
530    Value::Array(
531        bits.map(|bit| match layers.and_then(|layers| layers.name(bit)) {
532            Some(name) => Value::String(name.to_string()),
533            None => Value::Int(bit.into()),
534        })
535        .collect(),
536    )
537}
538
539fn mask_from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<LayerMask, ReflectError> {
540    let expected = "`\"all\"`, or a list of collision layers' names and bit numbers";
541    if value.as_str() == Some("all") {
542        return Ok(LayerMask::ALL);
543    }
544    let items = value
545        .as_array()
546        .ok_or_else(|| cx.expected(expected, value))?;
547    let mut mask = LayerMask::NONE;
548    for (index, item) in items.iter().enumerate() {
549        let bit = cx.index(index, |cx| match item {
550            Value::String(name) => {
551                let Some(layers) = cx.resource::<CollisionLayers>() else {
552                    return Err(cx.error(ReflectErrorKind::NoContext {
553                        needs: "the game's collision layer names (`App::collision_layers`)",
554                    }));
555                };
556                layers.bit(name).ok_or_else(|| {
557                    cx.error(ReflectErrorKind::UnknownName {
558                        what: "collision layer",
559                        name: name.clone(),
560                    })
561                })
562            }
563            Value::Int(bit) if (0..32).contains(bit) => {
564                Ok(u32::try_from(*bit).expect("0 to 31 fits"))
565            }
566            Value::Int(bit) => Err(cx.error(ReflectErrorKind::OutOfRange {
567                type_name: "a collision layer's bit, 0 to 31,",
568                value: bit.to_string(),
569            })),
570            _ => Err(cx.expected("a collision layer's name or bit number", item)),
571        })?;
572        mask = LayerMask(mask.0 | LayerMask::bit(bit).0);
573    }
574    Ok(mask)
575}
576
577fn kind_from_value(value: &Value, cx: &ReflectContext<'_>) -> Result<ColliderKind, ReflectError> {
578    match value.as_str() {
579        Some("Solid") => Ok(ColliderKind::Solid),
580        Some("Trigger") => Ok(ColliderKind::Trigger),
581        Some(found) => Err(cx.error(ReflectErrorKind::UnknownVariant {
582            type_name: "ColliderKind",
583            found: found.to_string(),
584            variants: &["Solid", "Trigger"],
585        })),
586        None => Err(cx.expected("`\"Solid\"` or `\"Trigger\"`", value)),
587    }
588}
589
590impl Reflect for Collider {
591    opaque!("Collider");
592
593    fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
594        let collider = self.0;
595        let kind = match collider.kind {
596            ColliderKind::Solid => "Solid",
597            ColliderKind::Trigger => "Trigger",
598        };
599        Value::Object(vec![
600            pair("shape", shape_to_value(collider.shape, cx)),
601            pair("offset", collider.offset.to_value(cx)),
602            pair("layer", mask_to_value(collider.layer, cx)),
603            pair("mask", mask_to_value(collider.mask, cx)),
604            pair("kind", Value::String(kind.to_string())),
605        ])
606    }
607
608    fn apply_value(
609        &mut self,
610        value: &Value,
611        cx: &mut ReflectContext<'_>,
612    ) -> Result<(), ReflectError> {
613        let members = object(value, cx, "an object of a collider's fields")?;
614        self.apply_members(members, true, cx)
615    }
616}
617
618impl Collider {
619    /// Applies the members of a collider's value: its shape too, if
620    /// `shape`.
621    fn apply_members(
622        &mut self,
623        members: &[(String, Value)],
624        shape: bool,
625        cx: &mut ReflectContext<'_>,
626    ) -> Result<(), ReflectError> {
627        for (key, member) in members {
628            let collider = &mut self.0;
629            match key.as_str() {
630                "shape" if !shape => {}
631                "shape" => collider.shape = cx.field("shape", |cx| shape_from_value(member, cx))?,
632                "offset" => {
633                    collider.offset = cx.field("offset", |cx| Vec2::from_value(member, cx))?;
634                }
635                "layer" => collider.layer = cx.field("layer", |cx| mask_from_value(member, cx))?,
636                "mask" => collider.mask = cx.field("mask", |cx| mask_from_value(member, cx))?,
637                "kind" => collider.kind = cx.field("kind", |cx| kind_from_value(member, cx))?,
638                _ => cx.unknown_field("Collider", key),
639            }
640        }
641        Ok(())
642    }
643}
644
645impl FromValue for Collider {
646    const TYPE_NAME: &'static str = "Collider";
647
648    /// A solid collider on every layer, colliding with every layer, at the
649    /// entity's position, as [`Collider::solid`] makes one, of the value's
650    /// `shape`, which it needs; then the other fields the value names.
651    fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
652        let members = object(value, cx, "an object of a collider's fields")?;
653        let shape = member(members, "shape")
654            .ok_or_else(|| cx.error(ReflectErrorKind::MissingField { field: "shape" }))?;
655        let shape = cx.field("shape", |cx| shape_from_value(shape, cx))?;
656        let mut collider = Collider::solid(shape);
657        collider.apply_members(members, false, cx)?;
658        Ok(collider)
659    }
660}
661
662impl Reflect for Animator {
663    opaque!("Animator");
664
665    /// Its clip's name. A clip that has none, or a context with no
666    /// [`Clips`], is written as `null`, with a warning; for a hash, as its
667    /// handle's index and generation, which tell clips apart and are the
668    /// same on every run, with no warning.
669    fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value {
670        let name = cx
671            .resource::<Clips>()
672            .and_then(|clips| clips.name(self.clip()))
673            .map(str::to_string);
674        let clip = match name {
675            Some(name) => Value::String(name),
676            None if cx.is_hashing() => {
677                let id = self.clip().id();
678                Value::Array(vec![
679                    Value::Int(id.index().into()),
680                    Value::Int(id.generation().get().into()),
681                ])
682            }
683            None => {
684                cx.field("clip", |cx| {
685                    cx.warn("an animator's clip with no name in the clips is written as null")
686                });
687                Value::Null
688            }
689        };
690        Value::Object(vec![pair("clip", clip)])
691    }
692
693    /// Plays the clip the value names, from its start.
694    fn apply_value(
695        &mut self,
696        value: &Value,
697        cx: &mut ReflectContext<'_>,
698    ) -> Result<(), ReflectError> {
699        *self = Self::from_value(value, cx)?;
700        Ok(())
701    }
702}
703
704impl FromValue for Animator {
705    const TYPE_NAME: &'static str = "Animator";
706
707    fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError> {
708        let members = object(value, cx, "an object `{\"clip\": name}`")?;
709        for (key, _) in members {
710            if key != "clip" {
711                cx.unknown_field("Animator", key);
712            }
713        }
714        let clip = member(members, "clip")
715            .ok_or_else(|| cx.error(ReflectErrorKind::MissingField { field: "clip" }))?;
716        cx.field("clip", |cx| {
717            let name = clip
718                .as_str()
719                .ok_or_else(|| cx.expected("a clip's name", clip))?;
720            let Some(clips) = cx.resource::<Clips>() else {
721                return Err(cx.error(ReflectErrorKind::NoContext {
722                    needs: "the clips (`Clips`), to find a clip by its name",
723                }));
724            };
725            let handle = clips.find(name).ok_or_else(|| {
726                cx.error(ReflectErrorKind::UnknownName {
727                    what: "clip",
728                    name: name.to_string(),
729                })
730            })?;
731            Ok(Animator::new(handle))
732        })
733    }
734}
735
736#[cfg(test)]
737mod tests {
738    use std::collections::HashMap;
739    use std::time::Duration;
740
741    use nadir_assets::{AssetError, AssetPath, OnFailure, Source};
742    use nadir_codec::{Limits, json, kbj};
743    use nadir_core::Rect;
744
745    use super::*;
746    use crate::{Clip, ClipFrame, Playback};
747
748    /// Files in memory, by path.
749    struct Memory(HashMap<String, Vec<u8>>);
750
751    impl Source for Memory {
752        fn read(&self, path: &AssetPath) -> Result<Vec<u8>, AssetError> {
753            self.0
754                .get(path.as_str())
755                .cloned()
756                .ok_or(AssetError::NotFound)
757        }
758    }
759
760    /// A server of one cooked atlas, `atlas/sprites.kbj`: the hero, two
761    /// frames of 12 × 20 on a page of 64, the first trimmed by a pixel.
762    fn server() -> AssetServer {
763        let atlas = r#"{ "version": 2,
764            "pages": [ { "path": "atlas/sprites_0.qoi", "w": 64, "h": 64 } ],
765            "sprites": [ { "name": "sprites/hero",
766                "frames": [ { "page": 0, "x": 0, "y": 0, "w": 11, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
767                            { "page": 0, "x": 12, "y": 0, "w": 12, "h": 20, "ox": 0, "oy": 0, "sw": 12, "sh": 20 } ],
768                "pivot": [6.0, 20.0] } ] }"#;
769        let value = json::parse(atlas, Limits::default()).expect("JSON");
770        let bytes = kbj::encode(&value, Limits::default()).expect("KBJ");
771        let files = HashMap::from([("atlas/sprites.kbj".to_string(), bytes)]);
772        AssetServer::with_source(Memory(files), OnFailure::Nothing)
773    }
774
775    fn value(text: &str) -> Value {
776        json::parse(text, Limits::default()).expect("the test's JSON")
777    }
778
779    #[test]
780    fn a_sprite_of_an_atlas_frame_writes_back_its_fields_and_reads_again() {
781        let mut server = server();
782        let mut cx = ReflectContext::new("test").loading(&mut server, Scope::Level);
783        let form = value(
784            r#"{ "atlas": "atlas/sprites.kbj", "sprite": "sprites/hero", "frame": 1,
785                 "layer": 1, "sort": { "Fixed": 3 }, "flip": { "x": true } }"#,
786        );
787        let sprite = Sprite::from_value(&form, &mut cx).expect("a sprite");
788        assert_eq!(sprite.size, Vec2::new(12.0, 20.0));
789        assert_eq!(sprite.layer, 1);
790        assert_eq!(sprite.sort, SortMode::Fixed(3));
791        assert!(sprite.flip.x && !sprite.flip.y);
792        assert!(
793            (sprite.uv.min.x - 12.0 / 64.0).abs() < 1e-6,
794            "{:?}",
795            sprite.uv
796        );
797        // Written back whole, with the page's path, and read to the same.
798        let written = sprite.to_value(&mut cx);
799        assert_eq!(
800            written.get("texture"),
801            Some(&Value::String("atlas/sprites_0.qoi".into()))
802        );
803        let again = Sprite::from_value(&written, &mut cx).expect("the written sprite");
804        assert_eq!(again, sprite);
805        drop(cx);
806        // Hashed, it leaves out what animators write.
807        let mut cx = ReflectContext::new("test").with_assets(&server).hashing();
808        let hashed = sprite.to_value(&mut cx);
809        for left_out in ["texture", "uv", "size", "pivot"] {
810            assert_eq!(hashed.get(left_out), None, "{left_out}");
811        }
812        assert_eq!(
813            json::to_string_compact(hashed.get("flip").expect("flip")),
814            r#"{"y":false}"#
815        );
816        assert_eq!(hashed.get("layer"), Some(&Value::Int(1)));
817    }
818
819    #[test]
820    fn a_sprite_needs_a_texture_or_an_atlas_and_names_what_is_wrong() {
821        let mut server = server();
822        let mut cx = ReflectContext::new("prefab").loading(&mut server, Scope::Level);
823        let error = Sprite::from_value(&value(r#"{ "layer": 1 }"#), &mut cx).expect_err("none");
824        assert_eq!(
825            error.kind,
826            ReflectErrorKind::MissingField { field: "texture" }
827        );
828        let error = Sprite::from_value(
829            &value(r#"{ "atlas": "atlas/sprites.kbj", "sprite": "sprites/villain" }"#),
830            &mut cx,
831        )
832        .expect_err("no such sprite");
833        assert!(
834            matches!(&error.kind, ReflectErrorKind::UnknownName { name, .. } if name == "sprites/villain"),
835            "{error}"
836        );
837        let error = Sprite::from_value(
838            &value(r#"{ "texture": "atlas/sprites_0.qoi", "sort": "Sideways" }"#),
839            &mut cx,
840        )
841        .expect_err("no such sort");
842        assert_eq!(error.path, "sort");
843        // Without a server to load with, a sprite cannot be read.
844        drop(cx);
845        let mut cx = ReflectContext::new("prefab");
846        let error = Sprite::from_value(&value(r#"{ "texture": "a.qoi" }"#), &mut cx)
847            .expect_err("no server");
848        assert!(
849            matches!(error.kind, ReflectErrorKind::NoContext { .. }),
850            "{error}"
851        );
852    }
853
854    #[test]
855    fn a_collider_writes_its_layers_by_name_and_reads_them_back() {
856        let layers = CollisionLayers::new(&["World", "People"]);
857        let mut cx = ReflectContext::new("test").with_resource(&layers);
858        let read = Collider::from_value(
859            &value(
860                r#"{ "shape": { "Circle": { "radius": 6 } }, "offset": [0, -3],
861                     "layer": ["People"], "mask": ["World", 5], "kind": "Trigger" }"#,
862            ),
863            &mut cx,
864        )
865        .expect("a collider");
866        assert_eq!(read.0.shape, Shape::Circle { radius: 6.0 });
867        assert_eq!(read.0.offset, Vec2::new(0.0, -3.0));
868        assert_eq!(read.0.layer, LayerMask::bit(1));
869        assert_eq!(
870            read.0.mask,
871            LayerMask(LayerMask::bit(0).0 | LayerMask::bit(5).0)
872        );
873        assert_eq!(read.0.kind, ColliderKind::Trigger);
874        let written = read.to_value(&mut cx);
875        assert_eq!(
876            json::to_string_compact(&written),
877            r#"{"shape":{"Circle":{"radius":6.0}},"offset":[0.0,-3.0],"layer":["People"],"mask":["World",5],"kind":"Trigger"}"#
878        );
879        assert_eq!(
880            Collider::from_value(&written, &mut cx).expect("again"),
881            read
882        );
883        // The defaults are a solid's, on and against every layer.
884        let solid = Collider::from_value(
885            &value(r#"{ "shape": { "Aabb": { "half": [5, 3] } } }"#),
886            &mut cx,
887        )
888        .expect("a box");
889        assert_eq!(
890            solid,
891            Collider::solid(Shape::Aabb {
892                half: Vec2::new(5.0, 3.0)
893            })
894        );
895        assert_eq!(
896            json::to_string_compact(solid.to_value(&mut cx).get("layer").expect("layer")),
897            r#""all""#
898        );
899        assert_eq!(layers.mask(&["World", "People"]), Some(LayerMask(0b11)));
900    }
901
902    #[test]
903    fn a_collider_s_mistakes_are_named() {
904        let layers = CollisionLayers::new(&["World"]);
905        let mut cx = ReflectContext::new("prefab").with_resource(&layers);
906        let cases = [
907            (
908                r#"{}"#,
909                "",
910                ReflectErrorKind::MissingField { field: "shape" },
911            ),
912            (
913                r#"{ "shape": { "Circle": {} } }"#,
914                "shape.Circle",
915                ReflectErrorKind::MissingField { field: "radius" },
916            ),
917            (
918                r#"{ "shape": { "Circle": { "radius": 1 } }, "mask": ["Enemy"] }"#,
919                "mask[0]",
920                ReflectErrorKind::UnknownName {
921                    what: "collision layer",
922                    name: "Enemy".into(),
923                },
924            ),
925        ];
926        for (text, path, kind) in cases {
927            let error = Collider::from_value(&value(text), &mut cx).expect_err(text);
928            assert_eq!((error.path.as_str(), error.kind), (path, kind), "{text}");
929        }
930        let error = Collider::from_value(
931            &value(r#"{ "shape": { "Square": { "side": 1 } } }"#),
932            &mut cx,
933        )
934        .expect_err("no such shape");
935        assert!(
936            matches!(error.kind, ReflectErrorKind::UnknownVariant { .. }),
937            "{error}"
938        );
939        let error = Collider::from_value(
940            &value(r#"{ "shape": { "Circle": { "radius": 1 } }, "layer": [32] }"#),
941            &mut cx,
942        )
943        .expect_err("a bit past 31");
944        assert_eq!(error.path, "layer[0]");
945        // Names need the game's layers.
946        let mut cx = ReflectContext::new("prefab");
947        let error = Collider::from_value(
948            &value(r#"{ "shape": { "Circle": { "radius": 1 } }, "layer": ["World"] }"#),
949            &mut cx,
950        )
951        .expect_err("no layers");
952        assert!(
953            matches!(error.kind, ReflectErrorKind::NoContext { .. }),
954            "{error}"
955        );
956    }
957
958    #[test]
959    #[should_panic(expected = "two collision layers are named `World`")]
960    fn two_layers_of_one_name_are_refused() {
961        let _ = CollisionLayers::new(&["World", "World"]);
962    }
963
964    #[test]
965    fn an_animator_is_its_clip_s_name() {
966        let mut clips = Clips::new();
967        let frame = |ms| {
968            ClipFrame::new(
969                Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN)),
970                Rect::new(Vec2::ZERO, Vec2::ONE),
971                Duration::from_millis(ms),
972            )
973        };
974        let walk = clips
975            .add_named(
976                "sprites/hero/walk",
977                Clip::new(vec![frame(100)], Playback::Loop),
978            )
979            .expect("a new name");
980        let nameless = clips.add(Clip::new(vec![frame(50)], Playback::Once));
981        let mut cx = ReflectContext::new("test").with_resource(&clips);
982        let read = Animator::from_value(&value(r#"{ "clip": "sprites/hero/walk" }"#), &mut cx)
983            .expect("an animator");
984        assert_eq!(read.clip(), walk);
985        assert_eq!(read.elapsed(), Duration::ZERO, "it starts its clip");
986        assert_eq!(
987            json::to_string_compact(&read.to_value(&mut cx)),
988            r#"{"clip":"sprites/hero/walk"}"#
989        );
990        // One whose clip has no name is written with a null clip.
991        assert_eq!(
992            json::to_string_compact(&Animator::new(nameless).to_value(&mut cx)),
993            r#"{"clip":null}"#
994        );
995        let error = Animator::from_value(&value(r#"{ "clip": "sprites/hero/fly" }"#), &mut cx)
996            .expect_err("no such clip");
997        assert_eq!(error.path, "clip");
998        assert!(
999            matches!(error.kind, ReflectErrorKind::UnknownName { .. }),
1000            "{error}"
1001        );
1002        let mut cx = ReflectContext::new("test");
1003        let error = Animator::from_value(&value(r#"{ "clip": "sprites/hero/walk" }"#), &mut cx)
1004            .expect_err("no clips");
1005        assert!(
1006            matches!(error.kind, ReflectErrorKind::NoContext { .. }),
1007            "{error}"
1008        );
1009    }
1010
1011    #[test]
1012    fn a_frame_without_its_atlas_and_a_shape_s_stray_member_are_not_dropped_in_silence() {
1013        let mut server = server();
1014        let mut cx = ReflectContext::new("prefab").loading(&mut server, Scope::Level);
1015        let mut sprite = Sprite::from_value(
1016            &value(r#"{ "atlas": "atlas/sprites.kbj", "sprite": "sprites/hero" }"#),
1017            &mut cx,
1018        )
1019        .expect("a sprite");
1020        // A derived layer that changes the frame alone cannot be applied.
1021        let error = sprite
1022            .apply_value(&value(r#"{ "frame": 1 }"#), &mut cx)
1023            .expect_err("a frame of no atlas");
1024        assert_eq!(
1025            error.kind,
1026            ReflectErrorKind::MissingField { field: "atlas" }
1027        );
1028        let error = Sprite::from_value(
1029            &value(r#"{ "texture": "atlas/sprites_0.qoi", "sprite": "sprites/hero" }"#),
1030            &mut cx,
1031        )
1032        .expect_err("a sprite of no atlas");
1033        assert_eq!(
1034            error.kind,
1035            ReflectErrorKind::MissingField { field: "atlas" }
1036        );
1037        // Naming them again applies.
1038        sprite
1039            .apply_value(
1040                &value(r#"{ "atlas": "atlas/sprites.kbj", "sprite": "sprites/hero", "frame": 1 }"#),
1041                &mut cx,
1042            )
1043            .expect("the second frame");
1044        assert_eq!(sprite.size, Vec2::new(12.0, 20.0));
1045        drop(cx);
1046
1047        let mut cx = ReflectContext::new("prefab");
1048        Collider::from_value(
1049            &value(r#"{ "shape": { "Circle": { "radius": 6, "offset": [0, -3] } } }"#),
1050            &mut cx,
1051        )
1052        .expect("a circle");
1053        let warnings: Vec<(&str, &str)> = cx
1054            .warnings()
1055            .iter()
1056            .map(|warning| (warning.field.as_str(), warning.path.as_str()))
1057            .collect();
1058        assert_eq!(warnings, [("offset", "shape.Circle")]);
1059    }
1060
1061    #[test]
1062    fn a_nameless_clip_hashes_as_its_handle() {
1063        let mut clips = Clips::new();
1064        let frame = ClipFrame::new(
1065            Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN)),
1066            Rect::new(Vec2::ZERO, Vec2::ONE),
1067            Duration::from_millis(100),
1068        );
1069        let first = clips.add(Clip::new(vec![frame], Playback::Loop));
1070        let second = clips.add(Clip::new(vec![frame], Playback::Loop));
1071        let mut cx = ReflectContext::new("hash").with_resource(&clips).hashing();
1072        let a = Animator::new(first).to_value(&mut cx);
1073        let b = Animator::new(second).to_value(&mut cx);
1074        assert_ne!(a, b, "two nameless clips hash apart");
1075        assert_eq!(
1076            a,
1077            Animator::new(first).to_value(&mut cx),
1078            "and the same each time"
1079        );
1080        assert_eq!(json::to_string_compact(&a), r#"{"clip":[0,1]}"#);
1081    }
1082}