Gorilla.Context.Backend Unit Reference
Overview
The Gorilla.Context.Backend unit selects the graphics backend (OpenGL / Vulkan), requests the high-performance GPU on hybrid systems, enumerates the physical GPUs of the machine and detects the hybrid copy-back constellation, in which one GPU renders the frame while another GPU scans out the display.
Nothing in this unit requires an OpenGL, Vulkan or Direct3D context — all functions may (and the configuration functions must) be called before Application.Initialize.
Calling convention: All functions are class methods of
TGorillaSystem(class function/class procedure) and are called without an instance, e.g.TGorillaSystem.GetGpuAdapters(LAdapters). The prose names them without the class prefix for readability.
Unit order:
Gorilla.Context.Backendis designed to be the first unit of the.dpr. It deliberately avoids pulling in FMX on Windows and Linux, so it stays loadable long before the FireMonkey framework is initialized.
Constants
PCI vendor ids, to be compared against TGorillaGpuAdapterInfo.VendorId / TGpuDisplayInfo.RenderAdapterVendorId:
GORILLA_GPU_VENDOR_NVIDIA = $10DE;
GORILLA_GPU_VENDOR_AMD = $1002; // AMD / ATI
GORILLA_GPU_VENDOR_INTEL = $8086;
GORILLA_GPU_VENDOR_MICROSOFT = $1414; // software adapters like WARP
GORILLA_GPU_VENDOR_QUALCOMM = $5143;
GORILLA_GPU_VENDOR_ARM = $13B5;
Conditional Defines
| Define | Effect |
|---|---|
| GORILLA_FORCE_HIGHPERFORMANCE_GPU | Calls ForceToUseNVIDIAorAMDGPU() in the initialization section of the unit — the earliest possible moment inside a Delphi process, before the .dpr body and before Application.Initialize. |
Types
TGorillaGraphicsBackend
TGorillaGraphicsBackend = (
gbDefault, // platform default: OpenGL / OpenGL ES
gbOpenGL, // explicitly select OpenGL / OpenGL ES
gbVulkan // explicitly select Vulkan (Windows, Linux, Android)
);
TGorillaGpuAdapterInfo
Description of a single physical GPU as reported by the operating system. Filled by GetGpuAdapters.
Fields
| Field | Type | Description |
|---|---|---|
| Name | String | Human readable adapter name, e.g. NVIDIA GeForce RTX 4070. |
| VendorId | UInt32 | PCI vendor id, compare against GORILLA_GPU_VENDOR_xxx. |
| DeviceId | UInt32 | PCI device id. |
| DedicatedVideoMemory | UInt64 | Size of the dedicated (on-board) video memory in bytes. |
| Luid | Int64 | Locally unique id of the adapter, stable while the system runs. On Linux derived from the PCI slot. |
| IsSoftware | Boolean | TRUE for software rasterizers (WARP / "Microsoft Basic Render Driver"). |
| OutputCount | Integer | Number of outputs DXGI reports for this adapter. Purely informational — see the caution below. |
| AttachedDisplayCount | Integer | Number of desktop displays this GPU really scans out, taken from the WDDM display path (D3DKMTOpenAdapterFromGdiDisplayName). |
| DrivesPrimaryMonitor | Boolean | TRUE when this adapter really scans out the primary monitor (Linux: the GPU marked by boot_vga). |
| DriverName | String | Name of the kernel driver bound to this GPU, e.g. nvidia, nouveau, amdgpu, i915. Linux only — empty on every other platform. |
| PciSlot | String | PCI slot of the GPU as 0000:01:00.0. Linux only — needed to build a DRI_PRIME selector. |
Caution: Do not derive display ownership from
OutputCount. On hybrid systems DXGI happily attributes the panel to the discrete GPU although the integrated GPU owns the display path. UseAttachedDisplayCount/DrivesPrimaryMonitor.
Methods
function VendorName() : String;
Returns a short vendor name derived from VendorId (NVIDIA, AMD, Intel, Microsoft, Qualcomm, ARM). Unknown vendors are returned as 0x%.4x.
function IsDiscreteVendor() : Boolean;
Returns TRUE for vendors that usually ship discrete GPUs (NVIDIA, AMD).
TGorillaGpuAdapterInfoArray
TGorillaGpuAdapterInfoArray = array of TGorillaGpuAdapterInfo;
TGpuDisplayInfo
Result of GetHybridGraphicsState — the render / display constellation of the system.
Fields
| Field | Type | Description |
|---|---|---|
| RenderAdapterName | String | GPU used for 3D rendering. |
| DisplayAdapterName | String | GPU used for display output. |
| IsHybridCopyBack | Boolean | TRUE when both adapters are not equal — every frame has to be copied between them. |
| Detected | Boolean | TRUE when render and display adapter could be identified reliably. When FALSE, IsHybridCopyBack is always FALSE and the name fields may be empty or best-effort guesses only. |
| RenderAdapterLuid | Int64 | LUID of the rendering GPU, 0 when unknown. |
| DisplayAdapterLuid | Int64 | LUID of the GPU driving the primary monitor, 0 when unknown. |
| RenderAdapterVendorId | UInt32 | PCI vendor id of the rendering GPU, 0 when unknown. |
| RenderAdapterHasOutputs | Boolean | TRUE when the rendering GPU scans out at least one desktop display. When this is TRUE while IsHybridCopyBack is TRUE, the user can escape the copy-back by moving the window to that monitor. |
| HardwareAdapterCount | Integer | Number of non-software adapters found in the system. |
IsHybridCopyBack is only set when all of the following hold — adapter names are never compared:
Detected and
(HardwareAdapterCount > 1) and
(RenderAdapterLuid <> 0) and
(DisplayAdapterLuid <> 0) and
(RenderAdapterLuid <> DisplayAdapterLuid)
TGorillaDisplayMode
A single video mode of a display. Filled by TGorillaSystem.GetDisplays.
| Field | Type | Description |
|---|---|---|
| Width | Integer | Horizontal resolution in physical pixels. |
| Height | Integer | Vertical resolution in physical pixels. |
| BitsPerPixel | Integer | Size of a framebuffer pixel in bits (usually 32), 0 when the platform does not report it. |
| RefreshRate | Double | Vertical refresh rate in Hz, 0 when unknown. |
| Method | Description |
|---|---|
ToString() : String |
e.g. 2560 x 1440, 32 bit, 143.97 Hz (invariant number format). |
IsSameMode(const AOther) : Boolean |
Same resolution and depth, refresh rates differ by less than 0.01 Hz. |
TGorillaDisplayModeArray = array of TGorillaDisplayMode;
TGorillaDisplayInfo
Description of a single display as reported by the operating system. Fields a platform cannot deliver stay 0 / empty — see GetDisplays.
| Field | Type | Description |
|---|---|---|
| DeviceName | String | OS name of the output. Windows: \\.\DISPLAY1; Linux: connector eDP-1; macOS: CGDirectDisplayID; Android: display id. |
| FriendlyName | String | Human readable monitor name, from the EDID where possible. |
| AdapterName | String | GPU that scans out this display (Windows, Linux). On hybrid systems the GPU owning the display path, not necessarily the rendering one. |
| AdapterId | Int64 | Id of that GPU — identical to TGorillaGpuAdapterInfo.Luid of the matching GetGpuAdapters entry. 0 when unknown. |
| Bounds | TRect | Position and size in the virtual desktop. Windows / Linux: pixels; macOS: points; Android: own coordinate space per display. |
| WorkArea | TRect | Bounds without task bar, dock, menu bar or system bars; equals Bounds where not reported (Linux). |
| IsPrimary | Boolean | Primary / main display. |
| CurrentMode | TGorillaDisplayMode | Active mode. |
| Modes | TGorillaDisplayModeArray | Supported modes, largest resolution / highest refresh first, no duplicates. Empty when AWithModes = False. |
| WidthMm, HeightMm | Integer | Physical image size in mm, 0 when unknown. |
| ScaleFactor | Single | UI scale, 1.0 = 100 % (96 dpi / 1x / mdpi). |
| Method | Description |
|---|---|
DiagonalInches() : Double |
Diagonal from the physical size, 0 when unknown. |
PixelsPerInch() : Double |
Horizontal pixel density of CurrentMode, 0 when the size is unknown. |
ToString() : String |
One line: name, device name, current mode, (primary). |
TGorillaDisplayInfoArray = array of TGorillaDisplayInfo;
Global Variables
var GorillaGraphicsBackend : TGorillaGraphicsBackend = gbDefault;
Global backend selector. Must be set before any Gorilla3D component is created.
{$IFDEF MSWINDOWS}
var
NvOptimusEnablement : UInt32;
AmdPowerXpressRequestHighPerformance : UInt32;
exports
NvOptimusEnablement,
AmdPowerXpressRequestHighPerformance;
{$ENDIF}
Exported symbols evaluated by the NVIDIA Optimus and the AMD PowerXpress driver to decide whether a process runs on the discrete GPU.
Notice: Delphi cannot export an initialized variable (
E2276), so the value cannot be baked into the export table of the image at link time like in C. It has to be assigned at runtime byForceToUseNVIDIAorAMDGPU, which only takes effect as long as the vendor OpenGL / Vulkan driver DLL has not been loaded yet. DefineGORILLA_FORCE_HIGHPERFORMANCE_GPUto have it assigned automatically in theinitializationsection of this unit.
Functions
class function TGorillaSystem.IsVulkanBackend() : Boolean; inline;
Returns TRUE when GorillaGraphicsBackend = gbVulkan.
class function TGorillaSystem.IsOpenGLBackend() : Boolean; inline;
Returns TRUE when GorillaGraphicsBackend is gbDefault or gbOpenGL.
class procedure TGorillaSystem.ForceToUseNVIDIAorAMDGPU();
Requests the best processor for work on systems with multiple GPUs — in most cases an NVIDIA or AMD GPU instead of an onboard Intel GPU.
| Platform | Behaviour |
|---|---|
| Windows | Sets NvOptimusEnablement := 1 and AmdPowerXpressRequestHighPerformance := 1. Cannot control the display output GPU. |
| Linux (NVIDIA proprietary) | __NV_PRIME_RENDER_OFFLOAD=1, __GLX_VENDOR_LIBRARY_NAME=nvidia, __VK_LAYER_NV_optimus=NVIDIA_only. |
| Linux (Mesa: amdgpu / radeon / nouveau) | DRI_PRIME=pci-<slot> (falls back to DRI_PRIME=1 when the slot is unknown) and MESA_VK_DEVICE_SELECT=<vendor>:<device>. |
| Linux (WSL2 / WSLg) | MESA_D3D12_DEFAULT_ADAPTER_NAME set from the vendor driver found below /usr/lib/wsl/lib. Nothing is set when the vendor cannot be determined. |
| Other platforms | No operation. |
On Linux nothing happens on a single-GPU system, and every variable is written with overwrite = 0, so an explicit setting made by the user or a launch script (DRI_PRIME=1 ./mygame) always wins.
Call this as early as possible — ideally as the very first statement of the
.dpr— because the vendor driver only evaluates the exported symbols / environment variables while its library is being loaded.
class function TGorillaSystem.GetGpuAdapters(out AAdapters : TGorillaGpuAdapterInfoArray) : Boolean;
Enumerates all GPUs of the system including the display outputs they really scan out. Does not need an OpenGL or Vulkan context.
Returns FALSE when the operating system offers no such enumeration.
| Platform | Source |
|---|---|
| Windows | IDXGIFactory1.EnumAdapters1 (only dxgi.dll is needed), display ownership resolved through the WDDM thunk D3DKMTOpenAdapterFromGdiDisplayName. When the thunk is unavailable, the DXGI output attribution is kept as best effort and AttachedDisplayCount falls back to OutputCount. |
| Linux | Walks /sys/class/drm/ — card* entries are GPUs, card*-<connector> entries are connectors whose status is counted; vendor, device, uevent (DRIVER, PCI_SLOT_NAME) and boot_vga fill the record, NVIDIA product names come from /proc/driver/nvidia/gpus/<slot>/information. Entries without a PCI vendor (virtual / vkms / simpledrm) are skipped. |
| WSL2 | Returns FALSE — /sys/class/drm holds a dxgkrnl node without any PCI attribute. |
| Other | Returns FALSE. On Android the renderer name is only known after the context has been created. |
class function TGorillaSystem.GetActiveDisplayAdapterName() : String;
Provides the first adapter name the operating system reports as attached to the desktop (Windows: EnumDisplayDevices). Empty string on other platforms.
class function TGorillaSystem.GetActiveRenderAdapterName() : String;
Provides the name of the GPU that will be used for rendering. On Windows this is the adapter Windows hands out for DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE — the same GPU the NVIDIA / AMD driver selects for a high-performance process. On Linux it is the discrete GPU the PRIME offload targets. Returns an empty string when it cannot be determined.
class function TGorillaSystem.GetHybridGraphicsState() : TGpuDisplayInfo;
Returns the GPU adapters and checks their equality, which tells whether the process runs in a hybrid copy-back scenario.
- Render adapter: DXGI 1.6 high-performance preference (Windows) / the discrete GPU (Linux). When DXGI 1.6 is unavailable (Windows 10 before build 1803), a discrete vendor is preferred, then the largest amount of dedicated video memory.
- Display adapter: the GPU owning the primary monitor, otherwise the first GPU scanning out any desktop display.
DisplayAdapterNamefalls back toGetActiveDisplayAdapterName()when the enumeration delivered nothing.
class function TGorillaSystem.GetGpuDiagnosticsReport() : String;
Builds a multiline, human readable report of all GPUs and the detected render / display constellation. Intended for log files and bug reports.
GPU adapters:
[0] NVIDIA GeForce RTX 4070 Laptop GPU (NVIDIA, device 0x28a0), displays 0, VRAM 8188 MB (dxgi outputs 1)
[1] Intel(R) Iris(R) Xe Graphics (Intel, device 0x46a6), displays 1, VRAM 128 MB, primary monitor
[2] Microsoft Basic Render Driver (Microsoft, device 0x008c), displays 0, software
Render adapter : NVIDIA GeForce RTX 4070 Laptop GPU
Display adapter: Intel(R) Iris(R) Xe Graphics
Detected : True
Hybrid copyback: True
Per adapter the line carries name, vendor, device id and AttachedDisplayCount, plus — when applicable — VRAM, the differing dxgi outputs count, the Linux driver, primary monitor and software. When the enumeration fails, the report states the reason (WSL, no PCI GPU below /sys/class/drm, or no enumeration on this platform).
class procedure TGorillaSystem.CheckHybridGraphicsState(const AThrowException : Boolean = false);
Checks for a hybrid copy-back scenario and reports it. Does nothing when IsHybridCopyBack is FALSE.
The message names both GPUs, explains that every frame has to be copied back between them, and recommends the MUX switch / "Discrete GPU Only" option of the manufacturer's control software or BIOS. When RenderAdapterHasOutputs is TRUE it suggests moving the window to the monitor already driven by the dedicated GPU, otherwise connecting an external monitor to the dedicated GPU's video output.
AThrowException |
Behaviour |
|---|---|
| True | Raises an Exception carrying the message. |
| False (default) | Windows: MessageBoxW (warning icon, topmost). Linux: written to ErrOutput — a stock Delphi Linux target has no FMX, so pass True or evaluate GetHybridGraphicsState yourself for a GUI message. Other platforms: ShowMessage. |
class function TGorillaSystem.GetDisplays(out ADisplays : TGorillaDisplayInfoArray;
const AWithModes : Boolean = true) : Boolean;
Enumerates all displays attached to the desktop with their current and supported modes. Does not need an OpenGL or Vulkan context. Returns FALSE when no display was found or the platform offers no enumeration (iOS). AWithModes = False skips the mode list — CurrentMode is filled anyway.
| Platform | Source |
|---|---|
| Windows | EnumDisplayMonitors / GetMonitorInfo (bounds, work area, primary), EnumDisplaySettings (modes), monitor EDID from HKLM\SYSTEM\CurrentControlSet\Enum\<instance>\Device Parameters (name, physical size), D3DKMTOpenAdapterFromGdiDisplayName (scanning GPU), GetDpiForMonitor from shcore.dll, resolved dynamically (scale; system DPI before Windows 8.1). |
| Linux | XRandR via dlopen of libX11.so.6 / libXrandr.so.2: every output that is connected and driven by a CRTC. Refresh rate computed from the mode timings (dotClock / (hTotal · vTotal), interlace / doublescan corrected), EDID from the EDID output property, scale from Xft.dpi. The DRM connectors below /sys/class/drm add the EDID where X has none and the owning GPU (via PCI_SLOT_NAME). Without an X server the connectors alone are reported: position unknown, CurrentMode = preferred EDID timing. |
| macOS | CGGetActiveDisplayList, CGDisplayBounds, CGDisplayCopyDisplayMode / CGDisplayCopyAllDisplayModes (desktop-usable modes, pixel size via CGDisplayModeGetPixelWidth), CGDisplayScreenSize; NSScreen for localizedName (10.15+), visibleFrame (converted to top-left origin) and backingScaleFactor. Call from the main thread. |
| Android | DisplayManager.getDisplays(): getRealMetrics (bounds, density, physical size from xdpi / ydpi), getMetrics (work area), getRefreshRate, getSupportedModes (natural orientation). |
| iOS | Returns FALSE. |
class function TGorillaSystem.GetPrimaryDisplay(out ADisplay : TGorillaDisplayInfo;
const AWithModes : Boolean = true) : Boolean;
Returns the display marked primary, or the first one when the platform marks none. FALSE when GetDisplays found nothing.
class function TGorillaSystem.GetDisplayDiagnosticsReport() : String;
Multiline report of all displays for log files and bug reports:
Displays:
[0] Lenovo DisplayHDR (\\.\DISPLAY1), primary
bounds 0,0 2560x1600, work area 0,0 2560x1552, scale 100%
current 2560 x 1600, 32 bit, 240.00 Hz, 52 modes
physical 345 x 215 mm, 16.0", 188 ppi
adapter Intel(R) Iris(R) Xe Graphics
Implementation Notes
IDXGIFactory5/IDXGIFactory6are not declared by the Delphi RTL (which stops atWinapi.DXGI1_4) and are declared inside this unit. Only the vtable layout matters; the inherited chain up toIDXGIFactory4is complete in the RTL.EnumDisplayDevicesandIDXGIAdapter.EnumOutputsare not trusted for display ownership. The first returns the GDI adapter string, which stays on the integrated GPU even after a MUX switch; the second attributes the panel to the discrete GPU although the integrated GPU owns the display path (measured on an RTX 4070 Laptop + Iris Xe).- sysfs reads use a plain
TFileStreamloop. sysfs reports a size of one page (4096) for every attribute while the actual read returns far fewer bytes, soTStringList.LoadFromFile/TFile.ReadAllTextraise. Missing attributes are the normal case and never travel as an exception, so the debugger does not stop on every probe. dxgi.dllis delay loaded by the RTL; a missing library is caught and simply reported as "no enumeration available".- Display enumeration on Windows only collects the
HMONITORhandles inside theEnumDisplayMonitorscallback; all further work happens outside, so no Delphi exception can travel throughuser32frames. - XRandR records are declared with
NativeUIntfor every Cunsigned long(XID, Atom, Time) — LP64. A compile-time check ({$MESSAGE ERROR}) guards the struct sizes against<X11/extensions/Xrandr.h>. While enumerating, a no-op Xlib error handler is installed, because the default handler terminates the process onBadRROutput/BadRRCrtc(monitor unplugged between two requests). NSScreen.localizedNameandCGDisplayModeGetPixelWidth/Heightare missing in the Delphi RTL and declared inside this unit.
Usage Notes
- Unit order: List
Gorilla.Context.Backendfirst in theusesclause of the.dprand applyGorillaGraphicsBackend/ForceToUseNVIDIAorAMDGPUbeforeApplication.Initialize. - Automatic GPU forcing: Define
GORILLA_FORCE_HIGHPERFORMANCE_GPUinstead of callingForceToUseNVIDIAorAMDGPUmanually when you cannot guarantee the call site runs early enough. - Copy-back cannot be fixed in software: Forcing the discrete GPU changes who renders, not who scans out. Report the state to the user (
CheckHybridGraphicsState) and logGetGpuDiagnosticsReport(). - Detection is conservative: Never treat
Detected = Falseas "no hybrid system" — it means the constellation could not be determined on this platform. - Diagnostics are context free:
GetGpuAdapters,GetHybridGraphicsStateandGetGpuDiagnosticsReportcan also be called later at runtime, for example behind a diagnostics menu item.