Reflection
Reflection: scripts and components (issue #41, with #52 step 3)
Status: decided (user, 2026-11-18; section 7) and implemented (section 8: steps 1-3 and 5 done 2026-11-18; the
editor ABI, step 4 in the list, waits for #52 step 5). The prototype is
Prototypes/Reflection/ (opt-in -DPRIMAL_REFLECTION_PROTO=ON, CMake only; build-msvc.ps1 builds it with MSVC in
the Windows VM).
Scope (user, 2026-11-18): registration and fields. Scripts and components register under stable names, and
declare fields (name, type, where it is, editor metadata) for the editor's inspector and for saving per-entity
values in scenes and game.bin. The editor and game.bin use them later (#52 step 5, #33); this decides how types
declare themselves, and what the engine keeps of them.
1. What the engine needs
- Stable names across binaries. The engine library is linked into EngineDLL, each game DLL and each game
executable, and each copy numbers what registers with it. Today scripts are keyed by an FNV-1a hash of the name
(#30), but ECS components are numbered in the order of first use per binary
(
ecs::detail::component_id_of<T>), so the editor, a game DLL and a saved file can't agree on a component. - Fields: name, type, location, metadata (range, tooltip, read-only), in declaration order, for components (plain data) and scripts (polymorphic classes).
- C++23 on clang, GCC and MSVC, no exceptions on MSVC, and game projects that the editor builds with MSBuild (no Visual Studio needed) and, later, CMake (#16).
- An in-class macro (the user's preference, #30/#41), like Unreal's
GENERATED_BODY().
2. The shared runtime (the same for every option)
Prototypes/Reflection/Reflect.h and Reflect.cpp, about 540 lines. All three options fill in the same tables, so
the option only decides how a type declares itself. A later switch, for example to C++26 reflection, replaces the
macros and leaves the engine, the editor ABI and the file formats alone.
-
TypeInfo: name, name hash, kind (component, entity script, game script), size, alignment, fields, and for entity scripts the creator function. One registry for scripts and components, keyed by the hash; a duplicate is logged and refused, as scripts are today. -
FieldInfo: name, name hash,FieldType, offset, address function,FieldMeta{.min, .max, .tooltip, .read_only}.- Components have offsets (plain data). Scripts have only an address function: a class with virtual
functions, or bases with members on both sides (
EntityScriptderives fromEntityandScriptBase), isn't standard-layout, andoffsetofisn't defined for it. The address function takes a pointer to the most derived class.
- Components have offsets (plain data). Scripts have only an address function: a class with virtual
functions, or bases with members on both sides (
-
Field types to start with:
bool,s32,u32,f32,math::v2/v3/v4, andgame_entity::Entityas an entity reference. Any other member type fails at compile time with a list of the allowed types.EntityIdcan't be the reference type:DEFINE_TYPED_IDmakes it a plainu32in Release, so it would look like au32field.- Strings, asset ids, enums and arrays come when something needs them.
-
Saved values are keyed by field name:
- a line naming a field the type no longer has is skipped;
- a field without a line keeps its default;
- a bad value fails with
std::expected<void, ReadError>.
Renaming or reordering fields doesn't break saved data. The prototype's format is text (
speed = 45); the binarygame.binwould key fields by name hash. -
Every option registers before
main(), through an inline static data member of the class. That also works in a header included by many files: the type registers once.
The checks (Checks.h), the same for every option on its own copy of two sample types (component Spinner, entity
script FanScript, 4 fields each, metadata on one):
- registration;
- field names, types and order;
- component offsets against
offsetof; - metadata;
- a text round trip;
- reading data saved from another version of the type;
- creating the script through the registry and setting its fields.
The name hashes come out the same in every build, on every compiler (Spinner 613dab7c…, FanScript c1dba0e2…):
those are the stable keys.
3. The options, as written in a game project
Option 1: in-class macros, C++23 (ReflectMacros.h, about 350 lines with 1b)
class FanScript : public script::EntityScript
{
PRIMAL_SCRIPT_BODY(FanScript)
public:
PRIMAL_PROPERTY(f32, speed, .min = 0.f, .tooltip = "Degrees per second"){45.f};
PRIMAL_PROPERTY(math::v3, axis){0.f, 0.f, 1.f};
f32 angle{0.f}; // not reflected
};
- The macro has to contain the declaration. A C++ macro can't see the declaration after it (that is what Unreal uses a generator for).
- C++23 can't name the enclosing class, so the body macro repeats the name. A
static_assertin a member function body (wherethisnames the class) catches a wrong name. - Each property declares a static function overloaded on its line number relative to the body macro's line
(
__LINE__, standard). It is linked to the previous property by overload resolution on a tag hierarchy (line_tag<n>derives fromline_tag<n - 1>).__COUNTER__would be simpler, but clang reports it as a C2y extension under-Wpedantic.- Rules: one property per line, and at most 256 lines from the body macro to the last property (a
static_assert). - 256 is close to the edge: clang 23 crashes (segfault, default 8 MB stack) at a depth of 384.
- Commas in a type (
std::array<f32, 3>) need an alias, as in any macro.
Option 1b: components without field macros (same header)
struct Spinner
{
PRIMAL_COMPONENT_AUTO(Spinner)
math::v3 axis{0.f, 1.f, 0.f};
f32 speed{90.f};
};
- Works for aggregates (components are plain data).
- How: the field count comes from aggregate initialization, the fields from structured bindings, and the names from
the compiler's function signature of a pointer to each member (
__PRETTY_FUNCTION__/__FUNCSIG__). This is Boost.PFR's technique, and works on all three compilers. - No per-field metadata: there's nowhere to write it.
Option 1c: ordinary declarations with a named marker (same header; added 2026-11-18 at the user's question)
class FanScript : public script::EntityScript
{
PRIMAL_SCRIPT_BODY(FanScript)
public:
PRIMAL_FIELD(speed, .min = 0.f, .tooltip = "Degrees per second")
f32 speed{45.f};
};
- The member stays an ordinary declaration (clang-format leaves it alone). The marker repeats only the name: the function it declares has a body, which is a complete-class context, so it may name a member declared after it, and the type comes from the member pointer.
- A name that doesn't match a member is a compile error. Same mechanism and limits as option 1 (the link chain, one marker per line, 256 lines).
- Writing the name only once, with an ordinary declaration, is impossible in C++23 without a generator: a macro sees only its arguments, and C++23 can't list the members of a class that isn't an aggregate (1b's structured bindings don't work on a class with a base, a constructor or virtual functions). That's what the generator (option 2) and C++26 reflection (option 3) add.
Option 2: a generator with marker macros (Generator/PrimalReflectGen.cpp, about 450 lines; ReflectGenerated.h)
#include "FanScript.generated.h" // the generated file, the last include
class FanScript : public script::EntityScript
{
PRIMAL_GENERATED_BODY()
public:
PRIMAL_PROPERTY(.min = 0.f, .tooltip = "Degrees per second")
f32 speed{45.f};
PRIMAL_PROPERTY()
math::v3 axis{0.f, 0.f, 1.f};
};
- Unreal's model with a strict syntax instead of a C++ parser. The generator reads tokens:
- it finds the classes with
PRIMAL_GENERATED_BODY()in their own body; - after each
PRIMAL_PROPERTY(...)it takes the declaration up to its initializer: the last identifier is the name.
- it finds the classes with
- It knows nothing about types. The generated code is compiled, so the compiler checks those (the same
make_field()as option 1). PRIMAL_GENERATED_BODY()expands to<file>_<line>_BODY, a macro the generated header defines (Unreal's trick).- Output is rewritten only when it changes.
- Its errors are in the compilers'
file:line: error:format:- a property outside a reflected class;
- an array or bit-field;
- a marker with no declaration after it.
- No libclang: one C++ file, no dependency, built like
ShaderCompilerTool.
Option 3: C++26 reflection (ReflectCpp26.h, about 130 lines; GCC 16 with -std=c++26 -freflection)
class FanScript : public script::EntityScript
{
PRIMAL_SCRIPT_BODY() // no name: access_context::current().scope() is the class
public:
[[=reflect::property{.min = 0.f}, =reflect::tooltip{"Degrees per second"}]] f32 speed{45.f};
[[=reflect::property{}]] math::v3 axis{0.f, 0.f, 1.f};
};
- P2996 + P3394 annotations. Neither the class name nor a generator is needed:
nonstatic_data_members_of,identifier_of,offset_of,annotations_of_with_type. - Components reflect every field; annotations only add metadata.
- Annotations must be structural types, so the tooltip is copied with
std::define_static_string. - Only GCC 16.2 has it (2026-11): clang 23 and MSVC have nothing. So it's out while the engine is C++23 on all
three compilers. It shows where options 1/2 would migrate to: the same runtime tables, with
PRIMAL_PROPERTY(.min = 0.f)becoming[[=property{.min = 0.f}]].
4. Results
Correctness: every check passes on every compiler that has the option.
| clang 23 | GCC 16.2 | MSVC (VM, /W4 /WX /permissive-, no exceptions) |
|
|---|---|---|---|
| Option 1 | yes | yes | yes |
| Option 1b | yes | yes | yes |
| Option 1c | yes | yes | yes |
| Option 2 | yes | yes | yes (generator built with MSVC too) |
| Option 3 | no reflection | yes | no reflection |
Compile time (compile_time.py). One translation unit with 100 components and 100 entity scripts, 4 reflected
fields each, -O0, best of 3, Ryzen 9 5900X. Seconds:
| clang, object | GCC, object | clang, syntax only | GCC, syntax only | |
|---|---|---|---|---|
no reflection (today's PRIMAL_SCRIPT) |
2.08 | 2.27 | 1.68 | 1.47 |
| option 1 | 4.17 | 4.39 | 3.07 | 1.76 |
| option 1b (components) + 1 (scripts) | 4.03 | 4.97 | 3.06 | 2.24 |
| option 1c | 4.23 | 4.39 | ||
| option 2 (incl. generator) | 2.70 | 3.60 | 1.91 | 1.66 |
| option 3 | - | 4.89 | - | 2.53 |
- Per reflected class, above no reflection, compiled to an object: option 1 about 10 ms; option 2 about 3 ms (clang) to 7 ms (GCC); option 3 about 13 ms.
- The generator itself takes 16 ms for the whole 200-class header (Debug build).
- MSVC wasn't timed.
- Option 1's first version looked up every line number up to the limit instead of following links: 30 s on GCC for the same file (9 s with a limit of 128 lines). The linked version is the one measured above.
Error messages:
- Option 1: readable on clang and GCC. A wrong class name in the body macro gives the
static_asserttext; an unsupported field type gives the list of allowed types. - Option 2: the generator's own messages for marker mistakes. Type errors come from the compiler, in the generated
macro: less direct, since they point into
<file>.generated.h.
Tools:
- clang-format 23 handles option 2's ordinary declarations well. It writes option 1's
PRIMAL_PROPERTY(...){init}asPRIMAL_PROPERTY(...) { init }, as if it were a function body, and option 3's annotations as[[ = ...]](it doesn't know P3394 yet). - Option 2 also needs an
IncludeCategoriesrule in.clang-format, to keep*.generated.hlast. - clangd/CLion: options 1 and 1b work with no build. Option 2's headers show errors until the first build has
generated their
.generated.h(Unreal has the same).
Build integration (option 2 only):
- CMake: one
add_custom_commandper header and an include directory for the output: 15 lines in the prototype; aprimal_reflect_headers(target ...)function in the engine. - MSBuild: a
.targetsfile with a target beforeClCompilethat runs the generator on the reflected headers and adds the output folder to the include path. The engine's projects and the editor's four game project templates import it, andGameProjectUpgrade.csadds it to older game projects. - The generator ships with the engine (like
PrimalShaderCompiler). - The editor builds game projects with MSBuild today, so nothing else changes there.
5. Side findings
- MSVC in the VM deprecates
/std:c++23preview("use/std:c++23instead", warning D9048). The.vcxprojfiles (stdcpp23) build without the warning there, so the toolset no longer mapsstdcpp23to the preview switch.Tools/WindowsCompileDb/gen_windb.pypasses/std:c++23previewto clang-cl, andDocs/Preferences.mddescribesstdcpp23as/std:c++23preview: update both when the desktop has the same toolset. __COUNTER__is flagged by clang 23 under-Wpedantic("C2y extension");__LINE__is the portable choice.- Overload resolution on a 384-deep class hierarchy crashes clang 23 (exit 139); 256 is fine on all three.
- An entity reference can't be a typed id (
EntityIdis au32in Release): references aregame_entity::Entity.
6. Recommendation
Option 2, the generator with marker macros, on the shared runtime of section 2. Reasons:
- It's the in-class macro the user asked for, in the form people know from Unreal (
GENERATED_BODY(),UPROPERTY()). Members stay ordinary declarations, which keeps types with commas, clang-format and IDE navigation working. - The cheapest compile: a quarter to a half of option 1's extra cost, with no limits on line distance and no template tricks near a compiler's limits (option 1's link chain is 256 lines away from a clang crash).
- Room to grow: the same pass can later generate the editor's C ABI bindings, binary serializers, or C# bindings for #47, which needs a description of the game API types anyway.
- The cost is bounded: about 450 lines of our own code, a CMake function and an MSBuild
.targetsfile. No libclang, no third-party code.
Option 1c is the fallback if no build step is wanted (option 1's machinery with ordinary declarations; the name is written twice). It works on all three compilers today, at about twice the compile cost, with a less natural syntax. Option 3 isn't usable before clang and MSVC have reflection. The shared runtime keeps a later move to it small, for either option.
Components: reflect every field of a component automatically, with PRIMAL_PROPERTY(...) only adding metadata
(as the option 3 sample does). A component is plain data that game.bin must store whole: a field the editor can't
see would be lost on save. In option 2 the generator does this for classes marked as components. Scripts: only
the marked fields, as in Unreal: scripts hold runtime state that isn't saved.
7. Decisions (user, 2026-11-18)
- Option 2, the generator, moving to C++26 reflection (option 3) once clang and MSVC fully support it. #47 was
decided against C# the same day (
Docs/CSharpScripting.md), so the generator writes C++ only. - Unreal's style: a marker before each type says what it is and holds its options —
PRIMAL_COMPONENT(),PRIMAL_SCRIPT(),PRIMAL_GAME_SCRIPT(),PRIMAL_ENUM()— and classes and structs havePRIMAL_GENERATED_BODY()inside. One rule for every kind; enums can't hold a macro inside, so the marker goes before (section 3's in-class-only style would need a second syntax for them). - Components reflect every field;
PRIMAL_PROPERTY(...)only adds metadata. A component is plain data thatgame.binstores whole. - Scripts reflect only the fields marked with
PRIMAL_PROPERTY(...)(runtime state isn't saved). - Registered names: the class name alone, as today, with an override for clashes:
PRIMAL_SCRIPT(.name = "Fan"). - Enums from the start:
PRIMAL_ENUM()on anenum classgives a name table; a field of that type is shown as a choice and saved by name. PRIMAL_SCRIPT(Type);after the class goes, with no transition (the 2026-11-13 rule; the test game projects are rebuilt).- DirectXMath in the game API (#6 decision 3) is decided with #52 step 4.
#include "FanScript.generated.h"
PRIMAL_ENUM()
enum class SpinDirection : u8
{
clockwise,
counter_clockwise,
};
PRIMAL_COMPONENT()
struct Spinner
{
PRIMAL_GENERATED_BODY()
math::v3 axis{0.f, 1.f, 0.f};
PRIMAL_PROPERTY(.min = 0.f, .max = 720.f, .tooltip = "Degrees per second")
f32 speed{90.f};
SpinDirection direction{SpinDirection::clockwise};
};
PRIMAL_SCRIPT()
class FanScript : public script::EntityScript
{
PRIMAL_GENERATED_BODY()
public:
PRIMAL_PROPERTY(.min = 0.f, .tooltip = "Degrees per second")
f32 speed{45.f};
private:
f32 _angle{0.f}; // not reflected
};
The way to C++26: each marker becomes an annotation (PRIMAL_PROPERTY(.min = 0.f) → [[=property{.min = 0.f}]],
PRIMAL_COMPONENT() → [[=component{}]]); the runtime tables, the engine and the file formats stay.
8. The implementation (#41 + #52 step 3)
- The runtime in the engine — done 2026-11-18 (details below the list):
- the type and field tables in a game API header (
Engine/EngineAPI/Reflection.h), with the registry and the serializer in a.cpp; - the script registry merged into it (
TypeInfo::create_script, the game script creator); script::detail::script_name_hash()becomes the shared name hash.
- the type and field tables in a game API header (
- ECS components by name:
- every component registers a
TypeInfo; the engine's own components (transform::Position, ...) get the body macro too; component_id<T>()stays the per-binary dense index for the 64-bit masks, and the world getsfind_component(name_hash);- files and the editor use the hash, never the index;
ecs::ComponentInfogets the name, hash and fields.
- every component registers a
- The generator (if option 2):
Tools/ReflectionTool/or next toShaderCompilerTool/, a CMake function and an MSBuild.targetsfile, the game project templates andGameProjectUpgrade.cs, and a.clang-formatinclude rule. Tests:- its parser, on header snippets, in
UnitTestsor a test of its own; - the registry and the serializer, in
UnitTests.
- its parser, on header snippets, in
- The editor's C ABI (
EngineDLL, later with #52 step 5): list the types, list a type's fields, and get/set a field's value as text or typed. The inspector andgame.binbuild on that. - Update the editor's new-script template,
CLAUDE.md("Scripts"), andDocs/Preferences.md.
Step 1, done (2026-11-18):
Engine/EngineAPI/Reflection.h(game API):FieldType(withenumeration),TypeKind,FieldMeta,EnumInfo/EnumEntry,FieldInfo,TypeInfo(with the entity and game script creators),name_hash()(FNV-1a),make_field<Self, &Self::member>(),detail::register_reflected<Self, kind>(name, fields), and theReflectedEnumconcept (the generatedprimal_enum_info(E), found by ADL). It only declaresEntityand the script classes, soGameEntity.hcan include it.Engine/Reflection/Reflection.cpp(a new layer,Reflection→Core,EngineAPIincheck_layers.py): the registry (register_type(),find_type()by hash or name,type_at(),type_count(),registration_errors(),find_field()) and the text values (value_to_text(),value_from_text(),write_text(),read_text(); enums by enumerator name, or the number when a value has no name).- One registry: the script registry of #30 is gone;
find_script_creator(),script_type_name()and game script start-up look in the reflection registry, andscript_name()reads the type by its registry index (script::detail::set_script_type()). Until step 5,PRIMAL_SCRIPT(Type)andPRIMAL_GAME_SCRIPT(Type)register a type with no fields through it. The editor'sget_script_names()lists scripts only (the registry also holds components). UnitTests/ReflectionTests.cpp: 10 cases (types written the way the generator's output declares them). Checked: clang + GCC Debug, clang-tidy,ci.sh checks; MSVC in the VM (Debug, DebugEditor, Release, 0 warnings; UnitTests Debug 178, Release 180). On the way:(std::numeric_limits<f32>::max)(), since<windows.h>may definemax, and doctest needs<ostream>on MSVC to print astd::string_view.
Steps 2, 3 and 5, done (2026-11-18):
- The generator,
ReflectionTool/(PrimalReflectGen; standard C++ only, no engine, so it builds first):ReflectParser(a token reader with a strict marker syntax: namespaces, nested classes, constructors with initializer lists, templates in member types; anything it can't read in a reflected class is an error with the line),ReflectWriter(a<file id>_<line>_BODYmacro per class; per enum a declaration ahead and a templatedprimal_enum_info(), compiled where it's used),Main(--out <folder> [--list <file>] <file>...; writes only for files with markers or that include their generated header, and only when the text changes). A UTF-8 BOM is skipped (Visual Studio and Windows PowerShell write one). 9 cases inUnitTests/ReflectionToolTests.cpp. - Build integration:
cmake/PrimalReflection.cmake(primal_reflect(<target> PUBLIC|PRIVATE <files>), one command and a stamp per target) andEngine/Reflection.targets(MSBuild: afterPrepareForBuild, since the module dependency scan reads sources beforeClCompile; allClInclude/ClCompileitems through a file list; the engine's generated headers inx64\<Configuration>\reflection\Engine\on every importer's include path).ReflectionTool.vcxproj(output alwaysx64\<Configuration>\),Primal.slnx(Engine, UnitTests and EngineTest depend on it), Engine/EngineDLL/UnitTests/EngineTest import the targets, the four game project templates too, andGameProjectUpgrade.csadds the import to older game projects and warns aboutPRIMAL_SCRIPT(Type);..clang-formatkeeps*.generated.hlast;ci.sh tidybuilds the reflection stamps before linting. - Scripts converted:
PRIMAL_SCRIPT(Type)/_NAMED/PRIMAL_GAME_SCRIPT(Type)are gone; every script in UnitTests, EngineTest and GraphicsTests uses the markers, and the editor's new-script template writes them. - Checked: Linux clang + GCC, UnitTests 192, GraphicsTests 21,
ci.sh checks,ci.sh tidy, header check; MSVC in the VM, all four configurations (0 C++ warnings), UnitTests Debug + Release, and a game project made from the EmptyProject template with a reflected enum, component and script: it builds, and its DLL registers the script (primal_get_script_creator("FanScript")) and not the component.
Step 4 in the plan's numbering (#52 step 3), ECS components by name, done (2026-11-18): ecs::ComponentInfo
has the type's reflect::TypeInfo; ecs::find_component(name_hash) and component_id<T>() give the same id, also
when a type is first registered by name (from its reflection: size, alignment). ecs::component_type(id). The six
transform components are reflected under qualified names (transform::Position, ...: the engine's types don't take
bare names a game may want), with a new field type m4x4. Deviation from the plan: reflection isn't required of
every ECS component; an unreflected one (tests, internal data) works as before but has no name, so it can't be saved
or found by name. 5 more cases in UnitTests/ReflectionTests.cpp.
Arrays, lists and strings (user, 2026-11-18: standard library types; our own only when a measurement asks for them):
FieldType::array:std::array<T, N>, in components and scripts (plain data, so a component's chunk holds it).FieldType::list:std::vector<T>orutl::vector<T>(any container withsize(),resize()anddata()), scripts only: it allocates, and a component is trivially copyable.FieldType::string:std::string, scripts only. A component holds a name hash or an asset id (u64) instead, as Unreal'sFName.- The elements are single values (the other field types); no arrays of arrays.
FieldInfohas the element type, its size and an array's length, and for a list aListOpstable (size, resize, data). A C array is refused by the generator ("use std::array<T, N>"). - Text:
[1 0 0, 0 2 0]for arrays and lists, a quoted and escaped"..."for strings, so a value stays on one line. An array needs exactly its length; a bad element or string leaves the field as it was. - 2 more cases in
UnitTests/ReflectionTests.cpp; checked on clang, GCC and MSVC (VM).
Open: the editor's C ABI and game.bin (with #52 step 5 and #33); the editor's new-script flow and
GameProjectUpgrade.cs were written blind (plan doc A38).