Viewport
The TGorillaViewport is the primary container for Gorilla3D scenes. It replaces FireMonkey's standard TViewport3D and TForm3D components and serves as the main rendering surface for 3D content.
Important: Gorilla3D is not compatible with TForm3D and TViewport3D. Always use TGorillaViewport for Gorilla3D applications.
Creating a Viewport
Design-Time Creation
- Locate TGorillaViewport in the tool palette under the Gorilla3D section
- Drag and drop it onto your form
- The viewport will typically be set to align client by default
Runtime Creation
var
Viewport: TGorillaViewport;
begin
Viewport := TGorillaViewport.Create(Self);
Viewport.Parent := Self;
Viewport.Align := TAlignLayout.Client;
Viewport.Color := TAlphaColors.Black;
end;
Transparent Background
If Color has an alpha value below 255, the viewport background becomes transparent:
components behind the viewport shine through, and only the rendered 3D content covers
them. The deferred composite pass keeps the alpha value instead of forcing it to 1.0.
// fully transparent - only the 3D objects are drawn over the form
GorillaViewport1.Color := TAlphaColorRec.Null;
// half transparent dark background
GorillaViewport1.Color := $80000000;
Note: Available since v1.5.3.3984.
Rendering Pipeline
TGorillaViewport uses a sophisticated rendering pipeline based on Weighted-Blended-Order-Independent-Transparency (WBOIT). The pipeline processes scenes through multiple stages:
Pipeline Stages
- Pre-processing Render Passes - Custom render passes executed before main rendering
- Main Render Pass
- Opaque objects rendering
- Transparent objects rendering (WBOIT)
- Emissive blurring
- Voxelization (for global illumination)
- Global illumination calculation
- Anti-aliasing (FXAA)
- Final compositing
- Post-processing Render Passes - Custom render passes executed after main rendering
Renderer Types
The viewport supports two renderer types:
Forward Renderer (Recommended)
Viewport.RendererType := TRendererType.ForwardRenderer;
The default renderer using WBOIT with multiple framebuffers and textures. Provides:
- Order-independent transparency
- Proper translucent object rendering
- Full support for Gorilla3D default materials
- Advanced effects (emissive blur, global illumination, etc.)
Legacy Renderer
Viewport.RendererType := TRendererType.LegacyRenderer;
A simple renderer with a single framebuffer. Use this when:
- You need maximum compatibility with FMX materials
- You're doing native OpenGL rendering
- Advanced Gorilla3D features are not required
Note: Legacy renderer has limited support for Gorilla3D default materials.
Key Properties
Frame Rate Control
Fixed Frame Rate
// Enable fixed framerate rendering (default on Windows, macOS, Linux and Android)
Viewport.UseFixedFrameRate := True;
Viewport.FixedFrameRate := 60; // 60 FPS
When enabled, the viewport renders continuously from its own frame rate tick and attempts to maintain a consistent frame rate. The rendered frames fire OnBeforeRender / OnAfterRender, see Frame Timing and Per-Frame Logic.
| Platform | Fixed frame rate | How the frames are rendered |
|---|---|---|
| Windows, macOS | ✓ (default True) |
Directly from the frame rate tick, the image is painted afterwards |
| Linux, Android | ✓ (default True, since v1.5.4) |
The tick only paces the rendering: each tick requests a paint, and the frame is rendered inside the regular FMX paint cycle |
| iOS | ✗ (always False) |
Event based only, setting UseFixedFrameRate has no effect |
Note: Before v1.5.4,
UseFixedFrameRatewas silently ignored on Linux and Android - both platforms always rendered event based.
On Linux and Android the frame rate therefore also depends on how fast FMX paints the form: if a paint takes longer than one tick, the frame rate drops below FixedFrameRate. The Skia display link presentation (see Skia) is only used on Windows.
VSync
Viewport.VSync := True;
Synchronizes rendering with the monitor's refresh rate, limiting the frame rate between FixedFrameRate and the monitor's maximum refresh rate.
Manual Rendering
Viewport.ManualRendering := True;
// Later, trigger rendering manually
Viewport.RenderManual();
Disables automatic rendering on property changes. Only takes effect with UseFixedFrameRate = False - the fixed frame rate tick keeps rendering regardless. Useful for:
- Precise control over rendering timing
- Performance optimization
- Integration with custom render loops
Use with TGorillaTimer for consistent intervals:
var
Timer: TGorillaTimer;
begin
Timer := TGorillaTimer.Create;
Timer.Interval := 16; // ~60 FPS
Timer.OnTimer := procedure(Sender: TObject)
begin
Viewport.RenderManual();
end;
end;
Performance Optimization
Frustum Culling
Viewport.FrustumCulling := True; // Default
Automatically culls objects outside the camera's view frustum. Significantly improves performance in large scenes.
Warning: May affect render passes using different view matrices.
Batching Updates
Viewport.BeginUpdate();
try
// Modify multiple properties
Viewport.FogDensity := 0.5;
Viewport.FogStart := 10.0;
Viewport.FogEnd := 100.0;
Viewport.FogColor := TAlphaColors.White;
finally
Viewport.EndUpdate();
end;
Batches multiple property changes into a single render instruction, improving performance.
Clipping Planes
Viewport.NearPlane := 0.1; // Default
Viewport.FarPlane := 10000.0; // Default
Controls the rendering clipping distances. Objects closer than NearPlane or farther than FarPlane are not rendered.
Render Resolution and Scaling
By default the scene is rendered in the native resolution of the viewport: one pixel of the render target per (logical) pixel of the viewport. The viewport can also render the scene in a different resolution and scale the finished image onto its area afterwards. The screen resolution of the monitor is not touched - only the internal render targets change.
Typical uses:
- Performance: render fewer pixels on weak GPUs or in fill-rate heavy scenes (
RenderScale := 0.5renders a quarter of the pixels) - Fixed game resolution: a resolution setting in your game options, e.g. 1280 x 720
- Supersampling: render more pixels than shown for smoother edges (
RenderScale := 2) - Pixel-art look: a very small resolution with blocky upscaling
There are two ways to set the resolution: a factor on the native size, or a fixed resolution in pixels.
Render Scale (Factor)
// half the width and height = a quarter of the pixels
Viewport.RenderScale := 0.5;
// supersampling: 4 times the pixels
Viewport.RenderScale := 2;
// back to the native resolution
Viewport.RenderScale := 1;
RenderScale multiplies the native size of the viewport (including the display scale of HighRes). Width and height are scaled alike, so the aspect ratio always stays the one of the viewport. The render resolution follows every resize of the viewport.
The value is clamped to 0.1 .. 4, the default is 1.
Fixed Render Resolution
// always render in 1280 x 720, whatever size the window has
Viewport.SetRenderSize(1280, 720);
// back to the native resolution
Viewport.SetRenderSize(0, 0);
A fixed resolution only takes effect if both RenderWidth and RenderHeight are greater than 0. Then it has priority and RenderScale is ignored. The default 0 x 0 means native resolution.
You can set the two published properties RenderWidth and RenderHeight one by one (e.g. in the Object Inspector). At runtime use SetRenderSize() or the public property RenderSize instead: they change both values with a single rebuild of the render targets. Setting the properties one after the other rebuilds twice, and the first rebuild runs with a mixed, unwanted resolution.
// the same as SetRenderSize(1920, 1080)
Viewport.RenderSize := Point(1920, 1080);
// read the current setting - Point(0, 0) = native
var LSize := Viewport.RenderSize;
Note:
RenderSizeis not published, becauseTPointcannot be streamed.RenderWidthandRenderHeightare stored in the form file instead.
Aspect Ratio: Letterbox or Stretch
A fixed resolution can have a different aspect ratio than the viewport, e.g. 1280 x 720 (16:9) in a window of 1000 x 800. RenderFit decides how the image is placed:
| Value | Result |
|---|---|
TGorillaRenderFit.rfLetterbox (default) |
Keeps the aspect ratio of the render resolution. The image is centered and the free borders are filled black. Nothing is distorted. |
TGorillaRenderFit.rfStretch |
Stretches the image onto the whole viewport, like a low resolution in fullscreen mode. Objects appear distorted if the aspect ratios differ. |
Viewport.SetRenderSize(1280, 720);
Viewport.RenderFit := TGorillaRenderFit.rfStretch;
The camera projection is always built with the aspect ratio of the rendered image (GetRenderAspectRatio), so the scene itself is never distorted inside the image - only rfStretch distorts it when it is shown.
With RenderScale the aspect ratio is always the one of the viewport, so RenderFit has no effect there.
Note: The types are declared with scoped enums - always write the type name in front, e.g.
TGorillaRenderFit.rfLetterbox.
Upscaling Filter
RenderFilter sets the interpolation used when the image is scaled onto the viewport:
| Value | Result |
|---|---|
TGorillaRenderFilter.rflLinear (default) |
Smooth (bilinear) scaling |
TGorillaRenderFilter.rflNearest |
Blocky scaling, e.g. for a pixel-art look |
// retro look: 320 x 180 with hard pixels
Viewport.SetRenderSize(320, 180);
Viewport.RenderFilter := TGorillaRenderFilter.rflNearest;
The filter only matters while the render resolution differs from the viewport. Changing it does not rebuild anything, it only repaints.
Important:
rflNearestonly works on canvases that honor theHighSpeedflag ofTCanvas.DrawBitmap(Direct2D, Skia). The FMX GPU canvas always scales linear.
HighRes
HighRes renders in the physical resolution of the display instead of the logical one. On a monitor with a scaling of 150 % a viewport of 800 x 600 logical pixels then renders 1200 x 900 pixels. RenderScale multiplies on top of that:
| Viewport (logical) | Display scaling | HighRes |
RenderScale |
Render target |
|---|---|---|---|---|
| 800 x 600 | 150 % | False | 1 | 800 x 600 |
| 800 x 600 | 150 % | True | 1 | 1200 x 900 |
| 800 x 600 | 150 % | True | 0.5 | 600 x 450 |
| 800 x 600 | any | any | any | 1280 x 720 with SetRenderSize(1280, 720) |
A fixed resolution ignores the display scaling: it is always exactly the given number of pixels.
Querying the Current Resolution
| Method | Returns |
|---|---|
IsRenderScaled() |
True if the scene is not rendered in the native resolution, because a fixed resolution or a RenderScale other than 1 is set |
HasFixedRenderResolution() |
True if RenderWidth and RenderHeight are both greater than 0 |
GetRenderTargetSize() |
Size in pixels the scene is really rendered in - the fixed resolution, or the viewport size multiplied by the display scale (HighRes) and RenderScale |
GetRenderDisplayRect() |
Rectangle in local viewport coordinates the image is shown in. LocalRect, except for a letterboxed fixed resolution |
GetRenderAspectRatio() |
Aspect ratio (width / height) of the rendered image |
var LSize := Viewport.GetRenderTargetSize();
Label1.Text := Format('Rendering in %d x %d', [LSize.X, LSize.Y]);
Render Passes
Render passes without an individual size (OverwriteViewportSize = False) automatically render in the same resolution as the main pass. You do not need to adjust them. Passes with an individual size (e.g. shadow maps) keep their own resolution. See Render Pass Controller.
Mouse Picking and Coordinates
All methods that take or return a position in the viewport work in local viewport coordinates - what the user sees, e.g. the mouse position from OnMouseDown. The mapping onto the render target (scale, letterbox offset, stretch) is done internally. This applies to ScreenToWorld, WorldToScreen, RayCastIntersect, ObjectAtPoint and the mouse events of 3D objects.
If you call the render context yourself (e.g. TContext3D.Pick or TGorillaContext.ScreenToWorld), convert the point first:
| Method | Converts |
|---|---|
ViewToRenderPoint(P) |
local viewport coordinates → coordinates the render context expects for picking |
RenderToViewPoint(P) |
the inverse |
Both return the point unchanged as long as neither a render resolution nor HighRes on a scaled display is in use.
Performance Notes
- Every change of
RenderWidth,RenderHeight,RenderSize,RenderScale,RenderFitorHighResrebuilds the render targets of the viewport and of all render passes, like a resize of the window. Do not change them every frame. - The cost of a frame mostly grows with the number of rendered pixels.
RenderScale := 0.5renders a quarter,RenderScale := 2four times the pixels. A value of 2 or more costs a lot of GPU memory with large windows. - For anti-aliasing at moderate cost,
MSAAorFXAAare usually cheaper than supersampling.
Example: Quality Setting in a Game Menu
procedure TForm1.ApplyResolution(const AIndex: Integer);
begin
case AIndex of
0: GorillaViewport1.SetRenderSize(0, 0); // native
1: GorillaViewport1.SetRenderSize(1920, 1080); // Full HD
2: GorillaViewport1.SetRenderSize(1280, 720); // HD
3: GorillaViewport1.SetRenderSize(854, 480); // low
end;
end;
procedure TForm1.ApplyPerformanceMode(const AEnabled: Boolean);
begin
// only effective without a fixed resolution
if AEnabled then
GorillaViewport1.RenderScale := 0.75
else
GorillaViewport1.RenderScale := 1;
end;
Frame Timing and Per-Frame Logic
Game logic such as movement, input handling or AI needs two things: a place that is called once per frame, and the time that passed since the previous frame. The viewport provides both: the OnBeforeRender event and the DeltaTime property.
How a Frame Is Produced
A frame is triggered either by the fixed frame rate tick (UseFixedFrameRate = True) or by an FMX paint after the viewport was invalidated (UseFixedFrameRate = False). From there every frame runs through the same steps:
- Frame clock advances -
PreviousFrameTime,CurrentFrameTimeandDeltaTimeare updated. OnBeforeRender(Sender, DeltaTime)- your per-frame logic.- Scene is rendered - the rendering list is collected, render passes and the main pass run.
OnAfterRender(Sender, DeltaTime)- read the results of the frame.- Frame is booked into
DiagnosticsandFramesPerSecond- only while measuring, see Performance Monitoring.
A frame only counts if it is really rendered. If the viewport cannot render (not visible, LockRendering, no context yet), all five steps are skipped: the clock does not advance, no event fires and nothing is counted. A paint that only shows the image rendered before (for example when FMX repaints the form) is not a frame either.
DeltaTime, CurrentFrameTime, PreviousFrameTime
| Property | Type | Meaning |
|---|---|---|
CurrentFrameTime |
Double | Start of the current frame in seconds, counted from the first rendered frame of this viewport |
PreviousFrameTime |
Double | Start of the previous frame in seconds, on the same clock |
DeltaTime |
Double | CurrentFrameTime - PreviousFrameTime - the seconds to scale per-frame movement with. 0 on the first frame |
The clock is the wall clock, measured with a high resolution stopwatch. Everything between two frames is included: the frame rate limit of UseFixedFrameRate and VSync, and any other work on the main thread. At 60 FPS DeltaTime is about 0.0167.
The values are set once per frame, before OnBeforeRender, and stay the same for the whole frame, including all render passes. You can read them anywhere during or after the frame, for example in OnRender of an object.
The frame clock always runs. It does not depend on DiagnosticsActive or DiagnosticsMeasuring.
Gaps are not clamped. While nothing is rendered (window hidden,
LockRendering, application halted in the debugger) the clock stands still, and the first frame afterwards reports the whole gap asDeltaTime- several seconds after a breakpoint. Clamp it in your game logic if objects must not jump (see the example below).
OnBeforeRender and OnAfterRender
type
TGorillaFrameEvent = procedure(ASender: TObject; const ADeltaTime: Double) of object;
Both events are published on TGorillaViewport, receive DeltaTime as ADeltaTime and are not called at design time.
OnBeforeRender |
OnAfterRender |
|
|---|---|---|
| Called | Before the scene is rendered | After the frame is complete |
| Changes you make | Show in this frame | Show from the next frame on |
| Use for | Game logic: move, add or remove objects, input, camera | Read results: Diagnostics, a screenshot, statistics |
| Render lock | Runs inside the render lock | Runs after the lock is released |
| Frame aborted | Not called | Not called |
uses
System.Math;
procedure TForm1.GorillaViewport1BeforeRender(ASender: TObject;
const ADeltaTime: Double);
const
MAX_STEP = 0.1; // never advance more than 100 ms in one frame
var
LDelta: Single;
begin
LDelta := Min(ADeltaTime, MAX_STEP);
// 90 degrees per second - independent of the frame rate
GorillaCube1.RotationAngle.Y := GorillaCube1.RotationAngle.Y + 90 * LDelta;
end;
Rules for OnBeforeRender:
- It runs on the main thread and adds to every frame - keep it fast.
- Moving, adding and removing objects is fine, the rendering list is collected right after the event.
- Do not free the viewport, call
Application.ProcessMessagesor render the viewport yourself (RenderManual) inside the event.
Why Not OnPaint or a Timer?
OnPaintfollows FMX painting, not rendered frames. FMX repaints the viewport for many reasons (form repaints, overlapping controls) and then only shows the last rendered image. WithUseFixedFrameRatethe scene is rendered by the frame rate tick and painted separately (on Linux and Android every tick requests a paint, but other repaints show the last image again), soOnPaintmatches neither the number of frames nor their timing.- A
TTimerruns at its own interval, unrelated to the frames. Logic and rendering drift apart, which shows up as stutter.
OnBeforeRender fires exactly once for every frame that reaches the screen, with and without UseFixedFrameRate.
When Frames Are Rendered
| Mode | Frames (and therefore the events) come ... |
|---|---|
UseFixedFrameRate = True (default on Windows, macOS, Linux and Android) |
continuously from the frame rate tick, limited by FixedFrameRate / VSync |
UseFixedFrameRate = False (iOS, or switched off) |
whenever the viewport is invalidated, e.g. by a changed object or a running animation |
ManualRendering = True with UseFixedFrameRate = False |
only when you call RenderManual() |
Outside the fixed frame rate the events therefore only fire while something makes the viewport render. For a game loop that must run continuously, use UseFixedFrameRate - available on all platforms except iOS.
Fog Configuration
Fog is a scene-wide atmospheric effect that requires TGorillaDefaultMaterialSource materials.
Enabling Fog
Viewport.Fog := True;
Viewport.FogKind := TGorillaFogKind.fkLinear;
Viewport.FogStart := 50.0;
Viewport.FogEnd := 200.0;
Viewport.FogColor := TAlphaColors.Lightgray;
Fog Modes
| Mode | Description | Use Case |
|---|---|---|
| fkLinear | Linear fog calculation | Outdoor scenes, precise control |
| fkExp | Exponential fog | Atmospheric effects, realistic fog |
| fkExp2 | Exponential squared | Dense fog, underwater effects |
Fog Parameters
// For linear fog
Viewport.FogStart := 50.0; // Distance where fog starts
Viewport.FogEnd := 200.0; // Distance where fog is maximum
// For exponential fog (fkExp, fkExp2)
Viewport.FogDensity := 0.05; // Density of fog
// Fog appearance
Viewport.FogColor := TAlphaColors.Lightgray;
Important: Fog only works with TGorillaDefaultMaterialSource materials, not standard FMX materials.
Rendering Effects
Saturation Control
Control color saturation for different rendering stages:
// Opaque objects saturation
Viewport.OpaqueSaturation := 0.0; // 0 = no saturation effect
// Translucent objects saturation
Viewport.TranslucentSaturation := 1.5;
// Final composition saturation
Viewport.CompositeSaturation := 0.0;
Note: Saturation only affects ForwardRenderer and DeferredRenderer, not LegacyRenderer.
Emissive Blur
Viewport.EmissiveBlur := 3; // 0 = disabled
Controls the intensity of emissive material blurring. Higher values create a stronger glow effect but significantly impact performance by increasing blur iterations and wideness.
Anti-Aliasing (FXAA)
Viewport.FXAA := 4; // 0-8, 0 = disabled
Fast Approximate Anti-Aliasing. Higher values = smoother edges but lower performance. Alternative to MSAA.
Viewport.MSAA := TMSAASamples.Samples4X; // Hardware MSAA
Fragment Depth Rendering
Viewport.FragmentDepthRendering := True;
Enables a pre-render pass that stores fragment depth for improved translucent rendering. Enhances visual quality but adds a render pass.
Tip: Disable if your scene has no transparent objects to improve performance.
Global Illumination
Global illumination provides realistic lighting with shadows and reflections through voxel-based rendering.
Availability: Only available in GAME_PACKAGE edition.
Configuration
// Set detail level (0-7)
Viewport.GlobalIllumDetail := 3; // 0 = off, 7 = highest quality
// Adjust rendering quality
Viewport.GlobalIllumSoftness := 1.0; // 0.0-5.0
Viewport.ShadowStrength := 0.4; // 0.0-10.0
Viewport.ReflectionStrength := 0.5; // 0.0-10.0
Detail Levels
| Level | Voxel Size | GPU Requirement | Min Texture3D Size |
|---|---|---|---|
| 0 | - | - | Global Illumination Off |
| 1 | 32 | Elder GPUs | 256 |
| 2 | 64 | Elder GPUs | 512 |
| 3 | 128 | Normal GPUs | 1024 |
| 4 | 192 | Normal GPUs | 2048 |
| 5 | 256 | Better GPUs | 2048 |
| 6 | 384 | High-performance GPUs | 4096 |
| 7 | 512 | High-performance GPUs | 4096 |
Parameters
- GlobalIllumSoftness: Controls how soft shadows and reflections appear (0.0 = sharp, 5.0 = very soft)
- ShadowStrength: Controls the darkness of global-illumination shadows (0.0 = invisible, 10.0 = very dark). This applies only to the GI pass — it has no effect on Cascaded Shadow Maps; for CSM darkness use
Viewport.Shadows.Strength(see Cascaded Shadow Maps). - ReflectionStrength: Controls reflection visibility (0.0 = invisible, 10.0 = very strong)
Advanced Features
Native OpenGL Rendering
You can implement custom OpenGL rendering via TDummy containers' OnRender events:
procedure TForm1.Dummy1Render(Sender: TObject; Context: TContext3D);
begin
// Your custom OpenGL code here
// You must manage transformation and projection matrices independently
Context.SetMatrix(TMatrix3D.Identity);
// ... custom rendering
end;
Graphics Library Selection
Modify the graphics library in your .dpr file before viewport initialization:
program MyApp;
uses
Gorilla.Context.Types;
begin
// Switch to OpenGL ES
GORILLA_CONTEXT_GRAPHICS_SETTINGS := TGorillaGraphicsLibrary.OpenGLES;
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
Available options (v1.1+):
TGorillaGraphicsLibrary.OpenGLTGorillaGraphicsLibrary.OpenGLES
Design Camera
The viewport includes a built-in design camera for development:
// Use design camera (default at design-time)
Viewport.UsingDesignCamera := True;
// Access design camera
var DesignCam := Viewport.GetDesignCamera();
// Access camera controller
var Controller := Viewport.GetDesignCameraController();
Edit Mode
Viewport.EditMode := True;
Enables interactive object manipulation at design-time and runtime with the gizmo tool.
Gizmo Control
// Show gizmo for an object
Viewport.ShowGizmo(MyMesh);
// Change gizmo mode
Viewport.ChangeGizmoMode(0); // 0=Translate, 1=Rotation, 2=Scale
// Check if active
if Viewport.IsGizmoActive() then
ShowMessage('Gizmo is active');
// Hide gizmo
Viewport.HideGizmo();
Coordinate System Conversion
Screen to World
var
ScreenPoint: TPointF;
WorldPoint: TPoint3D;
begin
ScreenPoint := PointF(100, 100);
WorldPoint := Viewport.ScreenToWorld(ScreenPoint);
end;
World to Screen
var
WorldPoint: TPoint3D;
ScreenPoint: TPointF;
begin
WorldPoint := Point3D(10, 0, 0);
ScreenPoint := Viewport.WorldToScreen(WorldPoint);
end;
Both methods work in local viewport coordinates, also with a changed render resolution - see Mouse Picking and Coordinates.
Object Selection
Ray Casting
var
ClickedObject: TControl3D;
MousePos: TPointF;
begin
MousePos := PointF(X, Y); // Mouse coordinates
ClickedObject := Viewport.RayCastIntersect(MousePos);
if Assigned(ClickedObject) then
ShowMessage('Clicked: ' + ClickedObject.Name);
end;
Screenshots
var
Screenshot: TBitmap;
begin
Screenshot := Viewport.MakeScreenshot();
try
Screenshot.SaveToFile('screenshot.png');
finally
Screenshot.Free;
end;
end;
The screenshot always has the size of the viewport (multiplied by the display scale), not the render resolution: an image rendered in a different resolution is scaled into it the same way it is shown on screen. With rfLetterbox the borders stay transparent in the screenshot instead of black.
Performance Monitoring
Measuring and Displaying Are Two Switches
| Property | Default | What it does |
|---|---|---|
DiagnosticsMeasuring |
True |
Collects the frame statistics: Diagnostics, FramesPerSecond, FPS |
DiagnosticsActive |
False |
Shows the diagnostics overlay on top of the rendered image |
The statistics are measured by default, whether the overlay is shown or not, so you can read FramesPerSecond or Diagnostics in your own UI without the overlay.
The measuring costs a little time in every frame (stopwatches, averaging). If you do not need the values, for example in a release build, switch it off:
Viewport.DiagnosticsMeasuring := False;
With DiagnosticsMeasuring = False:
FramesPerSecondand the frame rates and times inDiagnosticsread 0, as doesFPSwithoutUseFixedFrameRate(with it,FPScomes from the frame rate timer and keeps counting). The draw call, vertex and render pass counts inDiagnosticsare no longer updated.- Only the measuring stops, nothing that rendering needs.
DeltaTime,CurrentFrameTime,PreviousFrameTime,OnBeforeRenderandOnAfterRenderkeep working. - The overlay needs the values: with
DiagnosticsActive = Truethe viewport measures anyway. The same applies to the tick log (environment variableGORILLA_TICKLOG) andTGorillaViewport.ProfileMessagePump.
DiagnosticsMeasuring |
DiagnosticsActive |
Values measured | Overlay shown |
|---|---|---|---|
| True | False | ✓ | - |
| True | True | ✓ | ✓ |
| False | False | - | - |
| False | True | ✓ (forced by the overlay) | ✓ |
Every time one of the two switches changes, a new measure window starts. The first values after switching are therefore not mixed up with the time before the pause.
Three Frame Rates
The viewport reports three different frame rates. They answer different questions:
| Value | Question it answers | How it is computed |
|---|---|---|
Viewport.FramesPerSecond |
How many frames reach the screen per second? | Frames per second of wall clock. A frame limit shows up here: with UseFixedFrameRate it settles at FixedFrameRate. Same as Diagnostics.RealFramesPerSecond |
Diagnostics.AverageFramesPerSecond |
How fast could the renderer go? | 1000 / Diagnostics.AverageFrameTime - only the work inside one frame, without the idle time between two frames |
Viewport.FPS |
Legacy value | With UseFixedFrameRate the rate of the frame rate timer, otherwise an estimate from the scene rendering time |
FramesPerSecond and AverageFramesPerSecond are updated once per measure window, every Diagnostics.AverageFrameTimeClip (30) frames, and read 0 until the first window is complete. Compare the two:
- Both close together: the renderer sets the pace. To get more frames, make the scene cheaper.
AverageFramesPerSecondmuch higher: something outside the renderer sets the pace - the frame limit (FixedFrameRate,VSync) or other work on the main thread.
DeltaTime is not averaged: it is the time of exactly one frame. For a stable display value use FramesPerSecond, for movement use DeltaTime.
procedure TForm1.GorillaViewport1AfterRender(ASender: TObject;
const ADeltaTime: Double);
begin
Label1.Text := Format('%.0f fps (possible: %.0f), %d draw calls',
[GorillaViewport1.FramesPerSecond,
GorillaViewport1.Diagnostics.AverageFramesPerSecond,
GorillaViewport1.Diagnostics.DrawCalls]);
end;
Diagnostics
// Show the overlay
Viewport.DiagnosticsActive := True;
// Read the values (measured as long as DiagnosticsMeasuring is True)
var Diag := Viewport.Diagnostics;
The Diagnostics record contains:
- Frame count and average frame time (
TotalFrames,AverageFrameTimein ms) - Frame rates (
AverageFramesPerSecond,RealFramesPerSecond) - Draw calls and instances (
DrawCalls,DrawInstances) - Vertex and index counts (
TotalVertexCount,TotalIndexCount) - Render passes and object counts (
RenderPasses,RenderListSize,RenderedObjects) - Display refresh rate (
DisplayRefreshRate)
Read them in OnAfterRender, when the frame is complete.
Important Considerations
Animation Frame Rate Limitation
FireMonkey's TAnimation base class limits animation frame rates to 30 FPS. This is a FireMonkey limitation, not a Gorilla3D limitation. For movement that follows the real frame rate, animate in OnBeforeRender and scale by DeltaTime.
Translucent Rendering
Translucent rendering uses weighted color values requiring special GLSL calculations. The WBOIT algorithm provides order-independent transparency for correct rendering regardless of draw order.
Platform-Specific Features
- HighRes: Renders in the physical display resolution on high-DPI displays (Android, Windows with a display scaling above 100 %), see HighRes
- Fixed Frame Rate: Available on Windows, macOS, Linux and Android (Linux and Android since v1.5.4, paint paced). Not available on iOS. See Fixed Frame Rate
Material Compatibility
| Feature | Gorilla Materials | FMX Materials |
|---|---|---|
| Fog | ✓ Yes | ✗ No |
| Forward Renderer | ✓ Full Support | ○ Limited |
| Legacy Renderer | ○ Limited | ✓ Full Support |
| WBOIT Transparency | ✓ Yes | ○ Partial |
Best Practices
- Use BeginUpdate/EndUpdate when modifying multiple properties
- Enable FrustumCulling for large scenes
- Put per-frame logic into OnBeforeRender and scale it by
DeltaTime- not intoOnPaintor aTTimer - Disable FragmentDepthRendering if you have no transparent objects
- Start with GlobalIllumDetail level 3 and adjust based on performance
- Use ForwardRenderer unless you specifically need legacy compatibility
- Monitor Diagnostics during development to identify performance issues, and set
DiagnosticsMeasuring := Falsein release builds that do not show any frame statistics - Keep EmissiveBlur low (0-3) unless you specifically need strong effects
- Lower RenderScale (e.g. 0.75) on weak or fill-rate limited hardware instead of switching off effects, and use
SetRenderSize()for fixed resolution settings