# Reflection and data

> Mark a struct with HZ_REFLECT and it becomes editable, saveable, printable and loadable as a file.

C has no reflection, so Kaigen generates it. Put `HZ_REFLECT()` above a struct in a header, and the build tool writes a description of every field for you. From that one line you get:

- the struct's fields in the editor's inspector,
- saving and loading in scenes,
- `fmt_struct(T, &value)` in your logs,
- a text file format you can load as an asset.

A reflected component:

```
HZ_REFLECT()
ECS_COMPONENT(Enemy) {
  f32 speed;
  f32 sight_range;
  u32 health;
};
```

> Reflected types have to live in headers. The code generator only reads headers, so `HZ_REFLECT()` in a `.c` file silently does nothing.

## Ranges and units

`HZ_FIELD` in front of a field tells everything that reads it what's valid. The editor's slider, its clamp, and a warning in development builds all come from this one place.

Bounded fields:

```
HZ_REFLECT()
ECS_COMPONENT(Turret) {
  HZ_FIELD(.min = 0, .max = 50, .unit = FIELD_UNIT_METERS) f32 range;
  HZ_FIELD(.min = 0, .max = 1, .unit = FIELD_UNIT_PERCENT) f32 accuracy;
};
```

## Your own data files

Kaigen has exactly two file formats, and you never write a parser for either.

- **`.hzt`** (hztext) is the text you author and keep in git: a header naming the type, then one `field value` per line.
- **`.hza`** (hzasset) is what the cook turns it into: one block of memory the game loads with a single read, no parsing at run time.

Any reflected struct that starts with a `BlobAssetHeader` can be a data file:

game.h:

```
HZ_STRUCT_TYPEDEF(WaveTable) {
  BlobAssetHeader header;
  f32 spawn_interval;
  u32 enemies_per_wave;
};
```

assets/my_game/waves.hzt:

```
type WaveTable
version 1
---
spawn_interval 2.5
enemies_per_wave 12
```

Loading it:

```
HzHandleT(WaveTable) h = asset_load(WaveTable, assets, .path = "my_game/waves.hzt");
// later, once it's loaded
if (asset_is_ready(assets, h)) {
  WaveTable *waves = asset_get(assets, h, WaveTable);
}
```

`hz/hzbuild cook` (and every build) cooks it. There's no loader to register: the type name in the file is enough. Arrays are `BlobArray(T)`, read with `blob_array_get(T, &table->field)`, and links to other assets are `BlobAssetRef(T)`.

## Worth knowing

- You load by the *source* path (`my_game/waves.hzt`), never by the cooked one. The asset system finds the cooked file.
- In a `.hzt`, fields must be in the same order as in the struct. A field you add later is zero in the files that don't have it yet.
- Reflected type names are global to the project, so give yours a prefix if they might clash.

The details are in `hz/src/lib/reflect.h` and `hz/src/lib/blob_asset.h`.
