C++ runtime
The runtime lives in Code/Engine/GameEngine/DataTables/. A table is a plDataTableResource holding an immutable, columnar payload: a sorted key array, one packed array per column and pools for text and other variable-size values. It loads with one read and no per-row allocations.
| Header | Contents |
|---|---|
DataTableResource.h | plDataTableResource, plDataTableData (the payload). Includes DataTableView.h. |
DataTableView.h | plDataRowView, plDataColumn<T>, plDataTableView. |
DataQuery.h | plDataQuery, plDataOp, plDataOrder. |
DataRowRef.h | plDataRowRef, plDataRowRefAttribute. |
DataTableSetResource.h | plDataTableSetResource, plDataTableEvent. |
DataTables.h | plDataTables, the service on plGameApplication, and RunQueryString. |
DataStore.h | The writable store. See Data store & saving. |
DataTableValidator.h | Custom validation rules. |
Loading a table
Load a table by its asset GUID (Asset Browser: right-click the table, Copy Asset Guid).
plDataTableResourceHandle hWeapons = plResourceManager::LoadResource<plDataTableResource>("{ 4ec80001-6d67-1bc1-0100-64a7b3b6e00d }");
plResourceLock<plDataTableResource> pWeapons(hWeapons, plResourceAcquireMode::BlockTillLoaded);
if (pWeapons.GetAcquireResult() != plResourceAcquireResult::Final)
return; // the table is missing or failed to load
Keep the handle in the object that uses the table, for example as a component member set up when the component activates, rather than calling LoadResource for every lookup. Tables are small, so loading them up front, for example while a level loads, keeps a first lookup during gameplay from waiting on disk.
Looking rows up
plDataRowView row = pWeapons->GetRow("rifle_mk2"); // binary search over key hashes
if (row.IsValid()) // or simply: if (row)
{
const float fDamage = row.Get<float>("Damage");
const plHashedString sKey = row.GetKey();
}
for (plUInt32 i = 0; i < pWeapons->GetRowCount(); ++i)
{
plDataRowView each = pWeapons->GetRowByIndex(i); // rows in document order
}
A view is a pointer to the table plus a row index. It is cheap to copy and owns nothing. A missing key returns an invalid view, never another row. A key that was renamed with the Usages tab still resolves, because the table keeps its old keys.
Reading cells
Get<T>(column) takes a column name or index. The types below are read directly, and any other T goes through plVariant conversion. GetVariant(column) returns any cell as a variant.
| Column type | Typed read | Also |
|---|---|---|
| Bool | Get<bool> | GetBool |
| Int, Enumeration | Get<plInt32> | GetInt |
| Flags | Get<plUInt32> | GetUInt |
| Float | Get<float>, Get<double> | GetFloat |
| Name | Get<plHashedString> | GetName |
| String | Get<plStringView> | GetString |
| Text | none | GetText (translated), GetString (the translation key) |
| Tags | none | GetTags (;-separated), HasTag(column, "Heavy") |
| Vec2 / Vec3 / Vec4 | Get<plVec2> … | GetVec2 … |
| Color | Get<plColor> | GetColor |
| Time | Get<plTime> | GetTime |
| Angle | Get<plAngle> | GetAngle |
| Asset | none | GetAssetId: pass the result to plResourceManager::LoadResource |
| Row | Get<plDataRowRef> | GetRef, GetRefRow (resolves the reference) |
| Curve | none | GetCurve → const plCurve1D* |
| Array | none | GetArrayCount, GetArrayElement(column, i) |
| Struct | none | GetStruct → const plVariantDictionary* |
Column handles
Reading by name looks the column up in a hash table on every call. In code that reads many rows, resolve the column once with a plDataColumn<T>. It caches the column index per loaded table, so it stays correct across hot reloads and across different tables, and it is safe to share between threads.
static plDataColumn<float> s_Damage("Damage");
static plDataColumn<float> s_FireRate("FireRate");
float fTotal = 0.0f;
for (plUInt32 i = 0; i < pWeapons->GetRowCount(); ++i)
{
plDataRowView row = pWeapons->GetRowByIndex(i);
fTotal += row.Get(s_Damage) * row.Get(s_FireRate);
}
For fixed-offset access with named accessors, generate a row header: see Generated C++ row headers.
Row references
A plDataRowRef is a table handle plus a row key. Store references, not views, in components and in save data: a reference resolves by key and survives a table reload.
plDataRowRef m_Weapon; // a component property with plDataRowRefAttribute, see Getting started
plDataRowView weapon = m_Weapon.Lookup(); // blocks until the table is loaded
plDataRowView ammo = weapon.GetRefRow("Ammo"); // follow a Row column into another table
plDataRowRef ammoRef = weapon.GetRef("Ammo"); // or keep the reference itself
plDataRowRef made(hWeapons, plMakeHashedString("pistol")); // build one in code
| plDataRowRefAttribute argument | Description |
|---|---|
| Schema | The picker only offers tables that use this schema. The schema asset's GUID or data-directory relative path. Empty offers every table. |
| FixedTable | Optional. The picker only offers rows of this one table. |
plDataRowRef is a reflected type and a custom plVariant type, and it has stream operators, so it can be a component property, a message member or part of saved data.
Queries
plDataQuery filters, sorts and picks rows. Equality on an Indexed column uses the index. Every other filter scans the column, which stays fast into the tens of thousands of rows.
#include <GameEngine/DataTables/DataQuery.h>
// The five highest-DPS epic weapons.
plHybridArray<plDataRowView, 8> best;
plDataQuery(&pWeapons->GetData())
.Where("Rarity", plDataOp::Equal, "Epic") // Enumeration and Flags values can be given by name
.OrderBy("DPS", plDataOrder::Descending)
.Take(5)
.Run(best);
// A weighted loot roll: the chance of each row is proportional to its Weight.
plRandom rng;
rng.Initialize(uiSeed);
plDataRowView drop = plDataQuery(&pLoot->GetData())
.Where("Tier", plDataOp::LessEqual, iPlayerTier)
.PickWeighted("Weight", rng);
| Member | Description |
|---|---|
Where(column, op, value) | Keeps rows where the cell compares true. op: Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual, HasTag, Contains (text, ignoring case). Several Where calls must all be true. |
WhereRange(column, low, high) | Keeps rows where low ≤ cell ≤ high. |
WhereTag(column, tag) | Keeps rows whose Tags cell contains the tag. |
OrderBy(column, order) | Sorts by one column. Text sorts alphabetically, ignoring case. |
Skip(n), Take(n) | Paging, applied after sorting. |
Run(out_rows), Run() | Runs the query and returns the matching rows in order. |
Count(), First() | The number of matching rows, and the first one (or an invalid view). |
Sum, Min, Max, Average | Aggregates over a numeric column of the matching rows. |
PickWeighted(column, rng) | One matching row, with chance proportional to the column's value. Rows with a weight of zero or less are never picked. The same seed gives the same row. |
PickRandom(rng) | One matching row, each with the same chance. |
Comparisons on Name, String and Text columns compare for equality only. Use Contains for partial matches. There are no joins: follow a Row column with GetRefRow instead.
Queries as text
The console command DataTables.Query, the Live Data panel and the script function DataTables.FindRows take a query written as a method chain. The same parser is available in C++:
plDynamicArray<plDataRowView> rows;
plStringBuilder sError;
if (!plDataTables::RunQueryString(plDataTableView(&pWeapons->GetData()),
"Where(Damage > 30).OrderBy(Damage desc).Take(4)", rows, sError))
{
plLog::Error("{}", sError);
}
| Call | Example |
|---|---|
Where(Column op value) | Where(Damage >= 30). Operators: = == != < <= > >=, and ~= for Contains. |
HasTag(Column, tag) | HasTag(Tags, Heavy) |
OrderBy(Column [asc|desc]) | OrderBy(DPS desc) |
Skip(n), Take(n) | Skip(10).Take(10) |
An unknown column or a malformed call is an error, never an empty result. An empty string returns every row.
Tip
Set the cvar DataTables.LogQueries to log every query with its matched and returned row counts and its time. It shows which scans would benefit from an index.
Table sets
#include <GameEngine/DataTables/DataTableSetResource.h>
plDataTableSetResourceHandle hSet = plResourceManager::LoadResource<plDataTableSetResource>("{ set asset guid }");
plResourceLock<plDataTableSetResource> pSet(hSet, plResourceAcquireMode::BlockTillLoaded);
plDataRowView frostRifle = pSet->GetRow("rifle_frost"); // from the merged table
plDataQuery(pSet->GetView()).Where("Damage", plDataOp::Greater, 40.0f).Run(rows);
pSet->SetLayerEnabled("DLC_Frost", bOwnsDlc); // merges again if anything changed
pSet->m_Events.AddEventHandler([](const plDataTableEvent& e) { /* look rows up again */ });
The merged table is built the first time it is read and again after a layer is switched. Use table sets from the main thread. The layer tables are loaded when the set merges, so the first read of a set loads every enabled layer.
Hot reload and held views
When a table is edited in the editor, or re-transformed, the resource swaps in a new payload. Views taken before the swap keep pointing at the old payload, which is kept alive, so they read the old values rather than crashing. row.IsStale() tells you when that is the case.
Important
Do not keep a plDataRowView across frames. Keep the key or a plDataRowRef and look the row up when you need it. A lookup is a binary search, cheap enough to repeat every frame.
Threads
A loaded table is immutable and can be read from any thread. plDataColumn handles are thread safe. Table sets and the data store are main-thread objects. To query the store from a worker, hand the worker a snapshot (see Snapshots).
Text columns
A Text column holds player-facing text in several languages. When the table is transformed, each Text cell is replaced by a translation key, <TableName>.<row key>.<column>, and the authored text is written to Localization/en/DataTables/<TableName>.txt in the project, in the format the engine's file translator reads.
- Author the source-language text in the table.
- For each other language, copy the generated file to
Localization/<language>/DataTables/and translate the values. The keys stay as they are. - At runtime
GetTextreturns the text for the language selected with theApp.Languagecvar.GetStringon a Text column returns the key.
# Generated from the data table 'Weapons'. Do not edit; edit the table's Text columns.
Weapons.rifle_mk2.DisplayName;Rifle Mk II
Weapons.pistol.DisplayName;Service Pistol
Note
The en file is rewritten on every transform. Only edit the copies for other languages. A ; in the text is written as , because the file format uses ; as its separator.
Custom validation rules
Game code can add rules the transform checks, for example "every weapon's DPS stays under 200" or "every loot table's weights add up to more than zero". Derive from plDataTableValidator, reflect the class with an allocator, and make sure the module that defines it is loaded by the editor, as a project's runtime plugin is. The transform runs every validator on every table it applies to, after the built-in checks and the derived columns.
#include <GameEngine/DataTables/DataTableValidator.h>
class plWeaponBalanceValidator : public plDataTableValidator
{
PL_ADD_DYNAMIC_REFLECTION(plWeaponBalanceValidator, plDataTableValidator);
public:
virtual bool AppliesTo(const plDataTableData& table) const override
{
return table.FindColumn("DPS") != plInvalidIndex;
}
virtual void Validate(const plDataTableData& table, plDataTableValidationContext& ctx) const override
{
const plUInt32 uiDps = table.FindColumn("DPS");
for (plUInt32 i = 0; i < table.m_uiRowCount; ++i)
{
if (table.GetFloat(i, uiDps) > 200.0f)
ctx.Warning(table.m_RowKeys[i], "DPS", "DPS above 200 breaks the balance curve.");
}
}
};
PL_BEGIN_DYNAMIC_REFLECTED_TYPE(plWeaponBalanceValidator, 1, plRTTIDefaultAllocator<plWeaponBalanceValidator>)
PL_END_DYNAMIC_REFLECTED_TYPE;
ctx.Error(…) stops the transform, and ctx.Warning(…) is logged.