Reflection
Derive Reflect to read and change a value's fields by name at runtime, follow paths into nested data, build dynamic values and apply them as patches.
On this page
Reflection lets code work with a value without knowing its Rust type at compile time: list its fields, read one by name, set it, compare it, or copy it into another value. The engine uses it to save and load worlds, to show components in editors, and to let tools change data they've never seen. You opt a type in with #[derive(Reflect)].
Derive Reflect#
use neo::prelude::*;
#[derive(Component, Reflect, Default)]
#[reflect(Component, Default)]
pub struct Stats {
pub health: u32,
pub speed: f32,
pub tags: Vec<String>,
#[reflect(ignore)]
cache: Option<Vec3>, // not visible through reflection
}| Attribute | What it does |
|---|---|
#[reflect(Component, Default, ...)] | Registers type data for the type (see The type registry). Component and Resource are needed for a type to be saved in a world. |
#[reflect(ignore)] on a field | Hides the field. When the type is rebuilt from reflected data, the field gets its Default value. |
#[reflect(skip_serializing)] on a field | Keeps the field reflectable but leaves it out of serialized data. |
#[reflect(from_reflect = false)] on the type | Skips the FromReflect implementation, for types that can't be rebuilt from reflected data. |
Every field of a reflected type must be reflectable too. Numbers, strings, Vec, HashMap, Option, math types, colours, handles and most engine components already are.
Read and set fields#
use neo::reflect::structs::Struct;
let mut stats = Stats { health: 100, speed: 4.0, ..default() };
// by name, with the type you expect
*stats.get_field_mut::<u32>("health").unwrap() = 80;
assert_eq!(*stats.get_field::<u32>("health").unwrap(), 80);
// without knowing the type
for i in 0..stats.field_len() {
let name = stats.name_at(i).unwrap();
let value = stats.field_at(i).unwrap();
info!("{name} = {value:?}");
}Structs implement Struct, tuple structs TupleStruct, enums Enum, and lists, maps, sets and arrays their own traits. reflect_ref() and reflect_mut() tell you which kind a value is:
use neo::reflect::{enums::Enum, ReflectRef};
match stats.reflect_ref() {
ReflectRef::Struct(s) => info!("a struct with {} fields", s.field_len()),
ReflectRef::Enum(e) => info!("variant {}", e.variant_name()),
_ => {}
}Paths#
GetPath follows a path string into nested data: .field, [index] and .0 for tuple fields.
use neo::reflect::GetPath;
let first_tag: &String = stats.path(".tags[0]").unwrap();
*stats.path_mut::<f32>(".speed").unwrap() = 6.0;Dynamic values and patches#
A dynamic type holds reflected data without a concrete Rust type behind it: DynamicStruct, DynamicTupleStruct, DynamicEnum, DynamicList and so on. Deserialized data arrives as dynamic types. apply copies a dynamic value onto a real one, field by field; fields the patch doesn't mention keep their values.
use neo::reflect::{structs::DynamicStruct, PartialReflect};
let mut patch = DynamicStruct::default();
patch.insert("health", 50u32);
stats.apply(&patch); // health is 50, speed unchangedTo turn reflected data back into the real type, use FromReflect:
use neo::reflect::FromReflect;
// with #[reflect(Default)], fields the patch lacks come from Stats::default()
let copy: Option<Stats> = Stats::from_reflect(&patch);Reflect and PartialReflect#
| Trait | What it is |
|---|---|
PartialReflect | Any reflected value, concrete or dynamic. Field access, apply, reflect_partial_eq and reflect_clone live here. |
Reflect | A concrete Rust type. Adds downcast_ref::<T>(), downcast_mut::<T>() and take::<T>(). |
as_partial_reflect() goes from Reflect to PartialReflect; try_as_reflect() goes back when the value is concrete.
Function reflection#
With the reflect_functions cargo feature, functions and methods can be reflected and called with reflected arguments. It isn't on in NEO's builds. Example: cargo run --example function_reflection --features reflect_functions.
Examples#
Run them from the engine core's workspace (the folder of the engine source that holds the neo crate's Cargo.toml):
| Example | What it shows |
|---|---|
reflection | Fields by name, patches and serialization. |
reflection_types | The kinds of reflected types: structs, tuples, enums, lists, maps and opaque values. |
dynamic_types | Building and using dynamic values. |
generic_reflection | Reflecting generic types. |
custom_attributes | Your own attributes on reflected types and fields. |
mutation_by_reflection | Changing data at runtime when you only have it as reflected values. |