Architecture snapshot: December 2026. This article documents Play2Train's portal rendering and view-scheduling subsystem (src/engine/runtime/PortalSystem.h/.cpp, src/engine/runtime/PortalViewScheduler.h, src/engine/runtime/PortalMath.h, src/engine/components/PortalComponent.h, src/math/matrix_utils.h, src/engine/runtime/RenderViewTypes.h, src/engine/runtime/RenderViewDesc.h, Resources/Shaders/Engine/default.frag.glsl, and tests/native_portals.cpp — roughly 3,200 lines of core C++23 plus its 400-line headless test suite) inside Gattic's closed-source Play2Train SDK. Robot Universe uses the portal runtime for two-sided physical-depth portals (CityDemoPair), destination streaming-cell hints, and player traversal; tests/native_portals.cpp verifies seamless portals, oblique clipping, and camera-identity persistence headlessly; PloppyPals runs on the same engine and does not currently use portals.

A convincing 3D portal looks effortless when it works: you look through a doorway in one room and see another room a kilometer away as if the space between them simply ceased to exist. Step closer and the perspective opens up; step sideways and objects behind the frame slide across your view in natural parallax; walk forward and you emerge cleanly on the other side.

Making that illusion hold up in a real production game engine is surprisingly treacherous. Four subtle failures ruin most naive portal implementations:

  1. Flat-screen parallax. If you render the destination onto a rectangle like a movie projected onto a wall, walking around the doorway stretches the picture or shifts the horizon awkwardly.
  2. Foreground bleed-through. Because the virtual camera photographing the far room has to stand behind the far doorway (matching your distance in front of the near doorway), any wall, chair, or pillar sitting behind the far door blocks the lens and photobombs the portal.
  3. Messy authored art. In real game scenes, artists nest portals under scaled parent objects, introduce slight shear, or duplicate a front portal quad to make a back face without flipping its orientation — quietly warping views or turning portals inside out.
  4. Runaway GPU cost. Every portal capture renders the scene a second time. Put three portals in view at once and a 60 fps frame can suddenly triple its render cost unless the engine budgets captures deliberately.

Play2Train solves all four problems as one cohesive pipeline split across three clean headers: PortalMath.h carries the viewer's pose exactly through a pair and repairs non-orthogonal bases; PortalSystem.h/.cpp (with MatrixHelper::applyObliqueClipPlane) clips at the far surface with an oblique near plane, auto-corrects inverted back faces, and isolates split-screen slots; and PortalViewScheduler.h runs a pure, graphics-API-free policy that budgets textured captures by importance while guaranteeing seamless openings always render at full viewport resolution every frame.

Two kinds of portals: painted windows versus seamless openings

For non-technical readers, it helps to picture two very different objects that both show a distant room:

  • A live security TV mounted on a wall (PortalComponent::Presentation::Textured). It shows a live video feed of the other room mapped onto the screen's own rectangle. If you turn your head slightly or view it from across a hallway, updating that feed every second or fourth frame at 75% resolution looks completely fine — your brain accepts it as a glowing window or screen.
  • An actual doorway cut between two rooms (PortalComponent::Presentation::Seamless). There is no screen at all; light from the far room has to continue your own eyes' image pixel for pixel across the doorframe. Even a one-frame lag, a half-resolution blur, or a two-centimeter camera nudge immediately breaks the illusion as a visible seam around the frame.

Play2Train supports both modes explicitly on PortalComponent and lets them share the same core camera-mapping math (PortalMath::MapCameraPoseThroughPortal) while enforcing strict, separate contracts for each.

Diagram of Play2Train's portal pose mapping and presentation modes. The top panel traces PortalMath::MapCameraPoseThroughPortal from Source Portal A to Destination Portal B: the viewer camera's offset relative to srcRect.center is decomposed into (lx, ly, lz), scaled laterally by (dx/sx, dy/sy), flipped 180 degrees about the portal Y axis via (-lx, ly, -sz*lz) with depth scale sz clamped to [0.25, 4.0], and mapped along with forward and up vectors (followed by OrthonormalizeForwardUp) to place the capture camera behind Destination Portal B looking straight through its opening. The bottom panel contrasts Presentation::Textured (framed live monitor using Constant 0.6 m or Physical depth, minAbsDepth 0.05 m, cameraNudge 0.02 m, UV sampling via v_texCoord, and budgeted cadence/resolution scaling) against Presentation::Seamless (optical opening using Physical depth with zero clamps or nudge, screen-space sampling via gl_FragCoord, oblique near-plane clipping and aperture culling, and ExactView full-resolution rendering every frame).
Both portal styles share the same 180° local-space pose transform, but Seamless portals strip away safety nudges, clip at the far surface, and sample directly in screen space.

Carrying the viewer's pose through a pair (PortalMath.h)

Suppose you stand in front of Source Portal A looking toward it. To photograph what you should see through Destination Portal B, Play2Train puts a capture camera in the matching spot relative to B in four steps:

  1. Anchor at the portal surface center, never the entity origin. Authored portal meshes are often offset from their owning entity's pivot. MapCameraPoseThroughPortal computes rel = srcCamPos - srcRect.center using the explicit surface plane center rather than Transform::GetPosition(), avoiding subtle translation and parallax errors.
  2. Project into portal-local coordinates and scale for mismatched sizes. The relative vector is projected onto src's orthonormal basis (lx, ly, lz along right, up, fwd). Lateral offsets scale by the ratio of destination-to-source half-extents (dx / sx, dy / sy), so portals of different dimensions stay coherent.
  3. Apply a 180° rotation about portal-local Y. Walking into the front of Portal A means emerging out of the front of Portal B. In local coordinates that turn is simply (x, y, z) → (-x, y, -z). The exact same flip is applied to both the camera's position offset and its forward and up orientation vectors, followed by OrthonormalizeForwardUp(dstF, dstU) so Quaternion::fromLookRotation stays numerically well-conditioned.
  4. Choose depth behavior (DepthMode::Constant vs DepthMode::Physical).
    • In Constant mode (windowed textured portals), the capture camera sits at a fixed distance (captureDepthConstant = 0.6f) from the destination plane, so walking toward the portal does not push the camera into nearby destination geometry.
    • In Physical mode, depth scales by the mean aperture ratio sz = clamp(0.5 * (dx/sx + dy/sy), 0.25, 4.0) (dstDepth = lz * sz). For textured portals, PortalSystem keeps the camera slightly off the plane (captureMinAbsDepth = 0.05f, captureCameraNudge = 0.02f) for numerical stability. For seamless portals, PortalSystem forces DepthMode::Physical and passes 0.0f for both minAbsDepth and cameraNudge — carrying the viewer's pose through with zero distortion.
cpp
// PortalSystem.cpp — seamless captures carry the viewer's pose exactly;
// textured captures keep safety offsets off the far plane.
PortalMath::DepthMode mode = PortalMath::DepthMode::Constant;
if (job.seamless || pr.depthMode[portalIdx] == PortalComponent::DepthMode::Physical) {
    mode = PortalMath::DepthMode::Physical;
}

PortalMath::MappedPose pose{};
PortalMath::MapCameraPoseThroughPortal(
    *view.camera, srcB, dstB, srcRect, dstRect, mode,
    captureDepthConstant,
    job.seamless ? 0.0f : captureMinAbsDepth, // 0.0 m vs 0.05 m
    job.seamless ? 0.0f : captureCameraNudge, // 0.0 m vs 0.02 m
    pose);

Why screen-space sampling makes the seam vanish

Once the capture camera sits at that exact mapped pose and renders an offscreen RGBA16F image at the exact logical dimensions of the viewer's viewport (view.viewW × view.viewH) with the same lens and FOV, every pixel (x, y) in the capture corresponds to the exact same view ray as pixel (x, y) on the viewer's screen.

In the main pass, the fragment shader (Resources/Shaders/Engine/default.frag.glsl) does not stretch the texture across mesh UVs when u_portalScreenSpace is true — it simply looks up the pixel's own viewport position:

glsl
if (materialMode == 1 && u_usePortalTex) {
    vec2 portalUv = u_portalScreenSpace
        ? (gl_FragCoord.xy - u_portalViewport.xy) / u_portalViewport.zw
        : v_texCoord;
    vec4 p = texture(u_portalTex, portalUv);
    // Linear RGBA16F captures (encoding == 1) skip manual sRGB decode.
    FragColor = vec4(p.rgb * k, p.a * materialBaseColor.a);
    return;
}

One easy-to-miss edge case also separates the two modes during culling: for a textured portal, PortalSystem skips the capture if the portal's center lies behind viewerFwd (Dot(rel, viewerFwd) <= 0.0f). For a seamless opening, you can stand right next to a wide doorway looking sideways and still see half the opening in your peripheral vision even though its center is behind your camera plane — so seamless portals skip that center-behind-camera rejection and let the full frustum sphere test (PortalMath::SphereVisible) decide.

Property Presentation::Textured Presentation::Seamless
Everyday analogy Live security monitor on a wall Open doorway cut between two rooms
Depth mapping Constant (0.6 m) or Physical Always Physical (DepthMode ignored)
Stability offsets minAbsDepth = 0.05 m, nudge = 0.02 m 0.0 m and 0.0 m (exact pose carry)
Surface sampling Mesh texture UVs (v_texCoord) Viewport screen space (gl_FragCoord.xy)
Far-plane clipping Unclipped Oblique near plane + 4-side aperture cull
Capture resolution Area-scaled baseline × tier (1.0 / 0.75 / 0.5) Exact viewer viewport (view.viewW × view.viewH)
Scheduler policy Budgeted cadence, motion & max-age triggers Always ExactView every frame, all 5 passes
Side-of-camera visibility Requires portal center in front of viewerFwd Frustum sphere test alone (works beside camera)

Slicing the far room cleanly: oblique near planes and aperture culling

Imagine standing two meters in front of a doorway in Room A. Because the seamless capture camera mirrors your exact distance, it has to stand two meters behind the linked doorway in Room B. Now suppose there is a hallway wall, a potted plant, or a table sitting one meter behind that doorway in Room B. Without clipping, the capture camera photographs the back of that wall and paints it straight onto your doorway in Room A — completely destroying the portal.

The naive fix is to add a custom clip() or discard check to every single fragment shader in the engine (opaque meshes, skinned characters, terrain, foliage, particles, transparent glass). That creates shader permutation sprawl and still wastes GPU rasterizer work drawing triangles behind the doorway only to throw their pixels away.

Play2Train uses a classic, much cleaner mathematical trick: Eric Lengyel's oblique near-plane projection, implemented once in MatrixHelper::applyObliqueClipPlane (src/math/matrix_utils.h) and shared identically by both the OpenGL backend (Renderer.cpp) and the Vulkan backend (FullSceneRenderer.cpp and SceneWorldProducer.cpp).

Cross-section diagram of Play2Train's oblique near-plane clipping and tightened aperture culling. A capture camera stands behind an angled Destination Portal B with an occluding box in the danger zone between the camera and the doorway. Standard perspective projection would draw that box; MatrixHelper::applyObliqueClipPlane tilts the frustum's near plane flush with Destination Portal B (keeping dot(n, p) + d >= 0 with clipBias) and tilts the far plane to keep the opposite frustum corner q inside, clipping the occluder in hardware before rasterization. Four tightened side planes built by PortalMath::BuildCullingApertureFrustum connect the camera to the portal's four corners scaled by apertureSafety (1.05), culling off-aperture far-room geometry on the CPU while falling back independently to base frustum planes if any corner depth is at most 0.02 m. Three cards at the bottom highlight that only row 3 of the projection matrix changes (preserving screen X and Y bit-for-bit), both OpenGL and Vulkan share the helper, and the renderer automatically disables HZB occlusion culling when m_viewProjectionOblique is true.
Tilting row 3 of the projection matrix clips every object behind the far doorway in hardware with zero shader changes, while aperture planes trim CPU draw submissions.

How row 3 of the projection matrix acts like an invisible saw blade

In plain English, every 3D camera sees the world inside a chopped-off pyramid called a frustum. Normally, the flat front cap of that pyramid (the near plane) sits parallel to your monitor screen a few centimeters in front of your nose. Anything closer than the near plane is sliced off automatically by the GPU's fixed-function triangle clipper before a single pixel shader runs.

Lengyel's insight is that you can tilt that front cap so it lies completely flush with the far doorway's plane — turning the doorway itself into the near plane of the camera. Because the GPU computes screen position (x, y) from rows 1, 2, and 4 of the projection matrix and computes depth z solely from row 3, replacing only row 3 tilts the clipping plane without shifting a single pixel horizontally or vertically on screen.

Here is the exact calculation in src/math/matrix_utils.h:

cpp
// Planes transform by the inverse transpose of the view matrix.
float inverseView[16];
if (!invertAffine(view, inverseView)) return false;
float plane[4];
for (int i = 0; i < 4; ++i)
    plane[i] = (inverseView[i * 4 + 0] * planeWorld[0] +
                inverseView[i * 4 + 1] * planeWorld[1] +
                inverseView[i * 4 + 2] * planeWorld[2] +
                inverseView[i * 4 + 3] * planeWorld[3]) / normalLength;

// Camera (view-space origin) must lie strictly behind the plane.
if (!(plane[3] < -1e-4f)) return false;

// Far corner q of the frustum on the plane's kept side, in view space.
const float q[4] = {
    ((plane[0] >= 0.0f ? 1.0f : -1.0f) + projection[8]) / projection[0],
    ((plane[1] >= 0.0f ? 1.0f : -1.0f) + projection[9]) / projection[5],
    -1.0f,
    (1.0f + projection[10]) / projection[14]
};
const float dotPQ = plane[0]*q[0] + plane[1]*q[1] + plane[2]*q[2] + plane[3]*q[3];
if (!(dotPQ > 1e-12f) || !std::isfinite(dotPQ)) return false;

const float scale = 2.0f / dotPQ;
// Replace ONLY row 3 (indices 2, 6, 10, 14 in column-major storage).
projection[2]  = plane[0] * scale;
projection[6]  = plane[1] * scale;
projection[10] = plane[2] * scale + 1.0f;
projection[14] = plane[3] * scale;

Four careful engineering guards make this production-safe:

  • Strict behind-the-plane check (plane[3] < -1e-4f). In view space, the camera sits at the origin (0, 0, 0), so plane[3] is its exact signed distance to the portal plane. If the camera is already in front of or on the plane, applyObliqueClipPlane returns false and leaves the projection matrix untouched rather than inverting the frustum.
  • Grazing views still clip cleanly. Notice dotPQ > 1e-12f tests the furthest corner q of the frustum, not just the camera's central look ray. Even when the viewer looks almost parallel along the portal plane (explicitly tested in tests/native_portals.cpp), clipping stays valid.
  • Zero drift in screen coordinates. tests/native_portals.cpp asserts that all 12 non-depth entries (0, 1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15) are bit-for-bit identical before and after clipping, guaranteeing screen-space sampling aligns seamlessly with the main view.
  • Automatic HZB occlusion culling guard (Renderer.h). Here is a subtle trap that catches many engines: hierarchical Z-buffer (HZB) occlusion culling estimates a bounding sphere's closest depth by sliding its center forward by its radius along -Z. That shortcut is only exact for a standard projection! Under an oblique projection, depth varies across view-space x and y, so the estimated front depth can land behind the true front of an object and wrongly cull visible geometry. Play2Train records m_viewProjectionOblique whenever applyObliqueClipPlane succeeds and guards occlusion directly:
    cpp
    bool OcclusionCullingThisView() const {
        return m_enableOcclusionCulling && !m_viewProjectionOblique;
    }

Tightening CPU culling to the doorway aperture

Oblique projection clips triangles on the GPU, but what about objects sitting far to the left or right of the doorway that can never be seen through the opening? For seamless captures, PortalSystem also emits a RenderCullingAperture describing the far doorway's world-space center and half-extents (axisU, axisV), inflated by apertureSafety (default 1.05f, a 5% margin against seam popping).

Both the OpenGL (RendererFrame.cpp) and Vulkan (SceneWorldProducer.cpp) renderers pass that aperture into PortalMath::BuildCullingApertureFrustum, which constructs four new frustum side planes passing through the capture camera and each edge of the rectangular opening while keeping the camera's near and far planes. If either corner of an edge gets too close to the camera (depth ≤ 0.02 m), that individual side plane falls back cleanly to the camera's base frustum plane, and a final signed-distance check (≥ -1e-3f) verifies the aperture center lies strictly inside all six planes before tightening culling.

Surviving messy real-world content: orthonormal bases and auto-corrected back faces

In textbook demos, every portal is a pristine unit square sitting at (0, 0, 0) with clean right angles and perfectly opposed front and back normals. In real games built by real teams, portal entities get parented under rotated buildings with non-uniform scale, artists nudge meshes off their pivots, or someone duplicates a Front portal disk, labels the copy Back, and forgets to rotate it 180°.

Play2Train treats those authoring quirks as an expected part of production and builds four explicit defenses into PortalMath.h, PortalComponent.h, and PortalSystem.cpp.

Diagram of Play2Train's content-hardening pipeline for portals. The left panel illustrates PortalMath::OrthonormalizeBasis taking a sheared input basis caused by non-uniform parent scale (where right and up are not at 90 degrees and would warp portal views) and repairing it via four steps: Gram-Schmidt OrthonormalizeForwardUp with worldUp/worldRight fallbacks at 1e-6, cross-product reconstruction of right and up, and a Dot(origRight, right) < 0 sign check that flips right and up together to preserve handedness. The right panel illustrates PortalSystem's back-face normal contract: when both Front and Back surfaces exist and Dot(front.normal, back.normal) > 0.25, the engine auto-flips the Back surface's normal, right, and forward together (preserving right-handedness) and emits one throttled warning per PortalComponent change stamp; when an endpoint is Back-only with no Front reference, it refuses to guess, keeps the authored transform, and warns once. A bottom dark bar summarizes three supporting contracts: explicit aperture extents/offsets instead of guessing mesh bounds, change-stamp event-driven discovery, and automatic RenderLayers::PortalSurface isolation.
Play2Train repairs skewed portal bases mathematically, fixes inverted two-sided back faces while preserving handedness, and refuses to guess when authoring is genuinely ambiguous.

Straightening crooked bases with Gram-Schmidt (OrthonormalizeBasis)

Think of a portal's (right, up, fwd) vectors like a carpenter's square taped to a doorway. If a parent object scales unevenly (say 2× wide, 1× tall) under a rotation, that square shears into a parallelogram. Feed a sheared basis into portal camera mapping and the captured world tilts and skews subtly — and your oblique clip plane no longer aligns cleanly with the frame.

Whenever PortalSystem resolves a portal surface's Transform, it runs PortalMath::OrthonormalizeBasis before caching the basis for the frame:

  1. Prioritize fwd and up. OrthonormalizeForwardUp normalizes fwd (falling back to (0, 0, -1) if degenerate ≤ 1e-6f) and projects up orthogonal to fwd via Gram-Schmidt (up = up - fwd * Dot(up, fwd)). If up collapses to near-zero length, it falls back cleanly to worldUp = (0, 1, 0) and then worldRight = (1, 0, 0).
  2. Reconstruct an exact right-handed triad. right = NormalizedOr(Cross(up, fwd)) followed by up = NormalizedOr(Cross(fwd, right)).
  3. Preserve the author's intended handedness/sign. If Dot(origRight, right) < 0.0f, Play2Train negates right and up together — flipping 180° around fwd rather than mirroring space — so the basis stays strictly right-handed while keeping the author's horizontal orientation consistent.

Auto-correcting two-sided back faces — without guessing blindly

A portal endpoint can have a Front surface, a Back surface, or both coplanar surfaces so players can walk around and peer through either side. Historically, some content rotates the Back entity 180° so its normal opposes Front, while other content leaves both transforms aligned and expects the engine to treat Back as the opposite face.

Play2Train enforces a clear, conservative contract inside applyBackNormalContractIfNeeded (and mirrors it in ChooseVisibleSideIdx):

  • Both Front and Back exist: PortalSystem computes d = Dot(frontRect.normal, backRect.normal). If d > 0.25f, both faces are pointing roughly the same way — the back surface is effectively inside-out. For that frame, the engine flips inOutRect.normal and flips inOutBasis.right and inOutBasis.fwd together (preserving a right-handed frame!) so both camera mapping and clipping work seamlessly, while emitting an actionable warning telling the artist which entity to rotate.
  • Only Back exists (Back-only endpoint): Without a Front reference, the engine cannot know whether the author already flipped the transform. Rather than guessing wrong half the time, Play2Train keeps the authored Transform basis untouched and emits one warning advising the author to add a Front surface or verify the Back forward axis.

Explicit geometry, zero-spam diagnostics, and walking through

Three smaller contracts round out content reliability:

  • Explicit aperture geometry only. PortalComponent requires authored m_surfaceHalfU, m_surfaceHalfV (defaulting to 0.5 m × 0.5 m for a unit quad), and optional m_surfaceCenterOffsetU/V/N relative to the entity's transform. Mapping, culling, and traversal never guess a doorway's size from renderer mesh bounds — so decorative frames, glowing rings, or particle halos attached to the entity never distort the optical opening.
  • Event-driven discovery and throttled warnings. Scanning every PortalComponent in a large scene every frame (and twice in split-screen) is wasted work. PortalComponent setters call Scene::NotifyComponentMutated<PortalComponent>(), bumping a per-scene change stamp. RefreshFromPortalComponentsCached skips rediscovery completely when the stamp has not changed, invalidates every persistent capture cache immediately when topology does change, sorts pairs deterministically by pairId (supporting both (pairId, endpoint) and direct EntityRef pairing keyed as linked://<lo>:<hi>), and throttles authoring warnings to once per change stamp (with the warning map capped at kMaxIssues = 1024 to bound memory).
  • Automatic RenderLayer isolation. The moment a PortalComponent is constructed, EnsurePortalSurfaceLayer() moves its owning entity off RenderLayers::Default onto RenderLayers::PortalSurface (and restores Default in OnDestroy() if no other bits remain). Portal capture views render with visibilityMask = RenderLayers::All & ~RenderLayers::PortalSurface, preventing infinite mirror-in-mirror loops without mutating the ECS during rendering.
  • Traversal and streaming prefetch. PortalSystem::TryMapTraversal tests a character's movement segment (previousPosition → currentPosition) against each portal plane with SegmentCrossesPortalAperture (supporting aperturePadding so a character capsule whose feet sit just below the visual disk still enters cleanly), maps position and facing via MapPointAndDirectionThroughPortal, and pushes the exit point out to at least exitDistance from the destination plane to prevent instant ping-pong re-entry. Meanwhile, GetVisibleStreamingCells() returns a sorted, deduplicated list of streamingDestinationCell hints for every visible portal so WorldStreamingSystem can warm up the far room before the player steps across.

A GL-free budgeted view scheduler: deciding what refreshes each frame

Even with fast clipping and aperture culling, rendering multiple full-scene portal captures every frame can quickly blow a 16.6 ms (60 fps) frame budget. Yet you also do not want portal scheduling logic tangled up with OpenGL calls, Vulkan command buffers, or GPU timing queries that stall the CPU waiting for the graphics card to finish last frame.

Play2Train separates policy from graphics execution completely. src/engine/runtime/PortalViewScheduler.h is a 273-line, header-only, completely GL-free and Vulkan-free pure decision function. It owns zero textures, zero framebuffers, and zero renderer pointers. PortalSystem simply feeds it plain numbers (PortalViewScheduleRequest + PortalViewSchedulerConfig) and consumes a deterministic PortalViewScheduleDecision:

cpp
struct PortalViewSchedulerConfig {
    int   baseCadenceFrames             = 2;
    int   maximumAgeFrames              = 8;
    int   maximumRecursionDepth         = 1;
    float highProjectedAreaRatio        = 0.08f; // >= 8% of viewport
    float mediumProjectedAreaRatio      = 0.02f; // 2% .. 8% of viewport
    float mediumResolutionScale         = 0.75f;
    float lowResolutionScale            = 0.50f;
    float estimatedCaptureCostMs        = 2.0f;  // estimate-based, never blocks GPU
    float motionTranslationThreshold    = 0.25f; // meters
    float motionAngularThresholdDegrees = 2.0f;  // degrees
};

Think of SchedulePortalView like an air-traffic controller working off paper flight strips. It never walks out onto the tarmac to touch an airplane; it looks at each view's strip — is this a seamless doorway? how big is it on screen? how old is its cached image? did the camera move? how much estimated time is left in this frame's budget? — and stamps one of ten explicit ViewScheduleReason codes on the decision.

Flowchart of Play2Train's GL-free SchedulePortalView decision pipeline in PortalViewScheduler.h. Inputs include frameStamp, lastRenderStamp, cacheValid, topologyGenerationMatches, motionInvalidated, exactView, projectedAreaRatio, remainingUpdates, and remainingEstimatedMs. Stage 1 enforces guard rails: recursionDepth greater than maximumRecursionDepth (1) returns RecursionRejected, and frameStamp == 0 returns InvalidRequest. Stage 2 checks request.exactView == true for Seamless portals and immediately branches to ExactView: always render at resolutionScale 1.0, exact viewport size (viewW x viewH), ViewSchedulePassAll, and cadence 1, marking forcedBudgetOverrun if the frame budget is already spent. Stage 3 evaluates four forced refresh triggers for Textured portals in strict priority order: !cacheValid (CacheMiss), !topologyGenerationMatches (TopologyInvalidated), camera movement past 0.25 m or 2.0 degrees (MotionInvalidated), and cacheAgeFrames >= maximumAgeFrames (MaximumAge); any match forces a render at the portal's importance tier. Stage 4 checks cadence and budget for fresh cached Textured portals: if cacheAgeFrames >= cadenceFrames and both remainingUpdates > 0 and remainingEstimatedMs + 1e-6 >= estimatedCostMs hold, it renders via CadenceDue; otherwise it omits the view from the frame and reuses the persistent RGBA16F capture texture via BudgetReuse or CadenceReuse.
A strict four-stage decision tree guarantees seamless doorways never go stale, moving cameras stay responsive, and static background portals stay inside the frame's estimated time budget.

Why estimate-based budgets beat GPU queries

Notice that PortalSystem::Config budgets portal work using two deterministic, CPU-side caps (plus optional environment overrides P2T_PORTAL_CAPTURE_INTERVAL, P2T_PORTAL_CAPTURE_BUDGET, and P2T_PORTAL_CAPTURE_TIME_BUDGET_MS read at startup):

  • Update-count cap: maxCaptureUpdatesPerFrame (default 1 per view per frame; 0 means uncapped).
  • Estimated time budget: captureTimeBudgetMs (default 4.0 ms), against captureEstimatedCostMs (default 2.0 ms per capture).

Why use an estimated millisecond cost instead of measuring actual GPU time from the current frame? Because reading a current-frame GPU timer forces a synchronous CPU/GPU pipeline flush — stalling the very frame you are trying to keep smooth — and introduces non-deterministic thermal/driver jitter into scheduling decisions. An estimate-based budget is instantaneous, 100% deterministic, and trivially unit-testable without a GPU.

All ten ViewScheduleReason outcomes in priority order

Every portal candidate passes through SchedulePortalView in strict priority order. Crucially, when a capture is reused (decision.render == false), PortalSystem re-binds the cached persistent texture to the portal surface and omits the capture view from the frame's RenderViewDesc list altogether — avoiding both CPU scene-culling work and GPU draw passes for that portal.

Priority ViewScheduleReason Trigger condition Renders? Budget behavior
1 RecursionRejected recursionDepth > maximumRecursionDepth (default 1) No Reuses valid cache if present
2 InvalidRequest frameStamp == 0 No Rejects unstamped request
3 ExactView request.exactView == true (Presentation::Seamless) Always Bypasses budget (1.0×, viewW × viewH, all passes); flags forcedBudgetOverrun if spent
4 CacheMiss No valid loaded persistent texture (or tier dimensions changed) Forced Bypasses budget; flags forcedBudgetOverrun if spent
5 TopologyInvalidated cacheGeneration != m_captureCacheGeneration (edits, lighting/HDRI swap, traversal) Forced Bypasses budget; flags forcedBudgetOverrun if spent
6 MotionInvalidated Mapped capture camera moved > 0.25 m or turned > 2.0° (cos(θ) test) Forced Bypasses budget; flags forcedBudgetOverrun if spent
7 MaximumAge cacheAgeFrames >= maximumAgeFrames (default 8 frames) Forced Bypasses budget; guarantees no visible portal ever freezes indefinitely
8 CadenceDue lastRenderStamp == 0 or cacheAgeFrames >= cadenceFrames, and budget available Yes Deducts 1 update and estimatedCostMs (2.0 ms)
9 BudgetReuse Cadence is due, but remainingUpdates == 0 or remainingEstimatedMs < costMs No Reuses cached texture; defers refresh to a later frame
10 CadenceReuse cacheAgeFrames < cadenceFrames (still fresh for its tier) No Reuses cached texture; zero GPU work

Look closely at one clever two-step detail in PortalSystem.cpp (lines 1573–1585): resolution tiers are evaluated before checking cache validity. Suppose you walk closer to a textured portal so it crosses from the Medium tier (0.75×) into the High tier (1.00×). PortalSystem calls SchedulePortalView once to determine the target tier's resolutionScale, computes the quantized target dimensions (captureW, captureH), validates slotTex->GetWidth() == captureW && slotTex->GetHeight() == captureH, and then runs SchedulePortalView with that exact cacheValid flag. If the cached texture is the wrong size for the new tier, cacheValid becomes false, triggering a clean CacheMiss reallocation at the sharper resolution!

Importance tiers, resolution scaling, and split-screen stability

Not every textured portal deserves equal GPU horsepower. A giant archway filling 20% of your monitor should look crisp and update often; a small circular portal tucked at the far end of a corridor occupying 0.8% of your screen does not need full-resolution shadows or volumetric god rays every second frame.

Projected screen area drives resolution, cadence, and render passes

For each visible portal, EstimatePortalProjectedAreaRatio projects its world-space bounding sphere onto the viewport using vertical FOV:

text
radiusPixels = (radiusWorld / distanceWorld) * (0.5 * viewportHeight / tan(fovY / 2))
projectedAreaRatio = clamp(pi * radiusPixels^2 / (viewportWidth * viewportHeight), 0, 1)
importance         = clamp(sqrt(projectedAreaRatio) * qualityImportance * 2.0, 0, 1)

From projectedAreaRatio (plus the renderer's glbPortalImportance quality scalar), SchedulePortalView assigns every textured portal to one of three concrete tiers — while seamless portals override all three with ExactView (1.0× at exact viewW × viewH, cadence 1, all five passes):

Tier Projected viewport area Resolution scale Base cadence multiplier (base = 2) Enabled ViewSchedulePass flags Disabled on RenderViewDesc
Seamless (ExactView) Any visible opening Exact viewW × viewH 1 frame (every frame) All 5 (Opaque, Transparency, Shadows, Post, Volumetrics) None
High (Textured) ≥ 8% (0.08) 1.00× 1× → every 2 frames All 5 passes None
Medium (Textured) 2% – 8% (0.02..0.08) 0.75× 2× → every 4 frames Opaque, Transparency, Shadows, Post disableGodRays = true
Low (Textured) < 2% (< 0.02) 0.50× 4× → every 8 frames Opaque, Transparency, Post disableShadows = true, disableGodRays = true

Lowering qualityImportance (from RenderViewConfig::glbPortalImportance) stretches cadence gently without breaking visibility or the hard 8-frame ceiling: < 0.67 adds +1 to the multiplier, and < 0.34 doubles it, always clamped to [1, maximumAgeFrames].

Two-part chart of Play2Train's portal importance tiers and multi-portal frame pacing. The top panel compares the three projected screen-area tiers for Textured portals under default configuration: Low (area under 2 percent, 0.50x resolution, 8-frame cadence, 3 of 5 passes skipping shadows and volumetrics), Medium (2 to 8 percent area, 0.75x resolution, 4-frame cadence, 4 of 5 passes skipping volumetrics), and High (8 percent or more area, 1.00x resolution, 2-frame cadence, all 5 passes), noting Seamless overrides to every frame at exact viewport size. The bottom dark panel shows an 8-frame pacing schedule (F1 to F8) for 1 Seamless doorway plus 3 static Textured portals (High, Medium, Low) under a 2-update / 4.0 ms budget (2.0 ms per capture): Seamless runs EXACT on every single frame F1 through F8; on cold-start F1 all three textured portals populate via CacheMiss (Medium and Low recording forcedBudgetOverrun); High refreshes cleanly on F3, F5, and F7; Medium hits BudgetReuse on F5 when Seamless and High fill the budget and catches up on F6; Low reuses its cached RGBA16F texture across F2 through F8 until its 8-frame maximum age triggers on F9.
Projected screen area dials down resolution, cadence, and expensive passes for distant textured portals, while budgets stagger refreshes smoothly across frames without ever starving seamless openings.

Quantized capture sizing, split-screen isolation, and persistent camera IDs

Four runtime infrastructure details inside PortalSystem.cpp prevent the memory leaks, flickering, and split-screen bugs that commonly show up once a portal system enters daily production:

  1. Area-based, 8-pixel-quantized baseline sizing. Rather than allocating textured portal buffers relative to the full backbuffer (which wastes VRAM in split-screen), EnsureCaptureTexturesAllocated scales the baseline capture size (512 × 512 at 1080p) by sqrt((canvasW * canvasH) / (1920 * 1080)), clamps the scale to [0.5, 2.0], quantizes dimensions up to multiples of 8 pixels (captureQuantizeMultiple = 8), and clamps to [64, 2048]. Quantizing stops a 1-pixel viewport jitter during window resizing or split-screen layout from thrashing GPU texture allocations every frame.
  2. Per-slot split-screen ownership without material mutation. In split-screen, Player 1 and Player 2 stand in different places, so the exact same portal surface must show two different captured views in the same frame! PortalSystem maintains dual slot tables (slot 0 and slot 1) for frame captures (m_pairCapturesBySlot), persistent cadence captures (m_persistentCapturesBySlot), capture cameras (m_captureCamerasBySlot), and renderer-facing RenderPortalSurfaceOverride maps (m_surfaceOverridesBySlot). In mono mode, slot 1 is cleared immediately so no VRAM sits idle. Crucially, SetActiveSurfaceMaterialSlot publishes a per-view override table to the renderer instead of mutating MeshRenderer materials mid-render.
  3. Stable capture-camera identities across frames (and safe mid-frame edits). The renderer keys per-camera temporal caches (such as HZB occlusion pyramids) by Camera::GetStableId(). If PortalSystem constructed a fresh Camera object every frame, every portal would leak or rebuild temporal renderer state 60 times a second! Instead, CaptureCameraSet keeps a std::deque<Camera> per (pairKey, portalIdx, sideIdx, viewSlot) across frames:
    • Each frame resets usedThisFrame to 0 and assigns the n-th capture of that side to cameras[n] (preserving its GetStableId() across frames, and using a second camera if the same side is captured twice in one frame so already-queued RenderViewDesc pointers are never overwritten).
    • Because std::deque never invalidates element addresses on emplace_back, and stale pairs are pruned only between frames inside BeginFrame(), even renaming or destroying a portal between Player 1's and Player 2's view submissions inside the same frame leaves the already-queued capture camera valid until EndFrame() (verified directly by QueuedCaptureOutlivesItsPairChanging in tests/native_portals.cpp).
  4. Structured scheduler telemetry (SchedulingMetrics). GetSchedulingMetrics() exposes a versioned contract (kContractVersion = "portal-view-scheduler/1") tracking per-frame and cumulative counts (considered, rendered, reused, cacheMisses, cadenceReuses, budgetReuses, forcedBudgetOverruns, motionInvalidations, topologyInvalidations, maximumAgeRefreshes, recursionRejections, tier histograms, maximumObservedCacheAge, estimatedConsumedMs, and live persistent RGBA16F memory usage at 8 bytes/pixel). External systems such as HDRI/lighting swaps (ModernGame_Lighting.cpp) or player portal traversal (ModernGame_Gameplay.cpp) call InvalidateCaptureCache(), bumping m_captureCacheGeneration so the next visible portal refreshes immediately instead of flashing a stale lighting frame.

Honest boundaries and where the system stops

Play2Train's portal headers and tests are explicit about the limits of this design — keeping the runtime predictable instead of chasing fragile edge cases:

  • Single-scene pairs only. Cross-scene linkedEndpoint links are detected during discovery, logged once with a clear diagnostic, and ignored. Portals connect coordinates inside one active Scene (combining with WorldStreamingSystem cell prefetch hints for distant areas).
  • Bounded single-level recursion. maximumRecursionDepth defaults to 1 and capture views strip RenderLayers::PortalSurface from their visibilityMask, so portals do not recursively draw portals inside portals.
  • Matched shapes for seamless pairs. While textured portals gracefully scale mismatched rectangular openings, PortalComponent.h documents that seamless pairs must share equal (or uniformly scaled) half-extents so the carried screen-space perspective matches the opening's geometry without stretching.
  • Conservative occlusion and OIT behavior inside captures. Oblique projections automatically disable HZB occlusion culling (OcclusionCullingThisView) to prevent false-positive sphere culling, and GameEngine::RenderFrameViews disables weighted blended order-independent transparency (glbWeightedOITEnabled = false) during portal capture views so extent-cached scratch buffers cannot produce partial updates across rapid viewport changes.
  • Headless verification of the math and scheduling contracts. tests/native_portals.cpp runs without a window or display and verifies six invariants directly: oblique clipping keeps only the far side while leaving all 12 non-depth projection entries intact (even for grazing views), ExactView always overrides an exhausted budget, seamless captures carry the viewer's pose and screen-space overrides cleanly (including doorways beside the camera and one-sided back rejection), capture cameras preserve GetStableId() across frames and split-screen slots, mid-frame pair renames/deletions never dangle queued cameras, and textured portals retain their unclipped, scheduler-governed path.

Sources and further reading

  • Play2Train SDK (closed-source) — Gattic's internal C++23 engine containing src/engine/runtime/PortalSystem.h/.cpp, src/engine/runtime/PortalViewScheduler.h, src/engine/runtime/PortalMath.h, src/engine/components/PortalComponent.h, src/engine/runtime/RenderViewTypes.h, src/engine/runtime/RenderViewDesc.h, src/engine/runtime/GameEngine.cpp, src/engine/renderer/Renderer.h/.cpp, src/engine/renderer/RendererFrame.cpp, src/engine/renderer/RigidMaterialUniforms.h, src/engine/renderer/backends/vulkan/FullSceneRenderer.cpp, src/engine/renderer/backends/vulkan/SceneWorldProducer.cpp, src/math/matrix_utils.h, Resources/Shaders/Engine/default.frag.glsl, and tests/native_portals.cpp.
  • Eric Lengyel, "Oblique View Frustum Depth Projection and Clipping" (Journal of Game Development, 2005) — the mathematical foundation behind MatrixHelper::applyObliqueClipPlane.
  • Determinism as an Execution Contract in Play2Train — companion architecture deep dive covering DeterminismMode, queued pump points, stable parallelism, SSE MXCSR guards, and P2TR v6 replays.
  • Active Ragdolls with Staged Recovery in Play2Train — companion architecture deep dive covering Play2Train's soft D6 joint solver, implicit spring-damper drives, five-stage recovery state machine, and 1e6 J/kg fail-safe.
  • AI-Drivable Animation Authoring in Play2Train — companion architecture deep dive covering Play2Train's embedded Unix-socket posing server, two-bone IK, timeline HUD, and procedural quadruped generator.
  • Robot Universe (closed-source, in development) — open-world cyberpunk action adventure set in Haven City, consuming Play2Train::Engine and exercising PortalSystem for two-sided portals, world-streaming prefetch hints, and character traversal.
  • PloppyPals (closed-source, in development) — companion creature-care game built on Play2Train::Engine; it does not currently use portals.