Core¶
The core module contains fundamental engine components.
AbstractApplication¶
Base class for all Freya applications. Inherits from skr::IApplication and provides the main application loop.
class MyApp final : public fra::AbstractApplication
{
void Update() override; // only pure virtual; StartUp/ShutDown default to no-ops
};
Lifecycle Methods¶
StartUp()- Called once before the main loop begins (default: no-op)Update()- Called every frame (pure virtual, must be implemented)ShutDown()- Called once after the main loop ends (default: no-op)Run()- Starts the main application loop
Protected Members¶
| Member | Type | Description |
|---|---|---|
mWindow | skr::Arc<Window> | Main window |
mRenderer | skr::Arc<Renderer> | Main window renderer |
mEventManager | skr::Arc<EventManager> | Main window event manager |
mDeltaTime | float | Time since last frame (seconds) |
mMainScope | skr::Arc<skr::ServiceScope> | Skirnir scope for the main window |
Multi-window¶
Each window is a Skirnir service scope. Shared across windows (singletons): IPlatform, Instance, Device, MeshPool, TexturePool, MaterialPool. Per window (scoped): Window, Surface, SwapChain, CommandPool, Renderer, LightService, IndirectDrawSystem, shadows / pick / IBL.
// Resolve scoped services from the main window scope (not the root provider).
auto lights = GetMainServiceProvider()->GetService<fra::LightService>();
// F10-style secondary view with its own camera / lights, shared meshes.
auto game = CreateWindow([](fra::FreyaOptionsBuilder& o) {
o.SetTitle("Game").SetWidth(1280).SetHeight(720).SetFullscreen(false);
});
void UpdateSecondaryWindow(const skr::Arc<fra::Window>& window) override
{
auto renderer = GetRenderer(*window);
auto lights = GetWindowServices(*window)->GetService<fra::LightService>();
// ... upload instances using the shared MeshPool, then EndFrame()
}
// Close with the window itself — the app loop tears down its scope.
game->Close();
Run() pumps platform events once per frame, updates the main window, then each live secondary window. Window::Close() (or the OS close button) destroys the native window immediately; the next frame drops the window scope.
Bootstrap: resolve Device / PhysicalDevice for the first time from a window scope (AbstractApplication does this). Do not resolve them from the root provider — DeviceBuilder needs a Surface.
Renderer¶
Main rendering coordinator. Handles frame management, swap chain, and an ordered list of IFrameStage adapters that drive the deferred stack.
mRenderer->BeginFrame();
// Camera::Apply / lights → Scene::Upload
mRenderer->EndFrame(); // EndScene + Present
Scene (retained GPU proxy)¶
fra::Scene is the app-facing retained instance list. Prefer it over raw Begin/Upload/End (Advanced / ECS). Instances store packed world-space SceneTransform (position, scale, rotation); the GPU expands TRS→mat4 before cull.
fra::Scene::Instance ground {};
ground.mesh = groundMesh;
ground.material = groundMat;
ground.mobility = fra::Mobility::Static; // do not SetTransform every frame
scene.Add(ground);
fra::Scene::Instance actor {};
actor.mesh = mesh;
actor.material = mat;
actor.mobility = fra::Mobility::Dynamic; // default
auto id = scene.Add(actor);
// Per frame: mutate dynamics, then Upload (dirty-aware).
scene.SetTransform(id, model); // mat4 or SceneTransform
scene.Upload(*renderer);
| State | What Upload does |
|---|---|
| Unchanged | FiF slot commit only (skip rebuild / skip Copy if slot current) |
| Transforms / bones / flags | Begin/Reserve/Upload/End with packed TRS |
| Add / Remove / Clear | Full rebuild + sort by entityId |
Draw submission remains GPU-driven (ExpandTransforms → compute cull → MDI). Mobility is a contract hint: static props should stay off the per-frame SetTransform/Get path so the scene can stay clean.
For ECS parallel packing without a retained list:
renderer->BeginSceneInstances();
renderer->ReserveSceneInstances(expectedCount);
// any threads:
renderer->UploadSceneInstances(chunkSpan); // cumulative, thread-safe
// coordinator: join/wait for every worker before finalizing
renderer->EndSceneInstances();
Begin/Reserve/End run on the coordinator. End is not a worker join; late uploads are a contract violation. The same join requirement applies to light and bone upload windows.
Frame path¶
Frame stages¶
Default order:
GpuAnim → Pick → Shadow → DeferredGeometry → Ssao → ShadowMask → Lighting → Taa → Translucent → BillboardVfx → Bloom → Composite → BillboardUi → ModelPreview → ScreenUi → DebugDraw
#include <Freya/Advanced.hpp>
fra::Advanced(*mRenderer).InsertFrameStage("Bloom", cell->MakeStage());
InsertFrameStage(beforeName, stage) / ReplaceFrameStage(name, stage) live on fra::RendererAdvanced (via fra::Advanced(renderer)), not on Renderer.
See Flexibility.
Key Methods¶
| Method | Description |
|---|---|
BeginFrame() | Start a new frame |
EndScene() | Run frame stages |
Present() | Submit the command buffer and present |
EndFrame() | EndScene() + Present() |
RebuildSwapChain() | Recreate swap chain (e.g., on resize) |
SetVSync(bool) / SetWindowFlags(WindowFlags) | Enable/disable vertical sync / set presentation flags |
SetSamples(uint32_t) | Set MSAA sample count |
SetDrawDistance(float) | Set render distance |
Begin/Reserve/Upload/EndSceneInstances | Cumulative TRS upload (prefer Scene::Upload) |
Begin/Reserve/Upload/EndBoneMatrixUploads | Cumulative CPU bone palette upload |
GetCurrentFrameIndex() | Get current frame index |
GetFrameCount() | Get total frame count |
CalculateProjectionMatrix(float near, float far) | Calculate projection matrix |
ClearProjections() | Clear all projection matrices |
GetBillboardDraw() | CPU billboard queue for the frame |
GetUiDraw() / GetUiContext() | Screen-space game UI (ui.md) |
Frame-graph customization (InsertFrameStage / ReplaceFrameStage), GPU skinning (Advanced(renderer).GpuAnimation()), and the legacy Draw / DrawInstanced / SetInstanceModels (deprecated — prefer Scene::Upload) live on fra::RendererAdvanced via fra::Advanced(renderer) (<Freya/Advanced.hpp>).
Apps that do not customize the frame graph can keep calling EndFrame().
BillboardDraw¶
Per-frame queue of camera-facing quads (Renderer::GetBillboardDraw()). Cleared each BeginFrame. Use Quad / Quads for raw instances, or helpers:
| Helper | Notes |
|---|---|
Quads(span) | Batch append under one lock (used by ParticleEmitter) |
ConnectedQuad / ConnectedQuads(span) | Explicit-corner strip segments with shared edges (seamless) |
Strip(points, style, camRight, camUp) | Miter-joined camera-facing ribbon through centerline points (used by SplineRope, RibbonEmitter) |
HealthBar(pos, w, h, fill01, bg, fg, align = Cylindrical) | Background + left-aligned fill; same clip/blend/layer path |
Text(pos, utf8, font, height, color, …, align = Cylindrical) | SDF glyphs via `FontAtlas |
Thread-safety: concurrent Quad / Quads / ConnectedQuad / ConnectedQuads / Strip / HealthBar / Text from worker threads is safe (SpinLock). HealthBar, Text, Quads, ConnectedQuads, and Strip hold one lock for the whole multi-quad submit so a snapshot never sees a partial strip or nameplate. Readers must use Snapshot(out) / SnapshotConnected(out) (copies under lock) — the Vfx/Ui frame stages do this before packing GPU instances. Each queue is soft-capped at MaxQuads() (connected queue: default 1 << 14, see kDefaultMaxConnectedQuads).
Raw Billboard::align defaults to Screen; the HealthBar / Text helpers default to Cylindrical.
Alignment modes (BillboardAlign):
| Mode | Description |
|---|---|
Screen | View-plane aligned (camera right/up axes). |
Cylindrical | Yaw-only, world Y up. Default for nameplates. |
Spherical | Per-instance point-toward-camera (correct at wide FOV). |
FixedAxis | Cylindrical with custom up axis (Billboard::axisUp). |
Planar | Flat on a surface; axisUp is the surface normal. |
Extra features: - screenSpaceSize = true — size is treated as NDC half-extents; the billboard stays the same pixel size regardless of distance. Useful for map pins and waypoints. - velocityStretch = true — the quad's long axis aligns with velocity; length grows by length(velocity) * velocityStretchScale. For sparks, tracers, rain. - softParticle = true — alpha fades where the billboard intersects geometry (reads depth via subpass input attachment). softFadeRange controls the NDC transition width.
Call sites that omit align keep cylindrical nameplates.
auto& bb = mRenderer->GetBillboardDraw();
bb.HealthBar(head, 0.85f, 0.08f, hp, bg, fg); // cylindrical
bb.HealthBar(head, 0.85f, 0.08f, hp, bg, fg, fra::BillboardAlign::Screen);
Connected strips¶
Independent rotated quads leave gaps (or double-blended overlaps) where segments meet at an angle. Strip builds a seamless ribbon instead: each StripPoint carries a centerline position, full width, color, and u; StripStyle carries the shared texture/blend/layer plus a miter limit. Joints use mitered edges shared bitwise between neighbours, with a bevel fallback on hairpin turns. The quads land in the ConnectedBillboard queue (SnapshotConnected), rendered by a dedicated vertex shader (billboard_connected.vert) in the same Vfx/Ui passes.
std::vector<fra::StripPoint> pts;
for (const auto& sample : centerline)
pts.push_back({ sample.pos, sample.width, sample.color, sample.u });
fra::StripStyle style {};
style.blend = fra::BillboardBlend::Alpha;
draw.Strip(pts, style, camRight, camUp);
SplineRope::Submit samples its Catmull-Rom spline into a Strip (tapered width, gradient color, growT tip trim, uvRepeat tiling), and RibbonEmitter::Tick submits its trail the same way (with transposed UVs to keep the legacy U-across / V-along orientation).
Screen UI¶
World-space nameplates stay on BillboardDraw. For HUD / menus, use GetUiContext() / GetUiDraw() (screen-space, after tonemap).
ParticleEmitter¶
CPU emitter that simulates live particles and pushes Vfx billboards via BillboardDraw::Quads. Call Tick from one thread per emitter; different emitters may Tick concurrently against a shared BillboardDraw.
Window¶
Window management and input handling. Events are routed by IPlatform (SdlPlatform) so multiple windows do not steal each other's input.
mWindow->IsRunning(); // Check if window is running
mWindow->Update(); // Advance timing / FPS title (events via PumpEvents)
mWindow->GetDeltaTime(); // Get delta time in seconds
UniformBuffer¶
Uniform buffer for shader data.
LightService¶
Manages analytical lights (point, directional, spot, area) and uploads them to a shared UBO used by DeferredCompressed lighting.
FreyaOptions::maxLights (default 64, see kMaxLights / MAX_LIGHTS) caps how many lights AddLight accepts. Shader arrays are fixed at FREYA_MAX_LIGHTS (64) entries.
Light types¶
| Type | Factory | Notes |
|---|---|---|
| Point | MakePointLight(pos, color, radius, intensity) | Attenuates by distance |
| Directional | MakeDirectionalLight(dir, color, intensity) | Direction is normalized |
| Spot | MakeSpotLight(pos, dir, color, radius, innerRad, outerRad, intensity) | Cone angles in radians; stored as cosines |
| Area | MakeAreaLight(center, normal, tangent, halfW, halfH, color, intensity) | Rect panel; LTC in Deferred lighting |
Spot/inner and outer cutoffs on Light are cosines of the cone half-angles. The spot factory converts radians for you.
For area lights, outerCutoff stores half-width and halfHeight the half-extent along the bitangent (cross(normal, tangent)).
GPU packing (LightUniformBuffer, std140 SoA)¶
lightPositions[i]— xyz position / area center, w = LightTypelightColorsAndRadius[i]— rgb color, w radiuslightDirectionsAndCutoff[i]— xyz direction / area normal, w innerCutoff (cos)lightOuterCutoffAndIntensity[i]— x outerCutoff (spot cos) or halfWidth (area), y intensity, z halfHeight (area), w = shadow flag (1 when the light is on and shadows are enabled andcastShadows)lightAreaTangents[i]— xyz area tangentviewPosition,cameraForward,lightCount,iblIntensity,exposure
Set Light::castShadows = true on directional / spot / point lights that should write shadow maps. Area lights never cast shadows. Shadow budgets and quality come from FreyaOptions (see Shadows below).
Usage¶
auto lights = serviceProvider->GetService<fra::LightService>();
lights->AddLight(fra::MakeDirectionalLight(
glm::vec3(-0.4f, -1.0f, -0.3f), glm::vec3(1.0f), 0.4f));
const fra::LightHandle point =
lights->AddLight(fra::MakePointLight(
glm::vec3(0.0f, 5.0f, 0.0f),
glm::vec3(1.0f, 0.4f, 0.3f),
50.0f,
0.5f));
const fra::LightHandle spot =
lights->AddLight(fra::MakeSpotLight(
glm::vec3(0.0f, 8.0f, 4.0f),
glm::vec3(0.0f, -1.0f, -0.5f),
glm::vec3(0.9f, 0.95f, 1.0f),
60.0f,
glm::radians(12.0f),
glm::radians(22.0f),
1.0f));
lights->AddLight(fra::MakeAreaLight(
glm::vec3(0.0f, 6.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f),
glm::vec3(1.0f, 0.0f, 0.0f),
3.0f,
1.5f,
glm::vec3(1.0f, 0.95f, 0.9f),
4.0f));
// Per-frame: position-only or full replace (LightHandle, not raw indices)
lights->UpdateLightPosition(point, glm::vec3(2.0f, 5.0f, 0.0f));
if (const auto* current = lights->GetLight(spot))
{
fra::Light updated = *current;
updated.position = glm::vec3(1.0f, 6.0f, 2.0f);
updated.direction = glm::normalize(-updated.position);
// Light::type is fra::LightType (enum), not float
lights->UpdateLight(spot, updated);
}
For ECS parallel light updates (same staging contract as scene instances):
lights->BeginLightUploads();
lights->ReserveLightUploads(expectedCount);
// any threads:
lights->UploadLightUploads(chunkSpan); // LightUpload{handle, light}
lights->EndLightUploads(); // applies to host pool
// Renderer::UpdateCamera still packs the UBO
UpdateLight / UpdateLightPosition remain valid single-thread helpers; when a staging window is open they enqueue into the same staging buffer.
AddLight returns a null LightHandle when the pool is full (operator bool / IsValid()). RemoveLight / UpdateLight / GetLight take handles. Do not call AddLight / RemoveLight / ClearLights concurrently with UploadLightUploads without external sync.
Renderer::UpdateCamera refreshes the light UBO for the current frame when the light service is present (also uploads iblIntensity for IBL).
IBLService (internal, src-only)¶
Not part of the public headers — resolved as a scoped service inside the engine. Provides split-sum image-based lighting: an equirectangular environment map with GGX importance-sampled specular mips (roughness → LOD), a convolved irradiance map, a BRDF integration LUT, and parametric LTC LUTs used by rectangular area lights. Built at startup from FreyaOptions::environmentMapPath (Radiance .hdr via stbi_loadf; maps wider than 1024px are downsampled for irradiance; specular prefilter bakes at ≤512px wide). Default path is ./Resources/Environments/studio_small_09_4k.hdr (copied from the repo-root Resources/ into example binary dirs). Set the path to empty to force the procedural sky; if the file is missing, the procedural sky is used as well.
| Resource | Role |
|---|---|
| Environment | Specular IBL via textureLod (GGX prefiltered mips) |
| Irradiance | Diffuse IBL (CPU hemisphere convolution) |
| BRDF LUT | Specular split-sum scale/bias |
| LTC matrix/ampl | Linearly Transformed Cosines for area lights |
Configure with SetIblIntensity / SetEnvironmentMapPath on FreyaOptionsBuilder. Deferred lighting bindings 7–9 sample IBL; 10–11 are LTC.
Shadows¶
ShadowPass runs before deferred geometry each frame and produces:
| Target | Technique | Limit |
|---|---|---|
| Directional | Cascaded shadow maps (2D array, multiview) | shadowCascadeCount (1–4) |
| Spot | Perspective depth map (2D array) | maxSpotShadows (0–4) |
| Point | Cube array (multiview 6 faces) | maxPointShadows (0–2) |
Configure via FreyaOptionsBuilder: SetShadowQuality presets (Off / Low / Medium / High / Ultra) or individual setters (SetShadowCascadeCount, SetShadowMapResolution, SetShadowBias, SetMaxSpotShadows, SetMaxPointShadows, SetShadowSampleCount, SetShadowPointResolutionDivisor, SetShadowSpotResolutionDivisor, SetShadowPointUpdatePeriod). Off skips shadow maps entirely (RenderFlags::Shadows cleared); lighting then ignores castShadows.
Spot/point map size defaults to cascade resolution / 2. Point cubes rebuild every shadowPointUpdatePeriod frames when the light is stable. Directional CSM range is shadowCascadeDistance (default 80, Ultra 120), independent of drawDistance — stretching it too far enlarges near-cascade texels and world bias until contact shadows vanish. | Preset | Resolution | Cascades | Spot | Point | Soft taps | CSM range | |--------|------------|----------|------|-------|-----------|-----------| | Low | 512² | 2 | 2 | 2 | 4 | 40 | | Medium | 1024² | 3 | 4 | 2 | 8 | 60 | | High | 2048² | 4 | 4 | 2 | 16 | 80 | | Ultra | 4096² | 4 | 4 | 2 | 16 | 120 |
Ultra also rebuilds stable cascades / point cubes every frame (High keeps a 2-frame update period). High/Ultra use the same atlas resolution for cascade, spot, and point maps; Low/Medium keep half-res locals for cost.
RenderFlags::ShadowMask defaults to unset in every preset (including the no-preset defaults) — the directional shadow mask stage only runs when explicitly enabled.
Defaults without a preset: 4 cascades, 2048², bias 0.002, 4 spot / 2 point slots, 16 soft-shadow taps. Spot/point budgets of 0 keep a 1×1 descriptor stub instead of a full-resolution atlas.
Lighting shaders multiply each light’s radiance by a PCF shadow factor (hardware compare samplers). Deferred lighting bindings 12–15 hold the shadow UBO and cascade / spot / point maps.
DeferredCompressedPass (internal, src-only)¶
Balanced G-buffer (22 B/px of color with velocity) plus HDR scene color: depth pre-pass, then G-buffer. SSAO runs after geometry; lighting is a separate additive fullscreen pass, followed by TAA.
| RT | Format | Contents |
|---|---|---|
| Albedo | RGBA8_SRGB | albedo RGB, material ID (A) |
| Normal | A2B10G10R10 | octahedral normal (RG, 10+10), roughness(8)|variant(2) (B), shading flags (A) |
| PBR | RG8 | metalness (R); AO, or clearcoat(4)|coat roughness(4) when coated (G) |
| Scene color | RGBA16F | emissive HDR, then lighting accumulation |
| Velocity | RG16F | UV-space motion |
Packing lives in Shaders/Include/gbuffer.inc (GBufferPackNormal, GBufferUnpackNormal, ...). Octahedral normals must not be sampled with a linear filter.