Game Studio: entities, formulas and layouts
Game Studio exposes three backend tools: structured record editing, mathematical expression tuning and plugin widget placement. GameStudioController serves them over HTTP. The admin app has no Game Studio page of its own. The plugin record editor (PluginResourceStudioView.vue, at /plugins/:slug and /plugins/:slug/records) uses the entity endpoints, and the item rewards field (ItemRewardsEditor.vue) lists items records. PluginHistoryPanel.vue calls the history endpoint, but no admin page mounts it. The overview, formula and slot endpoints have no admin screen. The services can also be resolved in trusted backend code.
| Service | Use |
|---|---|
GameEntityStudioService |
Register entity field schemas and manage records. |
FormulaEngineService |
Evaluate, store and simulate bounded mathematical expressions. |
SlotLayoutStudioService |
Resolve plugin widgets and persist placement overrides. |
The HTTP routes live under /api/v1/admin/studio inside the authenticated admin/moderator group. The services do not themselves authorize the requesting user. Do not expose them through a public plugin route without a deliberate permission boundary.
Entity schemas
An entity schema describes a table and editable fields. Register your plugin's schema when its backend is loaded:
use App\Core\Services\GameEntityStudioService;
GameEntityStudioService::registerSchema('my-plugin.outposts', [
'label' => 'Outposts',
'table' => 'my_plugin_outposts',
'plugin' => 'my-plugin',
'fields' => [
'name' => ['type' => 'string', 'required' => true],
'capacity' => ['type' => 'integer', 'default' => 10, 'min' => 1],
'active' => ['type' => 'boolean', 'default' => true],
],
]);
This stores a definition in process memory. It does not make your plugin installed or enabled. Enabled registry records can also contribute config.entity_schemas. Runtime registered definitions override matching keys after the built-in and registry definitions are merged.
Table creation is an important side effect: getSchemas() calls ensureTableExists() on each discovered schema. Consequently, listing schemas or opening Studio overview can create missing tables. It is not a strictly read-only introspection operation. Plugin migrations remain the place to define intentional indexes, relationships, constraints and upgrade changes.
Entity API
Resolve with app(GameEntityStudioService::class). These methods are backed by query-builder operations, not arbitrary model instances:
| Method | Arguments/defaults | Return / side effects |
|---|---|---|
registerSchema(string $key, array $schema): void |
Stable key and schema | Static runtime registration. |
clearCustomSchemas(): void |
None | Clears all runtime custom definitions; useful in isolated tests. |
getSchemas(): array |
None | Keyed schema map, live record counts; may create missing tables. |
getSchema(string $entityKey): ?array |
Key | Matching schema/null; runs the full discovery path. |
listRecords(string $entityKey, array $params = []): array |
Search/filter/sort values | schema, records, total; no pagination. |
createRecord(string $entityKey, array $payload): array |
Editable values | Inserted, cast record; timestamps if present. |
updateRecord(string $entityKey, int|string $id, array $payload): array |
ID and partial values | Updated record; missing row raises InvalidArgumentException. |
bulkSaveRecords(string $entityKey, array $rows): array |
Arrays with optional id |
Transactional updated, created, records; entries that are not arrays are skipped. |
deleteRecord(string $entityKey, int|string $id): bool |
Target ID | Whether a row was removed. |
ensureTableExists(string $entityKey, ?array $schema = null): void |
Key, optional known schema | Creates a missing table. Does not reconcile an existing table's columns. |
Unknown entity keys raise InvalidArgumentException. Invalid payloads raise ValidationException; SQL errors remain database errors.
Field types and validation
| Type | Input handling | Created column |
|---|---|---|
string, select |
String; select can constrain options |
String |
text |
String | Nullable text |
integer |
Numeric validation, then integer conversion | Big integer |
number |
Numeric validation, then float conversion | Decimal (12,2) |
boolean |
Laravel boolean validation, then boolean conversion | Boolean |
json |
Accepts arrays or parses JSON strings | Nullable JSON |
Field metadata includes required, default, nullable, min, max and select options. Current integer validation uses numeric and then casts: it is not a strict integer-input validator. Validate stricter domain rules separately.
Partial updates ignore absent fields. Creation fills missing fields with defaults/null/conversion fallbacks. Unknown payload fields are not blindly inserted. The auto-created schema always adds an id and timestamps, but does not infer foreign keys or domain uniqueness.
Create and list records
Run only in a practice database where you intend to create this plugin's table/data:
use App\Core\Services\GameEntityStudioService;
$studio = app(GameEntityStudioService::class);
$record = $studio->createRecord('my-plugin.outposts', [
'name' => 'Relay One',
'capacity' => 12,
'active' => true,
]);
$result = $studio->listRecords('my-plugin.outposts', [
'search' => 'Relay',
'sort_by' => 'name',
'sort_dir' => 'asc',
]);
After the schema registration example, $record contains an ID and the three fields. $result['records'] includes the new row. Search covers string/text/select fields; direct query parameters matching declared field names apply equality filters. Unsupported sort columns fall back to id. The result is unpaginated, so large tables need a separately designed interface.
FormulaEngineService
The formula engine parses a restricted expression language into an expression tree; it does not evaluate PHP. Resolve it with app(FormulaEngineService::class).
Evaluate an expression
use App\Core\Services\FormulaEngineService;
$formulas = app(FormulaEngineService::class);
$damage = $formulas->evaluateExpression(
'round(base.damage * (1 + user.strength * 0.02))',
['base' => ['damage' => 10], 'user' => ['strength' => 20]]
);
Expected result is float 14.0. Nested numeric variables are flattened into dot names; already dotted keys also work. Numeric and boolean values become floats; unsupported values are not a way to call PHP objects.
Expressions support arithmetic, comparisons, parentheses, unary signs, ^ exponentiation and allowed functions: min, max, floor, ceil, round, abs, sqrt, pow, log, clamp, iff. An iff function is not a PHP control-flow block; expression arguments are parsed/evaluated by the engine. Do not assume every PHP mathematical convention, operator or lazy conditional behaviour exists.
The expression limit is 1,000 characters. Empty/invalid expressions and unknown variables/functions can raise InvalidArgumentException. Division/modulo by near-zero returns 0.0; non-finite final results become 0.0. Those behaviours matter when checking whether a formula is meaningful rather than merely accepted.
Formula API
| Method | Arguments/defaults | Returns / effect |
|---|---|---|
registerFormula(string $key, array $definition): void |
Key and definition | Static runtime registration. |
getFormulas(): array |
None | Definitions with active expression and is_customized. |
getFormula(string $key): ?array |
Key | Definition/null. |
hasOverride(string $key): bool |
Key | Whether a nonempty stored override exists. |
evaluateFormula(string $key, array $variables = []): float |
Key and context | Uses active expression plus variable defaults. Unknown key throws. |
saveFormula(string $key, string $expression): array |
Key and expression | Validates with sample defaults, saves override if settings table exists, returns active definition. |
resetFormula(string $key): array |
Key | Removes override if possible, returns current definition. |
validateExpression(string $expression, array $sampleVariables = []): array |
Expression and sample context | valid, plus result rounded to four decimals or error; catches evaluation exceptions. |
evaluateExpression(string $expression, array $variables = []): float |
Raw expression/context | Evaluated float or exception. |
simulateDistribution(string $expression, string $xVariable, float $min = 1, float $max = 50, int $steps = 25, array $fixedVariables = []): array |
Curve parameters | Expression, x_variable, points and summary. |
Saved overrides use settings keys game_studio.formula.{key} in group game_studio_formulas. Saving while the settings table is absent does not persist an override; inspect the returned definition. Runtime registration is process-local and must happen again when the application starts.
Register a formula your plugin actually calls
use App\Core\Services\FormulaEngineService;
FormulaEngineService::registerFormula('my-plugin.scan_reward', [
'label' => 'Scan Reward',
'default_expression' => 'max(1, user.level * 5)',
'variables' => [
'user.level' => ['label' => 'Level', 'default' => 1],
],
]);
$reward = app(FormulaEngineService::class)->evaluateFormula(
'my-plugin.scan_reward',
['user.level' => 4]
);
Expected reward is float 20.0. Your game handler must explicitly call evaluateFormula() to apply that value. Registering or tuning a formula does not automatically attach it to every mechanic.
The engine registers one formula of its own, progression.exp_needed (the level curve), which core PlayerStat consults with any saved override. Game formulas such as damage, success chances or training gains belong to the plugins that evaluate them: each registers its keys with registerFormula(), so inspect the plugin for its keys.
Simulate before saving
$curve = $formulas->simulateDistribution('user.level * 5', 'user.level', 1, 3, 3);
Expected points are (1,5), (2,10), (3,15). The summary provides min, max, mean, median, start and end. Steps clamp to 2–100; reversed min/max are swapped. X values are rounded/snapped by the implementation, so inspect points rather than assuming an exact uniform floating grid.
A formula passing one sample is not proof of good balance or absence of extreme-input errors. Test low/high/zero values and each variable used by real gameplay.
SlotLayoutStudioService
This service combines enabled plugins' declared widgets with operator overrides. It changes placement of existing components; it does not create or compile the Vue components themselves.
| Canonical slot | Accepted legacy aliases |
|---|---|
game.dashboard.primary |
dashboard-widget, game-dashboard-cards |
game.sidebar |
game-sidebar-stats, sidebar-widget |
game.header.stats |
game-header-actions, header-link |
game.profile.actions |
game-profile-tabs, profile-tab, user-profile-widget |
Layout methods
| Method | Returns / effect |
|---|---|
normalizeSlotName(string $slotName): string |
Canonical key when alias known, otherwise original name. |
hasCustomLayout(): bool |
Whether a nonempty stored override list exists. |
getLayout(): array |
has_custom_layout, keyed slots, flattened widgets; discovery plus overrides. |
saveLayout(array $payload): array |
Normalizes/saves overrides if settings exists, invalidates frontend manifest cache, returns layout. |
resetLayout(): array |
Removes settings override, clears manifest cache, returns default layout. |
getEffectiveFrontendSlotsForPlugin(InstalledPlugin $plugin): array |
Raw slots when no applicable override; otherwise enabled/sorted component placement for that package. |
buildResolvedSlotMap(iterable $enabledPlugins): array |
Slot map consumed by plugin registry slot endpoints. |
saveLayout() accepts either slots keyed by slot name or a flat widgets list. Each widget needs plugin_id (the slug) and component; flat entries also need slot. Optional fields include enabled and integer order. Invalid entries may be skipped; a payload with neither shape throws InvalidArgumentException.
In an authorized backend action, use actual widget identifiers returned by getLayout():
use App\Core\Services\SlotLayoutStudioService;
$layoutService = app(SlotLayoutStudioService::class);
$layout = $layoutService->getLayout();
$canonical = $layoutService->normalizeSlotName('dashboard-widget');
Expected $canonical is game.dashboard.primary. To save, send a complete intended placement list based on discovered component identifiers. The setting key is game_studio.slot_layout; group is game_studio_slots. The cache key invalidated is plugins.frontend_manifest.
An override cannot display a component that never registered in the runtime, enable a disabled plugin, or resolve a missing bundle/SRI mismatch. Check frontend runtime when placement succeeds but rendering fails.
HTTP surface
Under /api/v1/admin/studio:
GET /overview,GET /entities,GET /entities/{entity}.POST /entities/{entity},POST /entities/{entity}/bulk.PUTorPATCH /entities/{entity}/{id},DELETE /entities/{entity}/{id}.GET /formulas,POST /formulas/evaluate,POST /formulas/simulate.PUTorDELETE /formulas/{key}for override/reset.GET,PUT,DELETE /slotsfor layout/read/save/reset.
Inspect GameStudioController for exact payload fields and response wrapping. Successful create is 201; validation errors are 422; unknown entity/record is generally 404 on entity paths. Calling a service directly retains its PHP exception semantics.
Sources and tests
Entity service, formula service, slot service, controller. Existing coverage includes Phase3VisualGameStudioE2ETest; see testing for execution and limits.