Generated on 2026-11-08 11:32:26
We offer various ways to install Gorilla3D Addon Framework for Delphi. You can use the embedded GetIt Package Manager inside of your IDE, our installer tool or install the packages manually.
Embarcadero integrated Gorilla3D inside the IDE GetIt-Package-Manager for an easy installation process.

GetIt will do all the work for you including download, installation, configuration and the IDE restart afterwards.
Notice: GetIt-Package-Manager can only be used for Developer-Edition installation. If you bought a commercial license please use our Installer-Tool or the manual installation.
Notice: Due to delays in version rollout, the version in GetIt will not always be the latest package. If you're looking for the newest version, we recommend our Installer-Tool.
Gorilla Software provides an easy-to-use installer tool doing all the work for you to download, install and configure the packages in the IDE for you. The tool is able to manage Developer-Edition downloads or Commercial-Edition downloads with your individual credentials.
Download the Zip-Archive, extract it and run the "Gorilla3DInstaller.exe".
Download Installer for Windows
WARNING: Previously manually installed packages have to be uninstalled before running the installer. Otherwise path settings may be conflicting.

To install Gorilla3D packages correctly you have to follow the instructions.
You can download the latest Developer-Edition packages for your specific Delphi DX version at https://gorilla3d.de/files/
Go to the "packages" folder, choose your Delphi IDE version and download the highest version.
Latest Package for Community Edition: https://gorilla3d.de/files/packages/12.1.0/Gorilla3D_Delphi_C%2B%2B_12.1.0_1.1.13.3509.zip
The Developer-Edition is free for development purposes and max. 5 developers. When releasing your project you need to purchase a commercial license!
The free developer-edition contains the same features like the commercial version, it additionally contains multiple visual and hardcoded watermarks.
<installation-directory>).<installation-directory>\Win32\Release or <installation-directory>\Win64\Release (with 64-Bit IDE)Gorilla3D_Delphi_12_1_0_Athens.bplGorilla3D_DesignTime_12_1_0.bpl
After packages were added, we need to configure compiled source-code (DCU) paths.
Because the IDE has changed over the years, some configurations have been moved.
To insert DCU's go to:
<installation-directory>\Win32\Release\
To insert DCU's go to:
<installation-directory>\Win32\Release\By manual installation we need to take care of a few DLL files.
The IDE should be able to find those files at DesignTime, because while working in Delphi, the current directory is the IDE binary folder and not your project folder:
f.e. C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\
Copy OpenSSL DLL files to BDS directory or ensure the system is able to find them automatically by environment variables:
libeay32.dll and ssleay32.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\<installation-directory>\lib\WebView2\x86\WebView2Loader.dll from the package to the IDE binary folder C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\<installation-directory>\lib\WebView2\x64\WebView2Loader.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin64\<installation-directory>\lib\fmod\windows\fmodL.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\<installation-directory>\lib\fmod\windows\fmodL64.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin64\<installation-directory>\lib\Jolt\Windows\x86\Jolt32.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\<installation-directory>\lib\Jolt\Windows\x64\Jolt64.dll to C:\Program Files (x86)\Embarcadero\Studio\23.0\bin64\Notice: Take care of the IDE version used in the path. For community edition it is "23.0" for the latest Delphi IDE 13.0 it would be "37.0"!
After all steps were completed, you should restart the IDE.
Remark: Using Gorilla3D package in you project will force the IDE to use OpenGL instead of DirectX.
You can now start and enjoy the framework!
This guide outlines the hardware and software requirements for running the Gorilla3D Framework on different platforms.
Gorilla3D Framework is compatible with the following Delphi versions:
The framework includes C++ headers and library files for C++Builder compatibility. But we've tested support only since 11.3.
If you require packages for an IDE version not listed above (Delphi 10.1.1 or higher), please contact us through our support channels.
Gorilla3D is built for modern graphics hardware. It ships multiple rendering backends; the active backend can be selected at runtime via GorillaGraphicsBackend (see Windows):
| Backend | Platforms | Status |
|---|---|---|
| OpenGL / OpenGL ES (default) | Windows (x86/x64), Android, Linux | Reference implementation |
| Vulkan | Windows (x64) only | Experimental / opt-in |
| Metal | macOS, iOS | In active development |
Important: The framework prioritizes modern rendering techniques and does not support older graphics hardware. This decision enables us to leverage advanced graphics features and provide better visual quality. If a requested backend is unavailable on the target machine, the framework falls back to OpenGL.
The framework has been successfully tested on the following GPUs:
If you experience issues with your specific graphics hardware, please report them to help us improve compatibility and documentation.
Gorilla3D has been verified to work on the following Android devices:
| Device | Android Version | Status |
|---|---|---|
| LG D605 | 4.4.2 (KitKat) | Tested |
| Samsung Galaxy Tab A | 8.0 (Oreo) | Tested |
| Nokia 7 Plus | 9.0 (Pie) | Tested |
| Nokia 7 Plus | 10.0 | Tested |
| Google Pixel 6a | 15.0 | Tested |
| Google Pixel 9 | 16.0 | Tested |
For detailed Android development setup, deployment instructions, and troubleshooting, please refer to the Android documentation.
Since the release of Delphi 12.3, Gorilla3D can be compiled for the Linux 64-Bit platform. The graphics backend on Linux is OpenGL via Mesa / GLX through an X11 display surface.
libsk4d.so), PAServerLinux support is brand new with this release; a complete feature verification pass is still pending. See Linux for the full setup guide and feature matrix.
Gorilla3D supports macOS 64-Bit (Intel x64) through Apple's Metal graphics API (OpenGL is deprecated on macOS).
OSXARM64 build is on the roadmapmacOS support is in active development — several features are not yet implemented on the Metal backend. See macOS for the verified feature matrix and known issues before targeting a production release.
Running Gorilla3D in virtual machines requires special configuration due to OpenGL requirements.
Virtual machines need GPU passthrough enabled to provide proper OpenGL support. Without passthrough, the framework may not function correctly.
Add-VMRemoteFx3dVideoAdapter -VMName <MyVM>| Component | Requirement |
|---|---|
| IDE | Delphi 10.1.0+ or C++Builder 10.1.0+ (Delphi 12.3+ for Linux) |
| Graphics API | OpenGL 4.3+ (4.6 recommended); Vulkan 1.2 (Win64 only, opt-in); Metal (macOS) |
| Windows | Windows 10 / 11 with compatible graphics drivers |
| Android | Android 4.4.2+ (for mobile development) |
| Linux | x64 with X11 + Mesa (OpenGL 4.3+); FMXLinux + PAServer |
| macOS | Intel x64 (Metal-capable GPU); Xcode + PAServer |
| VM Environment | GPU passthrough enabled |
Once you've verified your system meets these requirements, proceed to the Installation Guide to set up Gorilla3D Framework.
For platform-specific setup, deployment and verified feature matrices, see the dedicated guides: Windows, Android, Linux and macOS.
If you have questions about system compatibility or encounter issues with your hardware configuration, please:
Gorilla3D Framework offers flexible licensing options to suit different development needs, from free development licenses to commercial packages for production applications.
The Developer Edition is perfect for learning, prototyping, non-commercial and non-published development.
Features:
Limitations:
Best For:
The Commercial Edition removes all restrictions and enables you to publish production-ready applications.
Features:
Licensing Requirements:
Best For:
Choose the package that matches your project requirements. Both packages include the same licensing terms.
Core 3D rendering capabilities for general-purpose 3D applications.
Included Features:
Ideal For:
Everything in the BASIC PACKAGE plus game-specific features and systems.
Additional Features:
Ideal For:
All packages support the following target platforms:
| Platform | Architecture | Status |
|---|---|---|
| Windows | 32-bit | Fully Supported |
| Windows | 64-bit | Fully Supported |
| Android | 32-bit | Partially Supported (JOLT not supported yet) |
| Android | 64-bit | Partially Supported (JOLT not supported yet) |
| Linux | 64-bit | Partially Supported (JOLT not supported yet) |
Stay current with the latest features and improvements:
If you have a valid subscription, you can renew at the end of the period. We will give you a discount on the current package price.
NOTICE: If your subscription expired, you have to buy again and pay the full price.
All Commercial Edition customers receive access to:
Our software is available for purchase on a try-before-you-buy basis. We provide a developer edition to let customers fully evaluate against their needs before making a purchase decision.
Customers should use the developer edition to make sure that the software meets their needs before purchasing a license. All of our software is fully functional inside the developer edition. Our software does not require registration.
Please note: Once the software is registered and unlocked we will be unable to offer a refund, we therefore advise customers to make full use of the developer edition, to ensure the software meets their specific needs.
During your test period, our support staff are available to assist in installation, configuration and usage via our help desk or our software support forum. We strongly recommend that all customers, install, and test developer versions of any product prior to making a purchase.
If you purchase one of our products, after your payment has cleared you will receive an email as part of the order process and will be asked to supply data to unlock your copy of your purchased program. During this time, you will receive regular e-mails to verify information and to advise you of progress. Orders maybe cancelled any-time before the unlock code is supplied, thereafter no refunds will be given.
In rare instances and only within 30 days of purchase, if due to technical difficulties or platform incompatibilities the software will not function, we may, at our discretion, issue a refund. In such instances, we require that you provide enough information for us to positively identify your purchase transaction (e.g., order number, your company name, date of transaction, purchase code, number of licenses purchased). If we are able to positively identify your order, and if your request is made within 30 days of purchase, you must submit to us a letter of destruction of software on your company letterhead before we will process the refund. ´Gorilla Software Eric Berger´ is not responsible for lost, delayed, or misdirected mail or email, delays for downloading, or other communication system delays.
Acceptance of this Refund Policy
It is your responsibility to familiarise yourself with this refund policy. By placing an order for any of our software, you indicate that you have read this refund policy and that you agree with and fully accept the terms of this refund policy.
If you do not agree with or fully accept the terms of this refund policy, we ask that you do not place an order with us.
Please send any questions regarding our refund policy to: support@gorilla3d.de.
Educational institutions and students may qualify for special pricing:
Pricing adjustments available for certain regions:
Ready to upgrade to the Commercial Edition?
| Feature | Developer Edition | Commercial Edition |
|---|---|---|
| Price | Free | Paid (see website) |
| Watermarks | Yes (visual + code) | None |
| Publishing Rights | No | Yes |
| Team Size | Up to 5 developers | Unlimited (1 license each) |
| Project Limit | Unlimited | Unlimited |
| Updates | Free during development | Optional subscription |
| Support | Community | Priority + Portal |
| License Duration | Forever | Forever (buy once) |
Q: Can I start with Developer Edition and upgrade later? A: Yes! Start with the free Developer Edition, and when you're ready to publish, purchase a Commercial license. Your code and projects remain compatible.
Q: Do I need to pay again for updates? A: No. Your license is perpetual. Update subscriptions are optional and provide access to new features, but you can continue using your version indefinitely.
Q: How many licenses do I need for my team? A: Developer Edition supports up to 5 developers for free. Commercial Edition requires one license per developer/machine.
Q: Can I use one license on multiple machines? A: No. Each license is tied to a single machine. If you work on multiple computers, you'll need separate licenses.
Q: What's the difference between BASIC and GAME packages? A: BASIC provides core 3D rendering. GAME adds audio, physics, particles, and game-specific systems like terrain and inventory.
Q: Do licenses expire? A: Never. "Buy once, keep it forever." Optional update subscriptions are for accessing new features only.
Not sure which edition or package is right for you?
LModel := TGorillaModel.LoadNewModelFromFile(GorillaViewport1, nil,
'Regular_Male_FullBody.gltf', GORILLA_ANIMATION_CACHING_DEFAULT);
LModel.Parent := GorillaViewport1;
LModel.AddAnimationFromFile('Animations\UAL1.glb', GORILLA_ANIMATION_CACHING_DEFAULT);
LModel.AnimationManager.PlayAnimation('Walk_Loop');
// put on an outfit and hide the body beneath it
LOutfit := LModel.AddSkinnedMeshFromFile('Clothes\Male_Ranger.gltf',
TGorillaSkinnedMeshOptions.Create(true));
// ... take it off again
LModel.RemoveSkinnedMesh(LOutfit);
if GorillaModel1.IsAnimationPlaying('walk') then
GorillaModel1.ResetToBindPose();
// re-bake only selected animations, drop the cache of others
GorillaModel1.RecacheAnimationsByName(['walk', 'run']);
GorillaModel1.DiscardAnimationCacheByName(['idle']);
// performance mode: a quarter of the pixels
GorillaViewport1.RenderScale := 0.5;
// fixed game resolution, letterboxed
GorillaViewport1.SetRenderSize(1280, 720);
GorillaViewport1.RenderFit := TGorillaRenderFit.rfLetterbox;
// back to the native resolution
GorillaViewport1.SetRenderSize(0, 0);
AI coding assistants such as Claude, GitHub Copilot or Cursor know FireMonkey well, but they have seen little Gorilla3D code. Without the documentation they tend to guess class names, properties and methods, or fall back to standard FMX components like TViewport3D, which are not compatible with Gorilla3D. This page shows how to give your assistant the complete, version-matching Gorilla3D documentation.
There are two ways:
| Option | Best for | Content |
|---|---|---|
| Claude Skill | Claude Code, Claude Desktop, claude.ai | The complete documentation of one version as a ZIP, including rules and an index |
| llms.txt | Any other AI tool or chatbot | An index and a single-file version of the documentation, available online |
A skill is a folder with instructions and reference material that Claude loads automatically when a task matches. Claude first only sees the name and description of the skill. When you work on Gorilla3D code, it reads the skill's overview and then only the documentation pages it needs, for example the particle reference for a particle effect. This keeps the context free for your own code.
Open the version overview of the documentation (click Version Overview or select a version on the start page) and click Export for AI. You receive a ZIP file named like gorilla3d-v1-5-skill-2026-10-13.zip.
Direct download for this version: https://docs.gorilla3d.de/export/zip?version=v1.5
Important: Use the skill of the Gorilla3D version you develop with. The API changes between versions, and the skill only describes the version it was exported from.
The ZIP contains one folder:
gorilla3d-v1-5/
├── SKILL.md rules for Gorilla3D development and an overview of all sections
├── INDEX.md every page with a short description
├── references/ all documentation pages as Markdown, same structure as this site
└── data/images/ images used by the pages
Unzip the archive so that the gorilla3d-v1-5 folder lies in one of the skill directories of Claude Code:
<your project>/.claude/skills/gorilla3d-v1-5/
Recommended if you have projects with different Gorilla3D versions. You can also commit the folder to your repository, so every developer of the team uses the same documentation.%USERPROFILE%\.claude\skills\gorilla3d-v1-5\ on Windows, ~/.claude/skills/gorilla3d-v1-5/ on macOS and Linux.Make sure SKILL.md is directly inside the gorilla3d-v1-5 folder and not in an additional subfolder created by your unzip tool.
Start a new Claude Code session afterwards. Claude now uses the skill automatically when you work with Gorilla3D. You can also call it explicitly with /gorilla3d-v1-5.
Open Settings, go to the skills section (under Capabilities) and upload the ZIP file as it is. Code execution must be enabled for skills to work. The skill is then available in all your chats.
When you update Gorilla3D, download the skill of the new version and remove the old one. Several installed Gorilla3D skills of different versions confuse the assistant, because it cannot know which version your project uses.
For assistants without skill support, the documentation is available in the llms.txt format:
| File | Content |
|---|---|
| https://docs.gorilla3d.de/llms.txt | Index of the latest version, every page with a short description and a link to its Markdown source |
| https://docs.gorilla3d.de/llms-full.txt | Complete documentation of the latest version in one file |
https://docs.gorilla3d.de/llms-v1.5.txt |
Index of a specific version |
https://docs.gorilla3d.de/llms-full-v1.5.txt |
Complete documentation of a specific version |
How to use them depends on the tool:
https://docs.gorilla3d.de/llms-full-v1.5.txt as a documentation source.llms-full-v1.5.txt, or single Markdown files from the references/ folder of the skill ZIP.llms-full is large. If your tool has a small context window, prefer the index or upload only the pages you need.
TGorillaViewport" leads the assistant to the right page faster than "make the scene look better".TGorillaParticleEmitter in the Gorilla3D docs and create a snow effect."Windows is the primary development and deployment target for Gorilla3D. Both 32-Bit (Win32) and 64-Bit (Win64) builds are fully supported and receive the most extensive testing of all platforms.
Gorilla3D ships two graphics backends on Windows:
When the Gorilla3D package is added to a project, the IDE is automatically forced to use the OpenGL renderer instead of DirectX in the FireMonkey designer. This is required for the framework's render passes and shaders to work consistently between design-time and run-time.
| Component | Minimum | Recommended |
|---|---|---|
| Operating System | Windows 10 | Windows 10 / 11 |
| Graphics API | OpenGL 4.3 | OpenGL 4.6 (2017+) or Vulkan 1.2 |
| GPU | OpenGL 4.3 capable, dedicated VRAM | Dedicated GPU with up-to-date driver |
| CPU | x86 (Win32) or x64 (Win64) | x64 multi-core |
| Delphi IDE | 10.1 Berlin | 12 Athens / 13 Florence |
For a list of GPUs that have been verified by us, see System Requirements.
By default Gorilla3D initializes the OpenGL context. To switch to Vulkan (Win64 only), set the renderer before any TGorillaViewport is created — typically in the project source (.dpr) before Application.Initialize:
uses
System.StartUpCopy,
Gorilla.Context.Backend, // first unit!
FMX.Forms, ...;
begin
{$IF Defined(MSWINDOWS) AND Defined(CPUX64)}
// Force Vulkan as graphics backend (Win64) before Application.Initialize
GorillaGraphicsBackend := gbVulkan;
{$ENDIF}
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
If the requested API is not available on the target machine, the framework falls back to OpenGL and writes a notice to the IDE event log / runtime log.
On notebooks with two GPUs (Intel/AMD integrated + NVIDIA/AMD discrete) the backend is only half of the story — which GPU renders and which GPU drives the panel decides the frame rate. See Graphics Backend & GPU Selection for forcing the discrete GPU and for detecting the hybrid copy-back scenario.
Depending on the features used by your application, the following libraries must ship next to the executable (or be available on PATH):
| Library | x86 path | x64 path | Required for |
|---|---|---|---|
libeay32.dll |
<install>\lib\OpenSSL\x86\ |
<install>\lib\OpenSSL\x64\ |
AssetsStore (HTTPS downloads) |
ssleay32.dll |
<install>\lib\OpenSSL\x86\ |
<install>\lib\OpenSSL\x64\ |
AssetsStore (HTTPS downloads) |
WebView2Loader.dll |
<install>\lib\WebView2\x86\ |
<install>\lib\WebView2\x64\ |
Sketchfab plugin login |
fmodL.dll |
<install>\lib\fmod\windows\ |
- | FMOD audio (Win32) |
fmodL64.dll |
- | <install>\lib\fmod\windows\ |
FMOD audio (Win64) |
Jolt32.dll |
<install>\lib\Jolt\Windows\x86\ |
- | JOLT physics (Win32) |
Jolt64.dll |
- | <install>\lib\Jolt\Windows\x64\ |
JOLT physics (Win64) |
Add these files via Project > Deployment so they are copied into the build output, or use the IDE deployment target Local Folder during development.
.skp) import is only supported on Win64 at runtime.The following matrix lists features that have been explicitly tested on Windows for the current release. Legend:
| Feature | OpenGL Win32/Win64 |
|---|---|
| FMX Primitives | ✅ |
| FMX MaterialSources | ✅ |
| Gorilla3D Primitives | ✅ |
| Gorilla3D Model | ✅ |
| Gorilla3D Model — STATIC | ✅ |
| Gorilla3D Model — Uncached Animations | ✅ |
| Gorilla3D Model — Cached Animations | ✅ |
| Gorilla3D Model — Instancing | ✅ |
| Texture formats other than BGRA | ✅ |
| Default Materials (Lambert, Phong, BlinnPhong) | ✅ |
| Sharing a G3D material with multiple objects | ✅ |
| Cross-Material (FMX ↔ G3D) test | ✅ |
| Pure Color material (no texture) | ✅ |
| VertexColor material | ✅ |
| No-Lighting tests | ✅ |
| POM material | ✅ |
| PBR material | ✅ |
| Atlas material (nearest texture limit) | ✅ |
| SplatMap material (extensive texture mapping) | ✅ |
| Layered materials | ✅ |
| Layer3D / Layout3D | ✅ |
| TextLayer3D | ✅ |
| Material Behaviours — fragment shaders (color adjust, rim light, caustics) | ✅ |
| Material Behaviours — vertex shaders (wobble, wind) | ✅ |
| Depth render pass | ✅ |
| Blur render pass | ✅ |
| EmissiveBlur | ✅ |
| Global Illumination | ✅ |
| WBOIT rendering | ✅ |
| Composite rendering (final image of opaque + translucent) | ✅ |
| OutputLayers | ✅ |
| Skybox — Procedural | ✅ |
| Skybox — Blank | ✅ |
| Skybox — CubeMap | ✅ |
| Reflection render pass | ✅ |
| Refraction render pass | ✅ |
| Environment mapping | ✅ |
| MSAA | ✅ |
| FXAA | ✅ |
| PostFX (with concat) | ✅ |
| User shader via VertexShader / SurfaceShader properties | ✅ |
| Water surface material | ✅ |
| Particle system — untextured | ✅ |
| Particle system — textured (smoke emitter) | ✅ |
| Volume rendering | ✅ |
OpenGL on Windows is the reference implementation — every Gorilla3D feature is verified here.
Vulkan support on Win64 is feature-rich but still considered experimental. Most rendering features pass parity tests with OpenGL; a few are still in evaluation or known not to work yet.
| Feature | Vulkan Win64 | Notes |
|---|---|---|
| FMX Primitives / MaterialSources | ✅ | |
| Gorilla3D Primitives / Model / Animations / Instancing | ✅ | |
| Texture formats other than BGRA | ✅ | |
| Default / Color / VertexColor / No-Lighting / POM / PBR materials | ✅ | |
| Atlas / SplatMap material | ✅ | |
| Layered materials | ❓ | Not yet fully verified |
| Layer3D / Layout3D / TextLayer3D | ❓ | Not yet fully verified |
| Material Behaviours — fragment & vertex shaders | ✅ | |
| Depth / Blur / EmissiveBlur | ✅ | |
| Global Illumination | ❌ | Not implemented for Vulkan yet |
| WBOIT / Composite / OutputLayers | ✅ | |
| Skybox (Procedural / Blank / CubeMap) | ✅ | |
| Reflection / Refraction render pass | ✅ | |
| Environment mapping | ❓ | Not yet fully verified |
| MSAA / FXAA / PostFX (concat) | ✅ | |
| User shaders | ✅ | |
| Water surface material | ✅ | |
| Particle system — untextured / textured | ✅ | |
| Volume rendering | ❌ | Not implemented for Vulkan yet |
Use OpenGL if you depend on Global Illumination or Volume Rendering. Vulkan is a good choice for deterministic frame timing and lower CPU overhead on modern GPUs.
libeay32.dll / ssleay32.dll are missing or the system's OpenSSL version does not match the Indy build used by Delphi. Copy the DLLs from the Gorilla3D package as described above.bin / bin64 folder. Copy the relevant DLL (FMOD, JOLT, WebView2) into C:\Program Files (x86)\Embarcadero\Studio\<ver>\bin[64]\.Jolt32.dll.Gorilla3D supports both Android 32-Bit (ARMv7) and Android 64-Bit (ARM64-v8a) as deployment targets. The renderer is OpenGL ES — version selection depends on the Delphi IDE you compile with.
Since August 2019 Google requires every new app and every update on Google Play to ship a 64-Bit binary. Producing a single 32-Bit-only build is therefore no longer an option for production releases — always deploy at least an ARM64-v8a APK / AAB.
| Delphi version | Default OpenGL ES | Notes |
|---|---|---|
| Delphi 10.1 / 10.2 | ES 2.0 | Render passes are limited; advanced post-processing is not available. |
| Delphi 10.3.x | ES 3.1+ | Requires NDK API level 21+. Order-Independent Transparency available since v0.8.1. |
| Delphi 10.3.3 | ES 3.1+ | Defaults to NDK API level 22. |
| Delphi 10.4 / 11 / 12 / 13 | ES 3.1+ | Recommended — full feature parity with Windows where the GPU allows. |
Important: Compilations with IDE versions older than 10.3.3 are considered deprecated for Android. We strongly recommend upgrading to the latest IDE before targeting Android.
Gorilla3D needs OpenGL ES 3.1, which requires NDK API level 18 at minimum and API level 21+ for Order-Independent Transparency.
android-18, replace it with at least android-18.android-21.If the linker complains about missing GLESv3 symbols (libGLESv3.so), the NDK API level is still too low — repeat the steps above and clean / rebuild the project.

Declare the OpenGL ES feature inside AndroidManifest.template.xml so the Play Store filters the APK to compatible devices:
<uses-feature
android:name="android.opengl.opengles"
android:glEsVersion="0x00030001"
android:required="true" />
If you target ES 3.2 features explicitly, change 0x00030001 to 0x00030002.
.gorilla, .glb, .gltf, …) and shaders to the assets\internal (or \library\lib\armeabi-v7a / arm64-v8a for native libs) destination.If you use third-party native libraries (FMOD, Jolt, …) make sure both the armeabi-v7a and arm64-v8a variants are deployed when you ship a universal APK. Mixed bitness will not load on the device.
We test on two reference configurations:
Legend: ✅ working — ❓ partially / not verified — ❌ not working / known issue
| Feature | BlueStacks (Android64) | Pixel 9 / Android 16 |
|---|---|---|
| FMX Primitives | ✅ | ✅ |
| FMX MaterialSources | ✅ | ✅ |
| Gorilla3D Primitives | ✅ | ✅ |
| Gorilla3D Model | ✅ | ✅ |
| Gorilla3D Model — STATIC | ✅ | ✅ |
| Gorilla3D Model — Uncached Animations | ✅ | ✅ |
| Gorilla3D Model — Cached Animations | ✅ | ✅ |
| Gorilla3D Model — Instancing | ✅ | ✅ |
| Texture formats other than BGRA | ✅ | ✅ |
| Default Materials (Lambert, Phong, BlinnPhong) | ✅ | ✅ |
| Sharing a G3D material with multiple objects | ✅ | ✅ |
| Cross-Material (FMX ↔ G3D) | ✅ | ✅ |
| Pure Color material | ✅ | ✅ |
| VertexColor material | ✅ | ✅ |
| No-Lighting tests | ✅ | ✅ |
| POM material | ✅ | ✅ |
| PBR material | ✅ | ✅ |
| Atlas material | ✅ | ✅ |
| SplatMap material | ✅ | ✅ |
| Layered materials | ❓ | ❓ |
| Layer3D / Layout3D | ❓ | ❓ |
| TextLayer3D | ❓ | ❓ |
| Material Behaviours — fragment shaders | ✅ | ✅ |
| Material Behaviours — vertex shaders (wobble, wind) | ✅ | ❌ only intermittent |
| Depth render pass | ✅ | ✅ |
| Blur render pass | ✅ | ✅ |
| EmissiveBlur | ✅ | ✅ |
| Global Illumination | ❓ | ❓ |
| WBOIT rendering | ✅ | ✅ |
| Composite rendering | ✅ | ✅ |
| OutputLayers | ✅ | ✅ |
| Skybox (Procedural / Blank / CubeMap) | ✅ | ✅ |
| Reflection render pass | ✅ | ✅ |
| Refraction render pass | ✅ | ✅ |
| Environment mapping | ❓ | ❓ |
| MSAA | ❌ | ❌ |
| FXAA | ✅ | ✅ |
| PostFX (with concat) | ✅ | ✅ |
| User shader via VertexShader / SurfaceShader | ✅ | ✅ |
| Water surface material | ❌ crashes when assigning textures | ❌ crashes when assigning textures |
| Particle system — untextured | ✅ | ✅ |
| Particle system — textured (smoke emitter) | ❌ rendered too dark | ❌ too dark; black fragments at blending edge when zooming out |
| Volume rendering | ❌ | ❌ |
glXxx (GLESv3)adb shell dumpsys SurfaceFlinger | findstr GLES.Since Gorilla Software became an official technology partner of Embarcadero in 2025, and with the release of Delphi 12.3, Gorilla3D can be compiled for the Linux 64-Bit platform. The graphics backend on Linux is OpenGL via Mesa / GLX through an X11 display surface.
Wayland is currently not supported. Make sure your session runs an X11 compositor (or XWayland), otherwise the framework cannot create a GL context.
To build and run Gorilla3D applications on Linux you need:
libsk4d.so) — modern FireMonkey applications require it.Linux64 target.We test against current Ubuntu LTS and Debian releases. Other distributions (Red Hat / Fedora, openSUSE, Arch) are expected to work as long as the package set below is satisfied — the package names and the package manager differ.
Install the X11 development headers and runtime:
sudo apt update
sudo apt install -y x11-apps libx11-dev libxext-dev libxrandr-dev libxi-dev libxcursor-dev libxfixes-dev
Install Mesa with up-to-date OpenGL support. On older Ubuntu releases the default Mesa is too old for OpenGL 4.3 — add the kisak-mesa PPA to upgrade:
sudo add-apt-repository ppa:kisak/kisak-mesa
sudo apt update
sudo apt install -y libgl1-mesa-dev libglu1-mesa-dev mesa-utils
Verify the OpenGL version after installation:
glxinfo | grep "OpenGL version"
You should see something like OpenGL version string: 4.6 (Compatibility Profile) Mesa 24.x.x. If the version is below 4.3, the GPU driver, the Mesa version or the active GLX renderer is the bottleneck.
WSL2 ships with a software renderer (d3d12) by default, which advertises only OpenGL 3.3 and is too slow for any non-trivial 3D content. Switch to the GPU exposed by your Windows host:
# Pick the physical GPU instead of the software adapter
export MESA_D3D12_DEFAULT_ADAPTER_NAME=NVIDIA # or "AMD", "Intel"
Make this permanent by adding it to your ~/.bashrc / ~/.profile. Inside Gorilla3D you can also set this from Pascal code before context creation:
uses
Gorilla.Context.Linux;
begin
TGorillaContextLinux.AUTO_SELECT_GPU := 'NVIDIA';
Application.Initialize;
// ...
end.
After switching the adapter, run glxinfo | grep "OpenGL version" again — the version must be 4.3 or higher.
Instead of setting the adapter manually, call
TGorillaSystem.ForceToUseNVIDIAorAMDGPU()as the first statement of your.dpr. It detects WSL2 and setsMESA_D3D12_DEFAULT_ADAPTER_NAMEfrom the vendor driver mounted below/usr/lib/wsl/lib, and on native Linux it enables PRIME render offload (__NV_PRIME_RENDER_OFFLOAD/DRI_PRIME/MESA_VK_DEVICE_SELECT). Variables you set yourself are never overwritten. See Graphics Backend & GPU Selection.
FireMonkey on Linux requires Embarcadero's FMXLinux library. It is distributed via GetIt:
Without FMXLinux the Linux64 platform will be available, but FireMonkey forms cannot be created and Gorilla3D will not link.
Modern FireMonkey applications use SKIA4Delphi as their 2D graphics renderer. Install the library and deploy libsk4d.so next to your binary on the Linux target:
linux-x64 archive and extract libsk4d.so..so as a deployment file for the Linux64 / Release configuration so PAServer copies it next to your executable. Alternatively install it system-wide into /usr/local/lib/ and run sudo ldconfig.PAServer is the Embarcadero Platform Assistant — the IDE talks to it over TCP to push binaries, debug and run on the target.
Copy PAServer-XX.X.tar.gz from your Delphi installation (PAServer/) to the Linux machine.
Extract and start it:
tar xzf PAServer-XX.X.tar.gz
cd PAServer-XX.X
./paserver
In the IDE go to Tools > Options > Deployment > Connection Profile Manager and create a new profile pointing at the Linux host and the password printed by PAServer.
libsk4d.so, your assets, and any third-party .so files you depend on.Linux support is brand new with this release. We have a working build pipeline through WSL2 with the kisak-mesa PPA, but a complete feature pass is still pending. The matrix below intentionally lists most entries as ❓ — the value will be filled in as the test suite progresses.
Legend: ✅ working — ❓ partially / not verified — ❌ not working / known issue
| Feature | Linux x64 (WSL / native) |
|---|---|
| FMX Primitives | ❓ |
| FMX MaterialSources | ❓ |
| Gorilla3D Primitives | ❓ |
| Gorilla3D Model | ❓ |
| Gorilla3D Model — STATIC | ❓ |
| Gorilla3D Model — Uncached / Cached Animations | ❓ |
| Gorilla3D Model — Instancing | ❓ |
| Texture formats other than BGRA | ❓ |
| Default Materials (Lambert, Phong, BlinnPhong) | ❓ |
| Sharing a G3D material with multiple objects | ❓ |
| Cross-Material (FMX ↔ G3D) | ❓ |
| Pure Color / VertexColor material | ❓ |
| POM material | ❓ |
| PBR material | ❓ |
| Atlas / SplatMap material | ❓ |
| Layered materials | ❓ |
| Layer3D / Layout3D / TextLayer3D | ❓ |
| Material Behaviours — fragment & vertex shaders | ❓ |
| Depth / Blur / EmissiveBlur | ❓ |
| Global Illumination | ❓ |
| WBOIT rendering | ❓ |
| Composite rendering | ❓ |
| OutputLayers | ❓ |
| Skybox (Procedural / Blank / CubeMap) | ❓ |
| Reflection / Refraction render pass | ❓ |
| Environment mapping | ❓ |
| MSAA / FXAA | ❓ |
| PostFX (with concat) | ❓ |
| User shader via VertexShader / SurfaceShader | ❓ |
| Water surface material | ❓ |
| Particle system — untextured / textured | ❓ |
| Volume rendering | ❓ |
If you run into specific feature failures on Linux, please file a report — Linux is the platform where community feedback shortens validation cycles the most.
XDG_RUNTIME_DIR not set — usually appears in fresh shells / over SSH. Either restart the desktop session or set export XDG_RUNTIME_DIR=/run/user/$(id -u) before launching.GLX: OpenGL 4.3 not supported — verify the active driver with glxinfo | grep "OpenGL renderer". On WSL2 set MESA_D3D12_DEFAULT_ADAPTER_NAME (see above). On native Linux make sure the proprietary NVIDIA driver (or mesa-vulkan-drivers + GLX) is installed.export GDK_BACKEND=x11) or log in to an X11 session.libsk4d.so: cannot open shared object file — deploy libsk4d.so next to the executable or install it system-wide and run sudo ldconfig.ldd ./MyApp shows unresolved shared libraries; strace -e openat ./MyApp shows where the loader is searching.For a deeper introduction to Linux deployment with Delphi, see Embarcadero's Linux Application Development documentation.
Check if all necessary libraries used by your application are available:
ldd /mnt/c/Temp/G3DDemo/G3DLinuxDemo
A classic runtime error 217 might occur, if anything is not correctly installed. You can run a check on your application with “strace”.
If you have not installed STRACE yet, run:
sudo apt-get install strace
Execute with stract for detailed output about the system flow:
strace /mnt/c/Temp/G3DDemo/G3DLinuxDemo
Gorilla3D supports macOS 64-Bit (Intel x64) through Apple's Metal graphics API. OpenGL has been deprecated on macOS by Apple — the framework therefore targets Metal as the primary backend on this platform.
macOS support is currently in active development. A working subset of the framework is verified, but several features are not yet implemented or have known issues. See the matrix below for details before committing to macOS for a production release.
OSX64 platform.The current macOS build targets Intel x64. On Apple-Silicon Macs the binary runs through Rosetta 2. A native OSXARM64 build is on the roadmap and will be added once we've stabilized the Metal toolchain for OSX64.
PAServer-XX.X.pkg from your Delphi installation to the Mac and run it./Applications) and note the password printed in the terminal window..dylib files.Gorilla3D's renderer is built around GLSL — every default material, render pass and behaviour ships its shader source as GLSL. Metal does not understand GLSL, so on macOS the framework needs to either translate GLSL into Metal Shading Language (MSL) at runtime, or fall back to hand-written MSL snippets that the framework compiles directly.
Both approaches coexist in the same project. You normally start with the parser and only hand-write MSL when the parser cannot represent a particular construct.
Each material / render pass stores its shaders in a list of architectures. Two are relevant on macOS:
GLSL-Arch — the GLSL source that drives OpenGL, OpenGL ES and (after on-the-fly translation) Vulkan. The Metal backend feeds this through the TGorillaParserGLSL translator and emits MSL.Metal-Arch — hand-written MSL source that bypasses the translator entirely.When the Metal backend prepares a shader, it picks the architecture in the following order:
Metal-Arch is registered → compile that MSL directly (fastest, no parsing).GLSL-Arch is registered → run the GLSL→MSL parser, compile the generated MSL.nil and the framework logs an error and skips the draw.Materials that already have a working GLSL implementation do not need a Metal-Arch entry in most cases — the parser handles them. Add a Metal-Arch only when you hit one of the parser limitations described below.
The translator (Gorilla.Material.Parser.GLSL.pas / Gorilla.Material.Parser.C.pas) walks the GLSL AST and emits MSL on the fly. It handles the bulk of the framework's built-in materials, including PBR, Lambert/Phong/BlinnPhong, Atlas, SplatMap, Layered, Layer3D and most material behaviours (color adjust, rim light, caustics, wobble, wind, …).
The translator also performs a few Metal-specific adaptations automatically:
buffer(0) = vertex data, buffer(1) = model matrix, buffer(2) = ShaderData UBO, buffer(N+2) = additional registered uniform blocks.std140 offsets are computed for the ShaderData struct so CPU-side uniform writes land at the same byte offset MSL reads from. The CPU buffer is uploaded as a single setVertexBytes / setFragmentBytes per draw._ProjectionMatrix, _ViewMatrix, …) inside the shader body are rewritten to struct-member access (params._ProjectionMatrix, …) where appropriate.colorf0 but the mesh has no vertex colors), the missing field is replaced by a constant default (float4(0)) so MSL still compiles.[[texture(N)]], [[sampler(N)]]) and never collide with buffer indices.The parser cannot represent every GLSL idiom. The cases below are the ones you are most likely to run into:
uniform declarations are dropped. Only uniform <Name> { … } blocks are translated. A bare uniform mat4 MyMatrix; will be silently ignored in the MSL output. Wrap individual uniforms in a layout block, or provide a Metal-Arch shader that accepts the value as a buffer.ShaderData (e.g. SkyBoxShaderData) are not auto-mapped to the params argument inside main(). Either rename to ShaderData or hand-write the MSL.ShaderData fields directly — only main() has params in scope. Pass the matrices/values as parameters into helpers (this is how Gorilla.Material.Behaviour.Wind.pas does it).mod() on a vector, smoothstep overloads, …) and get an MSL compile error, register it via DoRegisterEmbeddedFunc() or write the MSL by hand.When a shader cannot go through the translator (or when you simply want the lowest-overhead path), register an MSL source string under the Metal-Arch architecture. The framework compiles it with MTLLibrary newLibraryWithSource: and runs it directly.
The MSL must follow Gorilla3D's binding contract:
| Stage | Binding | Semantics |
|---|---|---|
| Vertex | [[buffer(0)]] |
VertexInput — generated from the mesh's vertex declaration via <#VertexDeclaration#>. |
| Vertex | [[buffer(1)]] |
ModelMatrixInput — per-instance model matrix (used for GPU instancing). |
| Vertex/FS | [[buffer(2)]] |
ShaderData — the std140-packed uniform block computed by the framework. |
| Vertex/FS | [[buffer(N+2)]] |
Additional registered UBOs (e.g. behaviour parameter blocks). N is the GLSL binding. |
| FS | [[texture(N)]] / [[sampler(N)]] |
Texture and sampler bindings, separate namespace from buffers. |
The framework provides a few placeholder tokens you can drop into your MSL source so the compiler stays in sync with the runtime:
<#VertexDeclaration#> — replaced by the active mesh's VertexInput struct.<#TVaryingStruct#> — replaced by the shared vertex→fragment varying struct.<#TRenderTargets#> — replaced by the MRT output struct (5 color attachments matching Gorilla3D's forward renderer).The framework also takes care of:
sign(params._ProjMatrix[1][1])) instead of negating in the matrix; FMX's projection convention conflicts with Metal's NDC.setFrontFacingWinding(MTLWindingClockwise) is configured globally to match FMX, no shader work required.[0..1]. The framework remaps the projection automatically; do not redo it in the shader.The pattern below mirrors how Gorilla.SkyBox.pas registers its hand-written shaders. Use it as a template when you need to bypass the translator for a custom material:
const
MSL_VS =
'#include <metal_stdlib>'#13#10 +
'using namespace metal;'#13#10 +
'<#VertexDeclaration#>'#13#10 +
'struct ModelMatrixInput { float4x4 ModelMatrix; };'#13#10 +
'struct ShaderData { float4x4 _ProjMatrix; float4x4 _ViewMatrix; };'#13#10 +
'<#TVaryingStruct#>'#13#10 +
'vertex TVaryingStruct vertexMain('#13#10 +
' VertexInput in [[stage_in]],'#13#10 +
' constant ModelMatrixInput& mm [[buffer(1)]],'#13#10 +
' constant ShaderData& params [[buffer(2)]]) { /* ... */ }';
MSL_FS =
'#include <metal_stdlib>'#13#10 +
'using namespace metal;'#13#10 +
'<#TVaryingStruct#>'#13#10 +
'<#TRenderTargets#>'#13#10 +
'fragment TRenderTargets fragmentMain(TVaryingStruct in [[stage_in]],'#13#10 +
' texturecube<float> cubeMap [[texture(0)]],'#13#10 +
' sampler cubeSampler [[sampler(0)]]) { /* ... */ }';
procedure RegisterMyMaterialShaders(const AMat : TGorillaMaterial);
begin
AMat.AddShaderArch('Metal-Arch', stVertex, MSL_VS, 'vertexMain');
AMat.AddShaderArch('Metal-Arch', stFragment, MSL_FS, 'fragmentMain');
end;
If you also keep the GLSL source for the OpenGL / Vulkan paths, simply register both architectures — the Metal backend picks Metal-Arch and the OpenGL / Vulkan backends pick GLSL-Arch.
ShaderData (e.g. SkyBoxShaderData).The framework writes MSL compile errors to FMX.Types.Log together with the generated source. Typical patterns:
no member named 'colorf0' in 'VertexInput' → the shader references a vertex attribute the mesh doesn't provide. The translator will normally patch this; if you are on Metal-Arch, declare a fallback or fix the mesh's vertex declaration.use of undeclared identifier '_ModelViewProjMatrix' → a loose uniform was dropped by the translator. Wrap it in a uniform ShaderData { … } block, or move it to Metal-Arch.'params' is unused / struct member not found → a helper function references params which is only in scope inside main(). Pass the value through as a parameter.Metal-Arch and GLSL-Arch produced no output. Check the log for the underlying parse / compile error.Tip: enable verbose logging on the Metal context to dump the generated MSL during development. Strip the dump again before shipping — the translator runs on every shader (re)compile.
Legend: ✅ working — ❓ partially / not verified — ❌ not working / known issue
| Feature | Metal / OSX64 |
|---|---|
| FMX Primitives | ❌ stretched (model-matrix issue) |
| FMX MaterialSources | ❌ |
| Gorilla3D Primitives | ✅ |
| Gorilla3D Model | ✅ |
| Gorilla3D Model — STATIC | ✅ |
| Gorilla3D Model — Uncached Animations | ✅ |
| Gorilla3D Model — Cached Animations | ✅ |
| Gorilla3D Model — Instancing | ✅ |
| Texture formats other than BGRA | ❌ |
| Default Materials (Lambert, Phong, BlinnPhong) | ✅ |
| Sharing a G3D material with multiple objects | ✅ |
| Cross-Material (FMX ↔ G3D) | ❓ |
| Pure Color material | ❓ |
| VertexColor material | ❓ |
| POM material | ❌ |
| PBR material | ❌ |
| Atlas material | ✅ |
| SplatMap material | ✅ |
| Layered materials | ✅ |
| Layer3D / Layout3D | ✅ |
| TextLayer3D | ✅ |
| Material Behaviours — fragment shaders (color adjust, rim light, caustics) | ✅ |
| Material Behaviours — vertex shaders (wobble, wind) | ✅ |
| Depth render pass | ✅ |
| Blur render pass | ❌ |
| EmissiveBlur | ❌ |
| Global Illumination | ❌ |
| WBOIT rendering | ✅ |
| Composite rendering | ✅ |
| OutputLayers | ✅ |
| Skybox — Procedural | ✅ |
| Skybox — Blank | ✅ |
| Skybox — CubeMap | ✅ |
| Reflection render pass | ✅ |
| Refraction render pass | ✅ |
| Environment mapping | ❌ |
| MSAA | ❌ |
| FXAA | ❌ |
| PostFX (with concat) | ❌ |
| User shader via VertexShader / SurfaceShader | ❌ |
| Water surface material | ❌ |
| Particle system — untextured | ✅ |
| Particle system — textured (smoke emitter) | ❌ particles too small and too dark |
| Volume rendering | ❌ |
MTLPixelFormat enumeration does not 1:1 map to OpenGL formats. The framework currently expects BGRA8 input on macOS; convert your textures before assignment.If macOS is on your release path, plan around these gaps and reach out to support so we can prioritize the features you depend on.
64211). Also check that the IDE's profile uses the same password PAServer printed.TGorillaTextureBitmap which handles channel order normalization.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.
var
Viewport: TGorillaViewport;
begin
Viewport := TGorillaViewport.Create(Self);
Viewport.Parent := Self;
Viewport.Align := TAlignLayout.Client;
Viewport.Color := TAlphaColors.Black;
end;
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.
TGorillaViewport uses a sophisticated rendering pipeline based on Weighted-Blended-Order-Independent-Transparency (WBOIT). The pipeline processes scenes through multiple stages:
The viewport supports two renderer types:
Viewport.RendererType := TRendererType.ForwardRenderer;
The default renderer using WBOIT with multiple framebuffers and textures. Provides:
Viewport.RendererType := TRendererType.LegacyRenderer;
A simple renderer with a single framebuffer. Use this when:
Note: Legacy renderer has limited support for Gorilla3D default materials.
// 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.
Viewport.VSync := True;
Synchronizes rendering with the monitor's refresh rate, limiting the frame rate between FixedFrameRate and the monitor's maximum refresh rate.
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:
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;
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.
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.
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.
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:
RenderScale := 0.5 renders a quarter of the pixels)RenderScale := 2)There are two ways to set the resolution: a factor on the native size, or a fixed resolution in pixels.
// 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.
// 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.
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.
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 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.
| 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 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.
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.
RenderWidth, RenderHeight, RenderSize, RenderScale, RenderFit or HighRes rebuilds the render targets of the viewport and of all render passes, like a resize of the window. Do not change them every frame.RenderScale := 0.5 renders a quarter, RenderScale := 2 four times the pixels. A value of 2 or more costs a lot of GPU memory with large windows.MSAA or FXAA are usually cheaper than supersampling.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;
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.
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:
PreviousFrameTime, CurrentFrameTime and DeltaTime are updated.OnBeforeRender(Sender, DeltaTime) - your per-frame logic.OnAfterRender(Sender, DeltaTime) - read the results of the frame.Diagnostics and FramesPerSecond - 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.
| 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).
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:
Application.ProcessMessages or render the viewport yourself (RenderManual) inside the event.OnPaint follows FMX painting, not rendered frames. FMX repaints the viewport for many reasons (form repaints, overlapping controls) and then only shows the last rendered image. With UseFixedFrameRate the 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), so OnPaint matches neither the number of frames nor their timing.TTimer runs 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.
| 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 is a scene-wide atmospheric effect that requires TGorillaDefaultMaterialSource materials.
Viewport.Fog := True;
Viewport.FogKind := TGorillaFogKind.fkLinear;
Viewport.FogStart := 50.0;
Viewport.FogEnd := 200.0;
Viewport.FogColor := TAlphaColors.Lightgray;
| 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 |
// 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.
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.
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.
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
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 provides realistic lighting with shadows and reflections through voxel-based rendering.
Availability: Only available in GAME_PACKAGE edition.
// 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
| 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 |
Viewport.Shadows.Strength (see Cascaded Shadow Maps).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;
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.OpenGLESThe 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();
Viewport.EditMode := True;
Enables interactive object manipulation at design-time and runtime with the gizmo tool.
// 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();
var
ScreenPoint: TPointF;
WorldPoint: TPoint3D;
begin
ScreenPoint := PointF(100, 100);
WorldPoint := Viewport.ScreenToWorld(ScreenPoint);
end;
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.
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;
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.
| 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:
FramesPerSecond and the frame rates and times in Diagnostics read 0, as does FPS without UseFixedFrameRate (with it, FPS comes from the frame rate timer and keeps counting). The draw call, vertex and render pass counts in Diagnostics are no longer updated.DeltaTime, CurrentFrameTime, PreviousFrameTime, OnBeforeRender and OnAfterRender keep working.DiagnosticsActive = True the viewport measures anyway. The same applies to the tick log (environment variable GORILLA_TICKLOG) and TGorillaViewport.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.
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:
AverageFramesPerSecond much 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;
// Show the overlay
Viewport.DiagnosticsActive := True;
// Read the values (measured as long as DiagnosticsMeasuring is True)
var Diag := Viewport.Diagnostics;
The Diagnostics record contains:
TotalFrames, AverageFrameTime in ms)AverageFramesPerSecond, RealFramesPerSecond)DrawCalls, DrawInstances)TotalVertexCount, TotalIndexCount)RenderPasses, RenderListSize, RenderedObjects)DisplayRefreshRate)Read them in OnAfterRender, when the frame is complete.
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 uses weighted color values requiring special GLSL calculations. The WBOIT algorithm provides order-independent transparency for correct rendering regardless of draw order.
| Feature | Gorilla Materials | FMX Materials |
|---|---|---|
| Fog | ✓ Yes | ✗ No |
| Forward Renderer | ✓ Full Support | ○ Limited |
| Legacy Renderer | ○ Limited | ✓ Full Support |
| WBOIT Transparency | ✓ Yes | ○ Partial |
DeltaTime - not into OnPaint or a TTimerDiagnosticsMeasuring := False in release builds that do not show any frame statisticsSetRenderSize() for fixed resolution settingsRenderers in Gorilla3D manage the rendering pipeline, controlling how 3D scenes are drawn to the screen. The framework provides different renderer types optimized for various use cases, with the Forward Renderer being the recommended default.
The default renderer using Weighted Blended Order Independent Transparency (WBOIT) for correct translucent object rendering regardless of draw order.
Features:
Use When:
Simple single-framebuffer renderer for maximum compatibility.
Features:
Use When:
The renderer is managed internally by the viewport:
// Get the main pass renderer
var Renderer := Viewport.MainPassRenderer;
// Get current active renderer (may differ during render passes)
var CurrentRenderer := Viewport.CurrentRenderer;
// Change renderer type
Viewport.RendererType := TRendererType.ForwardRenderer;
// or
Viewport.RendererType := TRendererType.LegacyRenderer;
Fragment Depth Pre-Pass (optional)
Viewport.FragmentDepthRenderingOpaque Rendering
Translucent Rendering
Post-Processing Passes
Compositing
Opaque Rendering
Translucent Rendering
Output
The Forward Renderer exposes various render targets for custom effects:
var
Renderer: TCompositeRenderer;
begin
if Viewport.MainPassRenderer is TCompositeRenderer then
begin
Renderer := Viewport.MainPassRenderer as TCompositeRenderer;
// Access render targets
var AlbedoTex := Renderer.AlbedoTexture; // Color
var NormalsTex := Renderer.NormalsTexture; // Normals
var PositionTex := Renderer.PositionTexture; // Positions
var EmissiveTex := Renderer.EmissiveTexture; // Emissive
var AlphaTex := Renderer.AlphaTexture; // Alpha
// Use in custom shaders or post-processing
end;
end;
Create glowing effects for emissive materials:
// Enable emissive blur (via viewport)
Viewport.EmissiveBlur := 3; // 0-10, higher = stronger glow
// Or via renderer
if Viewport.MainPassRenderer is TCompositeRenderer then
(Viewport.MainPassRenderer as TCompositeRenderer).EmissiveBlur := 3;
Performance Impact: Each increment adds blur iterations. Start low (2-3) and increase carefully.
Real-time voxel-based global illumination with shadows and reflections.
Availability: GAME_PACKAGE only
// Set quality level (0-7)
Viewport.GlobalIllumDetail := 3; // Good balance for normal GPUs
// Adjust appearance
Viewport.GlobalIllumSoftness := 1.0; // Shadow/reflection softness
Viewport.ShadowStrength := 0.4; // Shadow darkness
Viewport.ReflectionStrength := 0.5; // Reflection intensity
Quality Levels:
Post-process anti-aliasing alternative to MSAA:
// Enable FXAA
Viewport.FXAA := 4; // 0-8, higher = smoother but slower
Comparison:
You can use both together for best results on capable hardware.
Soft shadows computed in screen space.
Availability: If enabled in build
Viewport.SSS_Enabled := True;
Viewport.SSS_NumSamples := 128; // Lower for better performance
Viewport.SSS_SampleStep := 0.05; // Larger = wider shadow area
Viewport.SSS_ShadowStrength := 2.0; // Darkness
Warning: Very performance-intensive. Each light iterates all samples.
Adds realistic ambient shadows in crevices and corners.
Availability: If enabled in build
Viewport.SSAO_Enabled := True;
Viewport.SSAO_Radius := 1.0; // Sampling radius
Viewport.SSAO_Bias := 0.5; // Prevents self-shadowing
Viewport.SSAO_NoiseScale := PointF(1, 1);
Control color saturation at different rendering stages:
// Opaque objects - usually no adjustment needed
Viewport.OpaqueSaturation := 0.0; // 0 = no saturation effect
// Translucent objects - often benefits from extra saturation
Viewport.TranslucentSaturation := 1.5;
// Final composite - post-process saturation
Viewport.CompositeSaturation := 0.0;
Or via renderer:
if Viewport.MainPassRenderer is TCompositeRenderer then
with (Viewport.MainPassRenderer as TCompositeRenderer) do
begin
Saturation := Point3D(0, 1.5, 0); // X=Opaque, Y=Translucent, Z=Composite
end;
Visualize individual render passes for debugging:
// Show only normals
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputNormal;
// Show only albedo
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputAlbedo;
// Show positions
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputPosition;
// Show emissive only
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputEmissive;
// Show depth
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputDepth;
// Back to normal (all layers)
Viewport.RendererOutputLayer := TRendererOutputLayer.OutputAll;
Available Layers:
OutputAll - Normal renderingOutputAlbedo - Color/albedo onlyOutputTranslucentAlbedo - Translucent colorsOutputAlpha - Alpha channelOutputDepth - Depth bufferOutputPosition - World positionsOutputNormal - Surface normalsOutputEmissive - Emissive channelOutputComps - Material components (deferred)OutputAmbient - Ambient light (deferred)OutputSpecular - Specular light (deferred)OutputSSS - Screen space shadowsOutputSSAO - Ambient occlusion// Disable unused features
Viewport.FragmentDepthRendering := False; // If no transparency
Viewport.EmissiveBlur := 0; // If no glowing materials
Viewport.FXAA := 0; // If using MSAA or performance critical
// Reduce global illumination quality
Viewport.GlobalIllumDetail := 2; // Lower on older GPUs
// Disable expensive screen space effects
Viewport.SSS_Enabled := False;
Viewport.SSAO_Enabled := False;
The render resolution is set on the viewport, not on the renderer. The viewport rebuilds the main pass renderer and all render passes with the new size and scales the finished image onto its area.
// Render at half width and height (a quarter of the pixels) for performance
Viewport.RenderScale := 0.5;
// Or a fixed resolution, e.g. from a game options menu
Viewport.SetRenderSize(1280, 720);
Viewport.RenderFit := TGorillaRenderFit.rfLetterbox; // or rfStretch
Viewport.RenderFilter := TGorillaRenderFilter.rflLinear; // or rflNearest
// Back to the native resolution
Viewport.SetRenderSize(0, 0);
Viewport.RenderScale := 1;
The renderer reports the resulting size in pixels:
var LSize := Viewport.MainPassRenderer.Size; // = Viewport.GetRenderTargetSize()
Important: Do not set
TRenderer.SizeorTRenderer.Scaleyourself. The viewport overwrites them on the next resize.TRenderer.Scaleis the texture scale handed to the render context, not a resolution factor.
Render passes without an individual size (OverwriteViewportSize = False) render in the same resolution as the main pass. Passes with an individual size keep it.
See Render Resolution and Scaling for letterboxing, filters, HighRes and picking.
// High-end: Use both
Viewport.MSAA := TMSAASamples.Samples4X;
Viewport.FXAA := 2;
// Mid-range: MSAA only
Viewport.MSAA := TMSAASamples.Samples2X;
Viewport.FXAA := 0;
// Low-end: FXAA only
Viewport.MSAA := TMSAASamples.None;
Viewport.FXAA := 4;
// Minimum: Neither
Viewport.MSAA := TMSAASamples.None;
Viewport.FXAA := 0;
procedure ApplyLowQuality(AViewport: TGorillaViewport);
begin
AViewport.RenderScale := 0.75;
AViewport.MSAA := TMSAASamples.None;
AViewport.FXAA := 2;
AViewport.EmissiveBlur := 0;
AViewport.GlobalIllumDetail := 0;
AViewport.FragmentDepthRendering := False;
end;
procedure ApplyMediumQuality(AViewport: TGorillaViewport);
begin
AViewport.RenderScale := 1;
AViewport.MSAA := TMSAASamples.Samples2X;
AViewport.FXAA := 2;
AViewport.EmissiveBlur := 2;
AViewport.GlobalIllumDetail := 2;
AViewport.FragmentDepthRendering := True;
end;
procedure ApplyHighQuality(AViewport: TGorillaViewport);
begin
AViewport.RenderScale := 1;
AViewport.MSAA := TMSAASamples.Samples4X;
AViewport.FXAA := 4;
AViewport.EmissiveBlur := 4;
AViewport.GlobalIllumDetail := 5;
AViewport.FragmentDepthRendering := True;
end;
procedure SetupForRecording(AViewport: TGorillaViewport);
begin
// Maximum quality
AViewport.MSAA := TMSAASamples.Samples8X;
AViewport.FXAA := 6;
AViewport.EmissiveBlur := 5;
// Disable manual rendering for consistent frame output
AViewport.ManualRendering := False;
AViewport.UseFixedFrameRate := True;
AViewport.FixedFrameRate := 30; // Match video framerate
end;
Start with Forward Renderer: Use TRendererType.ForwardRenderer unless you have specific reasons for Legacy.
Enable Fragment Depth: Keep FragmentDepthRendering := True if you have any close up transparent objects.
Profile Before Optimizing: Use diagnostics to identify actual bottlenecks:
Viewport.DiagnosticsActive := True;
ShowMessage(Format('Draw Calls: %d, FPS: %.1f',
[Viewport.Diagnostics.DrawCalls, Viewport.Diagnostics.AverageFramesPerSecond]));
Scale Effects to Hardware: Test on minimum spec hardware and provide quality settings.
Debug with Output Layers: Use render target visualization during development to understand what's being rendered.
Global Illumination Requires Tuning: GI settings are scene-dependent. Experiment with softness and strength values.
Batch Rendering Changes: Use BeginUpdate/EndUpdate when changing multiple renderer settings.
Everything that decides which graphics API and which physical GPU your application runs on happens before the first Gorilla3D component exists. Gorilla.Context.Backend is the unit that controls it — backend selection, forcing the discrete GPU on hybrid laptops, enumerating the GPUs of the system and detecting the hybrid copy-back scenario that silently costs a large part of your frame rate.
Unit: Gorilla.Context.Backend
Platforms: Windows (full), Linux (full), WSL2 (reduced), Android / macOS (backend selection + display enumeration), iOS (backend selection only)
Important:
Gorilla.Context.Backendmust be the first unit in theusesclause of your.dprand every setting described here must be applied beforeApplication.Initialize. The vendor drivers evaluate the settings while their DLL / shared object is being loaded — afterwards they are ignored without any error message.
The unit covers four independent jobs:
| Job | Entry point |
|---|---|
| Choose OpenGL or Vulkan | GorillaGraphicsBackend |
| Ask the system for the discrete GPU | ForceToUseNVIDIAorAMDGPU |
| Enumerate all GPUs without a graphics context | GetGpuAdapters |
| Detect / report the hybrid copy-back scenario | GetHybridGraphicsState, CheckHybridGraphicsState, GetGpuDiagnosticsReport |
None of these functions needs an OpenGL, Vulkan or Direct3D context. They can — and should — run as the very first statements of your process.
Calling convention: All functions are class methods of
TGorillaSystemand are called without an instance, e.g.TGorillaSystem.ForceToUseNVIDIAorAMDGPU(). For readability, the text below names them without the class prefix; the code examples show the full call.
program MyProject;
uses
Gorilla.Context.Backend, // must be listed FIRST
System.StartUpCopy,
FMX.Forms,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
begin
{$IF Defined(MSWINDOWS) and Defined(CPUX64)}
GorillaGraphicsBackend := gbVulkan;
{$ENDIF}
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
| Value | Meaning |
|---|---|
gbDefault |
Platform default — OpenGL / OpenGL ES (default value) |
gbOpenGL |
Explicitly request OpenGL / OpenGL ES |
gbVulkan |
Explicitly request Vulkan (Windows x64, Linux, Android) |
Two inline helpers let you branch on the active backend anywhere in your code:
if TGorillaSystem.IsVulkanBackend() then
// Vulkan specific path
else if TGorillaSystem.IsOpenGLBackend() then
// OpenGL / GLES path (TRUE for gbDefault and gbOpenGL)
If the requested backend is not available on the target machine, the framework falls back to OpenGL. See Windows for the Vulkan feature matrix.
On a hybrid system (integrated GPU + discrete GPU) the operating system decides which GPU a process renders on. ForceToUseNVIDIAorAMDGPU requests the discrete one:
begin
TGorillaSystem.ForceToUseNVIDIAorAMDGPU(); // as early as possible!
Application.Initialize;
...
Or fully automatic — define GORILLA_FORCE_HIGHPERFORMANCE_GPU for your project and the unit calls it in its own initialization section, which is the earliest possible moment inside a Delphi process (before the .dpr body runs):
{$DEFINE GORILLA_FORCE_HIGHPERFORMANCE_GPU}
NVIDIA Optimus and AMD PowerXpress look for two exported symbols in the process image and switch to the discrete GPU when they are non-zero:
NvOptimusEnablement := 1;
AmdPowerXpressRequestHighPerformance := 1;
Why a runtime assignment and not a constant? Delphi cannot export an initialized variable (compiler error
E2276), so unlike in C the value cannot be baked into the export table of the image at link time. It has to be written at runtime, and it only takes effect as long as the vendor OpenGL / Vulkan driver DLL has not been loaded yet. That is exactly why the call has to be the first thing your process does.
Limitation: This selects the rendering GPU. It cannot change which GPU drives the display — that is what causes the copy-back described below.
Linux has no equivalent of the exported symbol. The GPU is selected through environment variables that libglvnd / Mesa / the Vulkan loader evaluate while they load their vendor library. ForceToUseNVIDIAorAMDGPU picks the discrete GPU (a discrete vendor that is not the one driving the console) and sets:
| Driver | Variables set |
|---|---|
Proprietary NVIDIA (nvidia) |
__NV_PRIME_RENDER_OFFLOAD=1, __GLX_VENDOR_LIBRARY_NAME=nvidia, __VK_LAYER_NV_optimus=NVIDIA_only |
Mesa stack (amdgpu, radeon, nouveau) |
DRI_PRIME=pci-0000_01_00_0 (unambiguous PCI form instead of the legacy DRI_PRIME=1), MESA_VK_DEVICE_SELECT=<vendor>:<device> |
| WSL2 / WSLg | MESA_D3D12_DEFAULT_ADAPTER_NAME=NVIDIA / AMD |
Nothing is done on a single-GPU system.
Your environment always wins. All variables are written with
overwrite = 0, so an explicit setting made by the user or by a launch script (DRI_PRIME=1 ./mygame) is never overwritten by Gorilla3D.
Inside WSL2 there is no PCI GPU enumeration at all — /sys/class/drm/card0 is a dxgkrnl node without vendor, device or boot_vga attributes and without any connector. Gorilla3D detects WSL, determines the vendor from the user-mode driver mounted below /usr/lib/wsl/lib (libnvidia-ml.so.1, nvidia-smi, libamdhip64.so, libhsa-runtime64.so) and sets MESA_D3D12_DEFAULT_ADAPTER_NAME accordingly. This replaces the manual assignment of TGorillaContextLinux.AUTO_SELECT_GPU. If the vendor cannot be determined, nothing is guessed. See Linux.
This is the single most common cause of "my 3D application runs at 20 FPS on a gaming laptop with an RTX GPU".
On a typical hybrid laptop the panel is physically wired to the integrated GPU, while your application renders on the discrete GPU:
+------------------+ PCIe copy per frame +-------------------+
| Discrete GPU | ----------------------> | Integrated GPU | --> Panel
| renders frame | (the "copy back") | scans out |
+------------------+ +-------------------+
Every single finished frame has to be copied from the video memory of the rendering GPU back over the PCIe bus into the memory of the display GPU before it can be shown. The effects are:
ForceToUseNVIDIAorAMDGPU cannot fix this. It makes the discrete GPU render — which is what you want — but the display path stays where the hardware put it. There are only three real remedies, and all of them live outside of the application:
TGpuDisplayInfo.RenderAdapterHasOutputs tells you whether such a monitor is already connected.That is why Gorilla3D does not try to work around the situation — it detects and reports it, so you and your users know what is going on instead of blaming the framework.
uses Gorilla.Context.Backend;
begin
TGorillaSystem.ForceToUseNVIDIAorAMDGPU();
// Shows a warning dialog when render GPU <> display GPU
TGorillaSystem.CheckHybridGraphicsState();
// ... or raise an exception instead of showing a dialog:
// TGorillaSystem.CheckHybridGraphicsState(True);
Application.Initialize;
CheckHybridGraphicsState does nothing at all when there is no copy-back. Otherwise it builds a message naming both GPUs, explaining the per-frame copy and listing the remedies above (including the "move the window" hint when the render GPU already drives a monitor) and then:
| Platform | Output |
|---|---|
| Windows | MessageBoxW with a warning icon — deliberately not FMX, so the unit stays usable as the very first unit of the .dpr |
| Linux | Written to stderr. A stock Delphi Linux target has no FMX (FmxLinux is a separate product), so pass AThrowException = True or evaluate GetHybridGraphicsState yourself when you want a GUI message |
| Other | ShowMessage |
var
LInfo : TGpuDisplayInfo;
begin
LInfo := TGorillaSystem.GetHybridGraphicsState();
if LInfo.IsHybridCopyBack then
begin
Log('Rendering on : ' + LInfo.RenderAdapterName);
Log('Displayed by : ' + LInfo.DisplayAdapterName);
if LInfo.RenderAdapterHasOutputs then
Log('Move the window to the monitor attached to the dedicated GPU.');
end;
end;
TGpuDisplayInfo| Field | Description |
|---|---|
RenderAdapterName |
GPU that will be used for 3D rendering |
DisplayAdapterName |
GPU that scans out the primary monitor |
IsHybridCopyBack |
TRUE when both are different — every frame is copied between them |
Detected |
TRUE only when both GPUs could be identified reliably. When FALSE, IsHybridCopyBack is always FALSE and the name fields may be empty or best-effort guesses |
RenderAdapterLuid |
LUID (Windows) / PCI slot id (Linux) of the rendering GPU, 0 when unknown |
DisplayAdapterLuid |
The same for the GPU driving the primary monitor |
RenderAdapterVendorId |
PCI vendor id of the rendering GPU, compare against GORILLA_GPU_VENDOR_* |
RenderAdapterHasOutputs |
TRUE when the rendering GPU scans out at least one desktop display. Combined with IsHybridCopyBack = TRUE this means the user can escape the copy-back by moving the window to that monitor |
HardwareAdapterCount |
Number of non-software adapters found in the system |
No false positives. A copy-back is only reported when both GPUs were identified by their LUID and both LUIDs differ. Adapter name strings are never compared — that would produce false positives as soon as one name is unknown or reported differently by two APIs.
var
LAdapters : TGorillaGpuAdapterInfoArray;
I : Integer;
begin
if TGorillaSystem.GetGpuAdapters(LAdapters) then
for I := 0 to High(LAdapters) do
if not LAdapters[I].IsSoftware then
Log(Format('%s (%s), %d MB VRAM, %d displays',
[LAdapters[I].Name,
LAdapters[I].VendorName(),
LAdapters[I].DedicatedVideoMemory div (1024 * 1024),
LAdapters[I].AttachedDisplayCount]));
end;
GetGpuAdapters returns FALSE when the operating system offers no context-independent enumeration (everything except Windows and native Linux — on Android the renderer name is only known after the context has been created).
TGorillaGpuAdapterInfo| Field | Description |
|---|---|
Name |
Human readable adapter name, e.g. NVIDIA GeForce RTX 4070 |
VendorId / DeviceId |
PCI ids — compare VendorId against the GORILLA_GPU_VENDOR_* constants |
DedicatedVideoMemory |
On-board video memory in bytes |
Luid |
Locally unique id, stable while the system runs (on Linux derived from the PCI slot) |
IsSoftware |
TRUE for software rasterizers (WARP / "Microsoft Basic Render Driver") |
OutputCount |
Number of outputs DXGI reports. Informational only — see the warning below |
AttachedDisplayCount |
Number of desktop displays this GPU really scans out |
DrivesPrimaryMonitor |
TRUE when this adapter really scans out the primary monitor / the console |
DriverName |
Kernel driver bound to the GPU (nvidia, nouveau, amdgpu, i915) — Linux only |
PciSlot |
PCI slot as 0000:01:00.0 — Linux only, needed to build a DRI_PRIME selector |
VendorName() |
Short vendor name derived from VendorId, hex fallback for unknown vendors |
IsDiscreteVendor() |
TRUE for vendors that usually ship discrete GPUs (NVIDIA, AMD) |
Do not use
OutputCountto decide who owns the display. On hybrid systems DXGI happily attributes the panel to the discrete GPU although the integrated GPU owns the display path. UseAttachedDisplayCount/DrivesPrimaryMonitorinstead.
| Constant | Value |
|---|---|
GORILLA_GPU_VENDOR_NVIDIA |
$10DE |
GORILLA_GPU_VENDOR_AMD |
$1002 |
GORILLA_GPU_VENDOR_INTEL |
$8086 |
GORILLA_GPU_VENDOR_MICROSOFT |
$1414 (software adapters like WARP) |
GORILLA_GPU_VENDOR_QUALCOMM |
$5143 |
GORILLA_GPU_VENDOR_ARM |
$13B5 |
GetGpuDiagnosticsReport builds a multiline, human readable report of all GPUs and the detected render / display constellation. Write it into your log file and ask for it in bug reports — it answers most "why is it slow on my machine" questions immediately:
Log(TGorillaSystem.GetGpuDiagnosticsReport());
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
The example above is the classic copy-back constellation: DXGI claims the NVIDIA GPU owns a display (dxgi outputs 1), the real display path says the Intel GPU does — and the Intel GPU is right.
TGorillaSystem.GetDisplays lists every display attached to the desktop — name, position in the virtual desktop, work area, current and supported video modes, physical size, UI scale factor and the GPU that scans it out. Like the GPU enumeration it needs no graphics context and may be called before Application.Initialize, e.g. to pick a fullscreen resolution or the monitor to open the main window on.
var LDisplays : TGorillaDisplayInfoArray;
LDisplay : TGorillaDisplayInfo;
LMode : TGorillaDisplayMode;
begin
if TGorillaSystem.GetDisplays(LDisplays) then
for LDisplay in LDisplays do
begin
Log(LDisplay.ToString()); // "DELL U2720Q [\\.\DISPLAY2] 3840 x 2160, 32 bit, 60.00 Hz"
for LMode in LDisplay.Modes do
Log(' ' + LMode.ToString());
end;
// only the primary display, without the (slower) mode list
if TGorillaSystem.GetPrimaryDisplay(LDisplay, false) then
Log(Format('%.1f" at %.0f ppi', [LDisplay.DiagonalInches(), LDisplay.PixelsPerInch()]));
end;
Modes is sorted from the largest resolution and highest refresh rate downwards and contains no duplicates — Modes[0] usually is the native mode of the panel. Pass AWithModes = False when you only need the current mode; enumerating all modes is the slowest part of the query on Windows.
TGorillaDisplayInfo| Field | Description |
|---|---|
DeviceName |
OS name of the output. Windows: \\.\DISPLAY1, Linux: connector eDP-1 / DP-2, macOS: CGDirectDisplayID, Android: display id |
FriendlyName |
Monitor name, e.g. DELL U2720Q — from the EDID where possible |
AdapterName / AdapterId |
GPU that really scans out the display. AdapterId equals TGorillaGpuAdapterInfo.Luid of the matching GetGpuAdapters entry (Windows, Linux) |
Bounds |
Position and size in the virtual desktop |
WorkArea |
Bounds without task bar, dock, menu bar or system bars |
IsPrimary |
Primary / main display |
CurrentMode |
Width, Height, BitsPerPixel, RefreshRate of the active mode |
Modes |
All supported modes (empty with AWithModes = False) |
WidthMm / HeightMm |
Physical image size, 0 when unknown |
ScaleFactor |
UI scale of the OS, 1.0 = 100 % |
DiagonalInches() / PixelsPerInch() |
Derived from the physical size, 0 when unknown |
| Windows | Linux (X11 / XWayland) | Linux (no X server) | macOS | Android | |
|---|---|---|---|---|---|
| Source | GDI + EDID (registry) + WDDM | XRandR + EDID | DRM connectors in /sys/class/drm |
CoreGraphics + NSScreen | DisplayManager |
Bounds |
pixels, virtual desktop | pixels, virtual desktop | unknown position, starts at 0,0 | points, global display space | pixels, own space per display |
WorkArea |
yes | = Bounds |
= Bounds |
yes | yes (without system bars) |
CurrentMode |
yes | yes | preferred mode of the monitor | yes (physical pixels) | yes (current orientation) |
Modes |
yes | yes | EDID timings + resolutions | yes (desktop usable) | yes (natural orientation) |
| Refresh rate | integer Hz | exact | EDID timings only | 0 on some built-in panels | yes |
FriendlyName |
EDID | EDID | EDID | localizedName (10.15+) |
Display.getName |
| Physical size | EDID | EDID, else XRandR | EDID | CGDisplayScreenSize |
from xdpi / ydpi |
ScaleFactor |
GetDpiForMonitor |
Xft.dpi (global) |
1.0 | backingScaleFactor |
density |
AdapterName |
yes (WDDM path) | yes (PCI slot of the card) | yes | — | — |
iOS returns FALSE.
Windows:
GetDpiForMonitorreports 96 dpi for DPI unaware processes, soScaleFactorstays 1.0 there. FMX applications are per-monitor DPI aware through their default manifest; plain console tools are not.Linux: XRandR is loaded dynamically (
libX11.so.6,libXrandr.so.2) — no link dependency, and the fallback to sysfs happens automatically under pure Wayland or on the console. The EDID is taken from the XRandREDIDoutput property and otherwise from the matching DRM connector; the match is done by connector name and, for the NVIDIA / AMD DDX drivers with their own naming (DP-0,DisplayPort-0), by identical EDID bytes. While enumerating, a no-op Xlib error handler is installed, because the default one terminates the process when a monitor is unplugged between two requests.macOS: call from the main thread (NSScreen).
GetDisplayDiagnosticsReport() formats all of this for log files:
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
On a hybrid laptop the adapter line is a quick cross-check of the copy-back report: the panel is scanned out by the integrated GPU.
| Question | Source |
|---|---|
| Which GPUs exist? | IDXGIFactory1.EnumAdapters1 — needs only dxgi.dll, no device |
| Which GPU renders? | IDXGIFactory6.EnumAdapterByGpuPreference with DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE — the same GPU the NVIDIA / AMD driver selects for a high-performance process |
| Which GPU scans out a display? | The WDDM kernel thunk D3DKMTOpenAdapterFromGdiDisplayName (gdi32.dll), which maps a GDI display name like \\.\DISPLAY1 to the LUID of the adapter that really owns that display path |
The two obvious alternatives lie on hybrid systems and are therefore not used:
EnumDisplayDevices returns the GDI adapter string, which stays on the integrated GPU even after a MUX switch.IDXGIAdapter.EnumOutputs attributes the panel to the discrete GPU although the integrated GPU owns the display path (measured on an RTX 4070 Laptop + Iris Xe: DXGI says NVIDIA owns DISPLAY1, the WDDM display path says Intel — and Intel is right).IDXGIFactory5 / IDXGIFactory6 are not declared by the Delphi RTL (which stops at Winapi.DXGI1_4), so the unit declares them itself. When DXGI 1.6 is unavailable (Windows 10 before build 1803) the render adapter is picked heuristically: a discrete vendor first, then the largest amount of dedicated video memory. When the WDDM thunk is unavailable, the DXGI output attribution is kept as a best-effort fallback.
The enumeration walks /sys/class/drm/:
card* entries without a dash are GPUs, entries with a dash (card0-eDP-1) are connectors.device/vendor, device/device and device/uevent deliver the PCI ids, DRIVER and PCI_SLOT_NAME. The PCI slot is converted into a 64-bit id — Linux has no LUID, but the slot is just as unique and just as stable while the system runs.device/boot_vga = 1 marks the GPU the firmware brought the console up on — the integrated GPU on a hybrid laptop, and the analogue to the primary monitor on Windows.status is connected increases AttachedDisplayCount of its card./proc/driver/nvidia/gpus/<pci-slot>/information instead.Attributes are read with a plain TFileStream loop on purpose: sysfs reports a size of one page (4096 bytes) for every attribute while the actual read returns far fewer bytes, so anything relying on Stream.Size (TStringList.LoadFromFile, TFile.ReadAllText) raises. A missing attribute is the normal case and never travels as an exception, so the debugger does not stop on every probe.
GetGpuAdapters returns FALSE and GetHybridGraphicsState reports Detected = False. On Android the renderer name is only known after the OpenGL or Vulkan context has been created. Backend selection via GorillaGraphicsBackend still works everywhere.
program MyProject;
uses
Gorilla.Context.Backend, // FIRST unit - before FMX, before everything else
System.StartUpCopy,
System.SysUtils,
System.IOUtils,
FMX.Forms,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
procedure WriteGpuLog();
begin
try
TFile.WriteAllText(
TPath.Combine(TPath.GetDocumentsPath(), 'gpu-report.txt'),
TGorillaSystem.GetGpuDiagnosticsReport());
except
// never let diagnostics kill the startup
end;
end;
begin
// 1) Request the discrete GPU - must happen before any driver DLL is loaded
TGorillaSystem.ForceToUseNVIDIAorAMDGPU();
// 2) Pick the graphics backend
{$IF Defined(MSWINDOWS) and Defined(CPUX64)}
GorillaGraphicsBackend := gbVulkan;
{$ENDIF}
// 3) Persist the constellation for support cases
WriteGpuLog();
// 4) Warn the user about an unavoidable per-frame copy
TGorillaSystem.CheckHybridGraphicsState();
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
Order matters. Steps 1 and 2 have to run before
Application.Initializeand before the first Gorilla3D component is created. Steps 3 and 4 only read the system state and may be moved anywhere — for example behind a "Diagnostics" menu item of your application.
| Function / Variable | Description |
|---|---|
GorillaGraphicsBackend : TGorillaGraphicsBackend |
Global backend selector (gbDefault, gbOpenGL, gbVulkan). Default gbDefault |
TGorillaSystem.IsVulkanBackend() : Boolean |
TRUE when the Vulkan backend is selected |
TGorillaSystem.IsOpenGLBackend() : Boolean |
TRUE for gbDefault and gbOpenGL |
TGorillaSystem.ForceToUseNVIDIAorAMDGPU() |
Requests the discrete GPU. Windows: exported Optimus / PowerXpress symbols. Linux: PRIME / Mesa environment variables |
TGorillaSystem.GetGpuAdapters(out AAdapters) : Boolean |
Enumerates all GPUs including the displays they really scan out. No graphics context needed. FALSE when unsupported |
TGorillaSystem.GetActiveDisplayAdapterName() : String |
First adapter name the OS reports as attached to the desktop (Windows) |
TGorillaSystem.GetActiveRenderAdapterName() : String |
Name of the GPU that will be used for rendering, empty when it cannot be determined |
TGorillaSystem.GetHybridGraphicsState() : TGpuDisplayInfo |
Full render / display constellation including IsHybridCopyBack |
TGorillaSystem.GetGpuDiagnosticsReport() : String |
Multiline report of all GPUs and the detected constellation, for logs and bug reports |
TGorillaSystem.CheckHybridGraphicsState(AThrowException = False) |
Warns about a copy-back scenario — dialog by default, exception when True |
GetDisplays(out ADisplays; AWithModes = True) : Boolean |
Enumerates all desktop displays with modes, physical size, scale and scanning GPU. No graphics context needed. FALSE on iOS |
GetPrimaryDisplay(out ADisplay; AWithModes = True) : Boolean |
The primary display, or the first one when none is marked primary |
GetDisplayDiagnosticsReport() : String |
Multiline report of all displays, for logs and bug reports |
NvOptimusEnablement, AmdPowerXpressRequestHighPerformance |
Exported symbols evaluated by the NVIDIA / AMD drivers (Windows). Assigned by ForceToUseNVIDIAorAMDGPU |
GORILLA_FORCE_HIGHPERFORMANCE_GPU |
Conditional define — calls ForceToUseNVIDIAorAMDGPU in the initialization section of the unit |
| Symptom | Cause / Remedy |
|---|---|
| Low frame rate on a gaming laptop, independent of the quality settings | Classic copy-back. Run GetGpuDiagnosticsReport() — when it says Hybrid copyback: True, enable the MUX switch / "Discrete GPU only" mode or move the window to a monitor attached to the dedicated GPU |
ForceToUseNVIDIAorAMDGPU has no effect |
Called too late — the vendor driver DLL was already loaded. Move it to the very first line of the .dpr or use GORILLA_FORCE_HIGHPERFORMANCE_GPU |
| Application still renders on the integrated GPU | A per-application override in the NVIDIA / AMD control panel or in the Windows graphics settings takes precedence over the exported symbols |
Detected = False, all names empty |
No context-independent enumeration on this platform (Android, macOS, iOS), or DXGI / sysfs delivered nothing. A copy-back is then never reported |
Hybrid copyback: False although two GPUs are installed |
Both LUIDs are identical or one GPU could not be identified — the check is deliberately conservative and never guesses |
WSL2: GPU adapters: not enumerable inside WSL |
Expected. The GPU is reached through the Mesa d3d12 driver. Set MESA_D3D12_DEFAULT_ADAPTER_NAME (done automatically when the vendor driver is detected below /usr/lib/wsl/lib) |
Linux: the wrong GPU is used although DRI_PRIME is set |
Intentional — an explicitly set environment variable is never overwritten by Gorilla3D |
GetDisplays: ScaleFactor is 1.0 on a scaled Windows desktop |
The process is not DPI aware (e.g. a console tool without manifest) — Windows then virtualizes the DPI to 96 |
Linux: all displays start at 0,0 and WorkArea = Bounds |
No X server reachable ($DISPLAY unset, pure Wayland without XWayland) — the sysfs fallback cannot know the desktop layout |
macOS: RefreshRate = 0 |
Many built-in panels do not publish their refresh rate through CoreGraphics |
Cameras in Gorilla3D control the viewpoint and projection of your 3D scene. The framework provides TGorillaCamera for basic camera functionality and TGorillaSmoothCameraController for interactive, smooth camera navigation.
TGorillaCamera extends FireMonkey's TCamera with additional Gorilla3D-specific features and better integration with the rendering pipeline.
TGorillaCamera onto your viewport from the tool paletteCamera propertyViewport.UsingDesignCamera := False;var
Camera: TGorillaCamera;
begin
Camera := TGorillaCamera.Create(Viewport);
Camera.Parent := Viewport;
Camera.Position.Z := -10;
Camera.FOV := 45;
Viewport.Camera := Camera;
Viewport.UsingDesignCamera := False;
end;
The field of view (FOV) controls how wide the camera's perspective is:
// Narrow FOV (zoomed in)
Camera.FOV := 30;
// Standard FOV
Camera.FOV := 45;
// Wide angle FOV
Camera.FOV := 75;
Guidelines:
Do not use a tiny FOV to fake an orthographic view. A common trick is to set a very small FOV and push the camera far back so the perspective flattens out. Use
ProjectionModeinstead. The trick forces a camera distance of roughly 57× the size of your subject, and at that distance depth precision collapses: for a 2 unit model with the defaultNearPlane/FarPlaneyou drop from about 5700 distinguishable depth steps at FOV 45 to about 2 at FOV 1, which means z-fighting on anything nearly coplanar.
ProjectionMode switches the camera between a perspective, an orthographic and
an isometric view.
// Perspective (default) - distant objects get smaller
Camera.ProjectionMode := TGorillaCameraProjection.cpPerspective;
// Orthographic - objects keep their size regardless of distance
Camera.ProjectionMode := TGorillaCameraProjection.cpOrthographic;
Camera.OrthoHeight := 10;
// Isometric - orthographic plus a fixed camera axis
Camera.ProjectionMode := TGorillaCameraProjection.cpIsometric;
Camera.IsometricPreset := TGorillaIsometricPreset.ipTrueIsometric;
| Mode | Projection | Typical use |
|---|---|---|
cpPerspective |
View pyramid, built from FOV |
Everything with a sense of depth |
cpOrthographic |
View box, built from OrthoHeight |
CAD-like views, 2D-in-3D, map overlays |
cpIsometric |
View box plus a fixed camera axis | Tile-based games, strategy maps, diagrams |
Isometry is not a projection of its own. It is what you get when you look at an
orthographic scene down one particular axis, which is why cpIsometric is
cpOrthographic with an orientation attached.
IsOrthographic() is True for both cpOrthographic and cpIsometric.
Important:
TGorillaViewport.UsingDesignCameradefaults toTrue, and while it is on the viewport renders through its own design camera — the camera assigned toCamerais ignored entirely, projection included. SwitchingProjectionModethen has no visible effect. See Creating a Camera.
OrthoHeight is the orthographic counterpart of FOV: it is the height of the
visible area in world units, and smaller values zoom in.
Camera.OrthoHeight := 10; // 10 world units fit on screen vertically
Camera.OrthoHeight := 4; // zoomed in
OrthoWidth defaults to 0, which means derive the width from OrthoHeight
and the viewport aspect ratio. That is almost always what you want, because it
keeps the image undistorted while the window is resized. Set it only to
reproduce an imported camera that pins both extents:
Camera.OrthoWidth := 0; // automatic (recommended)
Camera.OrthoWidth := 17.8; // fixed width, independent of the viewport
Unlike a perspective camera, moving an orthographic camera along its view axis
does not change the image at all — it only shifts the scene inside the
near/far range. Zoom by changing OrthoHeight. TGorillaSmoothCameraController
does this for you: under an orthographic camera the mouse wheel scales
OrthoHeight instead of moving the camera.
While ProjectionMode is cpIsometric, the camera orients itself from
IsometricPreset:
Camera.IsometricPreset := TGorillaIsometricPreset.ipTrueIsometric;
| Preset | Azimuth | Elevation | Notes |
|---|---|---|---|
ipTrueIsometric |
45° | 35.264° | View direction (1, 1, 1) — all three world axes foreshortened equally |
ipDimetric2To1 |
45° | 26.565° | The classic 2:1 pixel-art angle; a unit cube lands on whole pixel counts |
ipMilitary |
45° | 45° | Military / cavalier style top-down view |
ipCustom |
IsometricYaw |
IsometricPitch |
Your own angles |
The elevation of a true isometric view is ArcTan(1 / Sqrt(2)). Strictly
speaking ipDimetric2To1 is dimetric rather than isometric, but it is what most
tile engines mean by "isometric".
IsometricYaw and IsometricPitch are only read while the preset is
ipCustom. Selecting any other preset mirrors its angles into those two
properties, so switching to ipCustom afterwards continues from what is on
screen instead of jumping:
Camera.IsometricPreset := TGorillaIsometricPreset.ipCustom;
Camera.IsometricYaw := 30; // azimuth around the world Y axis
Camera.IsometricPitch := 40; // elevation above the horizon, positive looks down
The framework exposes the preset angles as constants, should you need them elsewhere:
GORILLA_ISOMETRIC_YAW // 45.0
GORILLA_ISOMETRIC_PITCH // 35.264389682...
GORILLA_DIMETRIC_PITCH // 26.565051177...
GORILLA_MILITARY_PITCH // 45.0
This depends on whether the camera has a Target:
RotationAngle.TCamera builds its view matrix towards the target and
ignores AbsoluteDirection, so a rotation would have no effect. The camera is
therefore placed on the isometric axis through its target instead, keeping
the distance it already had.Set AutoIsometricOrientation := False to keep the projection but orient the
camera yourself:
Camera.AutoIsometricOrientation := False;
Camera.RotationAngle.Point := Point3D(-30, 60, 0);
You can also trigger the orientation manually, which is what you need after changing angles while the automatic mode is off:
Camera.ApplyIsometricOrientation();
Switching projection is not limited to the main image — the rest of the pipeline follows automatically:
RayCastIntersect, ObjectAtPoint
and TGorillaMesh.PickTriangle all account for that.FOV.
A sky sits at infinity and has no orthographic interpretation: parallel rays
would sample a single direction across the whole screen. This is why FOV
still matters under an orthographic camera.Model formats that carry orthographic cameras — glTF and COLLADA among them —
are applied on import. TGorillaCamera.LoadFromDefinition reads the camera type
from the definition layer and sets ProjectionMode, deriving OrthoWidth and
OrthoHeight from the stored magnification and aspect ratio.
// Set position directly
Camera.Position.Point := Point3D(0, 5, -10);
// Or use individual components
Camera.Position.X := 0;
Camera.Position.Y := 5;
Camera.Position.Z := -10;
// Set rotation
Camera.RotationAngle.Point := Point3D(15, 0, 0);
In case you want to always focus a specific 3D element, you can set the Target property of your TCamera/TGorillaCamera component.
It will automatically adjust the camera's rotation to it.
The smooth camera controller provides interactive camera navigation with physics-based movement, perfect for viewers, object inspectors, and interactive 3D applications.
Every TGorillaViewport component has a built-in smooth camera controller, which you can access by GorillaViewport1.GetDesignCameraController()
This is also the default setup and default navigation available if you do not overwrite with your own camera settings.
You can modify the design camera controller at runtime, f.e. to increase movement speed.
with GorillaViewport1.GetDesignCameraController() do
begin
// Change the kind of mouse and keyboard inputs to control the camera
NavigationProfile := TGorillaCameraNavigationProfile.cnpOrbit;
// Timer interval for updating camera position
Interval := 10;
// Intensity values to control navigation speed
ShiftIntensity := 5;
IntensityZoom := 15;
IntensityRotate := 20;
IntensityUpAndDown := 5;
end;
var
Controller: TGorillaSmoothCameraController;
Camera: TGorillaCamera;
begin
// Create controller
Controller := TGorillaSmoothCameraController.Create(Viewport);
Controller.Parent := Viewport;
Controller.Position.Point := Point3D(0, 0, 0);
// Create camera as child
Camera := TGorillaCamera.Create(Controller);
Camera.Parent := Controller;
Camera.Position.Z := -10; // Distance from target
// Link them
Controller.Camera := Camera;
Controller.Viewport := Viewport;
Controller.Enabled := True;
end;
Choose a preset profile for familiar navigation:
// Default profile (no orbiting)
Controller.NavigationProfile := cnpDefault;
// - Rotate: Left mouse button
// - Shift XZ: Right mouse button
// - Shift XY: Shift + Right mouse button
// - Zoom: Mouse wheel
// Orbit profile
Controller.NavigationProfile := cnpOrbit;
// - Rotate: Right mouse button (orbits around target)
// - Shift XY: Left mouse button
// - Shift XZ: Shift + Left mouse button
// - Zoom: Mouse wheel
// Blender-like profile
Controller.NavigationProfile := cnpBlender;
// - Rotate: Ctrl + Right mouse button (orbits)
// - Shift XY: Ctrl + Left mouse button
// - Shift XZ: Shift + Left mouse button
// - Zoom: Mouse wheel
// Sketchfab-like profile
Controller.NavigationProfile := cnpSketchfab;
// - Rotate: Left mouse button (orbits)
// - Shift XY: Right mouse button
// - Shift XZ: Shift + Right mouse button
// - Move forward: Mouse wheel
// - Zoom: Ctrl + Mouse wheel
Non-Orbiting (Default)
Controller.Orbiting := False;
Orbiting Mode
Controller.Orbiting := True;
// Faster rotation
Controller.IntensityRotate := 2.0; // Default: 1.0
// Slower up/down movement
Controller.IntensityUpAndDown := 0.5;
// More sensitive zoom
Controller.IntensityZoom := 1.5;
// Faster shifting
Controller.ShiftIntensity := 2.0;
Higher damping = slower impulse decay = smoother, more "floaty" movement:
// Very smooth rotation
Controller.DampingRotate := 0.95; // Default: 0.85
// Quick stop for zoom
Controller.DampingZoom := 0.7;
// Smooth shifting
Controller.ShiftDamping := 0.9;
Constrain camera movement to specific bounds:
// Limit rotation angle (in degrees)
Controller.LimitRotationMin := -180;
Controller.LimitRotationMax := 180;
// Limit vertical movement
Controller.LimitUpAndDownMin := -10;
Controller.LimitUpAndDownMax := 20;
// Limit zoom distance
Controller.LimitZoomMin := 5;
Controller.LimitZoomMax := 50;
In orbit mode (Orbiting = True) the camera does not move up and down, it tilts. There
LimitUpAndDownMin / LimitUpAndDownMax limit the pitch of the camera (rotation
around X) in degrees. A range of less than 360 degrees is not wrapped round, so f.e.
-85..-5 keeps the orbiting camera above the ground:
Controller.Orbiting := True;
// never look from below the ground, never straight down
Controller.LimitUpAndDownMin := -85;
Controller.LimitUpAndDownMax := -5;
By default shifting forward/backward and left/right follows the view direction - a camera
looking down shifts its focus into the ground when shifted forward. With ShiftOnGround
the controller moves level on the ground plane (XZ), whatever the camera's pitch.
Shifting up and down is unaffected.
Controller.ShiftOnGround := True; // Default: False
// Rotate left (negative) or right (positive)
Controller.AddXImpulse(-0.5);
// Move up (positive) or down (negative)
Controller.AddYImpulse(0.3);
// Combined rotation and vertical movement
Controller.AddImpulse(PointF(0.5, -0.2));
// Zoom in
Controller.Zoom(1.0);
// Zoom out
Controller.Zoom(-1.0);
// Stronger zoom
Controller.Zoom(2.0);
Note: Under an orthographic or isometric camera these calls scale the
camera's OrthoHeight instead of moving it along the view axis — moving an
orthographic camera would not change the image. See
Orthographic Size.
// Shift on all axes
Controller.Shift(Point3D(1, 0, 0.5));
// Set exact position and angle
Controller.SetPositionAndAngle(
Point3D(0, 5, 0), // Position
Point3D(0, 45, 0) // Rotation angles
);
Define your own mouse/keyboard combinations:
// Use middle mouse button for rotation
Controller.Rotation := [cssMiddle];
// Use Ctrl + Left button for shifting
Controller.Shifting := [cssCtrl, cssLeft];
// Use Shift + Right mouse button to move the camera up or down
Controller.ShiftUp := [cssRight + cssShift];
// Use Alt + Mouse wheel for zoom
Controller.Zooming := [cssAlt, cssMouseWheel];
Selectively enable or disable control types:
// Enable all controls
Controller.Types := [scctRotateX, scctRotateY, scctMoveY, scctZoom,
scctShiftX, scctShiftY, scctShiftZ];
// Only allow rotation and zoom
Controller.Types := [scctRotateY, scctZoom];
// Lock camera (disable all controls)
Controller.Types := [];
React to camera movements:
procedure TForm1.CameraControllerBeforeModify(ASender: TObject;
AType: TGorillaSmoothCameraControlType; var AValue: Single);
begin
// Modify the value before it's applied
case AType of
scctZoom:
begin
// Limit zoom speed
if Abs(AValue) > 5 then
AValue := Sign(AValue) * 5;
end;
end;
end;
procedure TForm1.CameraControllerAfterModify(ASender: TObject;
AType: TGorillaSmoothCameraControlType; var AValue: Single);
begin
// React to camera changes
case AType of
scctZoom:
StatusBar1.Text := Format('Zoom: %.2f', [AValue]);
end;
end;
// Assign events
Controller.OnBeforeModify := CameraControllerBeforeModify;
Controller.OnAfterModify := CameraControllerAfterModify;
Perfect for viewing 3D models:
procedure SetupObjectInspector(AController: TGorillaSmoothCameraController);
begin
// Use orbiting mode
AController.Orbiting := True;
AController.NavigationProfile := cnpOrbit;
// Center on object
AController.Position.Point := Point3D(0, 0, 0);
// Set comfortable distance
AController.Camera.Position.Z := -20;
// Limit zoom range
AController.LimitZoomMin := 10;
AController.LimitZoomMax := 100;
// Smooth movement
AController.DampingRotate := 0.92;
AController.DampingZoom := 0.88;
end;
Navigation style for games and walkthroughs:
procedure SetupFirstPersonCamera(AController: TGorillaSmoothCameraController);
begin
// No orbiting
AController.Orbiting := False;
AController.NavigationProfile := cnpDefault;
// Quick response
AController.DampingRotate := 0.75;
AController.DampingZoom := 0.7;
// Higher sensitivity
AController.IntensityRotate := 1.5;
AController.IntensityZoom := 2.0;
// Limit vertical look angle
AController.LimitUpAndDownMin := -30;
AController.LimitUpAndDownMax := 30;
end;
Smoothly move camera to a target position:
procedure AnimateCameraToPosition(AController: TGorillaSmoothCameraController;
ATarget: TPoint3D);
var
Delta: TPoint3D;
begin
Delta := ATarget - AController.Position.Point;
// Add impulses to move toward target
AController.Shift(Delta * 0.1); // Adjust multiplier for speed
end;
// Call repeatedly in a timer or render loop until close enough
procedure AddCameraShake(AController: TGorillaSmoothCameraController;
AIntensity: Single);
begin
AController.AddImpulse(PointF(
Random * AIntensity * 2 - AIntensity, // Random X
Random * AIntensity * 2 - AIntensity // Random Y
));
end;
Always Link Viewport: Set the Viewport property for automatic mouse event handling
Choose Appropriate Profile: Use preset profiles when possible instead of custom configurations
Set Reasonable Limits: Always define min/max limits to prevent users from getting lost
Adjust Damping for Feel: Lower damping (0.7-0.8) for responsive controls, higher damping (0.9-0.95) for smooth, cinematic movement
Test on Target Platform: Camera feel can differ between desktop (mouse) and mobile (touch) platforms
Consider Scene Scale: Adjust intensity and zoom limits based on your scene size
Provide Visual Feedback: Show controller position with ShowController := True during development
Most often the design camera is still active. It renders instead of the camera
you assigned, so nothing you set on your own camera — position, rotation, FOV
or ProjectionMode — reaches the image.
Viewport.Camera := MyCamera;
Viewport.UsingDesignCamera := False; // easy to forget, defaults to True
// Verify which camera actually renders
if Viewport.CurrentCamera <> MyCamera then
ShowMessage('The design camera is still active!');
// Check all required properties are set
if not Assigned(Controller.Camera) then
ShowMessage('Camera not linked!');
if not Assigned(Controller.Viewport) then
ShowMessage('Viewport not linked!');
if not Controller.Enabled then
ShowMessage('Controller is disabled!');
// Adjust intensity
Controller.IntensityRotate := 0.5; // Slower
Controller.IntensityZoom := 2.0; // Faster
// Increase damping to stop movement faster
Controller.DampingRotate := 0.95;
Controller.DampingZoom := 0.92;
// Or reset impulses manually
Controller.Impulse := Point3D(0, 0, 0);
Controller.ShiftImpulse := Point3D(0, 0, 0);
Gorilla3D provides pre-built camera and character controllers for common 3D navigation patterns. These components handle keyboard, mouse, and gamepad input to move and rotate a camera or character in 3D space, saving you from implementing movement logic from scratch.
All camera controllers require a TGorillaInputController to receive input events. The inheritance hierarchy is:
| Controller | Class | Purpose |
|---|---|---|
| Character Controller | TGorillaCharacterController |
Abstract base with states, hotkeys, movement, jumping, crouching, crawling |
| First-Person Controller | TGorillaFirstPersonController |
Ego-perspective movement with mouse look |
| Third-Person Controller | TGorillaThirdPersonController |
Orbit camera around a character |
Additionally, the Trigger Point Manager (TGorillaTriggerPointManager) lets you define interactive 3D points that react when the player looks at or approaches them.
TDummy
└── TGorillaCharacterController (abstract base)
└── TGorillaFirstPersonController (first-person / ego)
└── TGorillaThirdPersonController (third-person / orbit)
All controllers are TDummy descendants, meaning they are 3D transform nodes. The camera becomes a child of the controller, and movement is applied to the controller itself.
TGorillaCharacterController is the abstract base class that provides the common functionality for all character controllers. You do not use this class directly — use TGorillaFirstPersonController or TGorillaThirdPersonController instead.
The controller maintains a set of states describing what the character is doing:
| State | Description |
|---|---|
fpIdle |
Character is not moving |
fpMoving |
Character is moving (WASD or thumbstick) |
fpBoost |
Running / sprinting (Shift held) |
fpCrouching |
Crouching (reduced height and speed) |
fpCrawling |
Crawling (further reduced height and speed) |
fpJumping |
Currently in a jump animation |
fpAiming |
Aiming mode active |
fpPushing |
Pushing action active |
fpPulling |
Pulling action active |
States can be combined — for example, a character can be [fpMoving, fpCrouching] simultaneously.
// Check current state
if fpMoving in FirstPersonController1.States then
ShowMessage('Character is moving');
// Manually add/remove states
FirstPersonController1.AddState(fpBoost);
FirstPersonController1.RemoveState(fpBoost);
The controller automatically registers default hotkeys when linked to an input controller:
| Action | Keyboard | Gamepad |
|---|---|---|
| Move Forward | W | Left Thumbstick Up |
| Move Backward | S | Left Thumbstick Down |
| Move Left | A | Left Thumbstick Left |
| Move Right | D | Left Thumbstick Right |
| Jump | Space | A Button |
| Crouch | C | B Button |
| Boost/Run | Left Shift | Left Trigger |
| Aim | Right Mouse | Right Trigger |
You can access and customize individual hotkeys via the HotKey indexed property:
// Access a specific hotkey
var LHotKey := FirstPersonController1.HotKey[OnCharacterMoveForward];
| Property | Type | Default | Description |
|---|---|---|---|
Speed |
Single | 0.25 | Base movement speed |
SidewayRotationSpeed |
Single | 1.0 | Rotation speed when using sideway keys |
CrouchingSpeedReduction |
Single | 0.75 | Speed multiplier when crouching (0.0–1.0) |
CrawlingSpeedReduction |
Single | 0.9 | Speed multiplier when crawling (0.0–1.0) |
RunningSpeedBoost |
Single | 2.0 | Speed multiplier when boosting (1–1000) |
JumpingHeight |
Single | 2.0 | Height of jump |
CrouchingHeight |
Single | 0.5 | How low the character crouches |
CrawlingHeight |
Single | 0.25 | How low the character crawls |
JumpingAnimationTime |
Single | — | Duration of jump animation in seconds |
CrouchingAnimationTime |
Single | — | Duration of crouch transition |
CrawlingAnimationTime |
Single | — | Duration of crawl transition |
MoveSideways |
Boolean | — | If true, A/D keys strafe; if false, A/D keys rotate |
RotateOnSideways |
Boolean | — | Rotate the controller on sideway movement |
LockXAxis |
Boolean | False | Prevent movement on X axis |
LockYAxis |
Boolean | False | Prevent movement on Y axis |
LockZAxis |
Boolean | False | Prevent movement on Z axis |
CameraYAngleLimit |
TPointF | (-180, 180) | Min/max horizontal rotation in degrees |
CameraXAngleLimit |
TPointF | (-45, 45) | Min/max vertical rotation in degrees |
| Event | Type | Description |
|---|---|---|
OnIdle |
TOnCharacterControllerEvent |
Fired when controller switches to idle |
OnMove |
TOnCharacterControllerMoveEvent |
Fired on any movement (provides direction and speed) |
OnRotate |
TOnCharacterControllerRotateEvent |
Fired on camera rotation (provides quaternion and delta) |
OnBoost |
TOnCharacterControllerEvent |
Fired when boost activates/deactivates |
OnCrouch |
TOnCharacterControllerEvent |
Fired on crouch toggle |
OnCrawl |
TOnCharacterControllerEvent |
Fired on crawl toggle |
OnJump |
TOnCharacterControllerEvent |
Fired when jumping |
OnAim |
TOnCharacterControllerEvent |
Fired on aim toggle |
OnPush |
TOnCharacterControllerEvent |
Fired on push action |
OnPull |
TOnCharacterControllerEvent |
Fired on pull action |
OnCustomAction |
TOnCharacterControllerHotKeyTriggered |
Fired by custom hotkeys |
OnClick |
TOnCharacterControllerHotKeyTriggered |
Fired by mouse button clicks |
OnHotKey |
TOnCharacterControllerHotKeyTriggered |
General hotkey trigger callback |
OnTriggerPoint |
TOnCharacterControllerTriggerPoint |
Fired when a trigger point is detected |
OnChangeSize |
TNotifyEvent |
Fired when character height changes (crouch/crawl) |
TGorillaFirstPersonController implements ego-perspective movement. The camera is placed at the character's eye level and rotates with mouse movement. WASD keys (or gamepad thumbstick) move the character forward, backward, and sideways.
TGorillaInputController onto your formTGorillaFirstPersonController onto your viewportInputController to link to the input controllerCamera to link to your TGorillaCameravar
InputCtrl: TGorillaInputController;
FPController: TGorillaFirstPersonController;
begin
// Create input controller
InputCtrl := TGorillaInputController.Create(Self);
InputCtrl.Viewport := GorillaViewport1;
// Create first-person controller
FPController := TGorillaFirstPersonController.Create(Self);
FPController.Parent := GorillaViewport1;
FPController.InputController := InputCtrl;
FPController.Camera := GorillaCamera1;
FPController.Speed := 0.35;
FPController.ShowCursor := False;
end;
| Property | Type | Default | Description |
|---|---|---|---|
MouseControllerSpeed |
Single | 0.075 | Sensitivity of mouse look rotation |
GamePadThumbstickSpeed |
Single | 0.5 | Sensitivity of gamepad thumbstick rotation |
ShowCursor |
Boolean | True | Show or hide the mouse cursor |
UseCameraDirection |
Boolean | True | Use camera direction for movement; if false, uses controller direction |
By default, mouse movement always rotates the camera. You can require a mouse button to be held for rotation or movement:
// Only rotate when right mouse button is held
FPController.RotationDragMode := True;
FPController.RotationDragModeButton := TGorillaMouseState.RButtonDown;
// Enable drag-to-move with middle mouse button
FPController.MovementDragMode := True;
FPController.MovementDragModeButton := TGorillaMouseState.MButtonDown;
// Optionally invert drag movement axes
FPController.InvertMovementDragModeXAxis := True;
FPController.InvertMovementDragModeYAxis := False;
Additional properties:
| Property | Type | Description |
|---|---|---|
RotateAroundCenter |
Boolean | Rotate the controller component itself instead of free camera rotation |
UseDefaultBehaviour |
Boolean | Enable/disable built-in hotkey behavior |
UseDefaultMovement |
Boolean | Enable/disable built-in WASD/gamepad movement (does not affect camera rotation) |
procedure TForm1.FormCreate(Sender: TObject);
begin
// Setup viewport and camera
GorillaViewport1.UsingDesignCamera := False;
// Create input controller
FInputCtrl := TGorillaInputController.Create(Self);
FInputCtrl.Viewport := GorillaViewport1;
// Create first-person controller
FFPCtrl := TGorillaFirstPersonController.Create(Self);
FFPCtrl.Parent := GorillaViewport1;
FFPCtrl.Position.Y := -1.8; // eye height
FFPCtrl.InputController := FInputCtrl;
FFPCtrl.Camera := GorillaCamera1;
// Configure movement
FFPCtrl.Speed := 0.3;
FFPCtrl.RunningSpeedBoost := 2.5;
FFPCtrl.ShowCursor := False;
FFPCtrl.CameraXAngleLimit := PointF(-80, 80);
// React to movement
FFPCtrl.OnMove := procedure(ASender: TObject;
AKind: TGorillaCharacterControllerHotKey; ADir: TPoint3D;
ACurrentSpeed: Single)
begin
// e.g., play footstep sounds, update animation
end;
end;
TGorillaThirdPersonController extends the first-person controller to provide an orbital camera that rotates around the character. The camera is placed as a child of the controller at a configurable distance. Mouse movement orbits the camera, and the scroll wheel zooms in/out.
var
TPController: TGorillaThirdPersonController;
begin
TPController := TGorillaThirdPersonController.Create(Self);
TPController.Parent := GorillaViewport1;
TPController.InputController := InputCtrl;
TPController.Camera := GorillaCamera1;
// Camera distance limits (absolute values)
TPController.CameraZLimit := PointF(-1, -25); // min 1, max 25 units away
TPController.MouseWheelSpeed := 1.5;
end;
The third-person controller places the camera behind and above the character. Mouse drag orbits the camera around the character, and the scroll wheel adjusts distance.
| Property | Type | Default | Description |
|---|---|---|---|
MouseWheelSpeed |
Single | 1.0 | Speed of mouse wheel zoom (0–10) |
CameraZLimit |
TPointF | (-1, -25) | Camera distance limits: X = closest, Y = farthest |
Defaults changed from FirstPerson:
UseCameraDirection defaults to False (orbit mode)RotateOnSideways defaults to TrueMoveSideways defaults to FalseCameraYAngleLimit defaults to (-180, 180)CameraXAngleLimit defaults to (-45, 45)procedure TForm1.FormCreate(Sender: TObject);
begin
GorillaViewport1.UsingDesignCamera := False;
FInputCtrl := TGorillaInputController.Create(Self);
FInputCtrl.Viewport := GorillaViewport1;
// Create third-person controller at character position
FTPCtrl := TGorillaThirdPersonController.Create(Self);
FTPCtrl.Parent := GorillaViewport1;
FTPCtrl.Position.Point := Point3D(0, -1, 0);
FTPCtrl.InputController := FInputCtrl;
FTPCtrl.Camera := GorillaCamera1;
// Orbit configuration
FTPCtrl.CameraZLimit := PointF(-2, -15);
FTPCtrl.MouseWheelSpeed := 2;
FTPCtrl.RotationDragMode := True;
FTPCtrl.RotationDragModeButton := TGorillaMouseState.RButtonDown;
FTPCtrl.Speed := 0.2;
end;
TGorillaTriggerPointManager manages a collection of trigger points in 3D space. When combined with a character controller, it automatically checks whether the player is looking at or standing near a trigger point, and fires events accordingly.
| Kind | Description |
|---|---|
StaticTriggerPoint |
Fixed 3D world coordinate that never moves |
DynamicTriggerPoint |
Follows a linked TControl3D, with the trigger point position as offset |
var
TriggerMgr: TGorillaTriggerPointManager;
TP: TGorillaTriggerPoint;
begin
TriggerMgr := TGorillaTriggerPointManager.Create(Self);
TriggerMgr.Enabled := True;
// Add a static trigger point
TP := TriggerMgr.AddTriggerPoint(
'Door', // Name
Point3D(5, -1, 3), // World position
5.0, // Tolerance (how close the view ray must be)
10.0 // Maximum detection distance
);
// Add a dynamic trigger point following a 3D object
TriggerMgr.AddTriggerPoint(
'NPC', // Name
SomeCharacterModel, // TControl3D to follow
Point3D(0, -1, 0), // Offset from control
3.0, // Tolerance
8.0 // Distance
);
// Link to character controller
FirstPersonController1.TriggerPoints := TriggerMgr;
end;
| Property | Type | Description |
|---|---|---|
Enabled |
Boolean | Activate or deactivate the trigger point |
Kind |
TGorillaTriggerPointKind |
StaticTriggerPoint or DynamicTriggerPoint |
LookInDirection |
Boolean | If true, triggers only when looking toward it; if false, triggers by proximity |
Control |
TControl3D | Linked 3D control for dynamic trigger points |
Position |
TPosition3D | World position (static) or offset (dynamic) |
Tolerance |
Single | Allowed deviation between view direction and point (0–100) |
Distance |
Single | Maximum detection distance (0–1000) |
Tag |
Integer | Custom integer data |
Data |
TValue | Custom data field (any type via RTTI) |
TriggerCount |
Integer | How many times the point has been triggered (read-only) |
Each trigger point can have individual events:
TP.OnTriggered := procedure(ASender: TGorillaTriggerPointManager;
const APos, AViewDir: TPoint3D; const APoint: TGorillaTriggerPoint;
const ADistance: Single)
begin
ShowHint('Press E to open ' + APoint.DisplayName);
end;
TP.OnUnTriggered := procedure(ASender: TGorillaTriggerPointManager;
const APos, AViewDir: TPoint3D; const APoint: TGorillaTriggerPoint;
const ADistance: Single)
begin
HideHint();
end;
You can also query trigger points manually:
var
LPoint: TGorillaTriggerPoint;
LDistance: Single;
begin
if TriggerMgr.ClosestTriggerPoint(CameraPos, CameraDir, LPoint, LDistance) then
Label1.Text := Format('Nearest: %s (%.1f m)', [LPoint.DisplayName, LDistance]);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FTriggerMgr := TGorillaTriggerPointManager.Create(Self);
// Door trigger - activates when looking at it within 8 units
var LDoor := FTriggerMgr.AddTriggerPoint('Door', Point3D(10, -1, 0), 3.0, 8.0);
LDoor.LookInDirection := True;
// Proximity trigger - activates when nearby regardless of view direction
var LZone := FTriggerMgr.AddTriggerPoint('SafeZone', Point3D(0, 0, 20), 5.0, 5.0);
LZone.LookInDirection := False;
// Link to controller
FFPCtrl.TriggerPoints := FTriggerMgr;
FFPCtrl.OnTriggerPoint := HandleTriggerPoint;
end;
procedure TForm1.HandleTriggerPoint(ASender: TObject;
AManager: TGorillaTriggerPointManager; APt: TGorillaTriggerPoint;
ADist: Single);
begin
if APt.DisplayName = 'Door' then
OpenDoor();
end;
The character controllers work best when combined with the TGorillaInputController. The input controller provides the raw input events, while the character controller interprets them as movement, rotation, and actions.
// The input controller handles raw input
InputCtrl := TGorillaInputController.Create(Self);
InputCtrl.Viewport := GorillaViewport1;
// The character controller interprets input as 3D movement
FPCtrl := TGorillaFirstPersonController.Create(Self);
FPCtrl.Parent := GorillaViewport1;
FPCtrl.InputController := InputCtrl;
FPCtrl.Camera := GorillaCamera1;
// You can also link an AudioManagerController for automatic sound playback
FPCtrl.AudioManagerController := AudioMgrCtrl;
For custom hotkeys beyond the built-in defaults, add them via the input controller and listen to the OnCustomAction event:
FPCtrl.OnCustomAction := procedure(ASender: TObject;
const AKind: TGorillaCharacterControllerHotKey;
const AHotKey: TGorillaHotKeyItem;
const AStates: TGorillaCharacterControllerStates;
const AMode: TGorillaInputMode)
begin
if AHotKey.Name = 'Interact' then
DoInteraction();
end;
UsingDesignCamera := False on the viewport when using a character controller camera.CameraXAngleLimit, CameraYAngleLimit) to prevent the camera from flipping.RotationDragMode := True so orbiting only happens when dragging, leaving the cursor free for UI interaction.UseDefaultMovement := False if you need custom movement logic (e.g., physics-based) while keeping the camera rotation behavior.LookInDirection := False are useful for area triggers (safe zones, damage zones) where proximity is sufficient.OnMove and applying forces to a physics body instead of letting the controller move directly.AudioManagerControllerLighting is essential for creating realistic 3D scenes. Gorilla3D provides TGorillaLight, an enhanced light component that extends FireMonkey's TLight with additional properties for advanced shading, attenuation control, and light scattering effects.
Omnidirectional light that emanates from a single point in all directions, like a light bulb.
var
PointLight: TGorillaLight;
begin
PointLight := TGorillaLight.Create(Viewport);
PointLight.Parent := Viewport;
PointLight.LightType := TLightType.Point;
PointLight.Position.Point := Point3D(0, 5, 0);
PointLight.Color := TAlphaColors.White;
end;
Use For:
Parallel light rays coming from a specific direction, like sunlight. Position doesn't matter, only rotation.
var
SunLight: TGorillaLight;
begin
SunLight := TGorillaLight.Create(Viewport);
SunLight.Parent := Viewport;
SunLight.LightType := TLightType.Directional;
SunLight.RotationAngle.X := -45; // Angle from above
SunLight.RotationAngle.Y := 45; // Angle from side
SunLight.Color := TAlphaColorRec.Lightyellow;
end;
Use For:
Cone-shaped light with position and direction, like a flashlight or stage spotlight.
var
SpotLight: TGorillaLight;
begin
SpotLight := TGorillaLight.Create(Viewport);
SpotLight.Parent := Viewport;
SpotLight.LightType := TLightType.Spot;
SpotLight.Position.Point := Point3D(0, 10, 0);
SpotLight.RotationAngle.X := 90; // Point downward
SpotLight.SpotCutOff := 30; // Cone angle
SpotLight.Color := TAlphaColors.White;
end;
Use For:
TGorillaLight onto your viewport from the tool paletteLightType in the Object Inspectorfunction CreateLight(AViewport: TGorillaViewport; AType: TLightType;
APosition: TPoint3D; AColor: TAlphaColor): TGorillaLight;
begin
Result := TGorillaLight.Create(AViewport);
Result.Parent := AViewport;
Result.LightType := AType;
Result.Position.Point := APosition;
Result.Color := AColor;
Result.Intensity := 1.0;
end;
Gorilla3D lights have three color components:
The main light color affecting directly lit surfaces.
Light.Color := TAlphaColors.White;
Indirect environmental light that brightens shadowed areas.
// Subtle ambient light
Light.Ambient := TAlphaColorF.Create(0.1, 0.1, 0.1, 1.0);
// Stronger ambient (reduces contrast)
Light.Ambient := TAlphaColorF.Create(0.3, 0.3, 0.3, 1.0);
// Colored ambient (e.g., blue sky light)
Light.Ambient := TAlphaColorF.Create(0.1, 0.15, 0.25, 1.0);
Color of shiny highlights on reflective surfaces.
// White highlights (most realistic)
Light.Specular := TAlphaColorF.Create(1, 1, 1, 1);
// Colored highlights (stylized look)
Light.Specular := TAlphaColorF.Create(1, 0.9, 0.8, 1); // Warm highlights
// No highlights
Light.Specular := TAlphaColorF.Create(0, 0, 0, 1);
Control light strength without changing color:
// Dim light
Light.Intensity := 0.5;
// Normal light
Light.Intensity := 1.0;
// Bright light
Light.Intensity := 2.0;
// Very bright (maximum)
Light.Intensity := 10.0;
Range: 0.0 to 10.0 (automatically clamped)
Attenuation controls how light intensity decreases with distance. Only affects Point and Spot lights.
Attenuation = 1 / (Constant + Linear × Distance + Quadratic × Distance²)
// Constant: Base attenuation (usually 1.0)
Light.ConstantAttenuation := 1.0;
// Linear: Proportional falloff
Light.LinearAttenuation := 0.35;
// Quadratic: Rapid falloff at distance
Light.QuadraticAttenuation := 0.44;
procedure SetLightRange(ALight: TGorillaLight; ARange: Integer);
begin
ALight.ConstantAttenuation := 1.0;
case ARange of
7: // Short range
begin
ALight.LinearAttenuation := 0.7;
ALight.QuadraticAttenuation := 1.8;
end;
13: // Medium range
begin
ALight.LinearAttenuation := 0.35;
ALight.QuadraticAttenuation := 0.44;
end;
20: // Long range
begin
ALight.LinearAttenuation := 0.22;
ALight.QuadraticAttenuation := 0.20;
end;
50: // Very long range
begin
ALight.LinearAttenuation := 0.07;
ALight.QuadraticAttenuation := 0.017;
end;
100: // Extremely long range
begin
ALight.LinearAttenuation := 0.045;
ALight.QuadraticAttenuation := 0.0075;
end;
end;
end;
// Sharp falloff (dramatic, close range)
Light.LinearAttenuation := 1.0;
Light.QuadraticAttenuation := 2.0;
// Gentle falloff (realistic, medium range)
Light.LinearAttenuation := 0.35;
Light.QuadraticAttenuation := 0.44;
// Very gentle (unrealistic, fills large areas)
Light.LinearAttenuation := 0.01;
Light.QuadraticAttenuation := 0.001;
Light scattering creates volumetric "god rays" effects visible in global illumination rendering.
Availability: Requires Global Illumination enabled (GAME_PACKAGE only)
// Enable global illumination first
Viewport.GlobalIllumDetail := 3;
// Configure light scattering
Light.ScatteringIntensity := 0.5; // How visible rays are
Light.ScatteringExposure := 0.01; // Ray brightness
Light.ScatteringDecay := 1.0; // Ray fadeout
Light.ScatteringDensity := 0.84; // Medium density
Controls how strongly scattering is mixed into the final image.
Light.ScatteringIntensity := 0.1; // Subtle effect
Light.ScatteringIntensity := 0.5; // Noticeable rays
Light.ScatteringIntensity := 2.0; // Strong dramatic rays
Controls the visibility/brightness of individual light rays.
Light.ScatteringExposure := 0.001; // Faint rays
Light.ScatteringExposure := 0.01; // Visible rays
Light.ScatteringExposure := 0.1; // Very bright rays
How quickly rays fade along their path.
Light.ScatteringDecay := 0.5; // Slow decay, long rays
Light.ScatteringDecay := 1.0; // Normal decay
Light.ScatteringDecay := 2.0; // Fast decay, short rays
Density of the scattering medium.
Light.ScatteringDensity := 0.3; // Thin atmosphere
Light.ScatteringDensity := 0.84; // Normal atmosphere
Light.ScatteringDensity := 2.0; // Dense fog/haze
procedure CreateSunbeams(ALight: TGorillaLight);
begin
ALight.LightType := TLightType.Directional;
ALight.RotationAngle.X := -60;
ALight.Color := TAlphaColorRec.Lightyellow;
ALight.Intensity := 1.5;
// Scattering
ALight.ScatteringIntensity := 0.8;
ALight.ScatteringExposure := 0.015;
ALight.ScatteringDecay := 1.2;
ALight.ScatteringDensity := 1.2;
end;
procedure CreateVolumetricSpotlight(ALight: TGorillaLight);
begin
ALight.LightType := TLightType.Spot;
ALight.SpotCutOff := 25;
ALight.Color := TAlphaColors.White;
ALight.Intensity := 3.0;
// Strong visible cone
ALight.ScatteringIntensity := 1.5;
ALight.ScatteringExposure := 0.02;
ALight.ScatteringDecay := 0.8;
ALight.ScatteringDensity := 2.0;
end;
procedure CreateAtmosphericLight(ALight: TGorillaLight);
begin
ALight.LightType := TLightType.Directional;
ALight.Color := TAlphaColorRec.Lightblue;
ALight.Intensity := 0.8;
// Subtle atmosphere
ALight.ScatteringIntensity := 0.3;
ALight.ScatteringExposure := 0.005;
ALight.ScatteringDecay := 1.0;
ALight.ScatteringDensity := 0.5;
end;
TGorillaLight can cast shadows through Gorilla3D's Cascaded Shadow Maps (CSM) system. Shadows are enabled per-viewport via Viewport.Shadows; each light then opts in with CastShadow.
// 1. Turn the shadow system on (once, on the viewport)
GorillaViewport1.Shadows.Enabled := True;
GorillaViewport1.Shadows.CascadeCount := 4;
GorillaViewport1.Shadows.MapResolution := 2048;
GorillaViewport1.Shadows.MaxDirLights := 1;
// 2. Flag the lights that should cast shadows
SunLight.CastShadow := True;
| Property | Type | Default | Purpose |
|---|---|---|---|
CastShadow |
Boolean |
False | Enables shadow casting for this light. |
ShadowBias |
Single |
0.0005 | Constant depth bias during the shadow comparison. |
ShadowSlopeBias |
Single |
0.001 | Slope-scaled bias against acne on grazing surfaces. |
ShadowNormalOffset |
Single |
0.02 | Sample offset along the surface normal (world units). |
ShadowStrength |
Single |
1.0 | Per-light shadow opacity [0..1] — 1.0 opaque, 0.0 disabled. Composes with the global Viewport.Shadows.Strength. |
ShadowNearFar |
TPointF |
(0, 0) | Near/far projection override (X = near, Y = far); only components > 0 apply. Spot/point: (0, 0) auto-derives from attenuation. Directional: clamps the cascade depth band (overrides the automatic fit); (0, 0) keeps auto-fit. |
Shadow darkness: the scene-wide dial is
Viewport.Shadows.Strength— notViewport.ShadowStrength, which only affects the Global Illumination pass.Small / close-up casters: directional cascades auto-fit to the scene geometry (
Viewport.Shadows.AutoFitCascades, on by default). For one small object, setLight.ShadowNearFar := PointF(0.1, 8)for the crispest result.
See Cascaded Shadow Maps for the full system configuration (filters, cascades, point/spot budgets, strength and cascade fitting).
Classic setup for object presentation:
procedure SetupThreePointLighting(AViewport: TGorillaViewport);
var
KeyLight, FillLight, BackLight: TGorillaLight;
begin
// Key Light (main light, 45° front-side)
KeyLight := TGorillaLight.Create(AViewport);
KeyLight.Parent := AViewport;
KeyLight.LightType := TLightType.Directional;
KeyLight.RotationAngle.Point := Point3D(-30, 45, 0);
KeyLight.Color := TAlphaColors.White;
KeyLight.Intensity := 1.5;
// Fill Light (softer, opposite side)
FillLight := TGorillaLight.Create(AViewport);
FillLight.Parent := AViewport;
FillLight.LightType := TLightType.Directional;
FillLight.RotationAngle.Point := Point3D(-20, -45, 0);
FillLight.Color := TAlphaColors.White;
FillLight.Intensity := 0.5;
FillLight.Ambient := TAlphaColorF.Create(0.2, 0.2, 0.2, 1);
// Back Light (rim lighting from behind)
BackLight := TGorillaLight.Create(AViewport);
BackLight.Parent := AViewport;
BackLight.LightType := TLightType.Directional;
BackLight.RotationAngle.Point := Point3D(20, 180, 0);
BackLight.Color := TAlphaColors.White;
BackLight.Intensity := 1.0;
end;
procedure SetupOutdoorLighting(AViewport: TGorillaViewport);
var
Sun, Sky: TGorillaLight;
begin
// Sun (directional, warm)
Sun := TGorillaLight.Create(AViewport);
Sun.Parent := AViewport;
Sun.LightType := TLightType.Directional;
Sun.RotationAngle.Point := Point3D(-50, 30, 0);
Sun.Color := TAlphaColorRec.Lightyellow;
Sun.Intensity := 2.0;
// Sky light (ambient, cool)
Sky := TGorillaLight.Create(AViewport);
Sky.Parent := AViewport;
Sky.LightType := TLightType.Directional;
Sky.RotationAngle.Point := Point3D(0, 0, 0);
Sky.Color := TAlphaColorRec.Lightblue;
Sky.Intensity := 0.3;
Sky.Ambient := TAlphaColorF.Create(0.2, 0.25, 0.3, 1);
end;
procedure SetupIndoorLighting(AViewport: TGorillaViewport);
var
CeilingLight: TGorillaLight;
i: Integer;
begin
// Multiple ceiling lights
for i := 0 to 3 do
begin
CeilingLight := TGorillaLight.Create(AViewport);
CeilingLight.Parent := AViewport;
CeilingLight.LightType := TLightType.Point;
CeilingLight.Position.Y := 8;
CeilingLight.Position.X := (i mod 2) * 10 - 5;
CeilingLight.Position.Z := (i div 2) * 10 - 5;
CeilingLight.Color := TAlphaColorRec.Lightgoldenrodyellow;
CeilingLight.Intensity := 1.5;
// Medium range attenuation
CeilingLight.ConstantAttenuation := 1.0;
CeilingLight.LinearAttenuation := 0.35;
CeilingLight.QuadraticAttenuation := 0.44;
// Soft ambient
CeilingLight.Ambient := TAlphaColorF.Create(0.15, 0.15, 0.12, 1);
end;
end;
procedure SetupCampfireScene(AViewport: TGorillaViewport);
var
Fire: TGorillaLight;
Moon: TGorillaLight;
begin
// Flickering fire (animate intensity in timer)
Fire := TGorillaLight.Create(AViewport);
Fire.Parent := AViewport;
Fire.LightType := TLightType.Point;
Fire.Position.Point := Point3D(0, 0.5, 0);
Fire.Color := TAlphaColorRec.Orange;
Fire.Intensity := 2.0;
Fire.LinearAttenuation := 0.22;
Fire.QuadraticAttenuation := 0.20;
// Dim moonlight
Moon := TGorillaLight.Create(AViewport);
Moon.Parent := AViewport;
Moon.LightType := TLightType.Directional;
Moon.RotationAngle.X := -60;
Moon.Color := TAlphaColorRec.Lightsteelblue;
Moon.Intensity := 0.2;
Moon.Ambient := TAlphaColorF.Create(0.05, 0.05, 0.08, 1);
end;
procedure TForm1.TimerFlickerTimer(Sender: TObject);
var
BaseIntensity: Single;
begin
BaseIntensity := 1.5;
TorchLight.Intensity := BaseIntensity + Random * 0.3 - 0.15;
end;
procedure TForm1.TimerRotateTimer(Sender: TObject);
begin
SpotLight.RotationAngle.Y := SpotLight.RotationAngle.Y + 2;
end;
var
PulseTime: Single = 0;
procedure TForm1.TimerPulseTimer(Sender: TObject);
begin
PulseTime := PulseTime + 0.05;
Light.Intensity := 1.0 + Sin(PulseTime) * 0.5;
end;
var
TimeOfDay: Single = 0; // 0-24 hours
procedure TForm1.UpdateDayNightCycle;
var
SunAngle: Single;
SunIntensity: Single;
begin
// Sun angle based on time
SunAngle := (TimeOfDay / 24) * 360 - 90;
SunLight.RotationAngle.X := SunAngle;
// Intensity based on sun height
SunIntensity := Max(0, Sin(DegToRad(SunAngle + 90)));
SunLight.Intensity := SunIntensity * 2;
// Color shift (warm at sunrise/sunset)
if (TimeOfDay > 5) and (TimeOfDay < 7) then
SunLight.Color := TAlphaColorRec.Orange // Sunrise
else if (TimeOfDay > 18) and (TimeOfDay < 20) then
SunLight.Color := TAlphaColorRec.Orangered // Sunset
else
SunLight.Color := TAlphaColors.White; // Day
TimeOfDay := TimeOfDay + 0.01; // Advance time
if TimeOfDay >= 24 then TimeOfDay := 0;
end;
Each light increases rendering cost:
// Good: Few lights, well-placed
procedure OptimalLighting;
begin
// 1 directional (sun) + 2-3 points = good performance
end;
// Problematic: Many lights
procedure TooManyLights;
var
i: Integer;
begin
for i := 0 to 100 do // Performance issues!
CreatePointLight(...);
end;
// Enable/disable lights based on visibility
procedure UpdateLights;
begin
if Distance(Camera.Position, Light.Position) > 50 then
Light.Enabled := False
else
Light.Enabled := True;
end;
Performance Ranking (best to worst):
Start Simple: Begin with one directional light, add more as needed
Use Realistic Values: Real-world lighting is often dimmer than you think:
Sun.Intensity := 1.5; // Not 10.0
Balance Color Components:
Match Attenuation to Scene Scale: If your scene is in meters, use real-world attenuation ranges
Limit Light Count:
Use Global Illumination Wisely: Enable only when the scene benefits from it
Test on Target Hardware: Lighting performance varies greatly between devices
// Check material type - must use Gorilla3D materials
if MyMesh.MaterialSource is TGorillaDefaultMaterialSource then
ShowMessage('Using Gorilla3D material - OK')
else
ShowMessage('Standard FMX material - limited lighting!');
// Add ambient light
Light.Ambient := TAlphaColorF.Create(0.2, 0.2, 0.2, 1);
// Or increase intensity
Light.Intensity := 2.0;
// Or add fill light
// Increase ambient to fill shadows
Light.Ambient := TAlphaColorF.Create(0.3, 0.3, 0.3, 1);
// Add fill light from opposite direction
// Reduce attenuation for longer range
Light.LinearAttenuation := 0.07;
Light.QuadraticAttenuation := 0.017;
// Or increase intensity
Light.Intensity := 3.0;
The TGorillaModel component is the primary container for loading and managing 3D models in Gorilla3D. It automatically handles sub-meshes, materials, animations, lights, cameras, and armatures, providing a comprehensive solution for 3D model integration.
Important: All 3D models must be children of a
TGorillaViewportinstance to be rendered.
Gorilla3D supports 12+ model formats with varying feature sets:
| Format | Key Features | Animation Support | Export |
|---|---|---|---|
| G3D | Complete support including animations, lights, cameras; internal format | ✓ Yes | ✓ Yes |
| USD | .usd, .usda, .usdc, .usdz; meshes, materials, textures, UsdSkel skeletons |
✓ Yes | ✓ Yes (.usda, .usdc, .usdz) |
| glTF/GLB | 2.0 format only; PBR materials, skinning | ✓ Yes | ✓ Yes (.glb) |
| DAE (Collada) | Animations, lights, cameras; v1.4+ | ✓ Yes | ✗ No |
| FBX | Animations, lights, cameras; Binary only (v7.1-7.7) | ✓ Yes (v7.3-7.7) | ✗ No |
| OBJ | ASCII format | ✗ No | ✓ Yes |
| STL | Binary and ASCII | ✗ No | ✓ Yes |
| Babylon | Limited features | ○ Partial | ✗ No |
| PLY | Limited features | ✗ No | ✗ No |
| SketchUp | Limited features | ✗ No | ✗ No |
All four USD flavours are handled by one loader (Gorilla.USD.Loader), the format is picked by the file extension:
| Extension | Container | Notes |
|---|---|---|
.usda / .usd |
ASCII stage | Human readable, easy to diff |
.usdc |
Binary crate | Compact, fast to parse |
.usdz |
ZIP archive | Carries the stage and its textures; the AR format of iOS Quick Look |
The importer builds the full Gorilla3D model definition from the stage: meshes, materials with their textures (inside .usdz they are read straight out of the archive), UsdSkel skeletons including the joint hierarchy and rest poses, and SkelAnimation clips, which arrive as regular TGorillaAnimation objects:
// The extension decides the parser - nothing else to set up
GorillaModel1.LoadFromFile('models/character.usdz');
// SkelAnimation clips arrive in the regular animation manager
for var LName in GorillaModel1.AnimationManager.Animations.Keys do
Memo1.Lines.Add(LName);
GorillaModel1.AnimationManager.PlayAnimation('Walk');
Store model data directly in .fmx files for quick prototyping:
TGorillaModel component to your formSource property to your model file pathWarning: Large embedded models slow IDE performance and can cause memory issues (3GB IDE-32Bit limit). When storing larges textures and vertex-data the IDE slows down due to
.fmxfile storing process, which is performed on making changes at design time.
Link external ZIP archives for better development workflow:
TGorillaAssetsManager componentAssetsManager and PackageName propertiesSource property to the model filename// Design-time setup
GorillaModel1.AssetsManager := GorillaAssetsManager1;
GorillaModel1.PackageName := 'MyAssets';
GorillaModel1.Source := 'character.dae';
Creates a new model instance and loads data from file:
var
MyModel: TGorillaModel;
begin
MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport, // Owner
nil, // Package (nil = load from file)
'models\character.dae', // Filename
[] // Caching flags
);
MyModel.Parent := Viewport;
end;
With an asset package:
var
MyModel: TGorillaModel;
begin
MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport,
MyAssetsPackage,
'character.g3d',
GORILLA_ANIMATION_CACHING_DEFAULT
);
MyModel.Parent := Viewport;
end;
Loads data into an existing model instance:
GorillaModel1.LoadFromFile(nil, 'models\character.dae', []);
For fine-grained control over the loading process:
var
Options: TGorillaLoadOptions;
begin
Options := TGorillaLoadOptions.Create('models\scene.fbx', [], nil, nil);
// Configure options
Options.ImportLights := False;
Options.ImportCameras := False;
Options.ImportAnimations := True;
Options.Caching := GORILLA_ANIMATION_CACHING_DEFAULT;
// Limit texture sizes
Options.TextureLimits := TPoint.Create(2048, 2048);
// Load the model
GorillaModel1.LoadFromFile(Options);
end;
Texture memory:
TextureLimitsmakes imported textures smaller — it trades resolution for memory and applies only to textures this model brings with it. If your problem is the total video memory of a scene, GPU block compression is usually the better first step: it saves a factor of four across all textures without touching their resolution. The two combine.
For loading from memory or custom sources:
var
Stream: TFileStream;
begin
Stream := TFileStream.Create('model.dae', fmOpenRead);
try
GorillaModel1.LoadFromStream(
nil, // Package
Stream, // Stream
'model.dae', // Path/filename for format detection
[] // Caching flags
);
finally
Stream.Free;
end;
end;
Add animations from separate files:
var
Anim: TGorillaAnimation;
begin
// Model must be loaded first
Anim := GorillaModel1.AddAnimationFromFile(
'character_run.dae',
[]
);
end;
Important: You can only add animations on an existing model, if the meta data from original model import is still available. Because after reloading a model, it's not loaded from the original file format again. So the meta data from a FBX or DAE is lost and animation data cannot be applied again.
Access animations through the built-in AnimationManager:
// List all animations
for var AnimName in GorillaModel1.AnimationManager.Animations.Keys do
Memo1.Lines.Add(AnimName);
// Play an animation
GorillaModel1.AnimationManager.PlayAnimation('Walk');
// Stop current animation
GorillaModel1.AnimationManager.StopAnimation();
// Get current animation
var Current := GorillaModel1.AnimationManager.Current;
if Assigned(Current) then
ShowMessage('Playing: ' + Current.Id);
Animation caching improves performance by pre-computing vertex positions:
| Flag | Description | Use Case |
|---|---|---|
| VertexPosition | Cache vertex positions only (recommended) | Fast playback, moderate memory |
| AllAttributes | Cache all vertex attributes | Maximum speed, high memory usage |
| Compressed | Compress cached data | Large animations, slower than direct caching |
// Recommended: Cache vertex positions only
MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport,
nil,
'character.dae',
[TAnimationCachingFlag.VertexPosition]
);
// For maximum performance (high memory)
MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport,
nil,
'character.dae',
[TAnimationCachingFlag.AllAttributes]
);
// For large animations (compressed)
MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport,
nil,
'character.dae',
[TAnimationCachingFlag.VertexPosition, TAnimationCachingFlag.Compressed]
);
Notice: A global constant
GORILLA_ANIMATION_CACHING_DEFAULTis recommended for usage.
A loaded model contains a hierarchy of components:
TGorillaModel
├─ TGorillaMesh (Sub-meshes)
│ ├─ TGorillaVertexGroup (Material groups)
│ └─ TGorillaMesh (Nested sub-meshes)
├─ TGorillaArmature (Skeleton)
│ └─ TGorillaJoint (Bones)
├─ TGorillaLight (Embedded lights)
├─ TGorillaCamera (Embedded cameras)
└─ TGorillaAnimation (Animations)
// Access meshes
for var i := 0 to GorillaModel1.Meshes.Count - 1 do
begin
var Mesh := GorillaModel1.Meshes[i];
ShowMessage('Mesh: ' + Mesh.Name);
end;
// Find specific mesh by name
var HeadMesh := GorillaModel1.FindControlByDeepSearch('Head') as TGorillaMesh;
if Assigned(HeadMesh) then
HeadMesh.MaterialSource := MyMaterial;
// Access armature
var Armature := GorillaModel1.GetFirstArmature() as TGorillaArmature;
if Assigned(Armature) then
begin
Armature.ShowJoints := True;
Armature.JointsRenderColor := TAlphaColors.Red;
end;
Print the model hierarchy to the event log:
GorillaModel1.DebugOut(False); // FMX hierarchy
GorillaModel1.DebugOut(True); // Component hierarchy
// Apply material to entire model
GorillaModel1.MaterialSource := MyMaterialSource;
// Apply to specific mesh
var Mesh := GorillaModel1.FindControlByDeepSearch('Body') as TGorillaMesh;
if Assigned(Mesh) then
Mesh.MaterialSource := BodyMaterial;
// Batch apply materials
GorillaModel1.ApplyMaterialSource(MyMaterialSource);
Warning: Applying a material to the entire model will overwrite individual mesh materials and cannot be automatically restored.
// Enable wireframe
GorillaModel1.Wireframe := True;
GorillaModel1.WireframeMaterial := MyWireframeMaterial;
Performance: Wireframe rendering is costly. Use only for debugging.
GorillaModel1.ShowNormals := True;
GorillaModel1.NormalsColor := TAlphaColors.Green;
GorillaModel1.ShowJoints := True;
GorillaModel1.JointsColor := TAlphaColors.Yellow;
ShowBoundingBox draws a box around the current pose of the model. The box follows skin animations (rigged models), vertex animations and animated sub-meshes, and it rotates with the model.
GorillaModel1.ShowBoundingBox := True;
GorillaModel1.BoundingBoxColor := TAlphaColors.Orange; // default
Both properties are published and can be set in the form designer. The box is drawn in the main render pass only (not in shadow, reflection or other render passes).
The properties are declared in TGorillaControl, so they are available on every Gorilla3D control, not only on models. What the box encloses depends on the class:
| Class | Box |
|---|---|
TGorillaModel |
Current pose of all sub-meshes, follows skin, vertex and node animations |
TGorillaMesh |
Vertices of the mesh and its sub-meshes, including the mesh matrix (WrapMode). Works for static meshes (IsStatic = True) too: their vertices are taken from the mesh definition |
TGorillaSingletonMesh (TGorillaCube, TGorillaSphere, TGorillaCylinder, ...) |
The body size (Width, Height, Depth), the same box IsMarked draws |
any other TGorillaControl (f.e. TGorillaGroup) |
The size box of the control (Width, Height, Depth) |
A sub-mesh of a model can show its own box as well, f.e. to highlight a single part:
GorillaModel1.Meshes[0].ShowBoundingBox := True;
GorillaModel1.Meshes[0].BoundingBoxColor := TAlphaColors.Red;
Note:
TGorillaParticleEmitterandTGorillaGaussianSplattingrender on their own and do not draw the box.
Not the same as
IsMarked: the box the IDE draws around a selected model (IsMarked) is built from the static vertex data and does not follow animations. It is kept that way on purpose, because the designer relies on it.
Performance: With animation caching the box of every frame is computed once while caching, so showing it costs (almost) nothing. Without caching all animated vertices are iterated each frame.
There are two ways to render the same model several times: GPU instancing (one draw call, shared geometry, material and animation state) and model cloning (independent copies sharing only the vertex data). Use GPU instancing for large numbers of identical objects (trees, rocks, crates, grass), use cloning if every copy needs its own animation or material.
Every TGorillaMesh - and therefore every TGorillaModel, TGorillaCube, TGorillaSphere, ... - owns an Instances collection (TGorillaMeshInstances). For each entry the mesh is drawn once more within the same draw call, the GPU only receives a different transformation matrix per instance.
Things to know before you start:
Position, RotationAngle, Scale of the component) is written to slot 0 of the instance list every frame. Each added instance is an additional copy.TGorillaModel are passed on to all of its sub-meshes automatically, so the complete model is instanced.FrustumCullingCheck is enabled, all instances disappear as soon as the source mesh leaves the camera view. Keep it disabled for instanced meshes that are spread across the scene.There are two APIs to add instances:
AddInstanceItem() |
AddInstance() |
|
|---|---|---|
| Creates | a TGorillaMeshInstance collection item |
only a matrix in the internal instance cache |
| Edit via | Position, RotationAngle, Scale, RotationCenter |
SetInstance(Index, Matrix) |
Visible in the Object Inspector / stored in .fmx |
yes | no |
| Passed on to sub-meshes of a model | yes | no - call it on each mesh with geometry |
| Memory / speed | an object with 4 TPosition3D per instance |
one TMatrix3D per instance (fastest) |
TGorillaMesh provides two overloads:
// Creates an item with identity transform (at the origin) and returns the item itself.
function AddInstanceItem(AName : String) : TGorillaMeshInstance; overload;
// Creates an item, applies the matrix and returns the INDEX of the item in the
// Instances collection (Mesh.Instances.Items[Index]).
function AddInstanceItem(AName : String; ATransform : TMatrix3D) : Integer; overload;
The returned TGorillaMeshInstance is a TCollectionItem with the same transformation properties you know from FMX 3D controls:
| Member | Description |
|---|---|
Position: TPosition3D |
Translation of the instance (absolute, see above) |
RotationAngle: TPosition3D |
Rotation in degrees around X, Y and Z |
Scale: TPosition3D |
Scaling, default (1, 1, 1) |
RotationCenter: TPosition3D |
Pivot the rotation is performed around, default (0, 0, 0) |
DisplayName: String |
Name of the instance (the AName argument) |
Transform: TMatrix3D |
Read-only, the resulting matrix uploaded to the GPU |
OwnerMesh: TGorillaMesh |
The mesh this instance belongs to |
SetTransform(Matrix) |
Sets the instance by a matrix; Position, Scale and RotationAngle are extracted from it |
ResetRotationAngle() |
Resets the rotation to (0, 0, 0) |
BeginUpdate() / EndUpdate() |
Defers matrix and buffer rebuilds, see below |
The matrix is composed in the order Scale → Rotation (around RotationCenter) → Translation.
uses
Gorilla.Mesh, Gorilla.Model;
procedure TForm1.AddTree(const AName : String; const APos : TPoint3D);
var LInst : TGorillaMeshInstance;
begin
LInst := GorillaModel1.AddInstanceItem(AName);
LInst.BeginUpdate();
try
LInst.Position.Point := APos;
LInst.RotationAngle.Point := Point3D(0, Random(360), 0);
LInst.Scale.Point := Point3D(1.5, 1.5, 1.5);
finally
LInst.EndUpdate();
end;
end;
Existing instances are accessed through the collection. Note that the collection does not contain the mesh itself, so Instances.Items[0] is the first additional instance:
var LInst : TGorillaMeshInstance;
begin
for var I := 0 to GorillaModel1.Instances.Count - 1 do
begin
LInst := GorillaModel1.Instances.Items[I] as TGorillaMeshInstance;
LInst.Position.Y := LInst.Position.Y + 1;
end;
end;
The variant with a matrix is handy if you already compute matrices:
var LIdx : Integer;
LInst : TGorillaMeshInstance;
begin
LIdx := GorillaModel1.AddInstanceItem('Crate',
TMatrix3D.CreateRotationY(DegToRad(45)) *
TMatrix3D.CreateTranslation(Point3D(4, 0, -2)));
// Position, Scale and RotationAngle were extracted from the matrix
LInst := GorillaModel1.Instances.Items[LIdx] as TGorillaMeshInstance;
LInst.Position.X := 6;
end;
RotationAngle behaves like in FMX: a change of an angle is applied as the difference to the previous value onto an internal quaternion. Setting
RotationAngle.Y := 90on an instance withY = 45rotates it by another 45 degrees, so the result is 90 degrees as expected. If you want to set a completely new orientation, callResetRotationAngle()first or useSetTransform().
Every single property change of an instance - each Position.X, each RotationAngle.Y, each Scale.Point - triggers:
Setting Position, RotationAngle and Scale of one instance therefore rebuilds the list at least three times. BeginUpdate() defers steps 1-3 until the matching EndUpdate(), which rebuilds the matrix and the instance list exactly once. Calls can be nested, only the outermost EndUpdate() performs the rebuild. Always use try..finally, otherwise an exception leaves the instance locked.
BeginUpdate()/EndUpdate() is the right choice when you change one or a few instances. Each EndUpdate() still rebuilds the whole list, so changing N instances this way costs N list rebuilds. For many instances use BeginInstancesEditing().
TGorillaMesh.BeginInstancesEditing() locks the instance list of the mesh, all of its instance items and all sub-meshes. While locked, property changes and newly added items only update their values. EndInstancesEditing() then rebuilds all instance matrices, the instance list and the sub-mesh lists once:
procedure TForm1.PlantForest(const ACount : Integer);
var LInst : TGorillaMeshInstance;
LScl : Single;
begin
GorillaModel1.BeginInstancesEditing();
try
GorillaModel1.ClearInstances();
for var I := 0 to ACount - 1 do
begin
// items created inside the bracket are covered as well
LInst := GorillaModel1.AddInstanceItem(Format('Tree_%d', [I]));
LInst.Position.Point := Point3D(Random(200) - 100, 0, Random(200) - 100);
LInst.RotationAngle.Point := Point3D(0, Random(360), 0);
LScl := 0.8 + Random * 0.6;
LInst.Scale.Point := Point3D(LScl, LScl, LScl);
end;
finally
// single rebuild for all instances
GorillaModel1.EndInstancesEditing();
end;
end;
The same pattern is used to animate many instances each frame:
procedure TForm1.SwayTrees(const ATime : Single);
var LInst : TGorillaMeshInstance;
begin
GorillaModel1.BeginInstancesEditing();
try
for var I := 0 to GorillaModel1.Instances.Count - 1 do
begin
LInst := GorillaModel1.Instances.Items[I] as TGorillaMeshInstance;
LInst.RotationAngle.Z := Sin(ATime + I) * 5;
end;
finally
GorillaModel1.EndInstancesEditing();
end;
end;
Inside BeginInstancesEditing()/EndInstancesEditing() you do not need BeginUpdate()/EndUpdate() on the single items. As with any lock, every BeginInstancesEditing() needs exactly one EndInstancesEditing().
| Scenario | Use |
|---|---|
| Change one instance | Item.BeginUpdate() / Item.EndUpdate() |
| Create, change or delete many instances | Mesh.BeginInstancesEditing() / Mesh.EndInstancesEditing() |
| Only the collection of a single mesh, without sub-meshes | Mesh.Instances.BeginUpdates() / Mesh.Instances.EndUpdates() |
On a
TGorillaModelalways useBeginInstancesEditing()/EndInstancesEditing()instead ofInstances.BeginUpdates()/EndUpdates()- it also takes care of the sub-meshes in the right order.
If you only need to place a large number of static instances at runtime, you can skip the collection items and add plain matrices to the instance cache. This is the fastest and most memory efficient way, but the instances are neither visible in the Object Inspector nor stored in the .fmx file.
procedure AddMatrixInstances(AMesh : TGorillaMesh; const ATransforms : TArray<TMatrix3D>);
begin
// matrix-only instances are NOT passed on to sub-meshes, so add them to
// every mesh of the hierarchy that has geometry
for var LTransform in ATransforms do
AMesh.AddInstance(LTransform);
if Assigned(AMesh.Meshes) then
for var I := 0 to AMesh.Meshes.Count - 1 do
AddMatrixInstances(AMesh.Meshes[I], ATransforms);
end;
procedure TForm1.FormCreate(Sender: TObject);
var LTransforms : TArray<TMatrix3D>;
begin
SetLength(LTransforms, 100);
for var X := 0 to 9 do
for var Z := 0 to 9 do
LTransforms[X * 10 + Z] := TMatrix3D.CreateTranslation(Point3D(X * 2, 0, Z * 2));
AddMatrixInstances(GorillaModel1, LTransforms);
end;
AddInstance() returns the index of the matrix in the instance cache, which can be used with GetInstance()/SetInstance(). Changes are uploaded with the next frame:
var LIdx : Integer;
begin
LIdx := GorillaCube1.AddInstance(TMatrix3D.CreateTranslation(Point3D(5, 0, 0)));
// ...
GorillaCube1.SetInstance(LIdx, TMatrix3D.CreateTranslation(Point3D(5, 2, 0)));
end;
Index 0 of the cache is the mesh itself and is overwritten every frame -
GetInstance(0)/SetInstance(0, ...)has no lasting effect. Cache indices of additional instances start at 1.
Do not mix both APIs on the same mesh. Whenever an instance item is added, changed or deleted, the cache is rebuilt from the collection items, and all matrix-only instances are dropped.
// remove a single instance item by its collection index
GorillaModel1.DeleteInstance(0);
// or free the item directly
GorillaModel1.Instances.Items[3].Free();
// remove all instance items and all matrix-only instances
GorillaModel1.ClearInstances();
TGorillaMesh.DeleteInstance() works on the collection index of instance items. To remove matrix-only instances, call ClearInstances() and add the remaining matrices again. When deleting many items, wrap the loop in BeginInstancesEditing()/EndInstancesEditing() as well.
The Instances property of every Gorilla3D mesh, model and primitive is published. Open the collection editor in the Object Inspector, add items and edit their Position, RotationAngle and Scale - the instances are rendered immediately in the form designer and stored in the .fmx file. Terrain planting (see Terrain) creates instance items the same way.
Instancing can be done by GPU and providing different transformation matrices like above or by cloning the visual component with all of it's data. Both ways have their advantages and disadvantages.
Use instancing if you want to re-render a mesh multiple times Use cloning if you need different visual feedback (like animations or materials), but if you want to reuse the vertex data itself In the following example we show how to load a complex animated model with multiple meshes and animations. We will load up a template (TModelDef), which will be used for duplication. The template (TModelDef) itself will not be rendered in our example, but of course that's possible too.
Each duplicated model will run a different animation to show instanciating is still fast, but allows to handle models differently. This demo code uses cached animations (GORILLA_ANIMATION_CACHING_DEFAULT), otherwise 32 animated instances will not render properly anymore, due to many vertex operations.
Create independent copies with separate animations and materials:
procedure TForm1.InstanciateModel(AModelsPath : String);
const
NUM_OF_MODELS = 32;
MODELS_SPACE = 8;
var LAnim : TGorillaAnimation;
LMdlPath : String;
I : Integer;
LPlayInst : TGorillaModel;
LOfs : Single;
begin
LAnim := nil;
// load player model
LMdlPath := IncludeTrailingPathDelimiter(AModelsPath) +
IncludeTrailingPathDelimiter('archer');
FPlayerTemplate := TGorillaModel.LoadNewModelFromFile(FGorilla, FPackage,
LMdlPath + 'archer.dae', GORILLA_ANIMATION_CACHING_DEFAULT);
FPlayerTemplate.Parent := FGorilla;
FPlayerTemplate.Scale.Point := Point3D(0.05, 0.05, 0.05);
FPlayerTemplate.SetHitTestValue(false);
// add various animations
FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-aim-idle.dae',
GORILLA_ANIMATION_CACHING_DEFAULT);
FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-idle2.dae',
GORILLA_ANIMATION_CACHING_DEFAULT);
FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-idle3.dae',
GORILLA_ANIMATION_CACHING_DEFAULT);
FPlayerTemplate.AddAnimationFromFile(LMdlPath + 'archer-crouch-idle.dae',
GORILLA_ANIMATION_CACHING_DEFAULT);
// now create instances
FPlayerInstances := TObjectList<TGorillaModel>.Create(false);
I := 0;
for I := 0 to NUM_OF_MODELS - 1 do
begin
// perform a real duplication of visual components by **FALSE** for the second parameter
// if second parameter is **TRUE**, only proxy components will be produced
LPlayInst := FPlayerTemplate.Duplicate(FGorilla, false) as TGorillaModel;
FPlayerInstances.Add(LPlayInst);
LPlayInst.Parent := FGorilla;
// line up characters in a row
LOfs := -(NUM_OF_MODELS div 2) * MODELS_SPACE;
LPlayInst.Position.Point := Point3D(LOfs + (I * MODELS_SPACE), 0, 0);
LPlayInst.RotationAngle.X := 180;
// select one of the available animations - so characters animate differently
case I mod 4 of
0 : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-aim-idle.dae'];
1 : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-idle2.dae'];
2 : LAnim := LPlayInst.AnimationManager.Animations.Items['archer-idle3.dae'];
else LAnim := LPlayInst.AnimationManager.Animations.Items['archer-crouch-idle.dae'];
end;
// start the duplicated character animation
if Assigned(LAnim) then
LAnim.Start();
end;
// we ignore the template for rendering
FPlayerTemplate.Visible := false;
end;
Export models to supported formats:
uses Gorilla.G3D.Exporter;
var
Exporter: TGorillaG3DExporter;
begin
Exporter := TGorillaG3DExporter.Create;
try
Exporter.Format := TGorillaG3DFormat.BSONFormat; // Binary
Exporter.Beautified := False;
Exporter.Zipped := True;
Exporter.SaveToFile(GorillaModel1.Def as TModelDef, 'output.g3d');
finally
Exporter.Free;
end;
end;
uses Gorilla.GLB.Exporter;
var
LExp: TGorillaGLBExporter;
begin
LExp := TGorillaGLBExporter.Create();
try
LExp.Generator := 'My Application'; // written into asset.generator
LExp.SaveToFile(FModel.Def as TModelDef, 'output.glb');
finally
LExp.Free();
end;
end;
Produces a self-contained glTF 2.0 binary file — geometry, PBR materials with embedded images, the node hierarchy, skins and animation samplers all live inside the single .glb container.
One exporter per container, all three write the same scene structure:
| Unit | Class | Extension | Output |
|---|---|---|---|
Gorilla.USDA.Exporter |
TGorillaUSDAExporter |
.usda |
ASCII stage, textures written next to the file |
Gorilla.USDC.Exporter |
TGorillaUSDCExporter |
.usdc |
Binary crate, textures written next to the file |
Gorilla.USDZ.Exporter |
TGorillaUSDZExporter |
.usdz |
ZIP archive holding the stage and its textures |
uses Gorilla.USDA.Exporter;
var
LExp: TGorillaUSDAExporter;
begin
LExp := TGorillaUSDAExporter.Create();
try
LExp.UpAxis := 'Y'; // default
LExp.DefaultPrimName := 'Model'; // name of the root Xform / defaultPrim
LExp.TimeCodesPerSecond := 24.0; // default
LExp.MultiAnimMode := TUSDAMultiAnimMode.VariantSet;
LExp.SaveToFile(FModel.Def as TModelDef, 'character.usda');
finally
LExp.Free();
end;
end;
Skeletons and animations are exported as UsdSkel: a SkelRoot with its Skeleton, the joint rest poses and one SkelAnimation per clip. Because skel:animationSource is a single-target relationship, multiple clips need a layout decision:
MultiAnimMode |
Layout |
|---|---|
VariantSet (default) |
One SkelRoot with one Skeleton and one Mesh; every clip is a sibling SkelAnimation, and a variant set anim switches between them. usdview selects the clip in the Meta Data panel, Blender imports all clips as Actions |
SeparateSkelRoots |
One fully self-contained SkelRoot per clip. Portable across every viewer, but the geometry is duplicated per clip |
SeparateFiles |
Each clip is written to its own sibling file <base>_<animName>.usda / .usdc, matching the Unity / Unreal clip-per-asset convention. The file passed to SaveToFile receives the first clip |
TGorillaUSDCExporter offers the same properties plus MetersPerUnit (default 1.0) and the two toggles EmitSkinPrimvars / EmitTimeSamples (both True), which control whether skin primvars and animation time samples are written.
For a single distributable file — the format iOS Quick Look and most AR viewers expect — use USDZ:
uses Gorilla.USDZ.Exporter;
var
LExp: TGorillaUSDZExporter;
begin
LExp := TGorillaUSDZExporter.Create();
try
LExp.InnerFormat := TUSDZInnerFormat.Usda; // default; Usdc for a binary stage
LExp.USDAEntryName := 'model.usda'; // stage name inside the archive
LExp.SaveToFile(FModel.Def as TModelDef, 'character.usdz');
finally
LExp.Free();
end;
end;
TGorillaUSDZExporterdescends fromTGorillaUSDAExporter, soUpAxis,DefaultPrimName,TimeCodesPerSecondandMultiAnimModeapply here as well. Unlike the.usdaexporter it does not dump the textures next to the file — they are packed into the archive.
Every exporter registers itself for its extension, so a generic save dialog does not need to know the classes:
uses System.IOUtils, Gorilla.Exporter;
var
LExp: TGorillaExporter;
begin
LExp := TGorillaExporter.GetExporter(
LowerCase(TPath.GetExtension(SaveDialog1.FileName))); // '.glb', '.usdz', ...
if Assigned(LExp) then
LExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName)
else
ShowMessage('No exporter registered for this file type.');
end;
GetExporter returns nil for an unregistered extension. The returned instance is owned by the registry — use it, but do not free it. TGorillaExporter.FileTypes holds all registered exporters and can be used to build the filter of the save dialog.
uses
Gorilla.OBJ.Exporter;
procedure TForm1.MenuItem1Click(Sender: TObject);
var LOBJExp : TGorillaOBJExporter;
begin
if Assigned(FModel) then
begin
if SaveDialog1.Execute() then
begin
LOBJExp := TGorillaOBJExporter.Create();
try
LOBJExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName);
finally
FreeAndNil(LOBJExp);
end;
ShowMessage('File successfully stored:'#13#10+
SaveDialog1.FileName);
end;
end;
end;
uses
Gorilla.STL.Exporter;
procedure TForm1.MenuItem1Click(Sender: TObject);
var LSTLExp : TGorillaSTLExporter;
LToBinary : Boolean;
LAllowMultipleMeshes : Boolean;
LUseMultipleFiles : Boolean;
begin
// ascii and binary format supported
LToBinary := true;
// because STL supports only single meshes per file (per default),
// we can split up a model with multiple meshes into multiple files
LAllowMultipleMeshes := true;
// but this exporter also allows to export multiple meshes to a single file
// just set UseMultipleFiles to false
LUseMultipleFiles := true;
if Assigned(FModel) then
begin
if SaveDialog1.Execute() then
begin
LSTLExp := TGorillaSTLExporter.Create();
try
LSTLExp.Binary := LToBinary;
LSTLExp.AllowMultipleMeshes := LAllowMultipleMeshes;
LSTLExp.UseMultipleFiles := LUseMultipleFiles;
LSTLExp.SaveToFile(FModel.Def as TModelDef, SaveDialog1.FileName);
finally
FreeAndNil(LSTLExp);
end;
ShowMessage('File successfully stored:'#13#10+
SaveDialog1.FileName);
end;
end;
end;
Get model dimensions and bounds:
var
BBox: TBoundingBox;
begin
BBox := GorillaModel1.GetBoundingBox();
ShowMessage(Format(
'Width: %.2f, Height: %.2f, Depth: %.2f',
[BBox.Width, BBox.Height, BBox.Depth]
));
end;
GetBoundingBox() is computed from the static (bind pose) vertex data. For the bounds of the currently animated pose use GetAnimatedBoundingBox(). It returns the box in local model space, so transform it with AbsoluteMatrix to get world coordinates:
var
LLocal, LWorld: TBoundingBox;
begin
LLocal := GorillaModel1.GetAnimatedBoundingBox();
LWorld := LLocal.Transform(GorillaModel1.AbsoluteMatrix);
end;
For every sub-mesh the box is taken from the first available source:
Note: Frames of an animation cache that was stored and loaded again do not carry a box. For those the static box is used.
Gorilla3D provides comprehensive ray casting and triangle picking functionality for detecting intersections with 3D models. This is essential for mouse interaction, collision detection, and object selection.
For basic ray-triangle intersection tests using absolute world-space coordinates:
var
RayPos, RayDir: TPoint3D;
Intersection, Normal: TPoint3D;
begin
// Absolute world-space ray
RayPos := Point3D(0, 10, 0);
RayDir := Point3D(0, -1, 0); // Downward
if GorillaModel1.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
begin
ShowMessage('Hit at: ' + Intersection.ToString);
ShowMessage('Surface normal: ' + Normal.ToString);
end;
end;
For mouse interaction, use screen coordinates directly:
procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Pick triangle at mouse position
if GorillaModel1.PickTriangle(X, Y, Intersection, Normal, A, B, C) then
begin
ShowMessage('Clicked at: ' + Intersection.ToString);
// Visualize hit point
HitMarker.Position.Point := Intersection;
HitMarker.Visible := True;
end;
end;
For comprehensive intersection data including distance and object reference:
procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
Result: TTriangleRayCastResult;
begin
if GorillaModel1.PickTriangle(X, Y, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f units', [Result.T]));
ShowMessage('Intersection: ' + Result.Intersection.ToString);
ShowMessage('Normal: ' + Result.Normal.ToString);
// Access triangle corners
ShowMessage(Format('Triangle: [%s, %s, %s]',
[Result.Triangle[0].ToString,
Result.Triangle[1].ToString,
Result.Triangle[2].ToString]));
// Check which mesh was hit
if Assigned(Result.Instance) and (Result.Instance is TGorillaMesh) then
ShowMessage('Hit mesh: ' + TGorillaMesh(Result.Instance).Name);
end;
end;
For custom ray tests (e.g., ground detection):
var
Result: TTriangleRayCastResult;
RayPos, RayDir: TVector3D;
begin
// Cast ray from character position downward to find ground
RayPos := Vector3D(Character.Position.X, Character.Position.Y + 1, Character.Position.Z);
RayDir := Vector3D(0, -1, 0);
if GorillaModel1.PickTriangle(RayPos, RayDir, Result) then
begin
// Place character on ground
var GroundHeight := Result.Intersection.Y;
Character.Position.Y := GroundHeight;
ShowMessage(Format('Ground found at height: %.2f', [GroundHeight]));
end;
end;
| Method | Input | Use Case |
|---|---|---|
| RayCastIntersect | Absolute ray (world space) | Basic intersection tests with custom rays |
| PickTriangle (X, Y) | Screen coordinates | Mouse interaction, object picking |
| PickTriangle (Ray) | Absolute ray (world space) | Ground detection, collision checks, AI vision |
| PickTriangle (Result) | Screen or absolute ray | When you need detailed intersection data |
Important: All methods perform deep search through the entire model hierarchy, testing all submeshes recursively.
Mark meshes as static for better performance when geometry doesn't change:
// Set at load time via TGorillaLoadOptions
Options.VertexDataFlags := []; // Static mesh
// Or modify after loading
for var i := 0 to GorillaModel1.Meshes.Count - 1 do
GorillaModel1.Meshes[i].IsStatic := True;
Firemonkey provides the HitTest property for all TControl3D objects. This property allows mouse interaction with the specific
3D model. Because this performs ray casting under the hood, it is recommended to disable this feature for elements that do not
need mouse interaction (click, mouse-down, mouse-up, mouse-move).
When working with large 3D models and many triangles/vertices it is also recommended to deactivate it.
Because the HitTest property can not be overwritten, Gorilla3D provides a traversing method to deactivate complete mesh and model structures with all their sub-meshes.
GorillaModel1.SetHitTestValue(false);
When you set the property value directly, only the specific control will be deactivated. This is useful if you only want selected meshes to be responsive.
GorillaModel1.Meshes[0].HitTest := false;
Reduce texture memory usage:
var
Options: TGorillaLoadOptions;
begin
Options := TGorillaLoadOptions.Create('model.dae', [], nil, nil);
Options.MaxTextureWidth := 1024;
Options.MaxTextureHeight := 1024;
GorillaModel1.LoadFromFile(Options);
end;
Enable per-mesh frustum culling:
for var i := 0 to GorillaModel1.Meshes.Count - 1 do
GorillaModel1.Meshes[i].FrustumCullingCheck := True;
Download models directly from Sketchfab at runtime:
Note: Requires OAuth credentials from Sketchfab developer portal. Currently disabled for security reasons but can be enabled.
var
Options: TGorillaLoadOptions;
begin
Options.FileInfo.OpenFormat := TGorillaFileOpenFormat.fofDownload;
Options.FileInfo.PathOrUID := 'model-uid';
Options.FileInfo.URL := 'https://sketchfab.com/api/...';
Options.FileInfo.OAuthMode := TGorillaOAuthMode.AuthCode;
Options.FileInfo.ClientId := 'your-client-id';
Options.FileInfo.ClientSecret := 'your-client-secret';
GorillaModel1.LoadFromFile(Options);
end;
.fmx filesSkinned models with several parts (glTF): Earlier versions stored a skin that drives several meshes incompletely in the
.fmxbinary data. A glTF mesh with several primitives is such a case, and so is a skin shared by several mesh nodes (e.g. BrainStem). The model looked correct in the designer, but at runtime only one part animated (e.g. only the hair of a character). The binary data now keeps the joint weights of every mesh. Models embedded with an older version have to be loaded again at design time (assignSourceonce more and save the form). The old binary data cannot be repaired because it does not contain the weights of the other parts.
| Aspect | Embedded | Asset Package |
|---|---|---|
| IDE Performance | Slower with large models | Fast |
| Deployment | Single executable | Requires external files |
| Development | Slow on changes | Fast iteration |
| Memory | Always loaded | Loaded on demand |
.usda while debugging (readable, diffable), .usdc for size and parse speed, .usdz to ship one file including texturesVertexPosition flag for balanced performance/memoryDriving skeletal animations directly: playback speed, exact positioning inside a clip, crossfading and vertex morphing.
Classes: TGorillaAnimationManager, TGorillaAnimation, TSkeletonKeyAnimation
Unit: Gorilla.Animation
TGorillaModel
└─ AnimationManager : TGorillaAnimationManager playback, clip switching, crossfade
└─ TGorillaAnimation one clip ("c-walk.dae")
└─ Skeleton : TSkeletonKeyAnimation the clock, the loop flag, the tick
└─ Interpolators one per animated joint / property
(TPoint3DKeyAnimation, TQuaternion3DKeyAnimation,
TTransformationKeyAnimation, TCoordinateKeyAnimation, ...)
The important part for fine-grained control: a TGorillaAnimation is not itself an FMX
animation. Its Skeleton is - it holds the clock (CurrentTime, Duration, Loop,
Pause) and, on every tick, copies its own time into each interpolator and lets them
write the joint values. Everything below works on Skeleton and on its
Interpolators list, both of which are public.
var LAnim : TGorillaAnimation;
// by ID, through the manager (recommended - this is the path that crossfades)
GorillaModel1.AnimationManager.PlayAnimation('c-walk.dae');
// or on the instance
LAnim := GorillaModel1.AnimationManager.GetAnimation('c-walk.dae');
LAnim.Start();
To find the ids, use AnimationManager.GetAnimationNames() (or GetSortedAnimations()
for the instances) - both naturally sorted, Walk2 before Walk10.
PlayNextAnimation / PlayPreviousAnimation step through that same order and wrap
around; see Listing Animations.
| Member | Effect |
|---|---|
Start() |
Enables the skeleton and makes the clip the manager's current one (no crossfade, the previous clip is not stopped) |
Stop() |
Disables the skeleton. FMX advances the clip to its final frame first |
StopAtCurrent() |
Disables the skeleton without the final-frame jump - the visible pose is kept |
Reset() |
Ticks all interpolators at time 0 |
IsRunning / IsPaused |
State of the skeleton (Skeleton.Running / the pause flag below) |
Skeleton.Pause |
Up to Delphi 12: True freezes playback; the pose stays where it is |
Skeleton.Paused |
Delphi 13+: the same, use it instead of Pause (see below) |
Skeleton.Loop |
Repeat the clip |
Pausing only stops the automatic advance: the animation tick keeps arriving and returns immediately. You can still position the clip yourself, see Stepping Through a Clip.
TGorillaModel offers shortcuts to ask for the animation state without checking
AnimationManager and AnimationManager.Current yourself:
| Member | Effect |
|---|---|
HasCurrentAnimation() |
True if the model has an animation manager with a current animation. The current animation does not need to be playing |
TryGetCurrentAnimation(out AAnim) |
Returns the current animation in AAnim, or nil and False if there is none |
IsAnimationPlaying() |
True if the current animation is playing at the moment |
IsAnimationPlaying(AId) |
True if the animation with id AId is playing - whether it is the current one or not (f.e. while blending). The id is looked up like GetAnimation does; unknown ids give False |
ResetToBindPose() |
Stops all animations and returns the model to its unanimated pose (shortcut for AnimationManager.ResetToBindPose) |
var LAnim : TGorillaAnimation;
if GorillaModel1.TryGetCurrentAnimation(LAnim) then
Label1.Text := LAnim.Id;
if GorillaModel1.IsAnimationPlaying('walk') then
GorillaModel1.ResetToBindPose();
Neither Stop() nor Reset() brings back the bind pose: Stop leaves the last pose of
the clip, Reset jumps to the first frame of the clip. ResetToBindPose works for cached
and CPU skinned animations alike:
Current stays assigned, PlayAnimation starts from the bind pose afterwardsUp to Delphi 12 skeletons are advanced by the FMX animation thread, and
TGorillaAnimationManager.ForceStep can step it right before a frame is drawn.
Delphi 13 replaced that thread with a display link that skips ticks while a paint is
pending - with a busy renderer that means poses advancing in lumps. Gorilla3D therefore
puts running skeletons (and TPoint3DAnimations) under TGorillaRenderClock:
Start hands them over, TGorillaViewport advances them once at the start of every
rendered frame, Stop gives them back. To keep FMX's own ticks out, the clock holds the
FMX Pause flag of every animation it drives, which has two consequences:
Skeleton.Paused (or read IsPaused), not Skeleton.PauseForceStep no longer steps anything on Delphi 13; it only reports whether the minimum
delta has passedprocedure TGorillaAnimation.SetSpeed(const ASpeed : Single);
The implementation multiplies the Duration of every interpolator by ASpeed:
LInter.Duration := LInter.Duration * ASpeed;
Three consequences worth knowing before using it:
SetSpeed(2.0) makes the clip take
twice as long, i.e. it plays at half speed. Use 1 / rate.2.0 gives a four times
longer clip. There is no "reset to original".Skeleton.Duration. The skeleton clock still loops or stops at
the original clip length, while the interpolators now normalize against a different
one - the clip would restart before the pose reached its end.So for anything but a one-off tweak, set both levels explicitly.
Remember the original durations once, then derive every later rate from them:
type
TAnimationRate = record
private
FAnim : TGorillaAnimation;
FBaseSkel : Single;
FBaseInts : TArray<Single>;
public
procedure Attach(const AAnim : TGorillaAnimation);
procedure SetRate(const ARate : Single);
end;
procedure TAnimationRate.Attach(const AAnim : TGorillaAnimation);
var i : Integer;
begin
FAnim := AAnim;
FBaseSkel := AAnim.Skeleton.Duration;
SetLength(FBaseInts, AAnim.Skeleton.Interpolators.Count);
for i := 0 to AAnim.Skeleton.Interpolators.Count - 1 do
FBaseInts[i] := AAnim.Skeleton.Interpolators[i].Duration;
end;
procedure TAnimationRate.SetRate(const ARate : Single);
var i : Integer;
begin
if (ARate <= 0) or not Assigned(FAnim) then
Exit;
// 1.0 = original speed, 2.0 = twice as fast, 0.5 = half speed
FAnim.Skeleton.Duration := FBaseSkel / ARate;
for i := 0 to FAnim.Skeleton.Interpolators.Count - 1 do
FAnim.Skeleton.Interpolators[i].Duration := FBaseInts[i] / ARate;
end;
Usage:
FWalkRate.Attach(GorillaModel1.AnimationManager.GetAnimation('c-walk.dae'));
FWalkRate.SetRate(1.6); // sprint
FWalkRate.SetRate(1.0); // back to authored speed
Durations live on the animation instance, and every TGorillaModel creates its own
instances - changing the rate on one character does not affect the others.
Everything is driven by one scalar. Skeleton.CurrentTime runs from 0 to
Skeleton.Duration (seconds); NormalizedTime is that value divided by the duration,
so 0.0 .. 1.0. The interpolators receive the skeleton's time on every tick and pick
the two keys surrounding it.
| Member | Meaning |
|---|---|
Skeleton.Duration |
Clip length in seconds |
Skeleton.CurrentTime |
Current position in seconds (read-only) |
Skeleton.NormalizedTime |
Current position as 0..1 (read-only) |
Skeleton.TransitionTime |
Last normalized time the skeleton evaluated |
Animation.FrameCount / FrameRate |
The cache grid, see below - not the source clip's frame rate |
Poses are not looked up per frame, they are interpolated between the two surrounding keys:
LTrans := (LNorm - LKey1.Key) / (LKey2.Key - LKey1.Key);
LVal := Self.InterpolatePoint3D(LV1, LV2, LTrans);
SLerp on quaternionsTCoordinateKeyAnimation): linear per vertexSo any position between two keys is a real interpolated pose, not a snap to the nearest frame. "Frame 14.5 of a 29-frame clip at 30 fps" is simply a time:
// frame index -> normalized position -> seconds
LNorm := 14.5 / 29; // 0.5
LTime := LNorm * LAnim.Skeleton.Duration; // seconds
Be careful with what "frame" means.
TGorillaAnimation.FrameCountandFrameRatedescribe the cache grid the engine can bake a clip onto (FrameRateis a build constant, 60 on Windows, 24 on some mobile platforms), not the frame count of the imported file. If your source clip has 29 frames at 30 fps, derive positions from your own frame count and the clipDuration, as above - do not assumeFrameCountmatches the authoring tool.
SeekTo puts the clock at an absolute time without evaluating a pose; ProcessTick
with a zero delta then evaluates exactly there:
procedure SeekNormalized(const AAnim : TGorillaAnimation; const APos : Single);
var LSkel : TSkeletonKeyAnimation;
begin
LSkel := AAnim.Skeleton;
// clamp slightly below 1.0: reaching Duration ends (or wraps) the clip
LSkel.SeekTo(Min(APos, 0.9999) * LSkel.Duration);
// deltaTime = 0 -> the clock stays where SeekTo put it, the pose is written
LSkel.ProcessTick(0, 0);
end;
SeekNormalized(LAnim, 0.5); // exactly half way through the clip
SeekNormalized(LAnim, 14.5 / 29); // "frame 14.5" of a 29-frame clip
Two conditions apply, both coming from FMX TAnimation.ProcessTick:
LAnim.Start()), and the FMX Pause flag must be
False - otherwise ProcessTick returns without evaluatingDuration runs the end-of-clip logic: with Loop = False the clip stops and
OnFinish fires, with Loop = True the clock wraps to zero. Hence the clamp.Delphi 13+: a running skeleton sits under
TGorillaRenderClock, which holds its FMXPauseflag - a directProcessTick(0, 0)therefore returns without evaluating. Either let the next rendered frame evaluate the position (SeekToalone; the render clock then adds that frame's delta), or take the skeleton off the clock for the evaluation:TGorillaRenderClock.Release(LSkel); // FPause back to the clip's own pause state try LSkel.SeekTo(LPos * LSkel.Duration); LSkel.ProcessTick(0, 0); finally TGorillaRenderClock.TakeOver(LSkel); // note: resets a Paused state to False end;
Because the clock is set absolutely before every evaluation, a tick from the FMX
animation thread in between does not accumulate - the next SeekTo discards it.
When you want the clip to advance only when you say so - batch rendering, a timeline
scrubber, deterministic recording - use the caching tick instead. It ignores the
Running and Pause flags and advances the interpolators directly:
procedure TSkeletonKeyAnimation.ProcessAnimationRemote(ATime, ADeltaTime : Single);
LAnim.Stop(); // the animation thread leaves it alone
...
// advance by exactly one output frame and write the pose
LAnim.Skeleton.ProcessAnimationRemote(0, 1 / 30);
This path is relative: each call advances by ADeltaTime from wherever the
interpolators currently are. Use it to walk a clip from its beginning at a fixed step;
use SeekTo + ProcessTick when you need to jump to an arbitrary position.
If a clip was loaded with caching flags, the engine bakes vertex buffers on a fixed grid and the renderer picks one by rounding:
LFrame := Round(Self.FFrameCount * FSkeleton.TransitionTime);
That rounding is exactly what you do not want for sub-frame positioning: two nearby positions can resolve to the same baked frame. Joints are still interpolated (they feed IK and bounds), but the drawn mesh comes from the baked buffer.
For frame-accurate work, load the clip without caching - which is the default:
GorillaModel1.AddAnimationFromFile(LPath + 'c-walk.dae', []); // no caching
The cache can be changed after loading - for all animations or only for selected ones (ids are compared case-insensitively, unknown ids are ignored):
| Method | Effect |
|---|---|
RecacheAnimations(ACaching = []) |
Throws the cached frames of all animations away and bakes them again |
RecacheAnimationsByName(AIds, ACaching = []) |
The same for the animations in AIds |
DiscardAnimationCache() |
Throws the cached frames of all animations away - they play skinned on the CPU afterwards |
DiscardAnimationCacheByName(AIds) |
The same for the animations in AIds |
// frame-accurate work on 'idle', everything else stays cached
GorillaModel1.DiscardAnimationCacheByName(['idle']);
// bake 'walk' and 'run' again
GorillaModel1.RecacheAnimationsByName(['walk', 'run']);
ACaching = [] keeps the flags each animation was cached with before - animations that
were never cached (or whose cache was discarded) stay uncached. Pass flags (f.e.
GORILLA_ANIMATION_CACHING_DEFAULT) to bake them again:GorillaModel1.DiscardAnimationCache();
GorillaModel1.RecacheAnimations(GORILLA_ANIMATION_CACHING_DEFAULT);
The engine does have a crossfade. It lives on TGorillaAnimationManager and interpolates
every joint from the pose that was visible at the switch into the new clip.
| Property | Default | Description |
|---|---|---|
BlendEnabled |
True |
Master switch for crossfading |
BlendDuration |
0.25 |
Base fade length in seconds; 0 disables blending |
BlendUseSmoothStep |
True |
Smoothstep easing instead of a linear ramp |
BlendAdaptive |
True |
Scale the fade by how far apart the two poses are |
BlendMaxDuration |
0.6 |
Upper bound for the adaptive duration |
BlendActive |
- | Read-only: True while a fade is running |
with GorillaModel1.AnimationManager do
begin
BlendEnabled := True;
BlendDuration := 0.2; // idle <-> walk feels tight at 0.15 - 0.25
BlendAdaptive := True; // mid-throw -> idle gets more time automatically
BlendMaxDuration := 0.5;
BlendUseSmoothStep := True;
end;
GorillaModel1.AnimationManager.PlayAnimation('c-walk-right.dae');
With BlendAdaptive, the effective length is derived from the largest angular distance
between the captured pose and the target pose and clamped to
[BlendDuration, BlendMaxDuration] - similar poses fade quickly, far-apart poses get
more time.
Some rigs (complex humanoid FBX exports such as ReadyPlayerMe characters) show limb skew during element-wise matrix blending. Turn the crossfade off per model in that case:
GorillaModel1.AnimationManager.BlendEnabled := False;
The crossfade is implemented inside PlayAnimation. It captures the current pose,
stops the old clip with StopAtCurrent (so its final frame never flashes), starts the
blend and then the new clip.
Assigning AnimationManager.Current does not blend - it stops the old clip and
switches hard. That is also the reason
TGorillaAnimationController switches without a
fade and why its tmBlend mode is still a placeholder: its Switch goes through
Current := ....
If you want transition-driven switching and crossfades, use the controller's transition table as a decision engine and perform the switch yourself:
var
LLay : TGorillaAnimationTransitionLayer;
LTr : TGorillaAnimationTransition;
LCur : TGorillaAnimation;
begin
LLay := GorillaAnimationController1.FindLayer('Layer0');
LCur := GorillaModel1.AnimationManager.Current;
if LLay.Transitions.TryGetTransition(LCur, AHotKey, AStates, LTr) then
begin
// PlayAnimation instead of the controller's own Switch -> crossfade
GorillaModel1.AnimationManager.PlayAnimation(LTr.AnimationTo);
GorillaModel1.AnimationManager.Current.Skeleton.Loop := LTr.Loop;
end;
end;
You take over Loop handling and the one-shot return that the controller would do for
you - see the controller guide for what that involves.
if GorillaModel1.AnimationManager.BlendActive then
GorillaModel1.AnimationManager.CancelBlend(); // hard cut, joints keep current values
Blends cascade: switching again while a fade is running captures the blended pose as the new starting point, so rapid switches stay smooth.
A clip whose animator moved the character forward - a walk or a run that travels - carries that travel in its keys. As soon as the application moves the object too, the character is moved twice: once by its own transform, once by the animation. The two movers cannot be cancelled against each other reliably, because the correction is written when the scene is updated while the drawn frame is picked later, during rendering, from a clock that advances on its own. Whenever the clip wraps between those two moments, a correction for the end of the travel meets frame zero, and the body is drawn the whole travel distance away for a single frame.
InPlace removes the second mover instead of fighting it.
var LAnim : TGorillaAnimation;
LAnim := GorillaModel1.AnimationManager.GetAnimation('c-run.dae');
LAnim.InPlace := True; // horizontal travel removed
GorillaModel1.AnimationManager.PlayAnimation(LAnim);
What this does and does not touch:
TAnimationDef.InPlace), so it applies to every
model instance that shares that definition - which is what you want, because the cached
frames are shared too. Duplicated characters do not each need their own call.InPlace := False puts the original track back; the clip travels again.The travel is not thrown away, it is only taken out of the skeleton - so the application can apply it to the object's own transform and stay in control of collision, steering and speed:
// does this clip travel at all? valid before InPlace is set as well
if LAnim.HasRootMotion then
begin
LTotal := LAnim.RootMotionTotal(); // first key to last key, model units
LPeak := LAnim.RootMotionPeak(); // largest distance reached anywhere
LNow := LAnim.RootMotionAt(LAnim.Skeleton.NormalizedTime); // at 0..1 of the clip
end;
RootMotionAt returns a TPointF - X is the world X component, Y is the world Z one -
relative to the first frame of the clip and in model units, so a scaled model needs the
value scaled as well. A typical locomotion step looks like this: remember the value of the
previous tick, move the character by the difference, remember the new value.
This is the part that costs people an afternoon.
A clip that was loaded with caching flags is not drawn from its joints. The engine bakes a
vertex buffer per frame, and from then on TGorillaMesh.Render asks
TGorillaAnimation.GetCurrentCachedFrame for the buffer to draw -
TSkeletonKeyAnimation.ProcessAnimation even skips the joint pass entirely while frames
are baked.
Those baked frames still contain the travel. Setting InPlace therefore throws them
away and resets the buffering state to None, and nothing rebuilds them afterwards:
baking happens in TModelDef.CacheAnimations, which the loaders call while a model is
read - playback never does. GetCurrentCachedFrame then answers nil, the renderer falls
back to the mesh's static buffer, and the character stands in its bind pose while the
animation happily reports IsRunning = True.
Since v1.5 there is a SetInPlace overload that closes the gap:
// model was loaded WITH caching flags:
LAnim.SetInPlace(True, True); // set the flag AND bake the clip again
procedure TGorillaAnimation.SetInPlace(const AValue : Boolean;
const ARebuildCache : Boolean); overload;
procedure TAnimationDef.SetInPlace(const AValue : Boolean;
const ARebuildCache : Boolean; const AModel : TComponent = nil); overload;
Rebuilding is opt-in and deliberately not the default: it costs exactly what the initial
caching cost, which for a character with twenty clips is seconds, and only the caller knows
whether this clip is worth it at this moment. Assigning the InPlace property keeps the
old behaviour - drop the frames, leave them dropped.
Notes on the rebuild:
TAnimationDef.CachingFlags). A clip
that was never cached has nothing to rebuild, and the call does nothing extra - which is
exactly right, because an uncached clip is skinned live and shows the change immediately.TGorillaAnimation overload restarts it through the manager when it was running.TAnimationDef the model parameter is optional; without it a temporary model instance
is built from the definition. The frames are stored per mesh definition either way, so
they arrive at every instance. The TGorillaAnimation overload passes its own model and
saves that throwaway instance.Which leaves three ways to use InPlace, all of them valid:
| Setup | What to call | Result |
|---|---|---|
| Loaded without caching flags | InPlace := True |
Skinned live, takes effect at once |
| Loaded with caching flags, clip worth baking | SetInPlace(True, True) |
Baked again, in place |
| Loaded with caching flags, before the first bake | InPlace := True, then TModelDef.CacheAnimations |
Baked once, in place |
The root joint is detected, not named: it is the animated joint whose horizontal
translation actually varies. Child joints translate by their constant bone offset, so
their range is zero, which identifies the root on any rig without relying on it being
called Hips or root. A clip that already animates in place has no joint with a range at
all and correctly reports HasRootMotion = False.
For a rig where that heuristic picks the wrong joint, name it explicitly on the definition
before touching InPlace:
TAnimationDef(LAnim.Def).RootMotionJoint := 'Hips';
LAnim.InPlace := True;
Two different things are often called morphing, and only one of them exists here.
Vertex animation (TCoordinateKeyAnimation) - supported. An animation can carry
keys that hold complete vertex arrays; playback interpolates them per vertex:
Result[i] := Start[i] + (Stop[i] - Start[i]) * T;
That is a real shape morph, and everything above applies to it: you can seek to an arbitrary position between two shape keys and get an interpolated mesh. The keys must belong to one animation on one mesh, so the vertex count and order have to match - authored in the DCC tool and exported as a mesh/vertex animation.
Runtime morph targets / blend shapes with weights, or morphing between two separate models - not supported. There is no API to mix several shape targets by weight, and the crossfade described above blends joint values of one skeleton, not geometry. A caterpillar turning into a butterfly therefore has to be one mesh with one vertex animation, not two models blended at runtime.
Rendering a clip into 2D frames needs exactly the two things above: a deterministic
position and a way to grab the result. TGorillaViewport.MakeScreenshot returns a
TBitmap of the rendered viewport.
procedure TForm1.RenderClip(const AAnimId : String; const AFrames : Integer;
const ADir : String);
var
LAnim : TGorillaAnimation;
LSkel : TSkeletonKeyAnimation;
LBmp : FMX.Graphics.TBitmap;
i : Integer;
LPos : Single;
begin
LAnim := GorillaModel1.AnimationManager.GetAnimation(AAnimId);
if not Assigned(LAnim) then
Exit;
LSkel := LAnim.Skeleton;
GorillaModel1.AnimationManager.BlendEnabled := False; // no fade into the first pose
LAnim.Start();
LSkel.Loop := False;
for i := 0 to AFrames - 1 do
begin
// sample positions evenly, never exactly at 1.0
LPos := i / AFrames;
LSkel.SeekTo(LPos * LSkel.Duration);
LSkel.ProcessTick(0, 0); // write the pose at that exact position
GorillaViewport1.RenderManual(); // render this pose synchronously
LBmp := GorillaViewport1.MakeScreenshot();
try
LBmp.SaveToFile(Format('%s\%s_%.3d.png', [ADir, AAnimId, i]));
finally
FreeAndNil(LBmp);
end;
end;
LAnim.Stop();
end;
RenderManual() draws the scene synchronously into the viewport's render target, which
is what MakeScreenshot() then copies - so the bitmap always shows the pose you just
seeked to, without waiting for the next paint cycle. The returned bitmap belongs to the
caller.
Notes for this use case:
AFrames is yours to choose - it is independent of the source clip's frame count,
because every position is interpolated. Sampling 12 sprites out of a 29-frame walk is
just i / 12.SetSpeed scales interpolator durations only, relatively and cumulatively, and > 1
means slower. Prefer setting Skeleton.Duration and the interpolator durations from
stored base values.Skeleton.ProcessTick needs a running, unpaused animation.
ProcessAnimationRemote works on a stopped one but advances relatively.PlayAnimation only, not when assigning
AnimationManager.Current - and therefore not for switches made by
TGorillaAnimationController.tmBlend in the animation controller is a placeholder and currently behaves like
tmSequentially.InPlace removes horizontal root motion only, and it acts on the definition - it cannot
be set per instance of a shared model. On a cached clip the rebuild
(SetInPlace(True, True)) re-bakes the whole clip; there is no partial update of the
baked frames.Materials in Gorilla3D define how 3D objects appear when rendered, controlling colors, textures, lighting, and advanced effects like normal mapping, PBR (Physically-Based Rendering), and shadows. The framework provides a comprehensive material system centered around TGorillaDefaultMaterialSource with 18+ specialized material types.
Important: Materials must be assigned to meshes via the
MaterialSourceproperty to be rendered.
Gorilla3D uses a node-based architecture to automatically generate GLSL shaders at runtime. This system:
TGorillaNodeEntity nodesTGorillaDefaultMaterialSource (Component)
└─ TGorillaDefaultMaterial (Material)
├─ Vertex Shader (TGorillaGLSLVertexShader)
│ └─ Nodes (position, displacement, transforms)
└─ Fragment Shader (TGorillaGLSLFragmentShader)
└─ Nodes (lighting, textures, PBR, effects)
The TGorillaDefaultMaterialSource is the primary material component providing:
Of course you can you the classical derivates of TGorillaDefaultMaterialSource like
TGorillaLambertMaterialSource, TGorillaPhongMaterialSource, TGorillaBlinnMaterialSource, ...
To set up a free configurable material source, we recommend to use a TGorillaCustomMaterialSource instance.
Because many properties are hidden in the TGorillaDefaultMaterialSource by default.
TGorillaCustomMaterialSource component to your formMaterialSource propertyvar
Material: TGorillaCustomMaterialSource;
begin
Material := TGorillaCustomMaterialSource.Create(Self);
Material.Diffuse := TAlphaColorF.Create(0.8, 0.8, 0.8, 1.0);
Material.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
Material.Shininess := 32.0;
// By default Texture0 is expected - deactivate to allow color rendering only
Material.UseTexture0 := false;
// Assign to mesh
Mesh.MaterialSource := Material;
end;
Shading models describe the way lights interacts with a material. The shading model has direct effect to the rendering performance. So simple mechanisms like lambert are much faster in rendering than physically-based rendering.
Simple diffuse lighting without specular highlights. Best for matte surfaces.
Material.ShadingModel := TGorillaShadingModel.smLambert;
Material.Diffuse := TAlphaColorF.Create(0.7, 0.5, 0.3, 1.0);
Classic lighting model with specular highlights. Good for shiny surfaces.
Material.ShadingModel := TGorillaShadingModel.smPhong;
Material.Diffuse := TAlphaColorF.Create(0.7, 0.5, 0.3, 1.0);
Material.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
Material.Shininess := 64.0;
Improved Phong model with better performance and visual quality.
Material.ShadingModel := TGorillaShadingModel.smBlinnPhong;
Material.Shininess := 32.0;
Realistic rendering using physical properties (metalness, roughness).
Material.ShadingModel := TGorillaShadingModel.smPBR;
Material.MetallicBias := 0.8; // 0=dielectric, 1=metal
Material.RoughnessBias := 0.3; // 0=smooth, 1=rough
Material.AOBias := 1.0; // Ambient occlusion
For extended PBR rendering special textures for those elements are needed.
To activate the texture usage for a property use UsePBRAlbedoTexture,
UsePBRAOTexture, UsePBRMetallicTexture, UsePBRRoughnessTexture or UsePBREmissiveTexture.
Base color/albedo map:
Material.UseTexturing := True;
Material.UseTexture0 := True;
Material.Texture.LoadFromFile('diffuse.png');
Every texture in a material lives in the material's bitmap pool (the Bitmaps property, a TGorillaBitmapPool of TGorillaBitmapPoolEntry items). Beside the raw image (Bitmap), each entry carries GPU sampling settings — among them Tiling and the Wrap modes.
Tiling (TPointF, default (1.0, 1.0)) controls how often the texture repeats across the surface UVs. The scalar components TilingX / TilingY address the axes individually:
// Repeat the diffuse texture 8×8 times
Material.Bitmaps.Items[0].Tiling := PointF(8.0, 8.0);
Material.Bitmaps.Items[0].WrapS := TGorillaTextureWrap.Repeated;
Material.Bitmaps.Items[0].WrapT := TGorillaTextureWrap.Repeated;
Important — black seam lines when tiling: Tiling is computed in GLSL via
mod(texcoord * tiling, 1.0)and therefore works regardless of the wrap mode. But for seamless tiles the wrap mode must beRepeatedorMirroredRepeat. IfWrapS/WrapT(orWrapRfor 3D textures) is left at a clamping mode (Clamp,ClampToEdge,ClampToBorder), the filter footprint at each tile seam clamps to the texture border and produces visible dark / black lines along the tile edges. A fresh bitmap entry defaults to a clamping wrap mode, so always setRepeatedexplicitly whenTiling > 1.
See Default Material → The Bitmaps Property for the full property list.
Surface detail without geometry:
Material.UseNormalMapping := True;
Material.NormalMap.LoadFromFile('normal.png');
Material.NormalIntensity := 1.0; // Adjust bump intensity
Material.InverseNormalMapping := False; // Set True for DirectX-style normals
Advanced depth mapping for realistic surface detail:
Material.UseParallaxOcclusionMapping := True;
Material.ParallaxOcclusionMap.LoadFromFile('pom_map.png');
Material.ParallaxLevels := 64; // 4-256 (higher = better quality, lower performance)
Material.NormalIntensity := 0.1; // Adjust parallax shifting intensity
Controls specular highlights per-pixel:
Material.UseSpecular := true;
Material.UseSpecularMapping := True;
Material.SpecularMap.LoadFromFile('specular.png');
Self-illuminating surfaces (glow effects):
Material.UseEmissiveColoring := True;
Material.UseEmissiveMapping := True;
Material.EmissiveMap := LoadBitmapFromFile('emissive.png');
// The color contains the base color for emission in RGB.
// The A (alpha) value is used for color intensity.
Material.Emissive := TAlphaColorF.Create(1.0, 0.8, 0.2, 1.0);
Transparency control via texture:
Material.UseOpacityMapping := True;
Material.OpacityMap := LoadBitmapFromFile('opacity.png');
Actual geometry displacement in vertex shader:
Material.UseDisplacementMapping := True;
Material.UseDisplacementTexture := True;
Material.DisplacementMap := LoadBitmapFromFile('displacement.png');
// Displacement scalar vector: Use (x, y, z) as scaling value for applying onto the normal of each vertex.
// w is the displacement direction, while -1 means shrinking, but +1 means extrusion.
Material.Displacement := Vector3D(0, 1, 0, 1);
To use a physically-based material, place a TGorillaPBRMaterialSource component onto your form.
Only then the full feature-set for PBR is available by default.
Full PBR material with texture maps:
Material.ShadingModel := TGorillaShadingModel.smPBR;
// Albedo (base color)
Material.UsePBRAlbedoTexture := True;
Material.Texture0.LoadFromFile('albedo.png');
// Metalness
Material.UsePBRMetallicTexture := True;
Material.MetalnessTexture.LoadFromFile('metallic.png');
// Roughness
Material.UsePBRRoughnessTexture := True;
Material.RoughnessTexture.LoadFromFile('roughness.png');
// Ambient Occlusion
Material.UsePBRAOTexture := True;
Material.AmbientOcclusionTexture.LoadFromFile('ao.png');
// Normal map
Material.UseNormalMapping := True;
Material.NormalMap.LoadFromFile('normal.png');
Material.NormalIntensity := 1.0;
// Emissive
Material.UsePBREmissiveTexture := True;
Material.EmissiveMap.LoadFromFile('emissive.png');
// Specular
Material.UsePBRSpecularTexture := True;
Material.SpecularMap.LoadFromFile('specular.png');
// Parallax Occlusion Mapping
Material.UseParallaxOcclusion := True;
Material.ParallaxOcclusionMap.LoadFromFile('pom_map.png');
Material.ParallaxLevels := 64;
Material.NormalIntensity := 0.1;
// Opacity mapping
Material.UseOpacityMapping := true;
Material.OpacityMap.LoadFromFile('opacity.png');
Recommended: For shadows, use the Cascaded Shadow Maps (CSM) system. It is enabled per-viewport via
Viewport.Shadows.Enabledand supports directional, spot and point lights — see Cascaded Shadow Maps. The legacy material-levelShadowMethodflags below are kept for compatibility.
To receive CSM shadows, a material opts in with Shadows := True and ShadowMethod := TGorillaShadowMethod.CascadedShadowMapping — no shadow pass needs to be wired up manually:
// Viewport side (once): enable and tune the system
GorillaViewport1.Shadows.Enabled := True;
GorillaViewport1.Shadows.Strength := 0.8; // global shadow darkness [0..1]
MyDirLight.CastShadow := True;
// Material side: receive cascaded shadows
Material.Shadows := True;
Material.ShadowMethod := TGorillaShadowMethod.CascadedShadowMapping;
For legacy shadow map rendering an attached shadow rendering pass is needed.
Warning: The material-level ShadowMapping and VarianceShadowMapping feature is not fully implemented and might lead to unexpected behaviour.
Enable shadow reception:
Material.Shadows := True;
Material.ShadowMethod := TGorillaShadowMethod.smShadowMapping; // or smVSM
Material.ShadowMapPass[0] := GorillaRenderPassSMStoreDepth1;
For correct planar reflection and refraction computation, you will need a linked TGorillaRenderPassReflection
and TGorillaRenderPassRefraction render pass controller component.
// Reflections
GorillaRenderPassReflection1 := TGorillaRenderPassReflection.Create(GorillaViewport1);
GorillaRenderPassReflection1.Parent := GorillaViewport1;
GorillaRenderPassReflection1.Viewport := GorillaViewport1;
GorillaRenderPassReflection1.Camera := GorillaCamera1;
GorillaRenderPassReflection1.MirrorPosition.Point := TPoint3D.Zero;
GorillaRenderPassReflection1.Enabled := True;
Material.Reflections := True;
Material.ReflectionPower := 0.5; // 0-1
Material.ReflectionPass := GorillaRenderPassReflection1;
// Refractions
GorillaRenderPassRefraction1 := TGorillaRenderPassRefraction.Create(GorillaViewport1);
GorillaRenderPassRefraction1.Parent := GorillaViewport1;
GorillaRenderPassRefraction1.Viewport := GorillaViewport1;
GorillaRenderPassRefraction1.Enabled := True;
Material.Refractions := True;
Material.RefractionPower := 0.8;
Material.UseRefractionDepth := True;
Material.RefractionPass := GorillaRenderPassRefraction1;
For correct environment mapping rendering, you will need a linked TGorillaRenderPassEnvironment component.
Because it's not a static image used to produce a result. Instead the computation basis comes from
a separated render pass.
Cube map reflections:
GorillaRenderPassEnvironment1 := TGorillaRenderPassEnvironment.Create(GorillaViewport1);
GorillaRenderPassEnvironment1.Parent := GorillaViewport1;
GorillaRenderPassEnvironment1.Viewport := GorillaViewport1;
GorillaRenderPassEnvironment1.IsDynamic := True;
GorillaRenderPassEnvironment1.Enabled := True;
Material.Environment := True;
Material.EnvironmentPass := GorillaRenderPassEnvironment1;
The depth information is used for some kind of effects in specific materials. A good example is here TGorillaWaterMaterialSource. It uses the depth value of the pre-rendered scene to perform blending on water edges and on changing the color with the depth of water.
GorillaRenderPassCustomDepth1 := TGorillaRenderPassCustomDepth.Create(GorillaViewport1);
GorillaRenderPassCustomDepth1.Parent := GorillaViewport1;
GorillaRenderPassCustomDepth1.Viewport := GorillaViewport1;
// TDepthMethod: dmDefault, dmMVPPosZ, dmModelViewPosZ
GorillaRenderPassCustomDepth1.DepthMethod := dmDefault;
GorillaRenderPassCustomDepth1.Enabled := true;
Material.UseDepthMap := True;
Material.DepthPass := GorillaRenderPassCustomDepth1;
Each vertex is able to hold a color information. To render this color instead of a texture color, you need to
activate UseVertexColor property. This property stands in conflict with UseTexturing property.
If UseVertexColor is set to True, the possibly assigned texture diffuse color is getting ignored.
Instead the vertex color will be used in the current fragment.
It's allowed to activate UseLighting for vertex coloring. In case you want flat colors, deactivate this property.
Material.UseVertexColor := True;
Discard fragments below threshold (for foliage, chains, etc.):
Material.UseAlphaCutoff := True;
Material.AlphaCutoff := 0.5; // 0-1
Tonemapping means modifying the final color of a material in a specific and predefined style.
Gorilla3D offers a few classic styles for coloring, which are available by the TGorillaTonemapping type.
| Value | Description |
|---|---|
| tmNone | No tonemapping. |
| tmExposure | Simple exposure adjustment. |
| tmNarkowicz | ACES Narkowicz approximation. |
| tmHill | ACES Hill operator. |
| tmHillBoost | ACES Hill with exposure boost. |
| tmReinhard | Reinhard operator. |
| tmLumaBasedReinhard | Luminance-based Reinhard. |
| tmWhitePreservingLumaBasedReinhard | White-preserving Reinhard. |
| tmRomBinDaHouse | RomBinDaHouse operator. |
| tmFilmic | Filmic operator. |
| tmUncharted2 | Uncharted 2 operator. |
Material.Tonemapping := TGorillaTonemapping.tmFilmic; // Recommended
// Options: tmNone, tmReinhard, tmUncharted2, tmFilmic, etc.
Material.TonemappingExposure := 1.0;
Discard pixels matching specific color:
Material.UseColorClipping := True;
Material.ClippingColor := TAlphaColorF.Create(1, 0, 1, 1); // Magenta
Material behaviours (v1.1+) provide modular, reusable shader functionality that can be attached to any material source.
| Behaviour | Description | Use Case |
|---|---|---|
| TGorillaWindBehaviour | Wind animation system | Grass, trees, flags |
| TGorillaWobbleBehaviour | Wobble effect | Jelly, soft bodies |
| TGorillaRimLightBehaviour | Rim/edge lighting | Character outlines, highlights |
| TGorillaCausticsBehaviour | Caustics effects | Underwater scenes |
| TGorillaColorAdjustBehaviour | Color adjustments | Hue, saturation, brightness |
var
WindBehaviour: TGorillaWindBehaviour;
begin
// Create behaviour component
WindBehaviour := TGorillaWindBehaviour.Create(Self);
WindBehaviour.Viewport := Viewport;
WindBehaviour.Strength := 0.5;
WindBehaviour.Speed := 1.0;
// Attach to material
Material.AttachMaterialBehaviour(WindBehaviour);
end;
Gorilla3D includes specialized materials for specific use cases:
Simple Lambert shading without specular.
Phong shading with specular highlights.
Blinn-Phong shading (optimized Phong).
Dedicated PBR material.
Bump mapping without normal maps.
Normal mapping only.
Parallax occlusion mapping.
Rim/edge lighting effects.
Vertex color only (no textures).
Animated water surface.
Grass rendering with wind.
Particle system rendering.
Terrain with height-based texturing.
Multi-texture terrain blending.
Multiple texture layers with blending.
Texture atlas support.
Debug grid rendering.
Share material data across instances.
Create materials at runtime.
Custom shader code.
Materials use TGorillaShaderData structure for efficient GPU data transfer:
TGorillaShaderData = packed record
ModelViewProjectionMatrix: TMatrix3D;
ViewMatrix: TMatrix3D;
ProjectionMatrix: TMatrix3D;
TimeInfo: TVector3D;
EyePos: TVector3D;
ViewDir: TPoint3D;
ShadingModel: FixedInt;
Material: TGorillaShaderMaterial;
Lights: Array of TGorillaShaderLight;
LightsCount: FixedInt;
FogMode: FixedInt;
FogDensity, FogStart, FogEnd: Single;
FogColor: TAlphaColorF;
// ... many more fields
end;
Use BeginChange/EndChange to batch property updates:
Material.BeginChange();
try
Material.Diffuse := NewDiffuse;
Material.Specular := NewSpecular;
Material.Shininess := NewShininess;
finally
Material.EndChange();
end;
// Efficient texture loading
Material.Texture := LoadBitmapFromFile('texture.png');
// Share textures across materials
Material2.Texture := Material1.Texture;
Shaders are automatically cached by the engine based on active features.
Platform-dependent light counts:
| Platform | OpenGL ES 3.0 | Metal/OpenGL 4.3+ |
|---|---|---|
| Windows | - | 32 lights |
| Linux | - | 32 lights |
| Android | 8 lights | - |
| macOS | - | 32 lights |
| iOS | - | 8 lights |
TGorillaCustomMaterialSource for maximum flexibilityBeginChange/EndChange for multiple updatesMaterial.ShadingModel := TGorillaShadingModel.smPBR;
Material.MetallicBias := 1.0;
Material.RoughnessBias := 0.1;
Material.Diffuse := TAlphaColorF.Create(0.9, 0.9, 0.9, 1.0);
Material.ShadingModel := TGorillaShadingModel.smPBR;
Material.MetallicBias := 0.0;
Material.RoughnessBias := 0.9;
Material.UseNormalMapping := True;
Material.UseEmissiveColoring := True;
Material.Emissive := TAlphaColorF.Create(1.0, 0.5, 0.0, 1.0);
Material.UseEmissiveMapping := True;
Material.EmissiveTexture := GlowTexture;
Material.Diffuse := TAlphaColorF.Create(0.9, 0.9, 1.0, 0.3);
Material.Refractions := True;
Material.RefractionPower := 0.9;
Material.UseSpecular := True;
Material.Shininess := 128.0;
Gorilla3D extends Delphi's built-in TTextureBitmap with TGorillaTextureBitmap, a specialized bitmap class that gives you full control over GPU texture configuration. This guide explains why the extension exists, how it relates to the FMX texture pipeline, and how to use it effectively.
FMX's TTextureBitmap is designed for UI rendering: it creates textures in BGRA/RGBA format with unsigned byte data, and does not expose settings like wrapping mode, internal format, data type, or mip-map levels. This is fine for 2D images, but 3D rendering requires much more control:
Depth24, Depth32)RGBA16F, RGBA32F)RG16F for normals, R32F for depth)ClampToEdge vs Repeated)TGorillaTextureBitmap solves all of these by extending TTextureBitmap with the missing GPU texture parameters while staying compatible with FMX's rendering pipeline.
In standard FMX, the texture pipeline works like this:
TBitmap (CPU image data)
└── TTextureBitmap (extends TBitmap, owns a TTexture)
└── TTexture (GPU texture handle)
TBitmap holds pixel data in CPU memoryTTextureBitmap extends TBitmap and internally creates a TTexture when the Texture property is accessedTTexture represents the GPU-side texture handle, always created with the FMX defaults (BGRA, unsigned byte, no wrapping control)The problem: FMX hard-codes the texture format. When TTextureBitmap creates its internal TTexture, it uses fixed pixel format, fixed data type, and overwrites the Style property — losing any MipMap settings you may have configured.
Gorilla3D inserts its own classes into this pipeline:
TBitmap
└── TTextureBitmap (FMX)
└── TGorillaTextureBitmap (Gorilla3D)
└── TGorillaTexture (extends TTexture)
TGorillaTextureBitmap stores all extended texture settings (format, components, wrapping, filtering, data type) and applies them when the GPU texture is created. TGorillaTexture extends TTexture with the actual GPU-level properties.
// FMX base classes
FMX.Graphics.TBitmap
└── FMX.Graphics.TTextureBitmap
└── Gorilla.Context.Texturing.TGorillaTextureBitmap
FMX.Types3D.TTexture
└── Gorilla.Context.Texturing.TGorillaTexture
uses Gorilla.Context.Texturing;
// Create a standard RGBA texture bitmap
var LBmp := TGorillaTextureBitmap.Create(512, 512);
try
// Use it...
finally
LBmp.Free;
end;
Use BeginSetup / EndSetup to batch property changes and avoid premature GPU texture creation:
var LBmp := TGorillaTextureBitmap.Create(1024, 1024);
LBmp.BeginSetup();
try
LBmp.Format := TPixelFormatEx.RGBA16F;
LBmp.Components := TPixelFormatEx.RGBA16F;
LBmp.DataType := TGorillaTextureDataType.dtHalfFloat;
LBmp.MinFilter := TTextureFilter.Linear;
LBmp.MagFilter := TTextureFilter.Linear;
LBmp.WrapS := TGorillaTextureWrap.ClampToEdge;
LBmp.WrapT := TGorillaTextureWrap.ClampToEdge;
LBmp.Style := [TTextureStyle.RenderTarget];
finally
LBmp.EndSetup();
end;
var LDepth := TGorillaTextureBitmap.Create(1024, 1024);
LDepth.BeginSetup();
try
LDepth.Format := TPixelFormatEx.Depth;
LDepth.Components := TPixelFormatEx.Depth24;
LDepth.DataType := TGorillaTextureDataType.dtUnsignedInt;
LDepth.MinFilter := TTextureFilter.Nearest;
LDepth.MagFilter := TTextureFilter.Nearest;
LDepth.WrapS := TGorillaTextureWrap.ClampToBorder;
LDepth.WrapT := TGorillaTextureWrap.ClampToBorder;
LDepth.BorderColor := TAlphaColorF.Create(1, 1, 1, 1);
finally
LDepth.EndSetup();
end;
| Property | Type | Description |
|---|---|---|
Kind |
TGorillaTextureKind |
Texture type: Texture2D, Texture3D, CubeMap, ImageTexture3D, Array2D |
Format |
TPixelFormatEx |
Pixel data format (e.g., BGRA, RGBA16F, Depth24) |
Components |
TPixelFormatEx |
Internal format / number of color components |
DataType |
TGorillaTextureDataType |
Data type per channel: dtUnsignedByte, dtFloat, dtHalfFloat, etc. |
Style |
TTextureStyles |
Texture styles: MipMaps, Dynamic, RenderTarget, Volatile |
| Property | Type | Description |
|---|---|---|
MinFilter |
TTextureFilter |
Minification filter: Nearest or Linear |
MagFilter |
TTextureFilter |
Magnification filter: Nearest or Linear |
| Property | Type | Description |
|---|---|---|
WrapS |
TGorillaTextureWrap |
Horizontal wrapping |
WrapT |
TGorillaTextureWrap |
Vertical wrapping |
WrapR |
TGorillaTextureWrap |
Depth wrapping (3D textures only) |
BorderColor |
TAlphaColorF |
Border color for ClampToBorder mode |
| Property | Type | Description |
|---|---|---|
MipMapLevels |
Integer |
Number of auto-generated mip-map levels |
IsMultiSampled |
Boolean |
Enable multisampled texture |
Multisamples |
Integer |
Multisample count (2, 4, 8, 16) |
Depth |
Integer |
Depth dimension for 3D textures |
IsCompressed |
Boolean |
Enable PNG compression for CPU-side storage. NOT the same as GPU block compression - see Compressed Textures |
ProtectFormatSettings |
Boolean |
Prevent FMX from overwriting format on Assign |
AttachedCubeMapFace |
TGorillaCubeMapFace |
Active cube map face for FBO rendering |
GorillaTexture |
TGorillaTexture |
The underlying GPU texture (read-only) |
TPixelFormatEx extends FMX's TPixelFormat with GPU-native formats:
| Category | Formats |
|---|---|
| Standard | RGB, RGBA, BGR, BGRA |
| 8-bit per channel | R8, RG8, RGB8, RGBA8, SRGB8, SRGB8_ALPHA8 |
| 16-bit float | R16F, RG16F, RGB16F, RGBA16F |
| 32-bit float | R32F, RG32F, RGB32F, RGBA32F |
| Integer | R8UI, R16UI, R32UI, RG8UI, RGBA8UI, RGBA32UI, etc. |
| Depth | Depth16, Depth24, Depth32 |
| Depth+Stencil | Depth24Stencil8, Depth32Stencil8 |
| FMX (TPixelFormat) | Gorilla (TPixelFormatEx) | Notes |
|---|---|---|
TPixelFormat.BGRA |
TPixelFormatEx.BGRA |
Default on Windows |
TPixelFormat.RGBA |
TPixelFormatEx.RGBA |
Default on macOS/iOS/Android |
| not available | TPixelFormatEx.RGBA16F |
HDR rendering |
| not available | TPixelFormatEx.Depth24 |
Shadow maps |
| not available | TPixelFormatEx.RG16F |
Normal maps, VSM |
| not available | TPixelFormatEx.R32F |
Single-channel float |
| Mode | Description | Use Case |
|---|---|---|
Clamp |
Clamp to [0,1] range | General purpose |
ClampToEdge |
Edge pixels are extended | Render targets, post-processing |
ClampToBorder |
Uses BorderColor outside [0,1] |
Shadow maps (white border = no shadow) |
Repeated |
Tile the texture | Terrain, tiling materials |
MirroredRepeat |
Tile with mirroring | Seamless tiling |
FMX does not expose wrapping at all — it always uses the platform default. With TGorillaTextureBitmap you can set wrapping per axis.
Note:
TGorillaTextureBitmapdefaults toClampToEdgeon all three axes, whereas the underlyingTGorillaTexturedefaults toRepeated. When you assign a texture bitmap to a material it carries its own wrap settings, so set them explicitly for the use case at hand.
Texture tiling — repeating an image multiple times across UV coordinates — is configured on the material's bitmap pool entry (Tiling / TilingX / TilingY, see Default Material → The Bitmaps Property). The tiling itself is performed in GLSL via mod(texcoord * tiling, 1.0) and is independent of the wrap mode.
The wrap mode, however, decides whether the tiling looks seamless. Because the bilinear/mip-map filter footprint straddles the tile seams, a clamping wrap mode samples and clamps to the texture border at every seam:
Important: For tiling,
WrapS/WrapT(andWrapRfor 3D textures) must not beClamp,ClampToEdgeorClampToBorder— otherwise dark / black lines appear along the tile edges. UseRepeated(orMirroredRepeat) for seamless tiling.
The clamping modes are intended for non-tiled use: render targets and post-processing (ClampToEdge) or shadow-map depth textures with a white border (ClampToBorder).
FMX's TTexture has MinFilter and MagFilter but they are not accessible through TTextureBitmap. TGorillaTextureBitmap exposes them directly.
LBmp.MinFilter := TTextureFilter.Linear; // smooth when shrinking
LBmp.MagFilter := TTextureFilter.Nearest; // sharp when enlarging
Used for volumetric effects and voxel cone tracing:
var LVol := TGorillaTextureBitmap.Create();
LVol.BeginSetup();
try
LVol.Kind := TGorillaTextureKind.Texture3D;
LVol.Format := TPixelFormatEx.RGBA8;
LVol.Components := TPixelFormatEx.RGBA8;
LVol.Set3DSize(64, 64, 64);
finally
LVol.EndSetup();
end;
Used for environment mapping and skyboxes:
var LCube := TGorillaTextureBitmap.Create(256, 256);
LCube.BeginSetup();
try
LCube.Kind := TGorillaTextureKind.CubeMap;
LCube.Format := TPixelFormatEx.RGBA8;
LCube.Components := TPixelFormatEx.RGBA8;
finally
LCube.EndSetup();
end;
// Upload each face
LCube.AttachedCubeMapFace := TGorillaCubeMapFace.PositiveX;
LCube.UpdateCubeMapFace(TGorillaCubeMapFace.PositiveX, LCube.GorillaTexture, AData, APitch);
// ... repeat for all 6 faces
Two very different things are called "texture compression", and Gorilla3D supports both. They solve different problems, and mixing them up is easy because both use the name IsCompressed — on two different classes.
| Storage compression | GPU block compression | |
|---|---|---|
| Property | TGorillaTextureBitmap.IsCompressed |
TGorillaTexture.IsCompressed — set by the backend, do not assign it yourself |
| What it compresses | The CPU-side bitmap, as PNG in a memory stream | The texture in video memory |
| Saves | System RAM, asset package size | VRAM, 4:1 to 6:1 |
| Controlled by | Per bitmap | One global switch |
| Backends | all | OpenGL only |
If your problem is "the dedicated GPU memory is full and the driver starts spilling into shared memory", the second one is what you want.
TGorillaTextureBitmap can keep its pixel data as PNG in a memory stream instead of as raw pixels. This reduces system memory and asset package size; the GPU texture is unaffected.
LBmp.IsCompressed := True;
// Bitmap data is stored as PNG in CompressedData stream
// Call Decompress() to restore pixel data when needed
LBmp.Decompress();
| Method | Description |
|---|---|
ClearAfterCompression() |
Free pixel data after compression |
Recompress() |
Re-compress current pixel data |
Decompress() |
Restore pixel data from compressed stream |
Block compression keeps the texture compressed for its entire life on the GPU. A 2048 × 2048 RGBA texture occupies 16 MB uncompressed and 4 MB as DXT5 — and it stays that way while it is being sampled.
Gorilla3D lets the driver do the compression: the image data is still handed to OpenGL as ordinary RGBA, only the internal format is a compressed one. That means no new file formats, no asset conversion, and no changes to your own code beyond the switch.
No. The default is off, so nothing changes in an existing project until you ask for it:
uses Gorilla.Context.Types;
GorillaTextureCompression := tcOff; // default
Set the global switch before the first texture is created — compression only applies to textures created afterwards. The safest place is your .dpr, before Application.Initialize:
program MyGame;
uses
Gorilla.Context.Types, // GorillaTextureCompression
FMX.Forms,
Unit1 in 'Unit1.pas' {Form1};
begin
// Block-compress textures in video memory. Must be set before any texture
// exists - a texture already uploaded stays uncompressed.
GorillaTextureCompression := tcFast;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
Setting it later (in FormCreate, or worse in FormShow) is a common mistake: by then the framework has usually created its render targets and the first material textures, and those stay uncompressed without any warning. The counters described below make that visible.
| Mode | Format | Ratio | Notes |
|---|---|---|---|
tcOff |
— | 1:1 | Default. Nothing is compressed. |
tcFast |
DXT5 (RGBA) / DXT1 (RGB) |
4:1 / 6:1 | Fast to encode. Visible artefacts on hard colour edges — text, logos, sharp gradients. |
tcQuality |
BC7 / BPTC |
4:1 | Clearly better than DXT on edges, but the driver's encoder is much slower. Expect a noticeably longer start-up. Falls back to DXT when GL_ARB_texture_compression_bptc is missing. |
Both modes require the matching driver extension (GL_EXT_texture_compression_s3tc, GL_ARB_texture_compression_bptc). If it is missing, the texture is simply created uncompressed — nothing fails.
Compression is applied only where it is safe and worthwhile. A texture is left uncompressed when it is:
TGorillaTextureKind.Texture2D — cube maps, 3D and array textures are excludedTTextureStyle.Volatile or TTextureStyle.ExternalGorillaTextureCompressionMinEdge on either axis// Only compress textures of at least 512 px per edge (default: 256).
// Small textures are usually the ones with hard edges - icons, fonts, colour
// ramps - which lose the most and save the least.
GorillaTextureCompressionMinEdge := 512;
Note on
TTextureStyle.Dynamic: dynamic textures are compressed. In FMXDynamiconly means "may be updated", and almost every texture created from aTBitmapcarries it — excluding them would mean compressing almost nothing. The consequence is that a texture you really do re-upload every frame gets re-compressed by the driver on every upload. If you have such a texture and it costs you frame time, either mark itVolatileor turn compression off.
Do not assume the driver honoured the request — a driver may accept a compressed internal format and still store the texture uncompressed. Gorilla3D asks it afterwards (GL_TEXTURE_COMPRESSED, GL_TEXTURE_COMPRESSED_IMAGE_SIZE) and keeps the tally:
uses Gorilla.Context.Profiler;
// after your scene has been built
Log.d('compressed: %d textures, %.1f MB, saved %.1f MB (factor %.2f)',
[TGorillaTextureStats.CompressedCount,
TGorillaTextureStats.CompressedBytes / (1024 * 1024),
TGorillaTextureStats.SavedBytes() / (1024 * 1024),
TGorillaTextureStats.Ratio()]);
// and when nothing was compressed, this says why
Log.d('considered %d, rejected %d: %s',
[TGorillaTextureStats.ConsideredCount,
TGorillaTextureStats.RejectedCount,
TGorillaTextureStats.RejectSummary()]);
| Member | Description |
|---|---|
CompressedCount / UncompressedCount |
Textures the driver did / did not compress |
PlainBytes / CompressedBytes |
What they would have cost, and what they cost |
SavedBytes() / Ratio() |
The difference, and the achieved ratio |
ConsideredCount / RejectedCount |
How often the decision was made at all, and how often it was negative |
RejectSummary() |
Reasons with counts, e.g. Rendertarget/MSAA=60, zu klein=3 |
HasS3TC / HasBPTC |
Extension availability (-1 = never queried) |
LastFormat / FormatName() |
The internal format actually used |
ConsideredCount matters more than it looks: "0 compressed textures" can mean the decision was never reached (switch set too late) or that it was always negative (a guard rejected everything). Those are different bugs.
A football game with a large painted pitch texture, a goal-net texture, kit atlases and imported stadium models, on an RTX 4070 Laptop:
| Textures | VRAM | |
|---|---|---|
tcOff |
208 | 1801 MB |
tcFast |
208 | 450 MB |
1350 MB saved, factor 4.00, with 60 render targets and 3 undersized textures correctly left alone. tcQuality saved exactly the same (BC7 is also 4:1) and added about 15 seconds to start-up.
| Backend | Supported | Why |
|---|---|---|
| OpenGL (Windows, Linux) | yes | The driver compresses on upload |
| Vulkan | no | No driver-side encoder — data must arrive already in blocks |
| Metal | no | Same |
GorillaTextureCompression has no effect on Vulkan and Metal. Supporting those means shipping pre-compressed assets (BCn DDS / KTX2) and uploading the blocks without decoding them.
Note: Gorilla3D can read DDS files containing DXT data, but the image layer currently decodes them to RGBA (
DecodeDXT1/3/5), so the blocks never reach the GPU. Loading a DDS therefore does not save video memory by itself — the switch above does.
For MSAA (multisample anti-aliasing) render targets:
LBmp.BeginSetup();
try
LBmp.IsMultiSampled := True;
LBmp.Multisamples := 4; // 2, 4, 8, or 16
finally
LBmp.EndSetup();
end;
On OpenGL, this changes the texture type from GL_TEXTURE_2D to GL_TEXTURE_2D_MULTISAMPLE.
FMX internally stores all bitmap data as BGRA/RGBA with unsigned bytes. When you need a different format (e.g., RG16F for variance shadow maps), the FMX bitmap buffer cannot hold the data correctly.
TGorillaTextureBitmap solves this with an internal Buffer:
Format differs from the default BGRA/RGBA, a separate buffer (Buffer / BufferSize) is allocatedUpdateBuffer()You typically do not interact with the buffer directly — it is managed automatically. But you can read the properties:
if LBmp.Buffer <> nil then
// Texture uses the workaround buffer (non-standard format)
WriteLn('Buffer size: ', LBmp.BufferSize);
TGorillaTexture extends FMX's TTexture with the same extended properties. It is created automatically by TGorillaTextureBitmap when the GorillaTexture property is accessed.
Key additions over TTexture:
| Property | Type | Description |
|---|---|---|
Kind |
TGorillaTextureKind |
Texture type |
Components |
TPixelFormatEx |
Internal format |
Format |
TPixelFormatEx |
Data format |
DataType |
TGorillaTextureDataType |
Channel data type |
WrapS/T/R |
TGorillaTextureWrap |
Per-axis wrapping |
MipMapLevels |
Integer |
Mip-map level count |
TextureUnit |
Integer |
Last bound texture unit |
IsCompressed |
Boolean |
Whether this texture is block-compressed in video memory. Written by the backend after asking the driver — read it, do not set it. Unrelated to TGorillaTextureBitmap.IsCompressed, which is PNG storage compression. |
Methods:
| Method | Description |
|---|---|
Clear() |
Clear texture data on GPU |
GenerateMipMap() |
Generate mip-maps on GPU |
RequestTextureData(ABytes, ASize, ALevel) |
Read texture data back from GPU |
BeginSetup() / EndSetup() when configuring multiple properties — this prevents intermediate GPU texture (re)creationProtectFormatSettings := True when assigning from FMX bitmaps to prevent format overrideStyle := [TTextureStyle.RenderTarget]ClampToEdge for render pass textures to avoid border artefactsClampToBorder with white BorderColor for shadow map depth texturesTPixelFormatEx.RGBA16F over RGBA32F for HDR — half the memory, sufficient precisionNearest filtering for depth/position G-buffer textures, Linear for colorTGorillaTextureBitmap handles this transparentlyGorillaTexture property returns the existing texture or creates one — use TextureReference if you only want to check without creatingGorillaTextureCompression in the .dpr before Application.Initialize, never in a form event — textures created earlier stay uncompressed, silentlyTGorillaTextureStats once after your scene is built. A driver may accept a compressed format and store the texture uncompressed anywayThe Gorilla3D Prefab System allows you to save and load scene elements as reusable templates. A prefab stores a component hierarchy with all property values and child elements, from which you can instantiate copies at runtime. Prefabs are stored as DFM (Delphi Form) data, either in files or embedded directly.
The prefab system consists of two classes:
| Class | Description |
|---|---|
TGorillaPrefabSystem |
Component that manages a collection of prefabs |
TGorillaPrefab |
Individual prefab template (collection item) |
TGorillaPrefabSystem onto your formPrefabs collection in the Object InspectorOwnerComponent to the root component of your templateFileName to the file path for the prefabvar
PrefabSys: TGorillaPrefabSystem;
Prefab: TGorillaPrefab;
begin
PrefabSys := TGorillaPrefabSystem.Create(Self);
Prefab := PrefabSys.AddPrefab('Tree', GorillaViewport1, 'prefabs/tree.prefab');
end;
// Add a prefab and link it to a component hierarchy
var LPrefab := PrefabSystem1.AddPrefab('Enemy', GorillaViewport1, '');
// Set the root component whose hierarchy will be saved
LPrefab.OwnerComponent := EnemyModel;
// Save to file
LPrefab.SaveToFile('prefabs/enemy.prefab');
// Or save to stream
var LStream := TMemoryStream.Create;
try
LPrefab.SaveToStream(LStream);
// use stream...
finally
LStream.Free;
end;
Prefabs can store DFM content directly instead of referencing a file:
LPrefab.DFM.Text := SomeDFMString; // DFM text content
When DFM content is set, Load() uses the embedded data instead of reading from file.
var
LComponents: TList<TComponent>;
begin
LComponents := PrefabSystem1.FindPrefab('Enemy').LoadFromFile('prefabs/enemy.prefab');
try
// LComponents contains all instantiated components
for var Comp in LComponents do
// position, configure, etc.
finally
LComponents.Free;
end;
end;
LComponents := LPrefab.LoadFromStream(MyStream);
// For compressed .prefabz files:
LComponents := LPrefab.LoadFromStream(MyStream, True); // AIsPrefabZ = True
var AllComponents: TObjectList<TComponent>;
begin
AllComponents := TObjectList<TComponent>.Create(False);
try
PrefabSystem1.LoadAllPrefabs(AllComponents);
// AllComponents contains everything loaded from all prefabs
finally
AllComponents.Free;
end;
end;
// Save individual prefab
LPrefab.Save();
LPrefab.SaveToFile('prefabs/enemy_v2.prefab');
// Save all prefabs
PrefabSystem1.SaveAllPrefabs();
| Property | Type | Description |
|---|---|---|
DisplayName |
String | Name identifier for the prefab |
FileName |
String | File path (not auto-loaded on set) |
OwnerComponent |
TComponent | Root node of the prefab hierarchy |
DFM |
TStrings | Embedded DFM content (overrides file loading) |
Stored |
Boolean | Whether loaded components are stored in the owner's DFM |
WriteFormMethods |
Boolean | Write event properties linked to form methods |
IgnoreUnresolvedEvents |
Boolean | Silently ignore missing event methods (default: False) |
| Event | Type | Description |
|---|---|---|
OnLoaded |
TOnPrefabLoadedEvent |
Fired after prefab components are loaded |
OnStored |
TNotifyEvent |
Fired after prefab is saved |
OnCreateComponent |
TOnCreateComponentEvent |
Custom component creation callback |
function AddPrefab(AName: String; AOwner: TComponent; const AFileName: String): TGorillaPrefab;
procedure RemovePrefab(AName: String);
function FindPrefab(AName: String): TGorillaPrefab;
function IndexOfPrefab(AName: String): Integer;
procedure LoadAllPrefabs(var AList: TObjectList<TComponent>);
procedure SaveAllPrefabs();
// Create a scene by loading multiple prefabs
var
LEnemy, LTree, LHouse: TGorillaPrefab;
begin
LEnemy := PrefabSystem1.AddPrefab('Enemy', GorillaViewport1, 'prefabs/enemy.prefab');
LTree := PrefabSystem1.AddPrefab('Tree', GorillaViewport1, 'prefabs/tree.prefab');
LHouse := PrefabSystem1.AddPrefab('House', GorillaViewport1, 'prefabs/house.prefab');
// Instantiate multiple enemies at different positions
for var I := 0 to 9 do
begin
var LComps := LEnemy.Load();
try
// Position each instance
if (LComps.Count > 0) and (LComps[0] is TControl3D) then
TControl3D(LComps[0]).Position.X := I * 5;
finally
LComps.Free;
end;
end;
end;
IgnoreUnresolvedEvents := True when loading prefabs in a different context than where they were createdOwnerComponent to define the parent for instantiated componentsSaveToFile/LoadFromFile for persistence.prefabz) use ZIP compression for smaller file sizesOnLoaded event to post-process instantiated components (apply materials, set positions)The Gorilla3D Assets Manager provides centralized media management through asset packages. Models, textures, audio, video, dialogues, inventories, scripts, prefabs, and skill system files are cached in ZIP-based packages for fast loading and modular organization.
| Class | Description |
|---|---|
TGorillaAssetsManager |
Main component managing packages |
TGorillaAssetsPackage |
A ZIP-based asset package |
TGorillaAssetsGroup |
A group of assets by type (models, textures, etc.) |
TGorillaAsset |
Base class for individual assets |
The assets manager supports these built-in asset groups:
| Constant | ID | Group | Description |
|---|---|---|---|
GORILLA_ASSETS_MODEL |
0 | MODEL | 3D models (G3D, FBX, glTF, etc.) |
GORILLA_ASSETS_TEXTURE |
1 | TEXTURE | Image textures (PNG, JPG, DDS, TGA) |
GORILLA_ASSETS_AUDIO |
2 | AUDIO | Sound files |
GORILLA_ASSETS_VIDEO |
3 | VIDEO | Video files |
GORILLA_ASSETS_MISC |
4 | MISC | Miscellaneous files |
GORILLA_ASSETS_DIALOGUE |
5 | DIALOGUE | Dialogue system files |
GORILLA_ASSETS_INVENTORY |
6 | INVENTORY | Inventory definitions |
GORILLA_ASSETS_SCRIPT |
7 | SCRIPT | Script files |
GORILLA_ASSETS_PREFAB |
8 | PREFAB | Prefab templates |
GORILLA_ASSETS_SKILLS |
9 | SKILLS | Skill system definitions |
TGorillaAssetsManager onto your formuses Gorilla.AssetsManager;
var
AssetsMgr: TGorillaAssetsManager;
begin
AssetsMgr := TGorillaAssetsManager.Create(Self);
end;
Packages are ZIP archives containing organized asset files and a asset.json metadata file. The default package name is 'default'.
// Packages are stored as ZIP files
// Internal structure:
// asset.json - metadata with version and asset listing
// MODEL/ - 3D model files
// TEXTURE/ - texture files
// AUDIO/ - audio files
// DIALOGUE/ - dialogue definitions
// INVENTORY/ - inventory definitions
// SKILLS/ - skill system files
// PREFAB/ - prefab files
// ...
var LAsset: TGorillaAsset;
begin
// Import auto-detects the asset type by file extension
LAsset := TGorillaAsset.ImportFromFile(SomeGroup, 'models/character.g3d');
end;
LAsset := TGorillaAsset.ImportFromStream(SomeGroup, 'character.g3d', MyStream);
| Flag | Description |
|---|---|
StrictFileName |
Match filename exactly (no path normalization) |
Cached |
Mark asset as cached immediately |
Assets are organized into groups by type. Each group can contain subgroups for further organization:
// Each asset knows its group
var LGroup := LAsset.Group;
// Assets provide JSON serialization for package storage
var LJSON := LAsset.ToJSON();
LAsset.FromJSON(LJSON);
| Property | Type | Description |
|---|---|---|
Id |
TGorillaGUID | Unique identifier |
Filename |
String | Original filename |
Extension |
String | File extension |
Cached |
Boolean | Whether data is buffered in memory |
IsStandalone |
Boolean | Created without a group reference |
State |
TAssetState | Current state (Loading, Loaded, Storing, Stored) |
Group |
TGorillaAssetsGroup | Parent group reference |
| State | Description |
|---|---|
asUndef |
Undefined |
asLoading |
Currently loading |
asLoaded |
Loaded and available |
asStoring |
Currently saving |
asStored |
Saved to package |
// Check if a file extension is supported
if TGorillaAsset.IsExtensionSupported('.g3d') then ...;
// Get the asset class for an extension
var LClass := TGorillaAsset.GetSupportedAssetClass('.png');
Asset packages include version information (current version: 1.3):
main_character.zip, level1.zip)Cached flag to keep frequently used assets in memoryRender Pass Controllers in Gorilla3D enable multi-pass rendering techniques by allowing you to execute custom rendering stages before, after, or during the main rendering loop. They are essential for implementing advanced effects like reflections, refractions, depth passes, post-processing, and custom shaders.
A render pass controller (TGorillaRenderPassController) manages a separate rendering stage with its own:
Common applications include:
Render passes execute at different stages of the rendering pipeline:
TRenderPassType.Pre)Executes before the main rendering loop.
Use Cases:
Example:
ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass._Type := TRenderPassType.Pre; // Executes before main scene
TRenderPassType.Post)Executes after the main rendering loop.
Use Cases:
Example:
BlurPass := TGorillaRenderPassCustomBlur.Create(Self);
BlurPass._Type := TRenderPassType.Post; // Executes after main scene
TRenderPassType.Intermediate)Executes during the main rendering loop.
Use Cases:
Example:
CustomPass := TMyCustomRenderPass.Create(Self);
CustomPass._Type := TRenderPassType.Intermediate;
Renders all 3D objects from the scene to the render pass FBO.
Behavior:
AllowedControls and IgnoredControlsUse Cases:
Example:
DepthPass.Method := TRenderPassMethod.RenderListToFBO;
Renders a fullscreen quad with a shader material to the FBO.
Behavior:
Use Cases:
Example:
BlurPass.Method := TRenderPassMethod.RectToFBO;
BlurPass.Shader := BlurShaderMaterial;
The RenderProc property controls how objects are rendered within a pass:
Uses complete WBOIT (Weighted Blended Order Independent Transparency) pipeline:
Use When:
Example:
ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering;
Renders all objects straight forward without separation:
Use When:
Example:
DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering;
Every render pass must be linked to a viewport:
var
ReflectionPass: TGorillaRenderPassReflection;
begin
ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass.Viewport := GorillaViewport1;
// Rest of configuration...
end;
Each render pass requires a unique identifier:
// Automatically set from component name at design-time
ReflectionPass.Name := 'ReflectionPass1'; // ID = 'ReflectionPass1'
// Or set manually
ReflectionPass.Id := 'WaterReflection';
Important: Duplicate IDs will cause conflicts. The new pass overwrites the existing one.
// Enable/disable pass
ReflectionPass.Enabled := True;
// Set rendering type
ReflectionPass._Type := TRenderPassType.Pre;
// Set rendering method
ReflectionPass.Method := TRenderPassMethod.RenderListToFBO;
// Set rendering procedure
ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering;
// Number of times to execute per frame
ReflectionPass.Iterations := 1; // Useful for ping-pong effects
Render passes can use custom viewport sizes different from the main viewport.
ReflectionPass.OverwriteViewportSize := False; // Use main viewport dimensions
The pass then renders in the render target size of the viewport (TGorillaViewport.GetRenderTargetSize()), which already contains HighRes, RenderScale and a fixed RenderWidth / RenderHeight - see Render Resolution and Scaling.
ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;
Use Cases:
ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 0.5; // Results in 512x512
Note:
ScaleViewportSizeonly works together withOverwriteViewportSize = True. Without an individual size the pass always renders in the render target size of the viewport, which already contains its scaling. To lower the resolution of the main pass and all such passes together, useViewport.RenderScale.
Use Cases:
ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 512;
ReflectionPass.ViewportHeight := 512;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 2.0; // Results in 1024x1024
Control filtering allows selective rendering of scene objects in a render pass.
Exclude specific objects from rendering:
// Exclude water plane from reflection pass
ReflectionPass.IgnoreControl(WaterPlane);
// Exclude multiple objects
ReflectionPass.IgnoreControl(WaterPlane);
ReflectionPass.IgnoreControl(UnderwaterRocks);
ReflectionPass.IgnoreControl(Seaweed);
Automatic Child Handling:
Design-Time Configuration:
// Via IgnoredControls collection in Object Inspector
ReflectionPass.IgnoredControls.Add();
// Then set Control property to desired object
Create an explicit allow-list for rendering:
// Only render specific objects
ReflectionPass.AllowControl(Sky);
ReflectionPass.AllowControl(Mountains);
ReflectionPass.AllowControl(Trees);
// Everything else is ignored
Behavior:
AllowedControls is empty: All objects render except those in IgnoredControlsAllowedControls is not empty: Only allowed objects render, then IgnoredControls is checked against themExample Scenario:
// Allow terrain and props
BackfacePass.AllowControl(Terrain);
BackfacePass.AllowControl(Props);
// But ignore specific prop
BackfacePass.IgnoreControl(TransparentWindow); // Excluded from allowed props
if ReflectionPass.IsControlIgnored(WaterPlane) then
ShowMessage('Water plane will not be rendered in reflection');
ReflectionPass.OverwriteColor := False; // Use viewport's background color
ReflectionPass.OverwriteColor := True;
ReflectionPass.BackgroundColor := TAlphaColorRec.Skyblue;
Use Cases:
Link multiple passes together by feeding one pass's output into another:
var
Pass1, Pass2: TGorillaRenderPassController;
begin
// Pass2 uses Pass1's output as input
Pass2.SetInputPass(Pass1);
// Or check current input
var InputPass := Pass2.GetInputPass();
end;
Common Pattern - Blur Ping-Pong:
// Horizontal blur
BlurH.SetInputPass(SourcePass);
// Vertical blur uses horizontal output
BlurV.SetInputPass(BlurH);
// Final composite uses vertical output
FinalPass.SetInputPass(BlurV);
Render passes provide events for custom logic at various stages:
Called once per frame before pass setup begins:
procedure TForm1.OnReflectionBeginSetup(ASender: TObject;
const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
// Prepare pass-specific data
// Update matrices
// Configure camera
end;
ReflectionPass.OnBeginSetup := OnReflectionBeginSetup;
Called once per frame after pass setup completes:
procedure TForm1.OnReflectionEndSetup(ASender: TObject;
const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
// Cleanup
// Reset states
end;
ReflectionPass.OnEndSetup := OnReflectionEndSetup;
Called before each iteration renders:
procedure TForm1.OnBlurBeginRender(ASender: TObject;
const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
// ACount indicates current iteration (0-based)
// Configure iteration-specific parameters
end;
BlurPass.OnBeginRender := OnBlurBeginRender;
BlurPass.Iterations := 3; // OnBeginRender called 3 times
Called after each iteration completes:
procedure TForm1.OnBlurEndRender(ASender: TObject;
const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
// Post-iteration cleanup
// Swap ping-pong buffers
end;
BlurPass.OnEndRender := OnBlurEndRender;
Get the render pass's output texture for use in materials or other passes:
var
OutputTex: TTexture;
begin
OutputTex := ReflectionPass.OutputTexture;
// Use in material
CustomPlaneMaterial.Texture := OutputTex;
end;
Gorilla3D includes several ready-to-use render pass implementations:
Renders reflected scene for water and mirror surfaces.
Features:
Example:
var
ReflectionPass: TGorillaRenderPassReflection;
begin
ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass.Viewport := Viewport;
ReflectionPass.Camera := Camera;
// Configure mirror plane (Y=0 plane for water)
ReflectionPass.MirrorPosition.Point := Point3D(0, 0, 0);
ReflectionPass.MirrorNormal.Point := Point3D(0, -1, 0);
ReflectionPass.MirrorSize := 100.0;
// Exclude water from rendering
ReflectionPass.IgnoreControl(WaterPlane);
end;
→ API reference: TGorillaRenderPassReflection
Renders refracted (underwater) scene for water surfaces.
Features:
Example:
var
RefractionPass: TGorillaRenderPassRefraction;
begin
RefractionPass := TGorillaRenderPassRefraction.Create(Self);
RefractionPass.Viewport := Viewport;
// Configure water surface
RefractionPass.SurfacePosition.Point := Point3D(0, 0, 0);
RefractionPass.SurfaceNormal.Point := Point3D(0, 1, 0);
// Exclude water from rendering
RefractionPass.IgnoreControl(WaterPlane);
end;
→ API reference: TGorillaRenderPassRefraction
Renders scene depth to texture for shadow mapping or depth effects.
Features:
Example:
var
DepthPass: TGorillaRenderPassCustomDepth;
begin
DepthPass := TGorillaRenderPassCustomDepth.Create(Self);
DepthPass.Viewport := Viewport;
DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering; // Faster
// Custom resolution for shadow map
DepthPass.OverwriteViewportSize := True;
DepthPass.ViewportWidth := 2048;
DepthPass.ViewportHeight := 2048;
end;
→ API reference: TGorillaRenderPassCustomDepth
The modern Cascaded Shadow Maps (CSM) system for directional, spot and point lights. It is an internal pass driven by the viewport — you do not create it manually. Enable and configure it through Viewport.Shadows (a TGorillaShadowSystemSettings instance), then flag the casting lights.
Example:
// Enable and tune the shadow system
GorillaViewport1.Shadows.Enabled := True;
GorillaViewport1.Shadows.CascadeCount := 4;
GorillaViewport1.Shadows.MapResolution := 2048;
GorillaViewport1.Shadows.MaxDirLights := 1;
GorillaViewport1.Shadows.Filter := TGorillaShadowFilter.PCF3;
GorillaViewport1.Shadows.Strength := 1.0; // global shadow darkness [0..1]
GorillaViewport1.Shadows.AutoFitCascades := True; // fit cascades to scene geometry
// Mark which lights cast shadows
MyDirLight.CastShadow := True;
→ API reference: TGorillaRenderPassCascadedShadows
Applies Gaussian blur to input texture.
Features:
Example:
var
BlurPass: TGorillaRenderPassCustomBlur;
begin
BlurPass := TGorillaRenderPassCustomBlur.Create(Self);
BlurPass.Viewport := Viewport;
BlurPass.Method := TRenderPassMethod.RectToFBO;
// Configure blur
BlurPass.BlurRadius := 5.0;
BlurPass.Iterations := 2; // Blur twice
// Input from previous pass
BlurPass.SetInputPass(SourcePass);
end;
→ API reference: TGorillaRenderPassBlur (CustomBlur)
Fast approximate anti-aliasing post-process.
Example:
var
FXAAPass: TGorillaRenderPassFXAA;
begin
FXAAPass := TGorillaRenderPassFXAA.Create(Self);
FXAAPass.Viewport := Viewport;
FXAAPass._Type := TRenderPassType.Post;
FXAAPass.Method := TRenderPassMethod.RectToFBO;
end;
→ API reference: TGorillaRenderPassFXAA
Captures the scene into a dynamic cube map for environment mapping and reflections.
Features:
Example:
var
EnvPass: TGorillaRenderPassEnvironment;
begin
EnvPass := TGorillaRenderPassEnvironment.Create(Self);
EnvPass.Viewport := Viewport;
EnvPass.Position := Point3D(0, 2, 0);
EnvPass.MapSize := 256;
EnvPass.IsDynamic := True;
EnvPass.IgnoreControl(ReflectiveObject);
end;
→ API reference: TGorillaRenderPassEnvironment
Renders front- or back-face vertex positions into a float texture — the entry/exit geometry for ray-cast volumetric rendering.
Features:
VertexUserFuncExample:
var
FacePass: TGorillaRenderPassFace;
begin
FacePass := TGorillaRenderPassFace.Create(Self);
FacePass.Viewport := Viewport;
FacePass.FaceKind := FrontFace;
FacePass.FaceOutput := ModelSpace;
end;
→ API reference: TGorillaRenderPassFace
Full-screen underwater post effect: distortion, depth fog, caustics, fisheye and vignette that fade in below a water surface.
Features:
Example:
var
UnderwaterPass: TGorillaRenderPassUnderwater;
begin
UnderwaterPass := TGorillaRenderPassUnderwater.Create(Self);
UnderwaterPass.Viewport := Viewport;
UnderwaterPass._Type := TRenderPassType.Post;
UnderwaterPass.SurfaceHeight := 0.0;
UnderwaterPass.TintColor := $FF14506E;
end;
→ API reference: TGorillaRenderPassUnderwater
Skip rendering a pass for specific frames:
procedure TForm1.OnTimer(Sender: TObject);
begin
// Only update reflection every 3rd frame for performance
if (FrameCount mod 3) <> 0 then
ReflectionPass.SkipRendering();
end;
Adjust pass resolution based on performance:
procedure TForm1.AdjustPassQuality(AFPS: Single);
begin
if AFPS < 30 then
begin
// Reduce reflection resolution (needs an individual pass size)
ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 0.5;
end
else if AFPS > 55 then
begin
// Restore full resolution
ReflectionPass.ScaleViewportSize := False;
end;
end;
Gorilla3D allows to write your own render pass controllers. The base classes for implementation are TGorillaRenderPassController, TGorillaRenderPassMaterial and TGorillaRenderPassMaterialSource.
It is important to define what the render pass is intended to do:
unit MyDepthRenderPass;
interface
uses
System.Classes,
System.Types,
System.UITypes,
System.SysUtils,
System.Generics.Collections,
System.Math.Vectors,
FMX.Types,
FMX.Types3D,
FMX.Controls3D,
FMX.Materials,
FMX.MaterialSources,
Gorilla.Context.Texturing,
Gorilla.Context.Rendering,
Gorilla.Controller;
type
TMyDepthMaterialSource = class;
TMyDepthMaterial = class(TGorillaRenderPassMaterial)
protected
FVertexShaderMVZ : TContextShader;
FPixelShaderZ : TContextShader;
procedure DoApply(const Context: TContext3D); override;
procedure DoInitialize(); override;
public
constructor Create(ASource : TCustomDepthMaterialSource); reintroduce; virtual;
destructor Destroy(); override;
end;
TMyDepthMaterialSource = class(TGorillaRenderPassMaterialSource)
protected
function CreateMaterial() : TMaterial; override;
procedure DoPassesChanged(Sender: TObject); override;
public
constructor Create(AOwnerPass : TGorillaRenderPassController); override;
destructor Destroy(); override;
end;
TMyDepthRenderPass = class(TGorillaRenderPassController)
protected
FDefaultColor : TAlphaColor;
FDefaultDepth : Single;
function CreateMaterialSource() : TGorillaRenderPassMaterialSource; override;
function GetMapSize() : TPoint;
procedure SetMapSize(AValue : TPoint);
procedure DoConfigure(); override;
procedure DoCreateRenderer(); override;
procedure DoOnCreateCompositeTexture(
ASender : TObject; const ASize : TPoint; const AScale : Single;
out ATexture : TGorillaTextureBitmap); override;
procedure DoOnBeginRenderPassSetup(const ACount : Integer;
const APass : TRenderPass); override;
procedure DoOnEndRenderPassSetup(const ACount : Integer;
const APass : TRenderPass); override;
procedure DoSetupTexturesByViewport(const AContext : TContext3D;
const AWidth, AHeight : Integer); override;
public
property MapSize : TPoint read GetMapSize write SetMapSize;
property BiasMatrix : TMatrix3D read FBiasMatrix;
property DefaultDepth : Single read FDefaultDepth write FDefaultDepth;
constructor Create(AOwner : TComponent;
const AId : String = 'MyDepth'); reintroduce; virtual;
destructor Destroy(); override;
function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
procedure SetupMatrices(const AContext : TContext3D); virtual;
function GetOutputTexture() : TTexture; override;
function GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = true) : TMatrix3D; override;
end;
implementation
uses
System.Math,
System.IOUtils,
Gorilla.Context.Buffers,
Gorilla.Context,
Gorilla.Renderer;
{$I ..\..\instance\material\glsl\Gorilla.GLSL.Common.inc}
ResourceString GORILLA_MYDEPTH_VS =
'in vec3 a_Position;'#13#10 +
'uniform mat4 _ModelViewProjMatrix;'#13#10 +
'void main(){'#13#10 +
' vec4 fvPosition = vec4(a_Position.x, a_Position.y, a_Position.z, 1.0);'#13#10 +
' gl_Position = _ModelViewProjMatrix * fvPosition;'#13#10 +
'}';
ResourceString GORILLA_MYDEPTH_FS =
'layout (location = 0) out float o_FragColor;'#13#10 +
'void main(){'#13#10 +
' o_FragColor = gl_FragCoord.z;'#13#10 +
'}';
{ TMyDepthMaterial }
constructor TMyDepthMaterial.Create(ASource : TMyDepthMaterialSource);
begin
inherited Create(ASource);
end;
destructor TMyDepthMaterial.Destroy();
begin
inherited;
end;
procedure TMyDepthMaterial.DoInitialize();
var LOGLBytes : TArray<Byte>;
begin
Inc(FShaderUpdateCounter);
///
/// VertexShader
///
/// The shader stores the simple gl_FragCoord.z value
LOGLBytes := TEncoding.ASCII.GetBytes(GORILLA_SHADER_VERSION + GORILLA_MYDEPTH_VS);
FVertexShader := TShaderManager.RegisterShaderFromData(
Format('MyDepth-%x-%x.fvs', [NativeUInt(Self), FShaderUpdateCounter]),
TContextShaderKind.VertexShader, '', [
TContextShaderSource.Create(TContextShaderArch.GLSL,
LOGLBytes,
[
TContextShaderVariable.Create('ModelViewProjMatrix', TContextShaderVariableKind.Matrix, 0, 4)
]
)
]);
///
/// PixelShader / FragmentShader
///
LOGLBytes := TEncoding.ASCII.GetBytes(GORILLA_SHADER_VERSION + GORILLA_MYDEPTH_FS);
FPixelShader := TShaderManager.RegisterShaderFromData(
Format('MyDepth-%x-%x.fps', [NativeUInt(Self), FShaderUpdateCounter]),
TContextShaderKind.PixelShader, '', [
TContextShaderSource.Create(TContextShaderArch.GLSL,
LOGLBytes,
[]
)
]);
end;
procedure TMyDepthMaterial.DoApply(const Context: TContext3D);
var LEyeMatrix : TMatrix3D;
LCtx : TGorillaContext;
begin
// Set shaders
Context.SetShaders(FVertexShader, FPixelShader);
if not (Context is TGorillaContext) then
Exit;
LCtx := TGorillaContext(Context);
LCtx.SetContextStates([TContextState.csFrontFace, TContextState.csZTestOn,
TContextState.csZWriteOn]);
LEyeMatrix := FSource.OwnerPass.GetCurrentModelViewProjectionMatrix();
LCtx.SetShaderVariable('ModelViewProjMatrix', LEyeMatrix, true);
end;
{ TMyDepthMaterialSource }
constructor TMyDepthMaterialSource.Create(AOwnerPass : TGorillaRenderPassController);
begin
inherited Create(AOwnerPass);
end;
destructor TMyDepthMaterialSource.Destroy();
begin
inherited;
end;
function TMyDepthMaterialSource.CreateMaterial() : TMaterial;
begin
FHasMaterial := true;
Result := TMyDepthMaterial.Create(Self);
end;
procedure TCustomDepthMaterialSource.DoPassesChanged(Sender: TObject);
begin
// do nothing
end;
{ TGorillaMyDepthRenderPass }
constructor TGorillaMyDepthRenderPass.Create(AOwner : TComponent;
const AId : String = 'MyDepth');
begin
inherited Create(AOwner, AId);
end;
destructor TGorillaMyDepthRenderPass.Destroy();
begin
FreeAndNil(FShader);
inherited;
end;
procedure TGorillaMyDepthRenderPass.DoConfigure();
begin
inherited;
// Depth pass rendering should be done before main pass
FType := TRenderPassType.Pre;
// We want all objects to be rendered individually
FMethod := TRenderPassMethod.RenderListToFBO;
// Because transparency is not important for depth pass rendering
// we can switch to simple list rendering
FRenderProc := TRenderPassRenderingProc.ListRendering;
FRendererFlags := [TRendererFlag.IgnoreRenderTargets,
TRendererFlag.IgnoreCompositeCtrl, TRendererFlag.IgnoreEmissiveBlur,
TRendererFlag.IgnoreGlobalIllum, TRendererFlag.IgnoreSSS,
TRendererFlag.IgnoreSSAO];
FRecalcProjMatrix := true;
FRecalcViewMatrix := true;
// optionally reduce the size of rendering
// FOverwriteViewportSize := true;
// FViewportSize := Point(1024, 1024);
FDefaultColor := TAlphaColorRec.Black;
FDefaultDepth := 1;
FShader := CreateMaterialSource();
FShader.Stored := false;
end;
function TGorillaMyDepthRenderPass.CreateMaterialSource() : TGorillaRenderPassMaterialSource;
begin
result := TMyDepthMaterialSource.Create(Self);
end;
function TGorillaMyDepthRenderPass.GetMapSize() : TPoint;
begin
Result := ViewportSize;
end;
procedure TGorillaMyDepthRenderPass.SetMapSize(AValue : TPoint);
begin
ViewportSize := AValue;
FRecalcProjMatrix := true;
end;
procedure TGorillaMyDepthRenderPass.DoSetupTexturesByViewport(
const AContext : TContext3D; const AWidth, AHeight : Integer);
begin
inherited;
end;
function TGorillaMyDepthRenderPass.GetOutputTexture() : TTexture;
begin
Result := inherited;
end;
function TGorillaMyDepthRenderPass.GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = true) : TMatrix3D;
begin
Result := inherited;
end;
function TGorillaMyDepthRenderPass.GetViewMatrix(const AContext : TContext3D) : TMatrix3D;
begin
Result := inherited GetViewMatrix(AContext);
end;
function TGorillaMyDepthRenderPass.GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D;
begin
Result := inherited GetProjectionMatrix(AContext);
end;
procedure TGorillaMyDepthRenderPass.SetupMatrices(const AContext : TContext3D);
var LViewMat,
LProjMat : TMatrix3D;
begin
LViewMat := GetViewMatrix(AContext);
LProjMat := GetProjectionMatrix(AContext);
FTextureMatrix := LViewMat * LProjMat;
AContext.SetCameraMatrix(LViewMat);
AContext.SetCameraAngleOfView(Viewport.CurrentCamera.AngleOfView);
end;
procedure TGorillaMyDepthRenderPass.DoCreateRenderer();
begin
inherited;
if Assigned(FRenderer) then
FRenderer.RenderTargets := [TRenderTarget.Color_0];
end;
procedure TGorillaMyDepthRenderPass.DoOnCreateCompositeTexture(
ASender : TObject; const ASize : TPoint; const AScale : Single;
out ATexture : TGorillaTextureBitmap);
var LTexRef : TTexture;
begin
// For depth we need at least 16 bit per channel, so we need to create a different
// texture than the default one
/// create fullscreen context rendering texture
/// this is a composition texture for WBOIT forward rendering OR deferred rendering
ATexture := TGorillaTextureBitmap.Create();
ATexture.BeginSetup();
try
ATexture.Style := [TTextureStyle.RenderTarget];
ATexture.SetSize(ASize.X, ASize.Y);
ATexture.BitmapScale := AScale;
ATexture.DataType := TGorillaTextureDataType.dtHalfFloat;
ATexture.Components := TPixelFormatEx.R16F;
// ATexture.DataType := TGorillaTextureDataType.dtFloat;
// ATexture.Components := TPixelFormatEx.R32F;
ATexture.Format := TPixelFormatEx.R;
ATexture.MinFilter := TTextureFilter.Linear;
ATexture.MagFilter := TTextureFilter.Linear;
ATexture.WrapS := TGorillaTextureWrap.ClampToBorder;
ATexture.WrapT := TGorillaTextureWrap.ClampToBorder;
ATexture.BorderColor := TAlphaColorF.Create(1, 1, 1, 1);
finally
ATexture.EndSetup();
end;
// Return a texture reference and set scaling
LTexRef := ATexture.Texture;
ITextureAccess(LTexRef).TextureScale := AScale;
end;
procedure TGorillaMyDepthRenderPass.DoOnBeginRenderPassSetup(
const ACount : Integer; const APass : TRenderPass);
var LCtx : TGorillaContext;
begin
inherited;
if not (Assigned(FRenderer) and Assigned(FRenderer.SharedContext)) then
Exit;
if not (FRenderer.SharedContext is TGorillaContext) then
Exit;
LCtx := TGorillaContext(Renderer.SharedContext);
LCtx.SetContextStates([TContextState.csZWriteOn, TContextState.csZTestOn,
TContextState.csFrontFace]);
LCtx.ClearEx([TRenderTarget.Color_0, TRenderTarget.Depth],
FDefaultColor, FDefaultDepth, 0);
LCtx.DefaultFrameBuf.Prepare([TRenderTarget.Color_0]);
SetupMatrices(FRenderer.SharedContext);
end;
procedure TGorillaMyDepthRenderPass.DoOnEndRenderPassSetup(
const ACount : Integer; const APass : TRenderPass);
begin
inherited;
end;
initialization
RegisterClasses([TGorillaMyDepthRenderPass]);
finalization
UnregisterClasses([TGorillaMyDepthRenderPass]);
end.
In case you want to render elements f.e. only with a different perspective, this mode expects not to create a render material and render material source.
In your render pass class the CreateMaterialSource needs to return NIL.
The controller will then select the current material of the elements rendered.
function TGorillaMyDepthRenderPass.CreateMaterialSource() : TGorillaRenderPassMaterialSource;
begin
result := nil;
end;
For post effects this mode is the intended way.
Resolution Matters: Lower resolution passes are much faster. Use scaled viewports for non-critical passes.
Minimize Passes: Each render pass has overhead. Combine effects when possible.
Use ListRendering for Depth: When transparency doesn't matter (depth/shadow passes), use TRenderPassRenderingProc.ListRendering.
Control Filtering: Exclude unnecessary objects. Every object tested has a small cost.
Conditional Execution: Skip passes when not visible or needed (use SkipRendering()).
Iterations Cost: Each iteration re-renders. Use sparingly.
Pass Order: Pre-passes execute first. Minimize pre-pass count.
Problem: Render pass doesn't seem to run.
Solutions:
Enabled := TrueViewport is assignedId property_Type is set correctlyProblem: OutputTexture is black or empty.
Solutions:
Viewport must be assigned)RectToFBO, ensure Shader is assignedOverwriteViewportSize configurationProblem: Ignored controls still render.
Solutions:
IgnoreControl() after objects are createdAllowedControls is not blocking exclusionIsControlIgnored() to debugProblem: Render passes cause slowdown.
Solutions:
ViewportScaleListRendering instead of DefaultRenderingIterations countAlways Exclude Self: Water reflections should exclude the water plane itself.
Use Pre-Passes Sparingly: Each pre-pass delays the main render. Minimize count.
Match Resolution to Use: Shadow maps can be lower res. Reflections should match quality needs.
Unique IDs: Use descriptive, unique IDs like 'WaterReflection' not 'Pass1'.
Event Usage: Use events for dynamic configuration, not fixed setup.
Chain When Possible: Link passes with SetInputPass() for cleaner code.
Profile First: Measure performance impact before optimizing.
FireMonkey can draw all 2D content with Skia instead of Direct2D (GlobalUseSkia := True). Gorilla3D works with the Skia canvas, but the combination used to cost a lot of performance: depending on the form, the frame rate dropped to a fraction of the Direct2D value and the main thread was fully loaded even at 60 FPS.
Gorilla3D v1.5.1 addresses this. This page explains where the cost comes from, what v1.5.1 changes, and which settings you have.
Units: Gorilla.Viewport, Gorilla.Layers
Platforms: Windows (all improvements), other platforms (repaint deferral and Skia animations in layers only)
TGorillaViewport does not draw onto the FMX form canvas directly. The 3D scene is rendered by Gorilla3D's own graphics context into an offscreen image. FMX then draws this image in TGorillaViewport.Paint, like any other bitmap, together with all 2D controls of the form. In fixed frame rate mode (UseFixedFrameRate, the default on all platforms except iOS) this repeats every frame: render the scene, then invalidate the viewport so that FMX paints the new image.
A FireMonkey canvas declares its capabilities in GetCanvasStyle. The Direct2D canvas supports clip rects (TCanvasStyle.SupportClipRects): when a control invalidates its area, FMX repaints only that area.
The Skia canvases do not declare SupportClipRects. Without it, TCustomForm.AddUpdateRect widens every invalidation to the full client area of the form. The form clears its background completely and paints all of its controls again.
For a 3D viewport, which invalidates itself every frame, this means:
TSkAnimatedImage), FMX animations, a camera controller. At 60 FPS the form was repainted 150-180 times per second.With Direct2D the same form repaints only the viewport rectangle, and the 2D controls around it are not touched.
Note: This is a property of the Skia canvas in FireMonkey, not of Gorilla3D. Any FMX control that invalidates frequently (video, game view, animation) is affected the same way. Gorilla3D v1.5.1 reduces how often the full repaint happens. The cost of one full repaint itself remains.
All changes are active automatically, but only when the active canvas cannot repaint partial regions (no SupportClipRects) and is not a GPU canvas that shares the render context. In practice this means the Skia canvases. Direct2D, the FMX GPU canvas (GlobalUseGPUCanvas), design time and event-based rendering (UseFixedFrameRate = False) behave as before.
The viewport checks the capabilities of the active canvas instead of GlobalUseSkia. This also covers the case where GlobalUseSkia is set but Skia could not be activated.
| Class function | Returns True if |
|---|---|
TGorillaViewport.CanvasRepaintsWholeForm |
the canvas has no SupportClipRects, so FMX repaints the whole form for every invalidation |
TGorillaViewport.CanvasSharesRenderContext |
the canvas is a GPU canvas (TCustomCanvasGpu) that shares the graphics context with the renderer |
TGorillaViewport.UsesWholeFormRepaintHandling |
the first is True and the second is False - the v1.5.1 handling applies |
The GPU canvas is excluded on purpose: it relies on the canvas scene during rendering.
Every change of a 3D object requests a repaint of the viewport: moving a mesh, an animated skeleton, particles, a rotation set in a timer, a camera controller update. In fixed frame rate mode such a repaint only draws the last rendered image again, because the next frame renders and invalidates anyway. On Skia each of these requests was a full form repaint.
Since v1.5.1 these requests are only recorded. The next render frame invalidates exactly once. This covers NeedRender (changes of 3D objects) as well as BeginUpdate / EndUpdate on the viewport.
The Gorilla3D render loop keeps running at FixedFrameRate on its own timer. What changes is the moment the new image is handed to FMX:
IFMXDisplayLinkService, the same clock FMX and Lottie animations run on) the viewport invalidates, if a new image is available,Result: one full repaint per display refresh, no matter how many animations are running, while the 3D scene is still rendered at FixedFrameRate. With FixedFrameRate above the display refresh rate, the additional frames are rendered, but only the latest one per refresh is shown.
The render frame no longer opens a scene on the form canvas when a Skia canvas is active. On the Skia Vulkan canvas every BeginScene / EndScene on the form presents a swap chain image, even when nothing was drawn. That showed a stale image in between and made the 3D area flicker.
A TSkAnimatedImage (Lottie) or TSkAnimatedPaintBox inside a 3D layer never animated. TGorillaCustomLayer3D now advances them itself, see Skia Content inside the 3D Scene.
Example measurements on Windows 11: 1600 x 900 form, a sidebar with 300 controls (TRectangle + TText) and 4 Lottie animations next to the viewport (not overlapping), FixedFrameRate = 60. CPU load is the load of the main thread in % of one core.
| Canvas | v1.5.0: form repaints / s | v1.5.0: main thread | v1.5.1: form repaints / s | v1.5.1: main thread |
|---|---|---|---|---|
| Direct2D | 121 (viewport area only) | 20 % | 121 (viewport area only) | 20 % |
| Skia raster | 150 (full form) | 89 % | 61 (full form) | 40 % |
| Skia GPU (Vulkan) | 182 (full form) | 76 % | 61 (full form) | 30 % |
With an unlimited frame rate (FixedFrameRate = 1000) the same scene renders on Skia at about 640-770 FPS in v1.5.1, compared to 94-156 FPS in v1.5.0. The form is still painted only once per display refresh.
Direct2D remains the cheapest option for forms with many 2D controls: it repaints only the areas that changed.
Skia is enabled by FireMonkey, not by Gorilla3D. Set GlobalUseSkia in the project file before Application.Initialize:
program MyProject;
uses
Gorilla.Context.Backend, // Gorilla3D backend unit first, see Graphics Backend
System.StartUpCopy,
FMX.Forms,
FMX.Skia,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
begin
GlobalUseSkia := True;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
If the canvas service has already started when GlobalUseSkia is set, the setting has no effect. In debug builds FMX raises an exception telling you to move it earlier. In that case set it in the initialization section of a small unit that is listed directly behind FMX.Forms in the .dpr.
You can check which canvas is actually active at runtime:
Log.d('Canvas: %s, Skia repaint handling: %s',
[TCanvasManager.DefaultCanvas.ClassName,
BoolToStr(TGorillaViewport.UsesWholeFormRepaintHandling(), True)]);
On Windows, Skia offers a CPU and a GPU canvas. GlobalUseSkiaRasterWhenAvailable (unit FMX.Skia) selects between them:
| Setting | Canvas | Notes |
|---|---|---|
True (default on Windows) |
TSkRasterCanvas |
Draws on the CPU and copies the result to the window (GDI BitBlt). The cost of a full repaint grows with window size and number of controls. |
False |
TVkCanvas (Delphi 13.2 and newer) |
Draws on the GPU via Vulkan. Lower CPU load per repaint. |
GlobalUseSkia := True;
GlobalUseSkiaRasterWhenAvailable := False; // GPU canvas
In the measurements above, the Skia GPU canvas needed about 25 % less main thread time than the raster canvas. Both work with Gorilla3D, including the v1.5.1 improvements.
| Setting | Effect with Skia (v1.5.1) |
|---|---|
TGorillaViewport.UseFixedFrameRate |
Must be True (default on all platforms except iOS) for the improvements 2-4. |
TGorillaViewport.FixedFrameRate |
Rate of the Gorilla3D render loop. Not limited by the display link. |
TGorillaViewport.VSync |
Limits the render loop to the refresh rate of the display, as before. |
GlobalPreferredFramesPerSecond (FMX, default 60) |
Rate of the FMX display link, and with it the rate at which the form is painted. It never exceeds the refresh rate of the display. Raise it (e.g. to 144) if you want the form painted more often on a high refresh display. |
Rendering faster than the form is painted only makes sense if you need the frames for something else, e.g. physics or an input latency budget. For a typical application, FixedFrameRate equal to the display refresh rate (or VSync := True) keeps the CPU load lowest.
Both switches are class variables of TGorillaViewport and apply to all viewports. Set them before the first viewport starts rendering.
| Switch | Default | True restores |
|---|---|---|
TGorillaViewport.ImmediateRepaints |
False |
Every change of a 3D object and every EndUpdate repaints the viewport immediately (change 2 above is off). |
TGorillaViewport.TimerPresentation |
False |
The viewport invalidates right after every render frame instead of on the display link (change 3 above is off). |
// behaviour of v1.5.0 on Skia
TGorillaViewport.ImmediateRepaints := True;
TGorillaViewport.TimerPresentation := True;
You normally do not need them. They are meant for comparison and as a fallback if an application relies on the old timing.
Skia controls (TSkLabel, TSkAnimatedImage, TSkSvg, ...) can be placed as 2D children of TGorillaViewport. FMX paints them on top of the 3D image. Lottie animations run normally there.
TGorillaLayer3D paints its 2D children into its own texture, which is shown on a quad in the 3D scene. Static Skia controls and controls that you redraw yourself (e.g. TSkPaintBox with Redraw) work as usual.
Skia animations (TSkAnimatedImage, TSkAnimatedPaintBox) cannot run inside any 3D layer by themselves: Skia only runs an animation when its scene is a form (TSkCustomAnimatedControl.CanRunAnimation), and inside a layer the scene is the layer. Since v1.5.1, TGorillaLayer3D and TGorillaTextLayer3D advance these animations themselves, once per rendered frame and at most about 80 times per second:
| Animation property | Supported |
|---|---|
Enabled, Pause, Loop, Speed |
yes |
Inverse, AutoReverse, Delay, StartProgress, StopProgress |
no (always plays forward) |
TLayer3D does not get this. Use TGorillaLayer3D.var
LLayer : TGorillaLayer3D;
LLottie : TSkAnimatedImage;
begin
LLayer := TGorillaLayer3D.Create(Self);
LLayer.Parent := GorillaViewport1;
LLayer.Resolution := 200; // pixels per 3D unit of the layer texture
LLayer.Width := 1.5;
LLayer.Height := 1.8;
LLottie := TSkAnimatedImage.Create(Self);
LLottie.Parent := LLayer;
LLottie.Align := TAlignLayout.Client;
LLottie.LoadFromFile('animation.json');
LLottie.Animation.Loop := True;
end;
Texture resolution: the layer texture is
Width x ResolutionbyHeight x Resolutionpixels. The defaultResolutionis 50 pixels per unit, so a large layer with the default resolution looks blurry and stretched. RaiseResolutionfor crisp 2D content.
TSkLabel, TSkAnimatedImage, ...) also work on the Direct2D canvas.GlobalUseSkiaRasterWhenAvailable := False, Delphi 13.2+) over the raster canvas.FixedFrameRate to the display, or use VSync.Invalidate / Repaint calls on the form or on 2D controls. Under Skia each one can be a full form repaint that is not merged with the 3D frame.Expected to some degree: Skia repaints the whole form for every paint. Check the number of 2D controls on the form, prefer the GPU canvas, and make sure UseFixedFrameRate is True so that the v1.5.1 improvements apply.
GlobalUseSkia was set after the canvas service started. Set it before Application.Initialize, or in the initialization section of a unit listed directly behind FMX.Forms.
Fixed in v1.5.1. On older versions this appeared as soon as the paint did not follow the render frame immediately.
Use TGorillaLayer3D (not FMX TLayer3D) and Delphi 12 or newer. Check that Animation.Enabled is True and Animation.Pause is False.
2D controls placed directly in the viewport take part in BeginUpdate / EndUpdate of the viewport. Each EndUpdate repaints them, which under Skia is a full form repaint. If a camera controller or your own code brackets updates with Viewport.BeginUpdate / EndUpdate very often, this adds repaints. Move frequently updated 2D overlays to their own layout outside the viewport where possible.
Gorilla3D has no dedicated "line component" for arbitrary debug or helper geometry. Lines are drawn directly through the graphics context — the same way the framework itself draws bounding boxes, physics colliders, particle emitter bounds, joint helpers and the terrain grid. This guide explains the line API of TGorillaContext, how it behaves on OpenGL, OpenGL ES and Vulkan, and how to use it safely from your own components.
Units: Gorilla.Context, Gorilla.Context.Types
Platforms: Windows / Linux (OpenGL, full), Android (OpenGL ES, reduced), Windows (Vulkan, reduced), macOS / iOS (Metal, reduced)
There are three layers you can use, from simplest to most flexible:
| Layer | Entry point | Typical use |
|---|---|---|
FMX helpers (inherited from TContext3D) |
DrawLine, DrawRect, DrawCube, DrawLines |
Debug lines, bounding boxes, axes, helpers |
| Gorilla primitive kinds | DirectDrawPrimitives(TGorillaPrimitivesKind.LineStrip, ...) |
Paths, polylines, curves |
| Static line meshes | TMeshDef.BufferObject.Kind := TGorillaPrimitivesKind.Lines |
Large, unchanging line sets (e.g. TGorillaGrid) |
On top of that, TGorillaContext adds line state:
| Method | Purpose |
|---|---|
BeginLineRendering(Width, Type, Persistent) |
Sets line width and line style (Solid / Dashed) for the following draw calls |
EndLineRendering() |
Restores the default line state |
DirectDrawWireframe(...) |
Draws a triangle mesh as wireframe |
All line drawing happens during rendering, i.e. inside a Render() override or an OnRender event of a 3D object. The TContext3D you receive there is a TGorillaContext whenever the object lives inside a TGorillaViewport:
uses
Gorilla.Context, Gorilla.Context.Types;
procedure TForm1.Dummy1Render(Sender: TObject; Context: TContext3D);
var LCtx : TGorillaContext;
begin
if not (Context is TGorillaContext) then
Exit;
LCtx := TGorillaContext(Context);
// ... draw lines here
end;
Note: The FMX helpers (
DrawLine,DrawCube, ...) are available on everyTContext3D. OnlyBeginLineRendering,EndLineRendering,DirectDrawWireframeand theTGorillaPrimitivesKindoverloads require the cast toTGorillaContext.
The quickest way are the FMX helpers. They create a temporary vertex/index buffer and a TColorMaterial internally, so you only pass positions and a color:
// a single line from A to B
LCtx.DrawLine(Point3D(0, 0, 0), Point3D(0, -2, 0), 1.0, TAlphaColorRec.Red);
// wireframe box (12 edges) around a center with a size
LCtx.DrawCube(Point3D(0, 0, 0), Point3D(1, 1, 1), 1.0, TAlphaColorRec.Yellow);
// rectangle outline
LCtx.DrawRect(Point3D(-1, -1, 0), Point3D(1, 1, 0), 1.0, TAlphaColorRec.Lime);
Coordinates are in the space of the current matrix of the context. Set the matrix of the object you want to annotate first and restore it afterwards:
LPrevMat := LCtx.CurrentMatrix;
try
LCtx.SetMatrix(MyModel.AbsoluteMatrix);
LCtx.DrawCube(TPoint3D.Zero, Point3D(2, 2, 2), 1.0, TAlphaColorRec.White);
finally
LCtx.SetMatrix(LPrevMat);
end;
DrawCube issues one draw call for all 12 edges. DrawLine issues one draw call per line — fine for a handful of helper lines, too slow for thousands.
For many lines, build a vertex and index buffer yourself and call DrawLines. Every pair of indices forms one line segment (GL_LINES / VK_PRIMITIVE_TOPOLOGY_LINE_LIST):
var LVtx : TVertexBuffer;
LIdx : TIndexBuffer;
LMat : TColorMaterial;
I : Integer;
begin
LVtx := TVertexBuffer.Create([TVertexFormat.Vertex], 2 * 10);
LIdx := TIndexBuffer.Create(2 * 10);
LMat := TColorMaterial.Create();
try
for I := 0 to 9 do
begin
LVtx.Vertices[I * 2] := Point3D(I, 0, 0);
LVtx.Vertices[I * 2 + 1] := Point3D(I, -1, 0);
LIdx[I * 2] := I * 2;
LIdx[I * 2 + 1] := I * 2 + 1;
end;
LMat.Color := TAlphaColorRec.Cyan;
LCtx.DrawLines(LVtx, LIdx, LMat, 1.0);
finally
LMat.Free();
LIdx.Free();
LVtx.Free();
end;
end;
Instead of a TColorMaterial you can pass the material of any material source, e.g. MyMaterialSource.Material, to get lit, textured or vertex-colored lines.
Performance: Allocating buffers in every frame is fine for debug output. For lines that never change, keep the buffers as fields of your component, or use a static line mesh.
FMX only knows Points, Lines and Triangles. Gorilla3D extends this with TGorillaPrimitivesKind (unit Gorilla.Context.Types):
TGorillaPrimitivesKind = (Points, Lines, Triangles, LineLoop, LineStrip,
TriangleStrip, TriangleFan);
A LineStrip connects all vertices in order, so a polyline of N points only needs N vertices. Use the raw-pointer overload of DirectDrawPrimitives. It does not apply a material itself — it draws with the shader/material that is currently bound on the context (this is how render passes use it). Call it from within your object's own draw, after its material has been applied:
LCtx.DirectDrawPrimitives(TGorillaPrimitivesKind.LineStrip,
LVtx.Buffer, LIdx.Buffer, LVtx.GetVertexDeclarations,
LVtx.VertexSize, LVtx.Length, LIdx.IndexSize, LIdx.Length);
Portability:
LineLoophas no Vulkan or Metal equivalent. Vulkan maps it to a line strip — the loop is not closed — and Metal raises an exception. For portable code, useLineStripand repeat the first vertex at the end.
Line width and style are context state. Wrap your line draws in a BeginLineRendering / EndLineRendering pair — always with try..finally, so the state is restored even if a draw call raises:
LCtx.BeginLineRendering(3); // 3 pixel, solid
try
LCtx.DrawCube(TPoint3D.Zero, Point3D(1, 1, 1), 1.0, TAlphaColorRec.Cornflowerblue);
finally
LCtx.EndLineRendering();
end;
LCtx.BeginLineRendering(2, TGorillaLineType.Dashed); // 2 pixel, dashed
| Parameter | Meaning |
|---|---|
ALineWidth |
Line width in pixels. Default of the context is DefaultLineWidth (1.0). |
AType |
TGorillaLineType.Solid (default) or TGorillaLineType.Dashed (fixed pattern $F0F0) |
APersistent |
Keep the state for all following line draws — see below |
The currently active width is readable through TGorillaContext.CurrentLineWidth. The value EndLineRendering returns to is DefaultLineWidth (read/write).
On desktop OpenGL, BeginLineRendering also switches the polygon mode to GL_LINE. Triangles drawn inside the block therefore appear as wireframe — this is exactly how DirectDrawWireframe works. Do not draw regular meshes inside a line block.
By default the line state is consumed by the first line draw call: after a Lines draw, the OpenGL backend automatically resets the width, the dash pattern and the polygon mode to their defaults. This keeps a forgotten EndLineRendering from leaking thick, dashed lines into the rest of the frame.
As a consequence, only the first draw call inside a non-persistent block uses your settings:
LCtx.BeginLineRendering(3);
try
LCtx.DrawLine(A, B, 1, TAlphaColorRec.Red); // 3 px
LCtx.DrawLine(B, C, 1, TAlphaColorRec.Red); // 1 px (!) - state already reset
finally
LCtx.EndLineRendering();
end;
Whenever a block contains more than one line draw call — several DrawLine calls, several DrawCube calls, a loop — pass APersistent = true:
LCtx.BeginLineRendering(2, TGorillaLineType.Dashed, true);
try
for I := 0 to High(FColliders) do
LCtx.DrawCube(FColliders[I].Center, FColliders[I].Size, 1, TAlphaColorRec.White);
finally
LCtx.EndLineRendering(); // mandatory with APersistent = true
end;
With APersistent = true the closing EndLineRendering() is mandatory; otherwise every line in the remaining frame is drawn with your width and style.
DirectDrawWireframe draws a triangle mesh as wireframe with a given line width. It is used by TGorillaMesh for its wireframe display:
LCtx.DirectDrawWireframe(
LVtxBuf.Buffer, LIdxBuf.Buffer,
LVtxBuf.GetVertexDeclarations, LVtxBuf.VertexSize, LVtxBuf.Length,
LIdxBuf.IndexSize, LIdxBuf.Length,
2, // line width
LMaterial, // TMaterial
1.0); // opacity
Internally this is BeginLineRendering + a triangle draw with polygon mode GL_LINE + EndLineRendering. Availability is limited — see the support matrix:
glPolygonMode does not exist. The call draws nothing.VK_POLYGON_MODE_FILL. The call currently draws the mesh filled.For a portable wireframe, convert the triangles into a line index list (each triangle a, b, c becomes the segments a-b, b-c, c-a) and draw it with DrawLines. TGorillaTerrain does exactly this for its ShowGrid option.
For large line sets that rarely change (grids, rulers, paths), let a mesh keep the lines in a GPU buffer instead of re-uploading them in every frame. Set the primitive kind of the mesh definition's buffer object to Lines after the mesh data has been applied. TGorillaGridLineMesh in Gorilla.Grid is the reference implementation:
LMeshDef := TMeshDef(FDef);
LMeshDef.IsStatic := false;
try
LMeshDef.ApplyFromMeshData(Self.MeshData); // vertices + line index pairs
Self.MeshData.VertexBuffer.Length := 0;
Self.MeshData.IndexBuffer.Length := 0;
finally
LMeshDef.IsStatic := true; // creates the buffer object
LMeshDef.BufferObject.Kind := TGorillaPrimitivesKind.Lines;
end;
The index buffer contains index pairs, exactly as for DrawLines. Such a mesh is drawn with the regular material pipeline of the mesh — no BeginLineRendering needed.
A complete component that draws an axis cross and a dashed bounding box around a target control. It follows the same rules as the built-in overlays (TGorillaControl.ShowBoundingBox, physics collider rendering):
unit MyDebugOverlay;
interface
uses
System.Classes, System.Types, System.UITypes, System.Math.Vectors,
FMX.Types3D, FMX.Controls3D, FMX.Objects3D,
Gorilla.Context, Gorilla.Context.Types, Gorilla.Context.Buffers;
type
TMyDebugOverlay = class(TDummy)
private
FTarget : TControl3D;
protected
procedure Render(); override;
public
property Target : TControl3D read FTarget write FTarget;
end;
implementation
procedure TMyDebugOverlay.Render();
var LCtx : TGorillaContext;
LPrevMat : TMatrix3D;
LPrevCache: TMeshBufferObject;
LSize : TPoint3D;
begin
inherited;
if not (Assigned(FTarget) and (Context is TGorillaContext)) then
Exit;
LCtx := TGorillaContext(Context);
// 1) only in the main pass - not in shadow, reflection, ... passes
if Assigned(LCtx.CurrentPass) then
Exit;
// 2) do not let the line draw consume a cached mesh buffer
LPrevCache := LCtx.CurrentCache;
LCtx.CurrentCache := nil;
// 3) several draw calls => persistent line state
LCtx.BeginLineRendering(2, TGorillaLineType.Dashed, true);
try
LPrevMat := LCtx.CurrentMatrix;
try
LCtx.SetMatrix(FTarget.AbsoluteMatrix);
LSize := Point3D(FTarget.Width, FTarget.Height, FTarget.Depth);
LCtx.DrawCube(TPoint3D.Zero, LSize, 1, TAlphaColorRec.Orange);
LCtx.DrawLine(TPoint3D.Zero, Point3D(LSize.X, 0, 0), 1, TAlphaColorRec.Red);
LCtx.DrawLine(TPoint3D.Zero, Point3D(0, -LSize.Y, 0), 1, TAlphaColorRec.Lime);
LCtx.DrawLine(TPoint3D.Zero, Point3D(0, 0, LSize.Z), 1, TAlphaColorRec.Blue);
finally
LCtx.SetMatrix(LPrevMat);
end;
finally
LCtx.EndLineRendering();
LCtx.CurrentCache := LPrevCache;
end;
end;
end.
Note: FMX uses a Y-down convention — "up" is negative Y.
| Feature | OpenGL 4.3+ (Windows / Linux) | OpenGL ES 3.1+ (Android) | Vulkan (Windows) | Metal (macOS / iOS) |
|---|---|---|---|---|
DrawLine / DrawCube / DrawLines |
✔ | ✔ | ✔ | ✔ |
LineStrip |
✔ | ✔ | ✔ | ✔ |
LineLoop (closed) |
✔ | ✔ | ✘ drawn as open strip | ✘ raises an exception |
| Line width > 1 | ✔ | driver dependent ¹ | ✘ always 1 px | ✘ always 1 px |
TGorillaLineType.Dashed |
✔ | ✘ solid | ✘ solid | ✘ solid |
DirectDrawWireframe |
✔ | ✘ draws nothing | ✘ draws filled | ✘ |
¹ OpenGL ES only guarantees a line width of 1. Many mobile drivers clamp glLineWidth to that value.
On the reduced backends BeginLineRendering / EndLineRendering are still safe to call — they only record the requested state. Your code stays portable; the lines simply render with 1 px, solid.
Need thick lines everywhere? Hardware line width is a legacy feature (Vulkan's
wideLines, Metal has none at all). For lines that must be wide on every platform, build them as geometry — thin quads facing the camera, or thin cylinders — and render them like any other mesh.
try..finally around BeginLineRendering / EndLineRendering and around SetMatrix.APersistent = true. Otherwise only the first draw uses your width and style.Render() is also called from the shadow, reflection, environment and other passes. Debug lines there end up in shadow maps or reflections. Check LCtx.CurrentPass and exit when it is assigned.CurrentCache, set it to nil, and restore it afterwards. Otherwise the line draw takes the cached buffer of the mesh — and resets it.GL_LINE there; meshes would turn into wireframe.DirectDrawWireframe for portable code — convert to a line list instead.Gorilla.Context)| Member | Description |
|---|---|
procedure BeginLineRendering(const ALineWidth: Single; const AType: TGorillaLineType = Solid; const APersistent: Boolean = false) |
Activates line width and style for the following line draws |
procedure EndLineRendering(APersistent: Boolean = false) |
Restores DefaultLineWidth, solid style and fill mode |
procedure DirectDrawWireframe(const AVertices, AIndices: Pointer; const AVertexDeclaration: TVertexDeclaration; const AVertexSize, AVertexCount, AIndexSize, AIndexCount: Integer; const ALineWidth: Single; const AMaterial: TObject; const AOpacity: Single) |
Draws a triangle mesh as wireframe |
procedure DirectDrawPrimitives(const AKind: TGorillaPrimitivesKind; const Vertices, Indices: Pointer; const VertexDeclaration: TVertexDeclaration; const VertexSize, VertexCount, IndexSize, IndexCount: Integer) |
Draws raw buffers with an extended primitive kind (LineStrip, LineLoop, ...) |
property DefaultLineWidth: Single |
Width restored by EndLineRendering (default 1.0) |
property CurrentLineWidth: Single |
Currently active line width (read-only) |
property CurrentPass: TRenderPass |
Active render pass, nil in the main pass (read-only) |
property CurrentCache: TMeshBufferObject |
Cached mesh buffer of the current draw |
FMX.Types3D)| Member | Description |
|---|---|
procedure DrawLine(const StartPoint, EndPoint: TPoint3D; const Opacity: Single; const Color: TAlphaColor) |
One line segment, one draw call |
procedure DrawRect(const TopLeft, BottomRight: TPoint3D; const Opacity: Single; const Color: TAlphaColor) |
Rectangle outline |
procedure DrawCube(const Center, Size: TPoint3D; const Opacity: Single; const Color: TAlphaColor) |
Box outline (12 edges, one draw call) |
procedure DrawLines(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Material: TMaterial; const Opacity: Single) |
Line list from buffers (index pairs) |
procedure DrawPoints(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Material: TMaterial; const Opacity: Single) |
Point list |
Gorilla.Context.Types)TGorillaLineType = (Solid, Dashed);
TGorillaPrimitivesKind = (Points, Lines, Triangles, LineLoop, LineStrip,
TriangleStrip, TriangleFan);Gorilla3D supports over 30 model file formats for import, from common industry standards to specialized CAD and game engine formats. The framework provides native parsers for the most common formats and uses the Mayo CLI tool for additional CAD formats.
| Format | Extension | Mesh | Materials | Animation | Skeleton | Notes |
|---|---|---|---|---|---|---|
| G3D | .g3d |
Yes | Yes | Yes | Yes | Native format, BSON/JSON + ZLib |
| glTF/GLB | .gltf, .glb |
Yes | PBR | Yes | Yes | Industry standard |
| FBX | .fbx |
Yes | Yes | Yes | Yes | ASCII + Binary |
| COLLADA | .dae |
Yes | Yes | Yes | Yes | XML-based, ZIP support |
| OBJ | .obj |
Yes | MTL | No | No | Simple, widely supported |
| STL | .stl |
Yes | No | No | No | ASCII + Binary, ZIP support |
| PLY | .ply |
Yes | Vertex Colors | No | No | Gaussian Splatting support |
| USD | .usd, .usda, .usdc, .usdz |
Yes | Yes | Yes | Yes | ASCII stage, binary crate and archive; UsdSkel |
| Babylon.js | .babylon |
Yes | Yes | Yes | Yes | JSON-based |
| X3D | .x3d, .x3dz |
Yes | Yes | Interpolators | H-Anim | XML/binary |
| SketchUp | .skp |
Yes | Yes | No | No | Via SketchUp C API SDK |
| STEP | .stp, .step |
Yes | No | No | No | B-Spline tessellation |
These formats use the Mayo CAD viewer CLI tool for import:
| Format | Extension | Description |
|---|---|---|
| STEP | .stp, .step |
STEP CAD (alternative loader) |
| IGES | .iges, .igs |
IGES CAD format |
| DXF | .dxf |
AutoCAD DXF |
| BREP | .brep, .rle, .occ |
OpenCascade BREP |
| 3MF | .3mf |
3D Manufacturing Format |
| AMF | .amf |
Additive Manufacturing |
| VRML | .wrl, .wrz, .vrml |
VRML 3D web |
| DirectX X | .x |
DirectX mesh format |
| 3DS | .3ds |
3D Studio Max (legacy) |
| OFF | .off |
Object File Format |
| Format | Extension | Unit | Notes |
|---|---|---|---|
| G3D | .g3d |
Gorilla.G3D.Exporter |
Full round-trip (materials, animation, skeleton) |
| glTF (binary) | .glb |
Gorilla.GLB.Exporter |
glTF 2.0, PBR materials with embedded images, skins, animations |
| USD (ASCII) | .usda |
Gorilla.USDA.Exporter |
Readable stage, UsdSkel skeletons + animations, textures next to the file |
| USD (crate) | .usdc |
Gorilla.USDC.Exporter |
Binary crate, same scene structure as .usda |
| USDZ | .usdz |
Gorilla.USDZ.Exporter |
ZIP archive with stage and textures — the AR delivery format |
| OBJ | .obj |
Gorilla.OBJ.Exporter |
Mesh + MTL materials |
| STL | .stl |
Gorilla.STL.Exporter |
Mesh only |
G3D is Gorilla3D's native format, optimized for fast loading:
// Load G3D natively
GorillaModel1.LoadFromFile('models/character.g3d');
// Save to G3D after importing from another format
GorillaModel1.SaveToFile('models/character.g3d');
The GL Transmission Format is the modern standard for 3D content. GLB is the binary variant.
Gorilla.GLTF.Loader, Gorilla.GLB.LoaderGorilla.GLB.Exporter (TGorillaGLBExporter) writes a self-contained .glbConverting to G3D: When a skinned glTF model is stored as G3D (
SaveToFile, the G3D exporter or the.fmxbinary data at design time), the joint weights of every primitive and mesh node are stored per mesh. This way the model animates completely after loading the G3D file, without the glTF source.
Autodesk's FBX format is widely used in game and film production.
Gorilla.Format.FBXAn XML-based interchange format.
Gorilla.Format.DAESimple and widely supported.
Gorilla.Format.OBJPixar's scene description format — the interchange format of DCC tools (Blender, Maya, Houdini, Omniverse) and the delivery format for AR on iOS. Gorilla3D reads and writes all four flavours.
| Extension | Container | Import | Export |
|---|---|---|---|
.usda / .usd |
ASCII stage — readable and diffable | Yes | Yes (Gorilla.USDA.Exporter) |
.usdc |
Binary crate — compact, fast to parse | Yes | Yes (Gorilla.USDC.Exporter) |
.usdz |
ZIP archive with stage and textures | Yes | Yes (Gorilla.USDZ.Exporter) |
Import (Gorilla.USD.Loader, one loader registered for all four extensions):
.usdz the images are read directly out of the archiveUsdSkel skeletons with joint hierarchy and rest posesSkelAnimation clips, which become regular TGorillaAnimation objects in the model's animation managerExport:
UsdSkel (SkelRoot → Skeleton → SkelAnimation)MultiAnimMode: VariantSet (default, one variant per clip), SeparateSkelRoots (self-contained root per clip) or SeparateFiles (one sibling file per clip)UpAxis (Y), DefaultPrimName (Model), TimeCodesPerSecond (24), and for .usdc also MetersPerUnit (1.0).usda and .usdc write the textures next to the file, .usdz packs them into the archive// Import - the extension picks the parser
GorillaModel1.LoadFromFile('models/character.usdz');
// Export as a single AR-ready file
uses Gorilla.USDZ.Exporter;
var LExp := TGorillaUSDZExporter.Create();
try
LExp.InnerFormat := TUSDZInnerFormat.Usda; // or Usdc for a binary stage
LExp.SaveToFile(GorillaModel1.Def as TModelDef, 'character.usdz');
finally
LExp.Free();
end;
See Models — Model Export for the full exporter properties.
Industry-standard CAD format with B-Spline surface tessellation.
Gorilla.Format.STEP| Format | Extensions | Description |
|---|---|---|
| Babylon.js | .babylon |
JSON format with materials, animation, skeletons |
| X3D | .x3d |
Web3D standard with H-Anim humanoid support |
| MD2/MD3/MD5 | .md2, .md3, .md5mesh |
Quake engine model formats |
| 3DS | .3ds |
Legacy 3D Studio Max |
| BVH | .bvh |
Motion capture data |
| Blender | .blend |
Blender native format |
| LWO/LWS | .lwo, .lws |
LightWave object/scene |
Gorilla3D supports these texture formats:
| Format | Extension | Unit |
|---|---|---|
| DDS | .dds |
Gorilla.Format.DDS |
| TGA | .tga |
Gorilla.Format.TGA (Vampyre Imaging Library) |
| PNG | .png |
Built-in (FMX) |
| JPEG | .jpg, .jpeg |
Built-in (FMX) |
| BMP | .bmp |
Built-in (FMX) |
// Simple loading - format auto-detected by extension
GorillaModel1.LoadFromFile('models/scene.gltf');
// Load with the Gorilla loader system
uses Gorilla.Loader;
var LLoader := TGorillaLoader.Create();
try
LLoader.LoadFromFile('models/character.fbx', GorillaViewport1);
finally
LLoader.Free;
end;
// FBX with separate animation
GorillaModel1.LoadFromFile('models/character.fbx');
GorillaModel1.LoadAnimationFromFile('animations/walk.fbx');
// glTF binary
GorillaModel1.LoadFromFile('models/scene.glb');
// USD - ASCII stage, binary crate or archive (textures included)
GorillaModel1.LoadFromFile('models/character.usdz');
// COLLADA from ZIP
GorillaModel1.LoadFromFile('models/scene.dae.zip');
// STL
GorillaModel1.LoadFromFile('models/part.stl');
// Export to G3D (preserves everything)
GorillaModel1.SaveToFile('output/model.g3d');
Every other format has its own exporter class, and each one registers itself for its extension:
uses System.IOUtils, Gorilla.Exporter,
Gorilla.GLB.Exporter, Gorilla.USDA.Exporter,
Gorilla.USDC.Exporter, Gorilla.USDZ.Exporter,
Gorilla.OBJ.Exporter, Gorilla.STL.Exporter;
var
LExp: TGorillaExporter;
begin
// Pick the exporter registered for the extension ('.glb', '.usdz', '.obj', ...)
LExp := TGorillaExporter.GetExporter(
LowerCase(TPath.GetExtension(SaveDialog1.FileName)));
if Assigned(LExp) then
LExp.SaveToFile(GorillaModel1.Def as TModelDef, SaveDialog1.FileName);
// NOTICE: the instance belongs to the registry - do not free it
end;
Only the units you actually list in uses register themselves, so include the exporters you want to offer.
.glb.usda while debugging a pipeline (readable, diffable), .usdc when size and parse speed matter, .usdz to hand out one file including textures (iOS Quick Look, AR viewers)Gorilla3D includes a comprehensive set of built-in primitive shapes for creating procedural geometry. These primitives can be used for prototyping, level design, visual effects, and as building blocks for more complex objects.
All primitives inherit from TCustomMesh or TGorillaMesh and can be placed at design-time or created at runtime. They generate their own mesh geometry automatically.
| Primitive | Unit | Description |
|---|---|---|
| Cube | Gorilla.Cube |
Box / rectangular prism |
| Sphere | Gorilla.Sphere |
UV sphere |
| Cylinder | Gorilla.Cylinder |
Cylinder with caps |
| Cone | Gorilla.Cone |
Cone with base |
| Capsule | Gorilla.Capsule |
Cylinder with hemispherical ends |
| Hemisphere | Gorilla.Hemisphere |
Half sphere |
| Torus | Gorilla.Torus |
Donut shape |
| Disk | Gorilla.Disk |
Flat circular disk |
| Plane | Gorilla.Plane |
Flat rectangular plane |
| Tube | Gorilla.Tube |
Hollow cylinder |
| RoundCube | Gorilla.RoundCube |
Cube with rounded edges |
| ExtrudedMesh | Gorilla.ExtrudedMesh |
Shape from extruded 2D profile |
| ProfileMesh | Gorilla.ProfileMesh |
Shape from swept profile |
| GearMesh | Gorilla.GearMesh |
Gear/cog shape |
| Grid | Gorilla.Grid |
Visual grid overlay |
| Layers | Gorilla.Layers |
Layer management |
| SkyBox | Gorilla.SkyBox |
Sky dome / skybox |
| Volumetric Mesh | Gorilla.Volumetric.Mesh |
Volumetric rendering mesh |
| Volumetric Noise | Gorilla.Volumetric.Noise |
Noise-based volumetric effects |
uses Gorilla.Cube;
var Cube := TGorillaCube.Create(Self);
Cube.Parent := GorillaViewport1;
Cube.Position.Point := Point3D(0, -1, 0);
Cube.Width := 2;
Cube.Height := 2;
Cube.Depth := 2;
uses Gorilla.Sphere;
var Sphere := TGorillaSphere.Create(Self);
Sphere.Parent := GorillaViewport1;
Sphere.Width := 2;
Sphere.Height := 2;
Sphere.Depth := 2;
uses Gorilla.Cylinder;
var Cyl := TGorillaCylinder.Create(Self);
Cyl.Parent := GorillaViewport1;
Cyl.Width := 1;
Cyl.Height := 3;
Cyl.Depth := 1;
uses Gorilla.Cone;
var Cone := TGorillaCone.Create(Self);
Cone.Parent := GorillaViewport1;
Cone.Width := 2;
Cone.Height := 3;
A cylinder with hemispherical caps — ideal for character colliders.
uses Gorilla.Capsule;
var Caps := TGorillaCapsule.Create(Self);
Caps.Parent := GorillaViewport1;
Caps.Width := 1;
Caps.Height := 2;
uses Gorilla.Hemisphere;
var HS := TGorillaHemisphere.Create(Self);
HS.Parent := GorillaViewport1;
HS.Width := 2;
HS.Height := 1;
uses Gorilla.Torus;
var Torus := TGorillaTorus.Create(Self);
Torus.Parent := GorillaViewport1;
Torus.Width := 3;
Torus.Height := 3;
uses Gorilla.Disk;
var Disk := TGorillaDisk.Create(Self);
Disk.Parent := GorillaViewport1;
Disk.Width := 2;
uses Gorilla.Plane;
var Plane := TGorillaPlane.Create(Self);
Plane.Parent := GorillaViewport1;
Plane.Width := 10;
Plane.Depth := 10;
A hollow cylinder.
uses Gorilla.Tube;
var Tube := TGorillaTube.Create(Self);
Tube.Parent := GorillaViewport1;
Tube.Width := 2;
Tube.Height := 3;
A cube with rounded edges for a softer look.
uses Gorilla.RoundCube;
var RC := TGorillaRoundCube.Create(Self);
RC.Parent := GorillaViewport1;
RC.Width := 2;
RC.Height := 2;
RC.Depth := 2;
Creates 3D geometry by extruding a 2D polygon profile along an axis.
uses Gorilla.ExtrudedMesh;
var Extr := TGorillaExtrudedMesh.Create(Self);
Extr.Parent := GorillaViewport1;
Creates 3D geometry by sweeping a 2D profile along a path (lathe/revolution).
uses Gorilla.ProfileMesh;
var Prof := TGorillaProfileMesh.Create(Self);
Prof.Parent := GorillaViewport1;
Generates gear/cog geometry with configurable teeth.
uses Gorilla.GearMesh;
var Gear := TGorillaGearMesh.Create(Self);
Gear.Parent := GorillaViewport1;
Displays a visual grid for scene orientation and scale reference.
uses Gorilla.Grid;
var Grid := TGorillaGrid.Create(Self);
Grid.Parent := GorillaViewport1;
Renders a skybox or sky dome around the scene.
uses Gorilla.SkyBox;
var Sky := TGorillaSkyBox.Create(Self);
Sky.Parent := GorillaViewport1;
// Assign skybox textures
3D manipulation gizmo for translate/rotate/scale operations.
uses Gorilla.Gizmo;
A small orientation cube shown in a viewport corner.
uses Gorilla.OrientationCube;
Base mesh for volumetric rendering effects (fog, clouds, etc.).
uses Gorilla.Volumetric.Mesh;
var Vol := TGorillaVolumetricMesh.Create(Self);
Vol.Parent := GorillaViewport1;
Noise-based volumetric effects using procedural noise generation.
uses Gorilla.Volumetric.Noise;
All primitives support standard 3D operations:
// Positioning
Cube.Position.Point := Point3D(3, -1, 0);
// Rotation
Cube.RotationAngle.Y := 45;
// Scaling
Cube.Scale.Point := Point3D(2, 1, 2);
// Applying materials
Cube.MaterialSource := GorillaDefaultMaterialSource1;
// Visibility
Cube.Visible := False;
// Parenting
Sphere.Parent := Cube; // Sphere follows Cube's transform
// Bounding box (debugging / highlighting)
Cube.ShowBoundingBox := True;
Cube.BoundingBoxColor := TAlphaColors.Yellow;
ShowBoundingBox draws the body box of the primitive (Width, Height, Depth). It rotates and scales with the primitive and is drawn in the main render pass only. GetAnimatedBoundingBox() returns the same box in local space. See Bounding Box Visualization.
TGorillaTerrain instead of planesGorilla3D provides a comprehensive animation system for bringing 3D scenes to life. The framework supports multiple animation types including skeletal/joint animation, vertex (mesh) animation, and property-based keyframe animation for transforming objects over time.
TGorillaAnimationManager (Component)
└─ TGorillaAnimation Collection
└─ TSkeletonKeyAnimation (Container)
└─ TPropertyKeyAnimation instances
├─ TPoint3DKeyAnimation
├─ TVector3DKeyAnimation
├─ TQuaternion3DKeyAnimation
├─ TTransformationKeyAnimation
└─ TCoordinateKeyAnimation
Gorilla3D supports several animation types:
| Type | Description | Use Case |
|---|---|---|
| TPoint3DKeyAnimation | Animates TPoint3D properties | Position, rotation, scale transforms |
| TVector3DKeyAnimation | Animates TVector3D properties | Directional transforms |
| TQuaternion3DKeyAnimation | Animates quaternion rotations | Smooth rotations without gimbal lock |
| TTransformationKeyAnimation | Animates full TMatrix3D transforms | Skeletal/joint animation |
| TCoordinateKeyAnimation | Animates vertex positions | Mesh morphing, vertex animation |
| TSkeletonKeyAnimation | Container for synchronized animations | Character animation, complex rigs |
The TGorillaAnimationManager is the central component for managing all animations associated with a 3D model or character.
A TGorillaAnimationManager instance will automatically be created, loading model data into a TGorillaModel component. The model component will take care of registering animations and setting up all necessary animations. Basically a TGorillaAnimationManager manages multiple TGorillaAnimation objects, which then hold multiple animation types.
In special cases it might be needed to instanciate a TGorillaAnimationManager object manually. In order to do that, follow this workflow.
var
Manager: TGorillaAnimationManager;
Animation: TGorillaAnimation;
begin
// the owner must be the mesh/model the animations belong to -
// the constructor casts it to TGorillaMesh and assigns it to Manager.Mesh
Manager := TGorillaAnimationManager.Create(GorillaModel1);
// Load animation from definition
Animation := TGorillaAnimation.CreateEx(Manager);
Animation.LoadFromAnimationDef(AnimationDef);
Manager.AddAnimation('Walk', Animation);
end;
The manager owns its animations - removing them from Animations or calling Clear()
frees them.
Animations is a hashmap, so enumerating it directly yields an arbitrary order that can
change whenever an animation is added. For anything shown to a user, ask the manager for
a sorted list instead:
var
LName: String;
LAnim: TGorillaAnimation;
begin
// ids only - e.g. to fill a combo box
ComboBox1.Clear();
for LName in GorillaModel1.AnimationManager.GetAnimationNames() do
ComboBox1.Items.Add(LName);
// or the instances themselves, in the same order
for LAnim in GorillaModel1.AnimationManager.GetSortedAnimations() do
Memo1.Lines.Add(Format('%s: %.2f s', [LAnim.Id, LAnim.Skeleton.Duration]));
end;
Both return a snapshot as a dynamic array - nothing to free. The instances in
GetSortedAnimations() still belong to the manager.
The order is natural: digit runs are compared by their numeric value, text
case-insensitively. Walk2 comes before Walk10, idle and Idle sort together, and
the result is deterministic on every platform.
Registered: Walk10, idle, Walk2, Run, Attack01
Sorted: Attack01, idle, Run, Walk2, Walk10
// Play a specific animation
Manager.PlayAnimation('Walk');
// Check current animation
if Manager.CurrentAnimationName = 'Run' then
ShowMessage('Character is running');
var
WalkAnim: TGorillaAnimation;
begin
WalkAnim := Manager.GetAnimation('Walk');
if Assigned(WalkAnim) then
Manager.PlayAnimation(WalkAnim);
end;
PlayAnimation is the switching path that crossfades from the current pose into the
new clip (see Crossfading). Calling
Start() on an animation or assigning Manager.Current switches hard. If the id is not
found, PlayAnimation returns nil and the current clip keeps playing.
The id of an animation loaded from a file is the file name, f.e. archer-idle.dae. Use
TGorillaAnimation.Id (or Manager.GetAnimationNames()) to list animations, not Name:
Name is the component name, which can not contain dots or dashes (archer_idle_dae).
GetAnimation and PlayAnimation accept the component name as fallback anyway.
// fill a combobox with all animations, naturally sorted
for var LAnim : TGorillaAnimation in Manager.GetSortedAnimations() do
ComboBox1.Items.Add(LAnim.Id);
// ... and play the selected one
Manager.PlayAnimation(ComboBox1.Items[ComboBox1.ItemIndex]);
The navigation routines walk the animations in the natural order of
GetAnimationNames() - not in the order they were added and not in hashmap order:
// registered ids: 'Walk10', 'Idle', 'Walk2'
Manager.PlayAnimation('Idle');
Manager.PlayNextAnimation(); // Walk2
Manager.PlayNextAnimation(); // Walk10
Manager.PlayNextAnimation(); // Idle - wraps around to the first
Manager.PlayPreviousAnimation(); // Walk10 - wraps around to the last
| Method | Result |
|---|---|
GetFirstAnimation() / GetLastAnimation() |
First / last animation in natural id order, nil if empty |
PlayNextAnimation() |
Next animation, wraps to the first; starts the first one if none is current |
PlayPreviousAnimation() |
Previous animation, wraps to the last; starts the last one if none is current |
Both play methods go through PlayAnimation and therefore crossfade as well.
In earlier builds these routines followed the internal hash order, which was unpredictable. If you relied on "first added = first played", name your clips so that their natural order is the intended one (e.g.
01-Idle,02-Walk,10-Jump).
// Get current animation
var CurrentAnim := Manager.Current;
if Assigned(CurrentAnim) then
begin
// Start animation
CurrentAnim.Start();
// Stop animation (FMX jumps to the final frame first)
CurrentAnim.Stop();
// Stop and keep the currently visible pose
CurrentAnim.StopAtCurrent();
// Reset to first frame
CurrentAnim.Reset();
// Scale the interpolator durations - NOTE: a duration factor,
// 2.0 = twice as long = half speed, and cumulative
CurrentAnim.SetSpeed(0.5);
// Check animation state
if CurrentAnim.IsRunning then
ShowMessage('Animation playing');
if CurrentAnim.IsPaused then
ShowMessage('Animation paused');
end;
{$IF CompilerVersion >= 37.0}
// Delphi 13+: the render clock occupies the FMX Pause flag
CurrentAnim.Skeleton.Paused := True;
{$ELSE}
CurrentAnim.Skeleton.Pause := True;
{$ENDIF}
IsPaused reads the right flag on every Delphi version. See
Animation Playback Control for an absolute playback rate,
seeking and crossfade settings.
Property key animations allow you to animate specific properties of 3D objects using keyframes.
Animates TPoint3D properties like Position, Scale, or Rotation.
var
Anim: TPoint3DKeyAnimation;
Key0, Key1, Key2: TPoint3DKey;
begin
Anim := TPoint3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Position.Point';
Anim.Duration := 2.0;
Anim.Loop := True;
// Add element to animate
Anim.AddElement(Cube1, True);
// Define keyframes
Key0 := TPoint3DKey(Anim.Keys.Add);
Key0.Time := 0.0;
Key0.Value[Cube1] := Point3D(0, 0, 0);
Key1 := TPoint3DKey(Anim.Keys.Add);
Key1.Time := 0.5;
Key1.Value[Cube1] := Point3D(0, 5, 0);
Key2 := TPoint3DKey(Anim.Keys.Add);
Key2.Time := 1.0;
Key2.Value[Cube1] := Point3D(0, 0, 0);
Anim.Start();
end;
// Single animation controlling multiple objects
Anim.AddElement(Cube1, True);
Anim.AddElement(Cube2, True);
Anim.AddElement(Sphere1, True);
// Set different values per object in each key
Key0 := TPoint3DKey(Anim.Keys.Add);
Key0.Time := 0.0;
Key0.Value[Cube1] := Point3D(0, 0, 0);
Key0.Value[Cube2] := Point3D(5, 0, 0);
Key0.Value[Sphere1] := Point3D(-5, 0, 0);
// Interpolation type
Anim.Interpolation := TInterpolationType.Linear;
// Options: Linear, Quadratic, Cubic, Quartic, Quintic,
// Sinusoidal, Exponential, Circular, Elastic, Back, Bounce
// Animation type (easing)
Anim.AnimationType := TAnimationType.InOut;
// Options: In, Out, InOut
// Looping and reversing
Anim.Loop := True; // Repeat animation
Anim.AutoReverse := True; // Reverse playback at end
Anim.Inverse := False; // Start from end to beginning
// Timing
Anim.Delay := 0.5; // Delay before starting (seconds)
Anim.Duration := 2.0; // Total animation duration
Animates TVector3D properties. Usage is identical to TPoint3DKeyAnimation:
var
Anim: TVector3DKeyAnimation;
Key: TVector3DKey;
begin
Anim := TVector3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Scale';
Anim.Duration := 1.0;
Key := TVector3DKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[Cube1] := Vector3D(1, 1, 1);
Key := TVector3DKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[Cube1] := Vector3D(2, 2, 2);
Anim.Start();
end;
Animates rotations using quaternions for smooth interpolation without gimbal lock:
var
Anim: TQuaternion3DKeyAnimation;
Key: TQuaternion3DKey;
Quat: TQuaternion3D;
begin
Anim := TQuaternion3DKeyAnimation.Create(Self);
Anim.PropertyName := 'RotationAngle';
Anim.Duration := 3.0;
Anim.Loop := True;
// Create quaternions from Euler angles
Quat := TQuaternion3D.Create(Vector3D(0, 0, 0));
Key := TQuaternion3DKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[Cube1] := Quat;
Quat := TQuaternion3D.Create(Vector3D(0, 180, 0));
Key := TQuaternion3DKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[Cube1] := Quat;
Anim.Start();
end;
Animates full transformation matrices, primarily used for skeletal animation:
var
Anim: TTransformationKeyAnimation;
Key: TTransformationKey;
Matrix: TMatrix3D;
begin
Anim := TTransformationKeyAnimation.Create(Self);
Anim.PropertyName := 'LocalMatrix';
Anim.AddElement(Joint1, True);
Key := TTransformationKey(Anim.Keys.Add);
Key.Time := 0.0;
Matrix := TMatrix3D.CreateTranslation(Point3D(0, 0, 0));
Key.Value[Joint1] := Matrix;
Key := TTransformationKey(Anim.Keys.Add);
Key.Time := 1.0;
Matrix := TMatrix3D.CreateTranslation(Point3D(0, 5, 0)) *
TMatrix3D.CreateRotationY(DegToRad(45));
Key.Value[Joint1] := Matrix;
Anim.Start();
end;
Skeletal (or armature) animation uses bones/joints to deform a mesh. This is the standard approach for character animation.
TSkeletonKeyAnimation is a container that synchronizes multiple TPropertyKeyAnimation instances:
var
SkeletonAnim: TSkeletonKeyAnimation;
Joint1Anim, Joint2Anim: TTransformationKeyAnimation;
begin
SkeletonAnim := TSkeletonKeyAnimation.Create(Self);
SkeletonAnim.Duration := 2.0;
SkeletonAnim.Loop := True;
SkeletonAnim.AutoRepaint := True; // Auto-update viewport
// Create joint animations
Joint1Anim := TTransformationKeyAnimation.Create(Self);
Joint1Anim.PropertyName := 'LocalMatrix';
Joint1Anim.AddElement(ArmJoint, True);
// ... add keys for Joint1Anim
Joint2Anim := TTransformationKeyAnimation.Create(Self);
Joint2Anim.PropertyName := 'LocalMatrix';
Joint2Anim.AddElement(LegJoint, True);
// ... add keys for Joint2Anim
// Add to skeleton container
SkeletonAnim.AddInterpolator(Joint1Anim);
SkeletonAnim.AddInterpolator(Joint2Anim);
// Start synchronized animation
SkeletonAnim.Start();
end;
// Start all joint animations together
SkeletonAnim.Start();
// Stop all
SkeletonAnim.Stop();
// Reset to first frame
SkeletonAnim.Reset();
// Adjust speed for all joints
SkeletonAnim.SetSpeed(0.5); // Half speed
// Access individual interpolators
for var Interpolator in SkeletonAnim.Interpolators do
begin
ShowMessage(Interpolator.PropertyName);
end;
The AutoRepaint property controls viewport updates:
// Automatic viewport repaint (default)
SkeletonAnim.AutoRepaint := True;
// Manual control for better performance
SkeletonAnim.AutoRepaint := False;
GorillaViewport1.BeginUpdate();
try
SkeletonAnim.Start();
// ... perform other operations
finally
GorillaViewport1.EndUpdate();
end;
Vertex (or mesh) animation directly modifies mesh vertices over time, useful for organic deformations and morph targets.
var
Anim: TCoordinateKeyAnimation;
Key: TCoordinateKey;
Vertices: TPoint3DDynArray;
begin
Anim := TCoordinateKeyAnimation.Create(Self);
Anim.PropertyName := 'Data.Vertices';
Anim.Duration := 2.0;
Anim.Loop := True;
Anim.AddElement(CustomMesh1, True);
// Key 0: Original vertices
Key := TCoordinateKey(Anim.Keys.Add);
Key.Time := 0.0;
SetLength(Vertices, 8);
Vertices[0] := Point3D(-1, -1, -1);
Vertices[1] := Point3D( 1, -1, -1);
// ... set all vertices
Key.Vertices[CustomMesh1] := Vertices;
// Key 1: Deformed vertices
Key := TCoordinateKey(Anim.Keys.Add);
Key.Time := 1.0;
Vertices[0] := Point3D(-1.5, -1, -1);
Vertices[1] := Point3D( 1.5, -1, -1);
// ... set deformed vertices
Key.Vertices[CustomMesh1] := Vertices;
Anim.Start();
end;
Animations are typically imported from 3D model files (G3D, DAE or FBX) using animation definitions.
It is not a recommended process, but good for understanding the structures behind.
var
Loader: TGorillaLoader;
ModelDef: TModelDef;
AnimDef: TAnimationDef;
Animation: TGorillaAnimation;
begin
Loader := TGorillaLoader.Create();
try
// Load model with animations
ModelDef := Loader.LoadUndefinedModelDefFromFile(nil, 'character.fbx');
// You need to setup FMX models and meshes, otherwise LoadFromAnimationDef
// may find references objects not.
// Iterate through embedded animations
for AnimDef in ModelDef.Animations do
begin
Animation := TGorillaAnimation.CreateEx(AnimationManager1);
Animation.LoadFromAnimationDef(AnimDef);
// Add to manager
AnimationManager1.AddAnimation(AnimDef.Id, Animation);
end;
finally
Loader.Free();
end;
end;
Transform animations for mirroring or custom modifications:
var
MirrorMatrix: TMatrix3D;
begin
// Create mirror matrix (flip on X axis)
MirrorMatrix := TMatrix3D.CreateScaling(Point3D(-1, 1, 1));
// Transform all keys in animation
Animation.Skeleton.Transform(MirrorMatrix);
end;
For performance optimization, Gorilla3D can cache animated frames:
// Enable caching during import
Animation.LoadFromAnimationDef(AnimDef);
// Get cached frame for rendering
var
MeshBuffer: TMeshBufferObject;
begin
MeshBuffer := Animation.GetCurrentCachedFrame(MeshDef);
if Assigned(MeshBuffer) then
begin
// Render cached frame
end;
end;
// Set specific frame for debugging
Animation.SetFixedCacheFrame(15); // Show frame 15
// Release fixed frame
Animation.UnsetFixedCacheFrame();
// Get animation frame info
ShowMessage(Format('Frames: %d, FPS: %d', [
Animation.FrameCount,
Animation.FrameRate
]));
Cached frames can be baked again or dropped at runtime, for all animations or by id:
// re-bake all animations with the default flags
GorillaModel1.RecacheAnimations(GORILLA_ANIMATION_CACHING_DEFAULT);
// re-bake only selected animations, drop the cache of others
GorillaModel1.RecacheAnimationsByName(['walk', 'run']);
GorillaModel1.DiscardAnimationCacheByName(['idle']);
Animations without cached frames are skinned on the CPU. See Re-Baking or Dropping the Cache for the details.
Note:
TAnimationCachingFlag.Compressedis not supported on Vulkan. A one-time warning is logged and the bind pose is shown.
Cached frames hold baked vertex positions, so anything that changes the pose of a clip
invalidates them. Removing the root motion does exactly that: InPlace drops the frames
and leaves them dropped, and a skinned mesh whose frames are gone is drawn from its static
buffer - the bind pose - while the animation still reports IsRunning = True.
// clip was loaded with caching flags
Animation.SetInPlace(True, True); // take the travel out AND bake the clip again
Assigning Animation.InPlace := True keeps the old behaviour and does not rebuild. An
uncached clip is skinned live and needs neither. See
Root Motion and In-Place Playback.
Force animation updates outside the normal FMX message loop for smoother playback:
// In your main rendering loop or timer
if TGorillaAnimationManager.ForceStep(0.01) then
GorillaViewport1.EndUpdate()
else
GorillaViewport1.EndUpdateWithoutInvalidate();
Parameters:
AMinDeltaTime: Minimum time (seconds) since last forced update (default: 0.01)Returns: True if step was forced and viewport needs updating
Delphi 13+: FMX has no animation thread left to step, so
ForceSteponly reports whetherAMinDeltaTimehas passed - it does not advance anything. Skeleton animations are driven byTGorillaRenderClockinstead, whichTGorillaViewportticks at the start of every rendered frame. Poses and image stay in step without any call on your side; existing code that uses the result as a rate gate keeps working.
React to animation progress:
procedure TForm1.AnimationProcess(Sender: TObject);
begin
// Called on each animation frame
ProgressBar1.Value := Animation.Skeleton.NormalizedTime * 100;
end;
procedure TForm1.AnimationFinish(Sender: TObject);
begin
// Called when animation completes
ShowMessage('Animation finished');
end;
// Assign events
Animation.Skeleton.OnProcess := AnimationProcess;
Animation.Skeleton.OnFinish := AnimationFinish;
For simple property animations without keyframes, use TPoint3DAnimation:
var
Anim: TPoint3DAnimation;
begin
Anim := TPoint3DAnimation.Create(Self);
Anim.Parent := Cube1;
Anim.PropertyName := 'Position.Point';
Anim.StartValue.Point := Point3D(0, 0, 0);
Anim.StopValue.Point := Point3D(10, 0, 0);
Anim.Duration := 2.0;
Anim.StartFromCurrent := True;
Anim.Start();
end;
Use Skeleton Animation for Characters: Group related joint animations in TSkeletonKeyAnimation for synchronized playback
Cache Complex Animations: Enable frame caching for CPU-intensive vertex animations
Control AutoRepaint: Disable AutoRepaint and manually control viewport updates for better performance
Use Quaternions for Rotation: TQuaternion3DKeyAnimation provides smoother rotation than Euler angles
Optimize Keyframe Count: Use only necessary keyframes; interpolation handles in-between frames
Force Stepping for Smoothness: Up to Delphi 12, use ForceStep() in rendering loops to avoid FMX timer jitter (Delphi 13+ does this through TGorillaRenderClock)
Check Animation State: Always verify IsRunning before operations that depend on active animation
Proper Cleanup: Always stop animations before destroying animated objects
Use Animation Manager: Centralize animation control through TGorillaAnimationManager and switch clips with PlayAnimation to get crossfades
Use Sorted Lists: Use GetAnimationNames() / GetSortedAnimations() instead of enumerating the Animations hashmap whenever order matters
Test Playback Speed: Adjust animation speed based on target platform performance
procedure CreateRotationAnimation(AObject: TControl3D);
var
Anim: TPoint3DKeyAnimation;
Key: TPoint3DKey;
begin
Anim := TPoint3DKeyAnimation.Create(AObject);
Anim.PropertyName := 'RotationAngle.Point';
Anim.Duration := 4.0;
Anim.Loop := True;
Anim.Interpolation := TInterpolationType.Linear;
Key := TPoint3DKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[AObject] := Point3D(0, 0, 0);
Key := TPoint3DKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[AObject] := Point3D(0, 360, 0);
Anim.Start();
end;
Anim := TPoint3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Position.Point';
Anim.Interpolation := TInterpolationType.Bounce;
Anim.AnimationType := TAnimationType.Out;
Anim.Duration := 1.0;
// ... add keys
Anim.Start();
Anim := TPoint3DKeyAnimation.Create(Self);
Anim.Loop := True;
Anim.AutoReverse := True; // Plays forward then backward
// ... configure and start
// Check animation is enabled
if not Animation.Skeleton.Enabled then
Animation.Skeleton.Enabled := True;
// Verify parent is set
if not Assigned(Animation.Parent) then
Animation.Parent := SomeContainer;
// Check duration is set
if Animation.Skeleton.Duration = 0 then
Animation.Skeleton.Duration := 2.0;
// Up to Delphi 12: use ForceStep for smoother updates
// (Delphi 13+ steps animations per rendered frame automatically)
TGorillaAnimationManager.ForceStep(0.01);
// Or adjust interpolation
Animation.Skeleton.Interpolation := TInterpolationType.Cubic;
// SetSpeed scales the interpolator DURATIONS (relative, cumulative)
Animation.SetSpeed(2.0); // twice as long -> half speed
Animation.SetSpeed(0.5); // half as long -> double speed
For an absolute, repeatable rate see An Absolute Playback Rate.
// Do not enumerate the hashmap - its order is arbitrary
for var LName in Manager.GetAnimationNames() do
ListBox1.Items.Add(LName);
// Enable caching to reduce real-time computation
// Ensure proper cleanup of cached frames
Gorilla3D provides multiple approaches for creating custom 3D geometry at runtime, from simple polygon-based construction to advanced vertex cache techniques. But besides adding vertex data, further steps are needed like arranging meshes in hierarchy, materials and animations.
At first we have to add mesh geometry / vertex data to finally render anything. There are three main approaches to creating custom meshes:
| Approach | Complexity | Use Case |
|---|---|---|
| Simple Polygon Method | Low | Basic shapes, quick prototyping |
| Direct TMeshData Manipulation | Medium | The old-school method by the TMeshData type of Firemonkey. Effective but not flexible. |
| TVertexCache | Medium-High | Complex geometry, custom normals/UVs, skeletal animation |
The straightforward approach involves creating a custom mesh class and defining geometry using polygon vertices.
uses
Gorilla.Mesh, Gorilla.DefTypes;
TUserMesh = class(TGorillaSingletonMesh)
public
constructor Create(AOwner : TComponent); override;
procedure Build();
end;
[...]
constructor TUserMesh.Create(AOwner: TComponent);
begin
inherited;
FDef := TMeshDef.Create(nil);
end;
procedure TUserMesh.Build();
begin
with TMeshDef(FDef) do
begin
AddPolygon([PointF(-0.5, -0.5), PointF(0.5, -0.5), PointF(0.5, 0.5), PointF(-0.5, 0.5)]);
AddPolygon([PointF(-0.5, -1.5), PointF(0.5, -1.5), PointF(0.5, -0.75), PointF(-0.5, -0.75)]);
AddPolygon([PointF(-1.5, -1.5), PointF(-0.75, -1.5), PointF(-0.75, -0.75), PointF(-1.5, -0.75)]);
// after all polygon vertices were added
// compute tex-coords, normals, tangents and binormals
CalcTextureCoordinates(TTextureMappingMethod.tmTriplanar);
CalcFaceNormals();
CalcTangentBinormals();
// after vertex data was finally setup - set mesh to static and push data
// to GPU
IsStatic := true;
end;
end;
[...]
// Create a visual instance at runtime
FUserMesh := TUserMesh.Create(GorillaViewport1);
FUserMesh.Parent := GorillaViewport1;
FUserMesh.Position.Point := Point3D(3, -1, 3);
FUserMesh.RotationAngle.X := -45;
// Build the vertex data
FUserMesh.Build();
// Apply an existing material
FUserMesh.MaterialSource := GorillaLambertMaterialSource1;
procedure TMyCustomMesh.BuildCubeMesh();
var
LDef: TMeshDef;
Vertices: TPoint3DDynArray;
begin
Self.Clear();
LDef := TMeshDef(FDef);
// Front face
SetLength(Vertices, 4);
Vertices[0] := Point3D(-1, 1, 1);
Vertices[1] := Point3D(1, 1, 1);
Vertices[2] := Point3D(1, -1, 1);
Vertices[3] := Point3D(-1, -1, 1);
LDef.AddPolygon(Vertices);
// Back face
Vertices[0] := Point3D(1, 1, -1);
Vertices[1] := Point3D(-1, 1, -1);
Vertices[2] := Point3D(-1, -1, -1);
Vertices[3] := Point3D(1, -1, -1);
LDef.AddPolygon(Vertices);
// Top face
Vertices[0] := Point3D(-1, 1, -1);
Vertices[1] := Point3D(1, 1, -1);
Vertices[2] := Point3D(1, 1, 1);
Vertices[3] := Point3D(-1, 1, 1);
LDef.AddPolygon(Vertices);
// Bottom face
Vertices[0] := Point3D(-1, -1, 1);
Vertices[1] := Point3D(1, -1, 1);
Vertices[2] := Point3D(1, -1, -1);
Vertices[3] := Point3D(-1, -1, -1);
LDef.AddPolygon(Vertices);
// Right face
Vertices[0] := Point3D(1, 1, 1);
Vertices[1] := Point3D(1, 1, -1);
Vertices[2] := Point3D(1, -1, -1);
Vertices[3] := Point3D(1, -1, 1);
LDef.AddPolygon(Vertices);
// Left face
Vertices[0] := Point3D(-1, 1, -1);
Vertices[1] := Point3D(-1, 1, 1);
Vertices[2] := Point3D(-1, -1, 1);
Vertices[3] := Point3D(-1, -1, -1);
LDef.AddPolygon(Vertices);
// Generate all necessary vertex attributes
LDef.CalcTextureCoordinates();
LDef.CalcFaceNormals();
LDef.CalcTangentBinormals();
LDef.IsStatic := True;
end;
After defining geometry with AddPolygon(), use these helper methods:
Automatically generates UV mapping based on vertex positions:
LDef.CalcTextureCoordinates(<TTextureMappingMethod>);
The TTextureMappingMethod type offers different computation algorithms.
| Algorithm | Description |
|---|---|
| TTextureMappingMethod.tmSpherical | |
| TTextureMappingMethod.tmCylindrical | |
| TTextureMappingMethod.tmCubic | |
| TTextureMappingMethod.tmTriplanar |
Computes surface normals for lighting:
LDef.CalcFaceNormals();
Calculates tangent and binormal vectors required for normal mapping:
LDef.CalcTangentBinormals();
Transfer mesh data to GPU memory for rendering:
LDef.IsStatic := True;
Important: Set
IsStatic := Trueonly after all geometry is finalized. Once static, vertex data cannot be modified.
The vertex data stays available in the mesh definition, so ShowBoundingBox and GetAnimatedBoundingBox() work for static meshes as well.
Firemonkey already offers to generate mesh geometry manually. This is done by TMeshData type.
This class holds a single vertex and index buffer to setting up vertex data.
uses
Gorilla.Mesh, Gorilla.DefTypes, Gorilla.Material.VertexColor;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Create a visual Firemonkey instance
var LMesh := TGorillaSingletonMesh.Create(GorillaViewport1);
LMesh.Parent := GorillaViewport1;
// Request the embedded mesh data instance
var LData := LMesh.MeshData;
if not Assigned(LData) then
raise Exception.Create('custom mesh does not provide TMeshData instance');
// Start generating geometry
try
// Initialize the vertex buffer
LData.VertexBuffer.Length := 4;
LData.VertexBuffer.Vertices[0] := Point3D(-0.5, -0.5, 0.0);
LData.VertexBuffer.Normals[0] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[0] := TAlphaColors.Red;
LData.VertexBuffer.Vertices[1] := Point3D(+0.5, -0.5, 0.0);
LData.VertexBuffer.Normals[1] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[1] := TAlphaColors.Green;
LData.VertexBuffer.Vertices[2] := Point3D(+0.5, +0.5, 0.0);
LData.VertexBuffer.Normals[2] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[2] := TAlphaColors.Blue;
LData.VertexBuffer.Vertices[3] := Point3D(-0.5, +0.5, 0.0);
LData.VertexBuffer.Normals[3] := Point3D(0, 0, -1);
LData.VertexBuffer.Color0[3] := TAlphaColors.Yellow;
// Initialize the index buffer to generate triangles
LData.IndexBuffer.Length := 6;
// 2 triangles to form a quad
// Counter-Clock-Wise Vertex Order (CCW)
LData.IndexBuffer.Indices[0] := 1;
LData.IndexBuffer.Indices[1] := 2;
LData.IndexBuffer.Indices[2] := 3;
LData.IndexBuffer.Indices[3] := 0;
LData.IndexBuffer.Indices[4] := 1;
LData.IndexBuffer.Indices[5] := 3;
// Apply this mesh data to a mesh definition in the background
// to enable static buffering
var LMeshDef := TMeshDef.Create(nil);
// Link it to the Firemonkey instance
LMesh.Def := LMeshDef;
// Push data to the definition and onto the GPU
LMeshDef.ApplyFromMeshData(LData);
LMeshDef.IsStatic := true;
// We have a static buffer, so we do not need that data anymore
LData.Clear;
// Create a vertex color material to see our mesh
var LMaterial := TGorillaVertexColorMaterialSource.Create(LMesh);
LMaterial.Parent := LMesh;
LMesh.MaterialSource := LMaterial;
except
// ... do anything ...
end;
end;
For complex meshes requiring custom normals, multiple texture coordinates, vertex colors, or skeletal animation, use TVertexCache.
TVertexCache maintains separate buffers for different vertex attributes:
| Buffer | Type | Purpose |
|---|---|---|
| PositionSource | TList<TPoint3D> | Vertex coordinates |
| NormalSource | TList<TPoint3D> | Surface normals |
| TangentSource | TList<TPoint3D> | Tangent vectors |
| BinormalSource | TList<TPoint3D> | Binormal vectors |
| TextureSource[0..31] | TList<TPointF> | UV coordinates (32 channels) |
| ColorSource[0..3] | TList<TAlphaColor> | Vertex colors (4 channels) |
| Vertices | TList<TVertexData> | Combined vertex structures |
| Indices | TList<UInt32> | Triangle indices |
uses
System.Generics.Collections, System.Generics.Defaults,
Gorilla.DefTypes, Gorilla.Loader;
type
TUserModelBuilder = class
protected
class function DoBuildMesh(AOwner : TMeshDef) : TMeshDef;
public
class function Build() : TModelDef;
class function AddMaterial(AModel : TModelDef; AMesh : TMeshDef;
AId : String; AFileName : String) : TMaterialDef;
class function AddArmatureAndController(AModel : TModelDef;
AMesh : TMeshDef) : TArmatureDef;
class function AddSkinAnimation(AModel : TModelDef;
AArmature : TArmatureDef; AId : String) : TAnimationDef;
end;
[...]
class function TUserModelBuilder.Build() : TModelDef;
var LMesh : TMeshDef;
LArma : TArmatureDef;
begin
// Create the model container
Result := TModelDef.Create(nil, nil);
Result.Id := 'CustomModel1';
// Create and add all meshes to it
LMesh := DoBuildMesh(Result);
// We generate texture coordinates, tangents and binormals automatically
LMesh.CalcTextureCoordinates();
LMesh.CalcTangentBinormals();
// Add a material with texture
AddMaterial(Result, LMesh, 'CustomMaterial1', 'brick-c.jpg');
// Add an armature and skin controller
LArma := AddArmatureAndController(Result, LMesh);
// Add skin animation
AddSkinAnimation(Result, LArma, 'Animation1');
end;
class function TUserModelBuilder.DoBuildMesh(AOwner : TMeshDef) : TMeshDef;
function GetVertexID(const APos, ANormal, ATangent, AColor : Integer) : TVertexID;
begin
FillChar(Result, SizeOf(Result), 0);
Result.Position := APos;
Result.Normal := ANormal;
Result.Tangent := ATangent;
Result.Colors.Count := 1;
Result.Colors.Indices[0] := AColor;
end;
var LCache : TVertexCache;
LVertIdxOfs: Integer;
// In our example we have 3 polygons/quads
LPolys : Array[0..2] of TPolygonID;
I : Integer;
begin
// Create the mesh object and add it to the supplied owner
Result := TMeshDef.Create(AOwner);
Result.Id := 'CustomMesh1';
Result.FaceOrientation := TFaceOrientation.TwoFace;
AOwner.AddMesh(Result);
// Setup a vertex cache
LCache := TVertexCache.Create();
try
LCache.UseBuffersAsArray := true;
// Start pushing vertex data into
LCache.SetPositionSource([
// quad #1 (vertex#0, vertex#1, vertex#2, vertex#3)
-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0,
// quad #2 (vertex#4, vertex#5, vertex#6, vertex#7)
-0.5, -1.5, 0, 0.5, -1.5, 0, 0.5, -0.75, 0, -0.5, -0.75, 0,
// quad #3 (vertex#8, vertex#9, vertex#10, vertex#11)
-1.5, -1.5, 0, -0.75, -1.5, 0, -0.75, -0.75, 0, -1.5, -0.75, 0
]);
// All vertices should have the same normal and tangent vector
LCache.SetNormalSource([0, 0, -1]);
LCache.SetNormalSource([1, 0, 0]);
// Each triangle should have its own color
LCache.SetColorSource(0, [1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1]);
// You can work with offsets on the cache - very useful for meshes using the same vertex data
LVertIdxOfs := 0;
// Prepare vertex data indices (from buffers) to add quads
// At first let's clear the triangle vertex data index structures
System.SetLength(LPolys[0], 4);
System.SetLength(LPolys[1], 4);
System.SetLength(LPolys[2], 4);
// Polygon/Quad #1 - Vertex #0, #1, #2, #3 (with its own color)
LPolys[0][0] := GetVertexID(0, 0, 0, 0);
LPolys[0][1] := GetVertexID(1, 0, 0, 0);
LPolys[0][2] := GetVertexID(2, 0, 0, 0);
LPolys[0][3] := GetVertexID(3, 0, 0, 0);
// Polygon/Quad #2 - Vertex #4, #5, #6, #7 (with its own color)
LPolys[1][0] := GetVertexID(4, 0, 0, 1);
LPolys[1][1] := GetVertexID(5, 0, 0, 1);
LPolys[1][2] := GetVertexID(6, 0, 0, 1);
LPolys[1][3] := GetVertexID(7, 0, 0, 1);
// Polygon/Quad #3 - Vertex #8, #9, #10, #11 (with its own color)
LPolys[2][0] := GetVertexID(8, 0, 0, 2);
LPolys[2][1] := GetVertexID(9, 0, 0, 2);
LPolys[2][2] := GetVertexID(10, 0, 0, 2);
LPolys[2][3] := GetVertexID(11, 0, 0, 2);
// Add the polygons one by one - with automatic triangulation
for I := Low(LPolys) to High(LPolys) do
LVertIdxOfs := LCache.AddPolygon(LVertIdxOfs, LPolys[I], LCache.Vertices, LCache.Indices);
// Load the TMeshDef (Result) from the cache
TGorillaLoader.LoadDefFromData(Result, LCache);
// When vertex data is added from cache, the vertex index map may be also produced automatically
// We should add it to the mesh for correct vertex mapping during animations
Result.AddVertexIndexMap(LCache.IndexMap);
finally
FreeAndNil(LCache);
end;
end;
Add single vertices or attributes:
| Method | Argument | Description |
|---|---|---|
| AddPositionSource | TSingleDynArray | Add a single vertex position by an array of 3 floating point values representing x, y and z |
| AddPositionSource | TPoint3D | Add a single 3D vertex position |
| AddNormalSource | TSingleDynArray | Add a single normal vector by an array of 3 floating point values representing x, y and z |
| AddNormalSource | TPoint3D | Add a single 3D normal vector |
| AddBinormalSource | TSingleDynArray | Add a single binormal vector by an array of 3 floating point values representing x, y and z |
| AddBinormalSource | TPoint3D | Add a single 3D binormal vector |
| AddTangentSource | TSingleDynArray | Add a single tangent vector by an array of 3 floating point values representing x, y and z |
| AddTangentSource | TArray |
Add multiple tangent vectors by an array of tangent vectors |
| AddTangentSource | TPoint3D | Add a single 3D tangent vector |
| AddTextureSource | AIndex, TSingleDynArray, AConvertToUV | Add a single texture coordinate by an array of 2 floating point values representing x, y. AConvertToUV will convert between st and uv coordinates. |
| AddTextureSource | AIndex, TPointF, AConvertToUV | Add a single 2D texture coordinate. AConvertToUV will convert between st and uv coordinates. |
| AddColorSource | AIndex, TSingleDynArray | Add single vertex color by an array of 4 floating point values representing r,g,b,a |
| AddColorSource | AIndex, TAlphaColorF | Add a single color value |
// Add positions one by one
var PosIdx0 := Cache.AddPositionSource(Point3D(0, 0, 0));
var PosIdx1 := Cache.AddPositionSource(Point3D(1, 0, 0));
var PosIdx2 := Cache.AddPositionSource(Point3D(0, 1, 0));
// Add normals
var NormIdx0 := Cache.AddNormalSource(Point3D(0, 0, 1));
var NormIdx1 := Cache.AddNormalSource(Point3D(0, 0, 1));
// Add texture coordinates (channel 0)
var TexIdx0 := Cache.AddTextureSource(0, PointF(0, 0));
var TexIdx1 := Cache.AddTextureSource(0, PointF(1, 0));
var TexIdx2 := Cache.AddTextureSource(0, PointF(0, 1));
// Add vertex colors (channel 0)
var ColorIdx0 := Cache.AddColorSource(0, TAlphaColors.Red);
var ColorIdx1 := Cache.AddColorSource(0, TAlphaColors.Green);
var ColorIdx2 := Cache.AddColorSource(0, TAlphaColors.Blue);
Warning: Pushing multiple vertex data will always clear the specific buffer and will not append the data.
| Method | Argument | Description |
|---|---|---|
| SetPositionSource | TSingleDynArray | Adds an array of multiple vertex positions flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetNormalSource | TSingleDynArray | Adds an array of multiple normal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetNormalSource | TSingleDynArray, ATransform | Adds an array of multiple normal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] and transforms the normal vectors by the supplied transformation matrix. |
| SetBiNormalSource | TSingleDynArray | Adds an array of multiple binormal vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetTangentSource | TSingleDynArray | Adds an array of multiple tangent vectors flattened into a straight array of floating point values, like [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, …] |
| SetTextureSource | AIndex, TSingleDynArray, AConvertToUV | Adds an array of multiple texture coordinates flattened into a straight array of floating point values, like [X1,Y1, X2,Y2, X3,Y3, …] at a certain position (starting with zero). AConvertToUV allows to convert those values between st and uv format. |
| SetColorSource | AIndex, TSingleDynArray | Adds an array of multiple color values flattened into a straight array of floating point values, like [R1,G1,B1,A1, R2,G2,B2,A2, R3,G3,B3,A3, …] at a certain position (starting with zero) |
Replace entire buffers with flattened arrays:
var
Positions: TSingleDynArray;
begin
// Flattened format: [X1,Y1,Z1, X2,Y2,Z2, X3,Y3,Z3, ...]
SetLength(Positions, 9); // 3 vertices * 3 components
// Vertex 0
Positions[0] := 0.0;
Positions[1] := 1.0;
Positions[2] := 0.0;
// Vertex 1
Positions[3] := -1.0;
Positions[4] := -1.0;
Positions[5] := 0.0;
// Vertex 2
Positions[6] := 1.0;
Positions[7] := -1.0;
Positions[8] := 0.0;
Cache.SetPositionSource(Positions);
end;
Similarly for normals:
var
Normals: TSingleDynArray;
begin
SetLength(Normals, 9); // 3 normals * 3 components
// All pointing forward
Normals[0] := 0.0; Normals[1] := 0.0; Normals[2] := 1.0;
Normals[3] := 0.0; Normals[4] := 0.0; Normals[5] := 1.0;
Normals[6] := 0.0; Normals[7] := 0.0; Normals[8] := 1.0;
Cache.SetNormalSource(Normals);
end;
Gorilla3D supports up to 32 texture coordinate channels:
// Primary UV set (channel 0)
Cache.AddTextureSource(0, PointF(0, 0));
Cache.AddTextureSource(0, PointF(1, 0));
// Lightmap UV set (channel 1)
Cache.AddTextureSource(1, PointF(0, 0));
Cache.AddTextureSource(1, PointF(0.5, 0.5));
// Use in vertex definition
Triangle[0].TexCoord0 := 0; // Channel 0 index
Triangle[0].TexCoord1 := 0; // Channel 1 index
Support for up to 4 color channels:
// Add vertex colors
Cache.AddColorSource(0, TAlphaColors.Red);
Cache.AddColorSource(0, TAlphaColors.Green);
Cache.AddColorSource(0, TAlphaColors.Blue);
// Use in vertex definition
Triangle[0].Color0 := 0; // Red
Triangle[1].Color0 := 1; // Green
Triangle[2].Color0 := 2; // Blue
Once we have filled the cache buffer with our vertex data for positions, normals and so on. We need to tell it, which kind of primitive it uses. Vertices could form triangles or polygons.
We could set up our index buffers manually, but often it is more useful to call AddTriangle or AddPolygon to fill indices.
| Method | Description |
|---|---|
| function AddTriangle(const AIndexOffset : Integer; const ATriangle : TTriangleID; const AVertices : TList |
Adds triangle vertices and indices to AVertices and AIndices based on the index values inside of TTriangleID VertexData values are taken from Cache.PositionSource and so on… |
| function AddPolygon(const AIndexOffset : Integer; const APolygon : TPolygonID; const AVertices : TList |
Adds polygon vertices and indices to AVertices and AIndices based on the index values inside of TPolygonID VertexData values are taken from Cache.PositionSource and so on… CAUTION: this method triangulates the polygon automatically |
All mesh definitions inherit from TTransformDef, enabling parent-child relationships.
Each TTransformDef object has an “Owner” and “Children” property to setup a hierarchy.
Add or remove objects to / from a parent object by the methods:
function AddChild(ATransform : TTransformDef) : Integer;
procedure RemoveChild(ATransform : TTransformDef);
procedure ClearChildren();
procedure AddMesh(const AMesh : TMeshDef);
In the following example we setup a model with sub-meshes and a deep hierarchy. You can search on that structure by FindChildById or you can Traverse to do certain things on each of the child instances.
var
ModelDef: TModelDef;
ParentMesh, ChildMesh: TMeshDef;
begin
ModelDef := TModelDef.Create(nil);
ParentMesh := TMeshDef.Create(ModelDef);
ParentMesh.Id := 'Parent';
ModelDef.AddChild(ParentMesh);
ChildMesh := TMeshDef.Create(ModelDef);
ChildMesh.Id := 'Child';
ParentMesh.AddChild(ChildMesh);
// Find child by ID
var Found := ParentMesh.FindChildById('Child', True);
// Traverse hierarchy
ModelDef.Traverse(
true,
function(AOwner : TTransformDef; const AIndex : Integer; ATransf : TTransformDef) : Boolean
begin
// do something
Result := true;
end
);
end;
VertexGroups, represented by an TVertexGroupDef instance are helper structures referring to an owner mesh, which holds original vertex data and complete indices list, while this structure only holds a separated index source for partially rendering a mesh.
They are used for example in the FBX format for rendering some triangles with a different material than others.
var
MeshDef: TMeshDef;
Group1, Group2: TVertexGroupDef;
begin
MeshDef := TMeshDef.Create(ModelDef);
// Create vertex groups
Group1 := TVertexGroupDef.Create(MeshDef);
Group1.Id := 'Group1';
MeshDef.AddMesh(Group1);
Group1.IndexSource.AppendIndices([0,1,2]);
// Link a material to render this group differently
Group1.SetMaterialReference(MaterialA);
Group2 := TVertexGroupDef.Create(MeshDef);
Group2.Id := 'Group2';
MeshDef.AddMesh(Group2);
Group2.IndexSource.AppendIndices([0,1,2]);
// Link a material to render this group differently
Group2.SetMaterialReference(MaterialB);
Warning: Vertex groups are currently incompatible with skeletal/vertex animations.
To expand the dynamic model setup, let's add a material to our sub-mesh.
uses
Gorilla.AssetsManager;
class function TUserModelBuilder.AddMaterial(AModel : TModelDef; AMesh : TMeshDef; AId : String; AFileName : String) : TMaterialDef;
var LTexDef : TTextureDef;
LAsset : TGorillaTextureAsset;
begin
// Materials are attached to the model to reuse them in multiple meshes
Result := TMaterialDef.Create(AModel, AId);
Result.Kind := TMaterialDefKind.mkLambert;
// Create a texture for the material
// 1) Create a standalone asset (possible to request one from an assets package too)
LAsset := TGorillaTextureAsset.Create(nil);
LAsset.ImportFromFile(AFileName);
// 2) Add a diffuse texture in the material
LTexDef := Result.AddTexture(TColorChannelDef.Diffuse, LAsset, true);
// Finally we need to link it to our mesh
AMesh.SetMaterialReference(Result);
end;
Adding animations can become a very challenging part due to complexity.
Not only an animation definition needs to be defined, but also stages, interpolators + armatures and joints for skeleton/skin animations need to be added and configured.
class function TUserModelBuilder.AddAnimation(AModel : TModelDef; AMesh : TMeshDef; AId : String) : TAnimationDef;
var LStage : TAnimationStageDef;
LInterp : TPoint3DInterpolatorDef;
begin
// Let's start with the animation main object
Result := TAnimationDef.Create(AModel);
Result.Id := 'CustomAnimation1';
AModel.AddAnimation(Result);
// Each animation should contain at least one stage definition
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'CustomMesh1Stage';
LStage.Reference := AMesh;
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'CustomMesh1PositionInterpolator';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'Position.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, -0.75, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, -1, 0), TAnimationKeyInterpolationType.Linear);
end;
You can add multiple interpolators per stage, but keep in mind it may slow down performance.
We do support different interpolator types, depending on your needs:
| Interpolator | Description |
|---|---|
| TPoint3DInterpolatorDef | Translation or Scaling interpolator by TPoint3D value to transform a stage reference property. |
| TVector3DInterpolatorDef | Rotation interpolator by TVector3D value to transform a stage reference RotationAngle property. |
| TQuaternion3DInterpolatorDef | Rotation interpolator by TQuaternion3D value to transform a stage reference RotationAngle property. |
| TTransformationInterpolatorDef | Transformation interpolator by TMatrix3D values to transform the stage reference object by position, rotation and scaling. |
| TMeshInterpolatorDef | Vertex position interpolator for direct vertex manipulation of mesh reference. |
To make skin- or skeleton-animations possible you will need an armature with a hierarchy of joints representing the internal skeleton of a body.
class function TUserModelBuilder.AddArmatureAndController(AModel : TModelDef; AMesh : TMeshDef) : TArmatureDef;
var LJt1,
LJt2 : TJointDef;
LCtrl : TControllerDef;
LJtRef : TJointRefDef;
LRes : Integer;
begin
//
// Create an armature definition and link it to the model
//
Result := TArmatureDef.Create(AModel);
Result.Id := 'Armature1';
AModel.AddArmature(Result);
// Afterwards you can add joints / bones for a hierarchy
// Starting with the root joint
Result.Root := TJointDef.Create(Result);
Result.Root.Id := 'SkeletonRoot';
// Then add the first child node with position offset
LJt1 := TJointDef.Create(Result);
LJt1.Id := 'Bone1';
LJt1.Transform := TMatrix3D.CreateTranslation(Point3D(0, -1, 0));
Result.Root.AddJoint(LJt1);
// And another child node with position offset
LJt2 := TJointDef.Create(Result);
LJt2.Id := 'Bone2';
LJt2.Transform := TMatrix3D.CreateTranslation(Point3D(-1, 0, 0));
LJt1.AddJoint(LJt2);
//
// After we have setup the armature with a bone hierarchy, we can create a skin-controller
//
LCtrl := TControllerDef.Create(AMesh);
LCtrl.Id := 'CustomMesh1Controller';
// Add the controller to the model controllers list
AModel.AddController(LCtrl);
// Link the controller also to the armature
Result.AddController(LCtrl);
// Add a skin to our controller - capable to manage deformation data depending on an armature hierarchy
LCtrl.Skin := TSkinDef.Create(LCtrl);
// Add the skeleton root reference joint (standalone reference)
LJtRef := TJointRefDef.Create(Result.Root, LCtrl, true);
LCtrl.Skin.Skeletons.Add(LJtRef);
// We have to link all relevant joint to the skin and add weights and vertex-indices
// "Weights" and "Indices" arrays has to have the same size.
// The sum of all weights (over all joints) for a specific vertex has to be 1.0!
LJtRef := LCtrl.Skin.LinkJoint(Result.Root);
LJtRef.Weights := [0.75, 0.75, 0.75, 0.75, 0.25, 0.25, 0.25, 0.25, 0, 0, 0, 0];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
LJtRef := LCtrl.Skin.LinkJoint(LJt1);
LJtRef.Weights := [0.25, 0.25, 0.25, 0.25, 0.75, 0.75, 0.75, 0.75, 0.25, 0.25, 0.25, 0.25];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
LJtRef := LCtrl.Skin.LinkJoint(LJt2);
LJtRef.Weights := [0, 0, 0, 0, 0.25, 0.25, 0.25, 0.25, 0.75, 0.75, 0.75, 0.75];
LJtRef.Indices := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
// Verify the setup
LRes := LCtrl.Skin.CheckMeshVerticesToBeAttachedCorrectly();
case LRes of
0 : ; // everything is okey
1 : raise Exception.Create('skin vertex not attached');
2 : raise Exception.Create('skin vertex not attached completely, meaning that total weight value is not equal to 1.0');
3 : raise Exception.Create('no mesh linked');
4 : raise Exception.Create('mesh vertex list is empty');
5 : raise Exception.Create('no skeleton root found');
6 : raise Exception.Create('no joints linked');
else raise Exception.Create('unexpected failure');
end;
end;
It's important that all vertices are attached correctly to a joint and the weight values are in sum 1.0.
LRes := LCtrl.Skin.CheckMeshVerticesToBeAttachedCorrectly();
case LRes of
0 : ; // everything is okey
1 : raise Exception.Create('skin vertex not attached');
2 : raise Exception.Create('skin vertex not attached completely, meaning that total weight value is not equal to 1.0');
3 : raise Exception.Create('no mesh linked');
4 : raise Exception.Create('mesh vertex list is empty');
5 : raise Exception.Create('no skeleton root found');
6 : raise Exception.Create('no joints linked');
else raise Exception.Create('unexpected failure');
end;
To animate the armature it's necessary to have compatible animation stages and interpolators.
Related to our armature and bones (joints) before, the code could look something like this:
class function TUserModelBuilder.AddSkinAnimation(AModel : TModelDef;
AArmature : TArmatureDef; AId : String) : TAnimationDef;
var LStage : TAnimationStageDef;
LInterp : TPoint3DInterpolatorDef;
begin
// Let's start with the animation main object
Result := TAnimationDef.Create(AModel);
Result.Id := 'CustomAnimation1';
AModel.AddAnimation(Result);
// ROOT JOINT
// Each animation should contain at least one stage definition
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'RootBoneStage';
LStage.Reference := AArmature.Root;
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'RootBonePosition';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'Position.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, -0.75, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, -1, 0), TAnimationKeyInterpolationType.Linear);
// JOINT1
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'Bone1Stage';
LStage.Reference := AArmature.Root.FindJointById('Bone1');
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'Bone1Rotation';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'RotationAngle.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, 90, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, 180, 0), TAnimationKeyInterpolationType.Linear);
// JOINT2
LStage := TAnimationStageDef.Create(Result);
LStage.Id := 'Bone2Stage';
LStage.Reference := AArmature.Root.FindJointById('Bone2');
Result.AddStage(LStage);
// In our example we simply want to move the mesh
// So we need to create a Point3D interpolator in the stage
LInterp := TPoint3DInterpolatorDef.Create(LStage);
LInterp.Id := 'Bone2Rotation';
LStage.AddInterpolator(LInterp);
// Configure the animation
LInterp.Path := 'RotationAngle.Point';
LInterp.Loop := true;
LInterp.Duration := 3.0; // 3 seconds
// To move the mesh, we need to add keys to the interpolator
LInterp.AddKey(0, Point3D(0, 0, 0), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(0.75, Point3D(0, 0, -90), TAnimationKeyInterpolationType.Linear);
LInterp.AddKey(1, Point3D(0, 0, -180), TAnimationKeyInterpolationType.Linear);
end;
NOTICE: You will need a stage for each joint to be modified during the animation.
Control TPoint3D properties like Position, RotationAngle or Scale by interpolators of that kind. Each 3D point consists of a X, Y and Z value.
Control TVector3D properties by interpolators of that kind. Each 3D vector consists of a X, Y, Z and W value.
Control TMatrix3D properties by interpolators of that kind. This might be the most common type for fast skin animations. It is able to contain position, rotation and scaling information at once represented by a 4x4 matrix.
Quaternions are 4-float vector structur able to manage rotation on 3 axis.
var
QuatInterp: TQuaternionInterpolatorDef;
Quat: TQuaternion3D;
begin
QuatInterp := TQuaternionInterpolatorDef.Create(StageDef);
QuatInterp.TargetId := 'ChildBone';
QuatInterp.PropertyName := 'RotationAngle';
// Create quaternions from Euler angles
Quat := TQuaternion3D.Create(Vector3D(0, 0, 0));
QuatInterp.AddKey(0.0, Quat);
Quat := TQuaternion3D.Create(Vector3D(0, 90, 0));
QuatInterp.AddKey(1.0, Quat);
StageDef.AddInterpolator(QuatInterp);
end;
By mesh or vertex animation we are able to modify single vertex positions. This is not controlled by vertex weights. Instead you can control vertices explicitly by this method.
var
MeshInterp: TMeshInterpolatorDef;
Vertices: TPoint3DDynArray;
begin
MeshInterp := TMeshInterpolatorDef.Create(StageDef);
MeshInterp.TargetId := 'SkinnedMesh';
// Key 0: Original vertices
SetLength(Vertices, MeshDef.VertexCount);
// ... fill vertices array
MeshInterp.AddKey(0.0, Vertices);
// Key 1: Deformed vertices
// ... modify vertices array
MeshInterp.AddKey(1.0, Vertices);
StageDef.AddInterpolator(MeshInterp);
end;
Convert definition structures to renderable FMX components:
procedure TForm1.FormCreate(Sender: TObject);
var LModelDef : TModelDef;
begin
// Create abstract model data
LModelDef := TUserModelBuilder.Build();
// Create visual component for the abstract model data
FModel := TGorillaModel.LoadNewModelFromDef(GorillaViewport1, LModelDef, []);
FModel.Parent := GorillaViewport1;
// For debugging purposes show the bones
FModel.ShowJoints := true;
// Run our skin animation
FModel.AnimationManager.Current.Start;
end;
procedure CreateAnimatedTriangle(AViewport: TGorillaViewport);
var
Cache: TVertexCache;
ModelDef: TModelDef;
MeshDef: TMeshDef;
AnimDef: TAnimationDef;
StageDef: TAnimationStageDef;
Interp: TVector3DInterpolatorDef;
Triangle: TTriangleID;
Model: TGorillaModel;
begin
Cache := TVertexCache.Create();
try
// Define triangle
Cache.AddPositionSource(Point3D(0, 1, 0));
Cache.AddPositionSource(Point3D(-1, -1, 0));
Cache.AddPositionSource(Point3D(1, -1, 0));
Cache.AddNormalSource(Point3D(0, 0, 1));
Cache.AddNormalSource(Point3D(0, 0, 1));
Cache.AddNormalSource(Point3D(0, 0, 1));
Triangle[0] := VertexID(0, 0, 0);
Triangle[1] := VertexID(1, 1, 0);
Triangle[2] := VertexID(2, 2, 0);
Cache.AddTriangle(0, Triangle, nil);
// Create model definition
ModelDef := TModelDef.Create(nil);
try
MeshDef := TMeshDef.Create(ModelDef);
MeshDef.Id := 'Triangle';
Cache.ApplyToMeshDef(MeshDef);
ModelDef.AddChild(MeshDef);
// Add rotation animation
AnimDef := TAnimationDef.Create(ModelDef);
AnimDef.Id := 'Spin';
ModelDef.AddAnimation(AnimDef);
StageDef := TAnimationStageDef.Create(AnimDef);
StageDef.Duration := 3.0;
AnimDef.AddStage(StageDef);
Interp := TVector3DInterpolatorDef.Create(StageDef);
Interp.TargetId := 'Triangle';
Interp.PropertyName := 'RotationAngle.Point';
Interp.AddKey(0.0, Vector3D(0, 0, 0));
Interp.AddKey(3.0, Vector3D(0, 360, 0));
StageDef.AddInterpolator(Interp);
// Create visual component
Model := TGorillaModel.LoadNewModelFromDef(AViewport, ModelDef, []);
Model.Parent := AViewport;
// Play animation
if Model.AnimationManager.Animations.Count > 0 then
begin
Model.AnimationManager.Current := Model.AnimationManager.GetFirstAnimation();
Model.AnimationManager.Current.Skeleton.Loop := True;
Model.AnimationManager.Current.Start();
end;
finally
ModelDef.Free();
end;
finally
Cache.Free();
end;
end;
Choose the Right Approach: Use simple polygon method for basic shapes or TVertexCache for complex geometry
Normalize Weights: Ensure vertex weights sum to 1.0 for skeletal animation
Validate Skin: Always call CheckMeshVerticesToBeAttachedCorrectly() after defining skin weights
Set IsStatic Appropriately: Only set IsStatic := True for geometry that won't change
Use Appropriate Index Format: Gorilla3D automatically uses UInt16 on mobile, UInt32 on desktop
Avoid Vertex Groups with Animation: Vertex groups currently don't support skeletal/vertex animation
Cache Animations: Use caching flags for better animation performance
Proper Hierarchy: Use AddChild() to maintain correct parent-child relationships
Test Normals: Verify normals point in correct direction for proper lighting
// Check normals are facing camera
Model.CalcFaceNormals();
// Verify mesh has material
if not Assigned(Model.MaterialSource) then
Model.MaterialSource := MyMaterialSource;
// Ensure IsStatic is set
Model.IsStatic := True;
// Show where the mesh actually is - the box encloses the vertices of the
// mesh and all of its sub-meshes, including the mesh matrix (WrapMode)
Model.ShowBoundingBox := True;
// Recalculate normals
Model.CalcFaceNormals();
// For normal mapping
Model.CalcTangentBinormals();
// Verify animation is loaded
if Model.AnimationManager.Animations.Count = 0 then
ShowMessage('No animations loaded');
// Check target IDs match
if Interp.TargetId <> MeshDef.Id then
ShowMessage('Target ID mismatch');
// Validate skin
if not LSkinDef.CheckMeshVerticesToBeAttachedCorrectly() then
ShowMessage('Skin validation failed');
// Clear cache after use
Cache.ClearBuffers();
The TGorillaDefaultMaterial is the core shader system of Gorilla3D. It uses a node-based architecture to generate GLSL shader source code at runtime. Instead of writing monolithic shaders, the system composes vertex and fragment shaders from a hierarchical tree of TGorillaNodeEntity nodes. This enables flexible shader customization by replacing or inserting specific nodes without rewriting entire shader code.
When a material is compiled, the TGorillaNodeBuilder instance traverses the node tree and calls ToString() on each TGorillaNodeEntity. Each node decides its output based on activated defines, allowing features to be toggled on or off at compile time.
Vertex Shader (TGorillaGLSLVertexShader):
Pragma (GLSL version)
└─ Globals (constants, types, uniforms, functions)
└─ Entry Point (main)
├─ Transformation nodes
├─ Displacement nodes
├─ Clipping nodes
├─ Surface Shader (custom user code)
└─ Output nodes
Fragment Shader (TGorillaGLSLFragmentShader):
Pragma (GLSL version)
└─ Globals (constants, types, uniforms, functions)
└─ Entry Point (main)
├─ Clipping / transformation
├─ Normal / bump mapping
├─ Parallax occlusion mapping
├─ Lighting loop (shading, attenuation, shadows)
├─ PBR preparation
├─ Surface Shader (final color computation)
└─ Multi-target output
| Class | Purpose |
|---|---|
TGorillaNodeEntity |
Base class; ToString() returns source code snippets |
TGorillaCompositeNode |
Container holding sub-nodes with hierarchical output |
TGorillaUniformsNode |
Manages input variables for specific shader languages |
TGorillaGlobalsNode |
Storage for globals, constants, attributes, types, uniforms |
TGorillaDeclarationNode |
Base for type/function declarations |
TGorillaOperationNode |
Builds mathematical/logical expressions in node format |
TGorillaSurfaceShaderNode |
Entry point for user-specific shader implementation |
| Node | Purpose |
|---|---|
TGorillaGLSLClippingPlaneNode |
Clipping plane computation |
TGorillaGLSLGetTransfVertPosNode |
Transformed vertex position |
TGorillaGLSLGetNormalNode |
Normal vector computation |
TGorillaGLSLGetBumpNormalNode |
Bump/normal map computation |
TGorillaGLSLPOMApplyNode |
Parallax occlusion mapping |
TGorillaGLSLLightsLoopNode |
Lighting loop (shading, attenuation, shadows) |
TGorillaGLSLGetBaseColorNode |
Base color / texture sampling |
TGorillaGLSLSpecularMapNode |
Specular map sampling |
TGorillaGLSLAddEnvironmentNode |
Environment map application |
TGorillaGLSLAddReflectionNode |
Reflection application |
TGorillaGLSLFragColorOutputNode |
Final fragment output |
TGorillaGLSLWeightedBlendedOITNode |
Order-independent transparency |
Features are toggled through compile-time defines. Add or remove defines to enable/disable shader functionality:
Material.AddDefine(GORILLA_GLSL_DEFINE_LIGHTING);
Material.RemoveDefine(GORILLA_GLSL_DEFINE_PBR);
Shader Type:
GORILLA_GLSL_DEFINE_VERTEXSHADER / GORILLA_GLSL_DEFINE_FRAGMENTSHADERLighting & Shading:
GORILLA_GLSL_DEFINE_LIGHTING — Core lighting computationGORILLA_GLSL_DEFINE_PHONG / GORILLA_GLSL_DEFINE_BLINNPHONG — Shading modelsGORILLA_GLSL_DEFINE_PBR — Physically-based renderingMapping Techniques:
GORILLA_GLSL_DEFINE_NORMALMAP / GORILLA_GLSL_DEFINE_BUMP — Normal/bump mappingGORILLA_GLSL_DEFINE_POM — Parallax occlusion mappingGORILLA_GLSL_DEFINE_DISPLACEMENT — Vertex displacementShadows & Effects:
GORILLA_GLSL_DEFINE_SHADOW with _SM or _VSM — Shadow / variance shadow mappingGORILLA_GLSL_DEFINE_REFLECTION / GORILLA_GLSL_DEFINE_REFRACTIONGORILLA_GLSL_DEFINE_ENVIRONMENT — Environment mappingTexturing:
GORILLA_GLSL_DEFINE_USE_TEXTURE — General texturingGORILLA_GLSL_DEFINE_USE_VERTEXCOLOR — Vertex color usageGORILLA_GLSL_DEFINE_SPECULARMAP — Specular texture mappingAll shader parameters are transmitted via a packed record (TGorillaShaderData) as a Uniform Buffer Object (UBO). This is more efficient than submitting variables individually.
Matrices:
ModelViewProjectionMatrix, ViewMatrix, ProjectionMatrixCamera & Timing:
TimeInfo — (start, current, previous, delta)EyePos — Camera positionViewDir — Camera directionMaterial & Lighting:
Material[0] — Material propertiesLights[0..MAX] — Light source arrayLightsCount — Active light countShadingModel — Lambert / Phong / PBRShadingIntensity, BrightnessFog:
FogMode, FogDensity, FogStart, FogEnd, FogColorScene Bounds:
FrustumMin/Max, SceneMin/Max, BoundaryMin/MaxViewSize — Viewport dimensions and camera near/farSpecial:
ClippingPlane — Single clipping planePassData[0] — Reflection/refraction matrices and PBR parametersSixteen standard attributes are pre-declared:
a_Position, a_Normal, a_Tangent, a_Binormal
a_TexCoord0, a_TexCoord1, a_TexCoord2, a_TexCoord3
a_Color, a_Color1, a_Color2, a_Color3
Data passed from vertex to fragment shader:
| Name | Type | Purpose |
|---|---|---|
vars.v_VertPos |
vec4 | Original vertex position |
vars.v_TransfVertPos |
vec3 | Transformed vertex position |
vars.v_TBN |
mat3 | Tangent-Binormal-Normal matrix |
vars.v_TBN_UT |
mat3 | TBN untransformed |
vars.v_TexCoord0 |
vec2 | Primary texture coordinates |
vars.v_Color0 |
vec4 | Vertex color data |
vars.v_ReflProjTextureCoords |
vec4 | Reflection texture projection |
vars.v_RefrProjTextureCoords |
vec4 | Refraction texture projection |
Modify these fields in the custom VertexShader function instead of varyings directly:
Position, TransfVertexPos, WorldViewProjVertPos
TexCoord0, TexCoord1, TexCoord2, TexCoord3, Color0
Normal, Tangent, Binormal
Displace
ClippingPlane
Available fields in the custom SurfaceShader function:
Lighting:
LightDir, LightVec, LightType, LightDist
Attenuation, SceneAttenuation
Ambient, Diffuse, Specular, Emissive
Geometry:
TransfVertPos, FragDepth
Normal, FragViewDir
TexCoord0, TexCoord1, TexCoord2, TexCoord3
Color Computation:
SpecularColor, BaseColor, SumColor
Alpha, Shading, ShadowSum, BumpSum
| Texture | Shader | Condition | Type |
|---|---|---|---|
_DisplacementMapTexture |
Vertex | DEFINE_DISPLACEMENT |
sampler2D |
_Texture0 |
Fragment | DEFINE_USE_TEXTURE |
sampler2D / samplerCube / sampler3D |
_NormalMapTexture |
Fragment | DEFINE_NORMALMAP |
sampler2D |
_SpecularMapTexture |
Fragment | DEFINE_SPECULARMAP |
sampler2D |
_EnvironmentTexture |
Fragment | DEFINE_ENVIRONMENT |
samplerCube |
_ReflectionTexture |
Fragment | DEFINE_REFLECTION |
sampler2D |
_RefractionTexture |
Fragment | DEFINE_REFRACTION |
sampler2D |
_DepthTexture |
Fragment | DEFINE_DEPTH |
sampler2D |
Multiple render target output from the fragment shader:
| Target | Value | Condition |
|---|---|---|
o_Albedo |
LOCALS.SumColor |
Always |
o_Alpha |
LOCALS.Alpha |
Always |
o_Position |
vec4(TransfVertPos, FragDepth) |
Always |
o_Normals |
LOCALS.Normal.xyz |
Always |
o_Components |
vec4(TexCoord0.xy, 1.0, 1.0) |
Deferred rendering |
o_Ambient |
LOCALS.Ambient.xyz |
Deferred rendering |
o_Emissive |
LOCALS.Emissive.xyz |
Deferred rendering |
o_Specular |
LOCALS.Specular.xyz |
Deferred rendering |
The TGorillaDefaultMaterialSource exposes two customizable shader functions: VertexShader and SurfaceShader. These allow you to inject custom GLSL code into the shader pipeline without creating a material subclass.
Modify vertex positions and transforms:
void VertexShader(inout TLocals DATA){
// Modify vertex position and related transforms
// IMPORTANT: When modifying Position, also update
// TransfVertexPos and WorldViewProjVertPos consistently
}
Compute the final fragment color:
void SurfaceShader(inout TLocals DATA){
// Compute final fragment color
// Set BaseColor, Alpha, and other lighting properties
DATA.BaseColor = tex2D(_Texture0, DATA.TexCoord0);
DATA.Alpha = DATA.BaseColor.a;
}
In the Object Inspector, expand the VertexShader or SurfaceShader property and write your GLSL code directly in the Text subproperty.
Important: The
VertexShaderandSurfaceShaderproperties are dynamic properties (published asTStrings). You cannot simply assign a string to.Textat runtime. Instead, you must assign aTStringListinstance to the property.
var
LShader: TStringList;
begin
LShader := TStringList.Create();
try
LShader.Add('void SurfaceShader(inout TLocals DATA){');
LShader.Add(' DATA.BaseColor = tex2D(_Texture0, DATA.TexCoord0);');
LShader.Add(' DATA.Alpha = DATA.BaseColor.a;');
LShader.Add('}');
// Correct: Assign TStringList to the property
Material.SurfaceShader := LShader;
finally
LShader.Free();
end;
end;
The same applies to the VertexShader property:
var
LShader: TStringList;
begin
LShader := TStringList.Create();
try
LShader.Add('void VertexShader(inout TLocals DATA){');
LShader.Add(' // Apply sine wave displacement');
LShader.Add(' float wave = sin(DATA.Position.x * 4.0 + _TimeInfo.y) * 0.1;');
LShader.Add(' DATA.Position.y += wave;');
LShader.Add(' DATA.TransfVertexPos = (_ModelViewMatrix * vec4(DATA.Position.xyz, 1.0)).xyz;');
LShader.Add(' DATA.WorldViewProjVertPos = _MVPMatrix * vec4(DATA.Position.xyz, 1.0);');
LShader.Add('}');
// Correct: Assign TStringList to the property
Material.VertexShader := LShader;
finally
LShader.Free();
end;
end;
Warning: Do not use
Material.SurfaceShader.Text := '...'orMaterial.VertexShader.Text := '...'at runtime. Since these are dynamic properties, writing to.Textdirectly will not trigger the necessary internal update mechanism. Always assign aTStrings/TStringListinstance.
void SurfaceShader(inout TLocals DATA){
float SPRITE_COLUMNS = 3.0;
float SPRITE_ROWS = 3.0;
uint NUM_SPRITES = 9;
uint idx = int(abs(sin(_TimeInfo.y) * 8.0)) % NUM_SPRITES;
vec2 pos = vec2(idx % 3, idx / 3);
DATA.BaseColor = tex2D(_Texture0, vec2(
(DATA.TexCoord0.x / SPRITE_COLUMNS) + pos.x * (1.0 / SPRITE_COLUMNS),
(DATA.TexCoord0.y / SPRITE_ROWS) + pos.y * (1.0 / SPRITE_ROWS)));
DATA.Alpha = DATA.BaseColor.a;
if(DATA.Alpha < 0.04) discard;
}
Define a packed record respecting OpenGL's std140 layout alignment (16-byte blocks):
type
TMyParams = packed record
Point: TPoint3D;
MyValue: Single; // Fits in same 16-byte block as Point
end;
Override DoUpdateShaderUniformBuffers() to register it:
procedure TMyMaterial.DoUpdateShaderUniformBuffers(const AProgram: TGorillaShaderProgram);
begin
inherited;
AProgram.RegisterUniformBuffer('MyParams', @FMyParams, SizeOf(FMyParams));
end;
Access in GLSL with underscore prefix: _MyParams._Point.
Override DoCreateDefaultBitmaps():
procedure TMyMaterial.DoCreateDefaultBitmaps();
var
LEntry: TGorillaTextureBitmapPoolEntry;
begin
inherited;
LEntry := DoAddOrUpdateBitmapToPool('MYTEXTURE0',
TPixelFormatEx.RGBA8, TPixelFormatEx.RGBA,
GORILLA_DEFAULT_TEXTURE_DATATYPE, false, true, true);
if Assigned(LEntry) then
LEntry.SetExtendedProperties(
TGorillaTextureWrap.Repeated, TGorillaTextureWrap.Repeated,
TGorillaTextureWrap.Repeated,
TTextureFilter.Linear, TTextureFilter.Linear);
end;
Access via _MYTEXTURE0 in shaders. The naming convention is: the pool name becomes _<NAME> in GLSL.
Override DoSetupFragmentShader():
procedure TMyMaterial.DoSetupFragmentShader();
var
LUniform: TGorillaGLSLUniformsNode;
begin
inherited;
// Register variable for the shader pipeline
FFSShaderSource.AddVariables([
TContextShaderVariable.Create('MyPointF',
TContextShaderVariableKind.Float2, FFSVarIndex, 0)
]);
Inc(FFSVarIndex);
// Add GLSL uniform declaration
LUniform := TGorillaGLSLUniformsNode.Create(FragmentShaderNode);
LUniform.AddDeclaration('_MyPointF', TGorillaShaderNodeVariableType.stVec2);
FragmentShaderNode.Globals.Uniforms.Add(LUniform);
end;
Create a declaration node class:
type
TMyFuncNode = class(TGorillaDeclarationNode)
function ToString: String; override;
end;
function TMyFuncNode.ToString: String;
begin
Result := 'vec4 MyFunc(sampler2D tex, vec2 uv){' +
'return texture2D(tex, uv);}';
end;
Register it in the shader globals:
FragmentShaderNode.Globals.Functions.Add(
TMyFuncNode.Create(FragmentShaderNode)
);
To replace an existing node (e.g., the base color computation):
var
LOldIdx: Integer;
begin
LOldIdx := FragmentShaderNode.SurfaceShader.IndexOf(
TGorillaGLSLGetBaseColorNode, '');
if LOldIdx > -1 then
begin
FragmentShaderNode.SurfaceShader.Delete(LOldIdx);
FragmentShaderNode.SurfaceShader.Insert(LOldIdx, LNewNode);
end;
end;
Every TGorillaDefaultMaterialSource exposes a published Bitmaps property of type TGorillaBitmapPool — an TOwnedCollection of TGorillaBitmapPoolEntry items. This pool is the central place where all textures of a material live, including the built-in ones (Texture0, NormalMap, SpecularMap, …) as well as any custom textures you add. Properties like Texture0 or NormalMap are convenience accessors that internally resolve to a pool entry.
Each entry maps to a GLSL sampler: an entry named MyTexture becomes _MyTexture in the shader code.
| Property | Type | Default | Purpose |
|---|---|---|---|
Name |
String |
— | Entry name; becomes _<Name> in GLSL |
Bitmap |
TBitmap |
— | The actual texture image data (BMP, PNG, JPEG). When you assign a TGorillaTextureBitmap, all of its extended GPU settings are honoured |
TextureKind |
TGorillaTextureKind |
Texture2D |
Texture2D, Texture3D, CubeMap, … |
ShaderKind |
TContextShaderKind |
Pixel |
Which shader stage uses the texture (Pixel / Vertex) |
Tiling |
TPointF |
(1.0, 1.0) |
Number of texture repeats across the X/Y axes |
TilingX |
Single |
1.0 |
Repeat count on the X-axis (component of Tiling) |
TilingY |
Single |
1.0 |
Repeat count on the Y-axis (component of Tiling) |
WrapS |
TGorillaTextureWrap |
ClampToEdge |
Horizontal wrap mode |
WrapT |
TGorillaTextureWrap |
ClampToEdge |
Vertical wrap mode |
WrapR |
TGorillaTextureWrap |
ClampToEdge |
Depth wrap mode (3D textures) |
MinFilter / MagFilter |
TTextureFilter |
Linear |
Minification / magnification filter |
Format / InternalFormat |
TPixelFormatEx |
— | Pixel format and internal GPU format |
DataType |
TGorillaTextureDataType |
— | Channel data type |
BorderColor |
TAlphaColor |
— | Border color used by ClampToBorder |
ProtectFormatSettings |
Boolean |
False |
Prevent FMX from overwriting the format settings at runtime |
IsDynamic |
Boolean |
False |
Texture is produced by a render pass (reflection/refraction/depth) |
The
Bitmapproperty is therefore the raw image source of a texture entry, whileFormat,DataType,WrapS/T/R, the filters andTilingdescribe how that image is uploaded to the GPU and sampled in the shader.
Tiling (and its scalar components TilingX / TilingY) controls how often a texture is repeated across the surface's UV coordinates. A value of (1.0, 1.0) shows the texture exactly once; (4.0, 4.0) repeats it four times along each axis.
Tiling is applied in GLSL by scaling and wrapping the texture coordinates, conceptually:
texcoord = mod(texcoord * tiling, 1.0);
// Repeat the diffuse texture 8×8 times across the mesh
Material.Bitmaps.Items[0].Tiling := PointF(8.0, 8.0);
Material.Bitmaps.Items[0].WrapS := TGorillaTextureWrap.Repeated;
Material.Bitmaps.Items[0].WrapT := TGorillaTextureWrap.Repeated;
Important — avoid black seam lines when tiling: Setting
Tilingalone does not change the wrap mode. Because the tiling is computed withmod(texcoord * tiling, 1.0), it works even with a clamping wrap mode — but withWrapS/WrapT(andWrapRfor 3D textures) set toClamp,ClampToEdgeorClampToBorder, the bilinear/mip-map filter footprint at every tile seam samples (and clamps to) the texture border. The result is visible dark / black lines along the tile edges.For seamless tiling you must explicitly set
WrapS/WrapT(/ WrapR) toTGorillaTextureWrap.Repeated(orMirroredRepeat). Note that a fresh bitmap pool entry defaults to a clamping wrap mode, so this step is required wheneverTiling > 1.
| Use case | Tiling | WrapS / WrapT (/ WrapR) | Result |
|---|---|---|---|
| No repetition | (1.0, 1.0) |
any | Single texture, edges controlled by wrap mode |
| Seamless repeating | (N, M) |
Repeated |
Seamless tiling, no dark seams |
| Seamless mirrored | (N, M) |
MirroredRepeat |
Seamless tiling with mirrored repeats |
| Single + custom border | (1.0, 1.0) |
ClampToBorder |
Single texture surrounded by BorderColor |
MyTexture)The texture name MyTexture becomes _MyTexture in GLSL code.
When you increase Tiling above
1, remember to also switch WrapS / WrapT (and WrapR for 3D textures) to Repeated or MirroredRepeat — otherwise black seam lines appear at the tile borders (see Texture Tiling).
Material Behaviours (introduced in v1.1) are modular, reusable shader building blocks that encapsulate complex GPU functionality. They enable sharing shader code across multiple TGorillaDefaultMaterialSource components while maintaining centralized parameter control.
Important: Material behaviours are only compatible with
TGorillaDefaultMaterialSourceand derived Gorilla3D materials. They do not work with FireMonkey's embedded materials likeTLightMaterialSourceorTColorMaterialSource.
Material behaviours function as collections of shader snippets that can be dynamically inserted into vertex and fragment shaders. Instead of duplicating shader code across multiple material sources or creating specialized material subclasses, you create a single behaviour component that can be attached to any number of materials.
Traditional Approach (before v1.1):
// Create specialized material class for each effect
TGorillaWindMaterial = class(TGorillaDefaultMaterialSource)
// Duplicate wind logic in shader
end;
TGorillaGrassMaterial = class(TGorillaDefaultMaterialSource)
// Duplicate wind logic again
end;
Behaviour Approach (v1.1+):
// One behaviour, multiple materials
var
WindBehaviour: TGorillaMaterialWindBehaviour;
begin
WindBehaviour := TGorillaMaterialWindBehaviour.Create(Self);
// Attach to any material
GrassMaterial.AttachMaterialBehaviour(WindBehaviour);
TreeMaterial.AttachMaterialBehaviour(WindBehaviour);
FlagMaterial.AttachMaterialBehaviour(WindBehaviour);
end;
TGorillaMaterialBehaviour (Component)
├─ Uniform Buffer Definition (std140)
├─ Shader Code (Vertex + Fragment)
└─ Parameter Management
Attached to:
├─ Material 1 (own uniform buffer instance)
├─ Material 2 (own uniform buffer instance)
└─ Material 3 (own uniform buffer instance)
Simulates GPU-based wind effects with waving animation.
Use Cases: Grass, trees, foliage, flags, cloth
Properties:
Example:
var
WindBehaviour: TGorillaMaterialWindBehaviour;
begin
// Create wind system
WindBehaviour := TGorillaMaterialWindBehaviour.Create(Self);
WindBehaviour.Viewport := Viewport;
// Configure wind channel
WindBehaviour.WindSource.Point := Point3D(0, 0, 0);
WindBehaviour.WindDir.Point := Point3D(1, 0, 0); // East direction
WindBehaviour.WindWidth := 20.0;
WindBehaviour.WindHeight := 10.0;
WindBehaviour.WindDistance := 50.0;
WindBehaviour.WindPower := 1.5;
WindBehaviour.WindWaving := 1.0;
WindBehaviour.WindSpeed := 2.0;
WindBehaviour.ShowVisualizer := True; // Debug visualization
// Attach to grass material
GrassMaterial.AttachMaterialBehaviour(WindBehaviour);
end;
Creates noise-based vertex position variation for jelly/soft body effects.
Use Cases: Jelly, soft bodies, water, organic movement
Properties:
Example:
var
WobbleBehaviour: TGorillaMaterialWobbleBehaviour;
begin
WobbleBehaviour := TGorillaMaterialWobbleBehaviour.Create(Self);
WobbleBehaviour.WobbleIntensity := 0.5;
WobbleBehaviour.WobbleSpeed := 1.0;
WobbleBehaviour.WobbleScale := 2.0;
JellyMaterial.AttachMaterialBehaviour(WobbleBehaviour);
end;
Adds rim/edge lighting effect highlighting object silhouettes.
Use Cases: Character outlines, object highlighting, stylized rendering
Properties:
Example:
var
RimLightBehaviour: TGorillaMaterialRimLightBehaviour;
begin
RimLightBehaviour := TGorillaMaterialRimLightBehaviour.Create(Self);
RimLightBehaviour.RimColor := TAlphaColorRec.Cyan;
RimLightBehaviour.RimIntensity := 0.3;
CharacterMaterial.AttachMaterialBehaviour(RimLightBehaviour);
end;
Simulates underwater caustics (light patterns from water surface).
Use Cases: Underwater scenes, swimming pools, water effects
Properties:
Example:
var
CausticsBehaviour: TGorillaMaterialCausticsBehaviour;
begin
CausticsBehaviour := TGorillaMaterialCausticsBehaviour.Create(Self);
CausticsBehaviour.CausticsIntensity := 0.8;
CausticsBehaviour.CausticsSpeed := 0.5;
CausticsBehaviour.CausticsScale := 2.0;
UnderwaterFloorMaterial.AttachMaterialBehaviour(CausticsBehaviour);
end;
Provides comprehensive color manipulation controls.
Use Cases: Post-processing effects, color grading, visual adjustments
Properties:
Example:
var
ColorAdjustBehaviour: TGorillaMaterialColorAdjustBehaviour;
begin
ColorAdjustBehaviour := TGorillaMaterialColorAdjustBehaviour.Create(Self);
ColorAdjustBehaviour.Brightness := 0.2; // Slightly brighter
ColorAdjustBehaviour.Contrast := 1.2; // More contrast
ColorAdjustBehaviour.Saturation := 0.3; // More saturated
ColorAdjustBehaviour.Gamma := 1.1; // Gamma adjustment
SceneMaterial.AttachMaterialBehaviour(ColorAdjustBehaviour);
end;
Special behaviour for design-time shader customization without coding.
Use Cases: Quick prototyping, designer-friendly customization, runtime experiments
Features:
TDesignTimeUBO)Example:
var
DesignTimeBehaviour: TGorillaMaterialDesignTimeBehaviour;
Param: TDesignTimeUBOParameter;
begin
DesignTimeBehaviour := TGorillaMaterialDesignTimeBehaviour.Create(Self);
// Add custom parameters
Param := DesignTimeBehaviour.DesignTimeParams.Add();
Param.Name := 'CustomIntensity';
Param.DataType := TDesignTimeUniformDataType.udtFloat;
Param.InputValue := '0.5';
// To declare functions, which can be used inside of
// DesignTimeBehaviour.VertexShader / DesignTimeBehaviour.FragmentShader
DesignTimeBehaviour.AdditionalVertexShader := 'void helperVertexFunc(){}';
DesignTimeBehaviour.AdditionalFragmentShader := 'void helperFragmentFunc(){}';
// Assign custom shader code (vertex/fragment)
DesignTimeBehaviour.VertexShader := 'custom GLSL code...';
DesignTimeBehaviour.FragmentShader := 'custom GLSL code...';
Material.AttachMaterialBehaviour(DesignTimeBehaviour);
end;
TGorillaMaterialWindBehaviour)Behaviours collection in Object InspectorBehaviour property to your behaviour componentvar
Behaviour: TGorillaMaterialWindBehaviour;
begin
Behaviour := TGorillaMaterialWindBehaviour.Create(Self);
Behaviour.WindPower := 2.0;
// Attach behaviour to material
Material.AttachMaterialBehaviour(Behaviour);
end;
// Remove specific behaviour
Material.DetachMaterialBehaviour(WindBehaviour);
// Remove all behaviours
Material.ClearMaterialsBehaviours();
// Check if behaviour is attached
if Material.MaterialBehaviourAttached(WindBehaviour) then
ShowMessage('Wind behaviour is active');
// Get behaviour index
var Index := Material.IndexOfMaterialBehaviour(WindBehaviour);
if Index >= 0 then
ShowMessage('Behaviour found at index: ' + IntToStr(Index));
var
WindBehaviour: TGorillaMaterialWindBehaviour;
begin
WindBehaviour := TGorillaMaterialWindBehaviour.Create(Self);
WindBehaviour.WindPower := 1.5;
// Attach to multiple materials
GrassMaterial.AttachMaterialBehaviour(WindBehaviour);
TreeMaterial.AttachMaterialBehaviour(WindBehaviour);
FlowerMaterial.AttachMaterialBehaviour(WindBehaviour);
// Changing WindPower affects all materials
WindBehaviour.WindPower := 2.0;
end;
// Combine multiple effects
Material.AttachMaterialBehaviour(WindBehaviour);
Material.AttachMaterialBehaviour(RimLightBehaviour);
Material.AttachMaterialBehaviour(ColorAdjustBehaviour);
To create your own material behaviour, inherit from TGorillaMaterialBehaviour and implement required methods:
type
TMyCustomBehaviour = class(TGorillaMaterialBehaviour)
private
FMyParams: TMyParamsRecord;
protected
// Define uniform buffer
function DoOnRegisterUniformBuffer(out AName: String;
out AUBO: Pointer; out AUBOSize: Integer): Boolean; override;
// Initialize buffer
procedure DoOnInitializeUniformBuffer(AMaterial: TMaterial;
var AInitialized: Boolean); override;
// Add shader code
procedure DoOnCreateShader(ABuilder: TGorillaNodeBuilder;
AKind: TContextShaderKind); override;
// Update shader (if needed)
procedure DoOnUpdateShader(ABuilder: TGorillaNodeBuilder;
AKind: TContextShaderKind); override;
// Remove shader code
procedure DoOnRemoveShader(ABuilder: TGorillaNodeBuilder;
AKind: TContextShaderKind); override;
// Apply/update uniforms
procedure Apply(AMaterial: TMaterial; AContext: TContext3D;
AItem: TGorillaMaterialBehaviourItem); override;
public
constructor Create(AOwner: TComponent); override;
published
property MyParameter: Single read FMyParam write SetMyParam;
end;
Behaviours must use OpenGL std140 layout for uniform buffers. Key rules:
Example struct (correct std140 layout):
TMyParams = packed record
Color: TAlphaColorF; // vec4 - 16 bytes
Intensity: Single; // float - 4 bytes
Speed: Single; // float - 4 bytes
Scale: Single; // float - 4 bytes
Reserved: Single; // padding - 4 bytes (total 16-byte alignment)
end;
Behaviours add nodes to the shader builder:
procedure TMyBehaviour.DoOnCreateShader(ABuilder: TGorillaNodeBuilder;
AKind: TContextShaderKind);
var
MainNode: TGorillaGLSLMainNode;
MyNode: TMyCustomNode;
begin
if AKind = TContextShaderKind.FragmentShader then
begin
MainNode := ABuilder.FindNode(TGorillaGLSLMainNode) as TGorillaGLSLMainNode;
MyNode := TMyCustomNode.Create(ABuilder);
MainNode.AddNode(MyNode);
end;
end;
Some behaviours require viewport for rendering debug visualizations:
WindBehaviour.Viewport := Viewport;
WindBehaviour.ShowVisualizer := True; // Shows wind direction arrow
Uniform Buffer Updates: Behaviours update GPU buffers every frame. Minimize parameter changes.
Shader Compilation: Adding/removing behaviours triggers shader recompilation. Attach behaviours once at initialization.
Multiple Behaviours: Each behaviour adds shader code. Too many behaviours increase shader complexity.
Shared Behaviours: One behaviour instance for multiple materials is more efficient than multiple instances.
Memory Layout: Incorrect std140 alignment causes GPU errors. Always pad structs properly.
Gorilla Materials Only: Behaviours don't work with FireMonkey materials (TLightMaterialSource, TColorMaterialSource, etc.)
Shader Complexity: Too many behaviours may exceed shader complexity limits on older hardware
Platform Differences: Some GLSL features may behave differently across platforms (OpenGL vs OpenGL ES vs Metal)
Design-Time: Behaviour changes at design-time may not update immediately; recompile project
Share Behaviours: Create one behaviour instance per effect type, attach to multiple materials
Initialize Early: Attach behaviours during form creation, not runtime loops
Use Events: Handle OnAttached/OnDetached events for cleanup
Batch Updates: Use Material.BeginChange()/EndChange() when modifying multiple properties
Debug Visualization: Enable visualizers during development, disable for production
Test on Target: Verify behaviour effects on target platform before deployment
Monitor Shader Size: Check generated shader code size; excessive complexity impacts performance
Profile Performance: Measure GPU performance impact, especially with multiple behaviours
var Wind: TGorillaMaterialWindBehaviour;
begin
Wind := TGorillaMaterialWindBehaviour.Create(Self);
Wind.Viewport := Viewport;
Wind.WindSource.Point := Point3D(0, 0, 0);
Wind.WindDir.Point := Point3D(1, 0, 0.5);
Wind.WindWidth := 50.0;
Wind.WindHeight := 20.0;
Wind.WindDistance := 100.0;
Wind.WindPower := 1.5;
Wind.WindWaving := 1.2;
Wind.WindSpeed := 2.0;
// Apply to all vegetation
for var Mat in VegetationMaterials do
Mat.AttachMaterialBehaviour(Wind);
end;
var Rim: TGorillaMaterialRimLightBehaviour;
begin
Rim := TGorillaMaterialRimLightBehaviour.Create(Self);
Rim.RimColor := TAlphaColorRec.Cyan;
Rim.RimIntensity := 0.25;
CharacterSkinMaterial.AttachMaterialBehaviour(Rim);
CharacterArmorMaterial.AttachMaterialBehaviour(Rim);
end;
var Caustics: TGorillaMaterialCausticsBehaviour;
begin
Caustics := TGorillaMaterialCausticsBehaviour.Create(Self);
Caustics.CausticsIntensity := 0.6;
Caustics.CausticsSpeed := 0.8;
Caustics.CausticsScale := 3.0;
FloorMaterial.AttachMaterialBehaviour(Caustics);
WallMaterial.AttachMaterialBehaviour(Caustics);
PropsMaterial.AttachMaterialBehaviour(Caustics);
end;
The water material system in Gorilla3D creates realistic water surfaces by combining multiple render passes and texture maps. The TGorillaWaterMaterialSource component provides a comprehensive shader-based water rendering solution with wave animation, reflections, refractions, foam, and interactive ripples.
Water rendering in Gorilla3D uses a specialized material that combines:
A complete water surface requires:
TGorillaPlane or custom water meshTGorillaWaterMaterialSourceTGorillaRenderPassReflectionTGorillaRenderPassRefractionvar
WaterMaterial: TGorillaWaterMaterialSource;
WaterPlane: TGorillaPlane;
ReflectionPass: TGorillaRenderPassReflection;
RefractionPass: TGorillaRenderPassRefraction;
begin
// Create water material
WaterMaterial := TGorillaWaterMaterialSource.Create(Self);
WaterMaterial.Diffuse := TAlphaColorF.Create(0.1, 0.3, 0.5, 0.8);
// Load required textures
WaterMaterial.DUDVTexture.LoadFromFile('water_dudv.png');
WaterMaterial.NormalMap.LoadFromFile('water_normal.png');
WaterMaterial.SpecularMap.LoadFromFile('water_spec.png');
// Configure render passes
WaterMaterial.Reflections := True;
WaterMaterial.ReflectionPass := ReflectionPass;
WaterMaterial.Refractions := True;
WaterMaterial.RefractionPass := RefractionPass;
// Create water plane
WaterPlane := TGorillaPlane.Create(Self);
WaterPlane.Width := 100.0;
WaterPlane.Height := 100.0;
WaterPlane.MaterialSource := WaterMaterial;
end;
A DUDV map stores directional displacement information, primarily in the Red and Green channels. This texture creates the wave distortion effect.
Characteristics:
Property: DUDVTexture: TBitmap
Example:
WaterMaterial.DUDVTexture.LoadFromFile('water_dudv.png');
Surface normal information for lighting calculations and wave detail.
Characteristics:
Property: NormalMap: TBitmap
Example:
WaterMaterial.NormalMap.LoadFromFile('water_normal.png');
Controls specular highlight intensity across the water surface.
Characteristics:
Property: SpecularMap: TBitmap
Example:
WaterMaterial.SpecularMap.LoadFromFile('water_spec.png');
Vertex displacement for actual geometry deformation (wave height).
Characteristics:
Properties:
DisplacementMap: TBitmapDisplacement: TVector3D - Direction vectorDisplIntensity: Single - Displacement strength (0.0-100.0)Example:
WaterMaterial.DisplacementMap.LoadFromFile('water_height.png');
WaterMaterial.Displacement := Vector3D(0, 1, 0); // Y-axis displacement
WaterMaterial.DisplIntensity := 0.5;
Surface foam overlay texture.
Property: FoamTexture: TBitmap
Related Properties:
FoamDirection: TPointF - Foam movement directionFoamIntensity: Single - Foam visibility (0.0-10.0)Example:
WaterMaterial.FoamTexture.LoadFromFile('foam.png');
WaterMaterial.FoamDirection := PointF(0.5, 0.5);
WaterMaterial.FoamIntensity := 1.0;
Shore foam texture displayed at shallow water edges.
Property: ShoreTexture: TBitmap
Related Properties:
ShoreWidth: Single - Shore effect range (0.0001-100.0)ShoreIntensity: Single - Shore foam brightness (0.0-10.0)Example:
WaterMaterial.ShoreTexture.LoadFromFile('shore_foam.png');
WaterMaterial.ShoreWidth := 2.0;
WaterMaterial.ShoreIntensity := 3.0;
| Property | Type | Default | Range | Description |
|---|---|---|---|---|
| WaveSpeed | Single | 1.0 | 0.0+ | Animation speed multiplier. Higher = faster wave movement. |
| WaveSize | Single | 1.0 | 0.0+ | Wave distortion strength/amplitude. |
Example:
WaterMaterial.WaveSpeed := 0.8; // Slower waves
WaterMaterial.WaveSize := 1.5; // Larger waves
| Property | Type | Description |
|---|---|---|
| Diffuse | TAlphaColorF | Base water color (RGB + transparency). |
| DiffusePower | Single | Mix ratio between diffuse color and refraction. |
| Specular | TAlphaColorF | Specular highlight color. |
| Shininess | Single | Specular sharpness (higher = sharper highlights). |
Example:
WaterMaterial.Diffuse := TAlphaColorF.Create(0.05, 0.2, 0.4, 0.7);
WaterMaterial.DiffusePower := 1.0;
WaterMaterial.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
WaterMaterial.Shininess := 128.0;
| Property | Type | Range | Description |
|---|---|---|---|
| DepthIntensity | Single | 0.001-10.0 | Depth map influence on transparency and effects. |
Controls how depth information affects water appearance. Lower values = more transparent deep water, higher values = more opaque deep water.
Example:
WaterMaterial.DepthIntensity := 1.5;
| Property | Type | Range | Description |
|---|---|---|---|
| Reflections | Boolean | - | Enable reflection mapping. |
| ReflectionPass | TGorillaRenderPassController | - | Linked reflection render pass. |
| ReflectionPower | Single | 0.0-1.0 | Reflection intensity. |
| ReflCorrection | TVector3D | - | RGB color correction for reflections. |
| Refractions | Boolean | - | Enable refraction mapping. |
| RefractionPass | TGorillaRenderPassController | - | Linked refraction render pass. |
| RefractionPower | Single | 0.0-1.0 | Refraction intensity. |
| RefrCorrection | TVector3D | - | RGB color correction for refractions. |
Example:
// Reflection setup
WaterMaterial.Reflections := True;
WaterMaterial.ReflectionPass := ReflectionPass;
WaterMaterial.ReflectionPower := 0.6;
WaterMaterial.ReflCorrection := Vector3D(1.0, 1.0, 1.0);
// Refraction setup
WaterMaterial.Refractions := True;
WaterMaterial.RefractionPass := RefractionPass;
WaterMaterial.RefractionPower := 0.8;
WaterMaterial.RefrCorrection := Vector3D(1.0, 1.0, 1.1); // Slight blue tint
The OutputLayer property allows visualization of individual shader components for debugging.
| Value | Description |
|---|---|
| wolAll | Normal rendering (all layers combined). |
| wolDUDV | Show DUDV displacement map only. |
| wolNormal | Show normal map only. |
| wolSpecular | Show specular highlights only. |
| wolFoam | Show foam layer only. |
| wolDepth | Show depth map visualization. |
| wolRefraction | Show refraction pass only. |
| wolReflection | Show reflection pass only. |
| wolReflPlusRefr | Show reflection + refraction blend. |
| wolTexCoords | Show texture coordinates. |
Example:
WaterMaterial.OutputLayer := wolDepth; // Debug depth mapping
Interactive ripples were introduced in v0.8.3.2265 for dynamic water surface disturbances.
| Property | Type | Description |
|---|---|---|
| RipplesActive | Boolean | Enable/disable ripple computation. |
| RippleAmplification | Single | Ripple height/amplitude. |
| RippleProximity | Single | Ripple width (basis value). |
| RippleDecay | Single | Fade-out speed. |
procedure AddRipple(APos: TVector3D); overload;
procedure AddRipple(APos: TPoint3D); overload;
procedure AddRipples(const AArr: TArray<TVector3D>);
procedure SetRipples(const AArr: TArray<TVector3D>);
procedure ClearRipples();
Limitations:
Example:
// Enable ripples
WaterMaterial.RipplesActive := True;
WaterMaterial.RippleAmplification := 0.5;
WaterMaterial.RippleProximity := 2.0;
WaterMaterial.RippleDecay := 0.95;
// Add ripple at world position
WaterMaterial.AddRipple(Point3D(10.0, 0.0, 5.0));
// Add multiple ripples
var Positions: TArray<TVector3D>;
SetLength(Positions, 3);
Positions[0] := Vector3D(0, 0, 0);
Positions[1] := Vector3D(5, 0, 5);
Positions[2] := Vector3D(-5, 0, 5);
WaterMaterial.AddRipples(Positions);
// Clear all ripples
WaterMaterial.ClearRipples();
The reflection pass must exclude the water plane to prevent self-reflection artifacts.
var
ReflectionPass: TGorillaRenderPassReflection;
begin
ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass.Viewport := Viewport;
ReflectionPass.Camera := Camera;
// Exclude water plane from reflection
ReflectionPass.IgnoreControl(WaterPlane);
// Configure reflection plane
ReflectionPass.MirrorPosition.Point := TPoint3D(WaterPlane.AbsolutePosition);
ReflectionPass.MirrorSize := WaterPlane.Width;
end;
The refraction pass provides both underwater color and depth information.
var
RefractionPass: TGorillaRenderPassRefraction;
begin
RefractionPass := TGorillaRenderPassRefraction.Create(Self);
RefractionPass.Viewport := Viewport;
// Exclude water plane from refraction
RefractionPass.IgnoreControl(WaterPlane);
// Configure refraction plane
RefractionPass.SurfacePosition.Point := TPoint3D(WaterPlane.AbsolutePosition);
end;
When using displacement mapping, the water plane's visual position shifts. Adjust render pass planes to compensate:
ReflectionPass.MirrorPosition.Point := TPoint3D(FWaterPlane.AbsolutePosition) + Point3D(0, -WaterMaterial.DisplIntensity, 0);
RefractionPass.SurfacePosition.Point := TPoint3D(FWaterPlane.AbsolutePosition) + Point3D(0, -WaterMaterial.DisplIntensity, 0);
procedure TForm1.CreateWaterScene;
var
WaterMaterial: TGorillaWaterMaterialSource;
WaterPlane: TGorillaPlane;
ReflectionPass: TGorillaRenderPassReflection;
RefractionPass: TGorillaRenderPassRefraction;
begin
// Create render passes
ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass.Viewport := Viewport;
ReflectionPass.Camera := Camera;
RefractionPass := TGorillaRenderPassRefraction.Create(Self);
RefractionPass.Viewport := Viewport;
// Create water material
WaterMaterial := TGorillaWaterMaterialSource.Create(Viewport);
// Basic appearance
WaterMaterial.Diffuse := TAlphaColorF.Create(0.1, 0.25, 0.4, 0.75);
WaterMaterial.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
WaterMaterial.Shininess := 128.0;
// Load textures
WaterMaterial.DUDVTexture.LoadFromFile('textures\water_dudv.png');
WaterMaterial.NormalMap.LoadFromFile('textures\water_normal.png');
WaterMaterial.SpecularMap.LoadFromFile('textures\water_spec.png');
WaterMaterial.FoamTexture.LoadFromFile('textures\foam.png');
WaterMaterial.ShoreTexture.LoadFromFile('textures\shore_foam.png');
// Wave animation
WaterMaterial.WaveSpeed := 0.5;
WaterMaterial.WaveSize := 1.2;
// Foam configuration
WaterMaterial.FoamDirection := PointF(0.3, 0.7);
WaterMaterial.FoamIntensity := 1.5;
WaterMaterial.ShoreWidth := 3.0;
WaterMaterial.ShoreIntensity := 2.5;
// Depth and transparency
WaterMaterial.DepthIntensity := 1.8;
WaterMaterial.DiffusePower := 1.0;
// Reflection setup
WaterMaterial.Reflections := True;
WaterMaterial.ReflectionPass := ReflectionPass;
WaterMaterial.ReflectionPower := 0.5;
WaterMaterial.ReflCorrection := Vector3D(1.0, 1.0, 1.0);
// Refraction setup
WaterMaterial.Refractions := True;
WaterMaterial.RefractionPass := RefractionPass;
WaterMaterial.RefractionPower := 0.8;
WaterMaterial.RefrCorrection := Vector3D(1.0, 1.0, 1.15);
// Ripples
WaterMaterial.RipplesActive := True;
WaterMaterial.RippleAmplification := 0.4;
WaterMaterial.RippleProximity := 2.5;
WaterMaterial.RippleDecay := 0.92;
// Create water plane
WaterPlane := TGorillaPlane.Create(Self);
WaterPlane.Width := 100.0;
WaterPlane.Height := 100.0;
WaterPlane.SubdivisionsWidth := 64;
WaterPlane.SubdivisionsHeight := 64;
WaterPlane.MaterialSource := WaterMaterial;
// Exclude water from render passes
ReflectionPass.IgnoreControl(WaterPlane);
RefractionPass.IgnoreControl(WaterPlane);
end;
procedure TForm1.OnWaterPlaneMouseClick(ASender: TObject; X, Y: Single);
var LPt3D : TPoint3D;
begin
/// add a ripple by clicking with the left mouse button onto the water plane (Caution: HitTest needs to be activated)
if (ssLeft in fShiftState) then
begin
LPt3D := GorillaViewport1.ScreenToWorld(PointF(X, Y));
GorillaWaterMaterialSource1.AddRipple(Point3D(LPt3D.X, LPt3D.Z, -LPt3D.Y));
end;
end;
Subdivision Density: Higher mesh subdivision improves displacement mapping but increases vertex processing cost.
Render Pass Resolution: Lower resolution reflection/refraction textures improve performance significantly.
Ripple Count: Each active ripple adds computation cost. Limit simultaneous ripples for best performance.
Texture Sizes: Use power-of-two textures (256x256, 512x512) for optimal GPU performance.
Platform Differences: Mobile platforms have lower limits regarding texture performance.
Cause: Missing or incorrectly configured render passes.
Solution:
Reflections and Refractions are enabledReflectionPass and RefractionPass are assignedIgnoreControl()Cause: Water plane not excluded from render passes.
Solution:
ReflectionPass.IgnoreControl(WaterPlane);
RefractionPass.IgnoreControl(WaterPlane);
Cause: RipplesActive is false or ripple parameters too subtle.
Solution:
WaterMaterial.RipplesActive := True;
WaterMaterial.RippleAmplification := 1.0; // Increase for visibility
Cause: Render pass planes don't account for displacement offset.
Solution: Adjust reflection/refraction plane positions by displacement amount.
TGorillaVolumetricMesh renders a 3D scalar field (a volume) with a GPU ray-marching algorithm. Instead of a surface made of triangles, every pixel casts a ray through a 3D texture and accumulates the voxel values along the way. This is the technique used for medical imaging (CT / MRI / MRT scans), scientific data, and — with the Volumetric Noise subclass — for fog, clouds and smoke.
The volume is stored as a 3D texture (width × height × depth voxels). At render time the mesh rasterizes a surrounding box (or sphere / cylinder) and, for every fragment, marches a ray from the entry point to the exit point, sampling the 3D texture at fixed steps and compositing the samples.
| Feature | Description |
|---|---|
| Unit | Gorilla.Volumetric.Mesh |
| Class | TGorillaVolumetricMesh (inherits TGorillaSingletonMesh) |
| Data | 3D texture, 8/16-bit or float, single- or multi-channel |
| Technique | GPU ray marching (front-to-back compositing) |
| Typical use | CT/MRI/MRT scans, scientific fields, fog / clouds / smoke |
uses
Gorilla.Volumetric.Mesh,
Gorilla.Controller.Passes.Face;
var Vol := TGorillaVolumetricMesh.Create(GorillaViewport1);
Vol.Parent := GorillaViewport1;
Vol.SetSize(1, 1, 1);
Ray marching needs the ray entry and exit positions per pixel. The volumetric mesh obtains them from two pre-render passes that render the surrounding box's front and back faces into position textures. A volumetric mesh will not render without them.
uses Gorilla.Controller.Passes.Face;
// Front face pass = ray entry points
FFrontFace := TGorillaRenderPassFace.Create(GorillaViewport1, 'FrontFace');
FFrontFace.FaceKind := TFaceKind.FrontFace;
FFrontFace.Viewport := GorillaViewport1;
FFrontFace.Enabled := True;
// Back face pass = ray exit points
FBackFace := TGorillaRenderPassFace.Create(GorillaViewport1, 'BackFace');
FBackFace.FaceKind := TFaceKind.BackFace;
FBackFace.Viewport := GorillaViewport1;
FBackFace.Enabled := True;
// Assign them to the volume and allow the passes to render it
Vol.FrontFaceRenderPass := FFrontFace;
Vol.BackFaceRenderPass := FBackFace;
FFrontFace.AllowControl(Vol);
FBackFace.AllowControl(Vol);
You can share the same two passes across several volumes in the scene.
The volume texture is filled from raw binary data. Wrap size/type changes in BeginUpdate / EndUpdate so the texture is only rebuilt once.
Vol.BeginUpdate;
try
Vol.Sizes := TGorillaVolumetricMeshSize.vms256x256x256;
Vol.DataType := TGorillaVolumetricMeshDataType.vmdtUInt8;
finally
Vol.EndUpdate;
end;
Vol.LoadFromRawFile('teapot.raw', 256, 256, 178,
TGorillaVolumetricMeshDataType.vmdtUInt8);
NRRD headers carry size, spacing and data type, so no extra parameters are needed:
Vol.LoadFromNRRDFile('skull.nrrd');
Assemble a volume from a numbered sequence of 2D images (e.g. slice_000.jpg … slice_255.jpg):
Vol.LoadFromImageSlices('scans\', 'slice_%s.jpg',
0, 255, // from / to index
3, '0', // pad the index to 3 digits with '0'
256, 256, 256 // target texture width / height / depth
);
Push your own buffer directly. The data layout must match Sizes and DataType:
Vol.SetRawData(MyBufferPtr, MyBufferSizeInBytes);
Sizes selects a fixed cubic resolution; use vmsCustom together with CustomWidth/CustomHeight/CustomDepth (or CustomSize) for non-cubic volumes.
TGorillaVolumetricMeshSize |
Resolution |
|---|---|
vms4x4x4 … vms1024x1024x1024 |
4³ … 1024³ |
vmsCustom |
Use CustomWidth / CustomHeight / CustomDepth |
DataType describes one voxel:
TGorillaVolumetricMeshDataType |
Bytes / voxel | Notes |
|---|---|---|
vmdtUInt8 |
1 | 8-bit unsigned (most CT/MRI raw data) |
vmdtUInt16 |
2 | 16-bit unsigned |
vmdtHalfFloat |
2 | 16-bit float, filterable |
vmdtFloat |
4 | 32-bit float |
vmdtRGBUInt8 / vmdtRGBAUInt8 |
3 / 4 | color volumes |
vmdtRGBFloat / vmdtRGBAFloat |
12 / 16 | float color volumes |
Tip: enable
LinearFilteringfor smooth trilinear interpolation between voxels. With it off, integer textures are point-sampled and every voxel shows as a hard cube.
The mesh composites samples along each ray. Two blend models are available, and choosing the right one is the single most important decision:
The default front-to-back blend saturates: dense data becomes opaque and forms a surface. Combined with lighting this gives a solid, shaded object (e.g. a CT scan of a skull or teapot).
Vol.SetLinearBlend; // this is the default; call it only to switch back
Vol.UseLighting := True;
For a medium you look through, use the physically based Beer-Lambert blend. Its per-step opacity is exponential in the optical density, so it accumulates smoothly and never hard-saturates into a shell (which would show up as concentric "onion-ring" step banding from inside a dense body).
Vol.SetEmissionAbsorptionBlend(1.0); // 1.0 = neutral, resolution-independent
AAbsorptionScale controls opacity and is internally normalized by the volume resolution, so 1.0 looks comparable on a 64³ and a 256³ volume. Raise it for a denser medium, lower it for a thinner one.
Rule of thumb:
- Solid, lit object → linear blend (default).
- Fog / cloud / smoke / any see-through medium →
SetEmissionAbsorptionBlend.Using the emission-absorption blend on a solid object makes it translucent (you lose the surface); using the linear blend on a dense medium produces hard saturation terraces.
With UseLighting := True the ray marcher detects the first voxel that crosses IsoSurfaceLimit, computes a surface normal from the volume gradient, and shades it with the selected ShadingModel. The surface hit is refined to sub-sample precision automatically, so lit iso-surfaces stay smooth instead of terracing at the discrete ray steps.
Vol.UseLighting := True;
Vol.IsoSurfaceLimit := 0.15; // threshold that defines "the surface"
Vol.ShadingModel := TGorillaShadingModel.smBlinnPhong;
Vol.ShadingIntensity := 1.0;
Vol.Brightness := 1.0;
Iso-surface lighting is a surface model — it is intended for solid objects with the linear blend, not for fog/clouds (a homogeneous medium has no iso-surface, so the normal falls back to the cube face). See Volumetric Noise for the correct fog/cloud model.
A gamut texture maps scalar voxel values to colors — the classic transfer function for medical visualization. Assign a 1D gradient bitmap and choose how it is applied:
Vol.Gamut.LoadFromFile('gamut.png');
Vol.GamutMode := TGorillaVolumetricGamutMode.GamutBySum;
Vol.GamutFactor := 0.75;
Vol.GamutIntensity := 1.0; // RGB contribution
Vol.GamutAlphaIntensity := 1.0; // alpha contribution
TGorillaVolumetricGamutMode |
Meaning |
|---|---|
GamutNone |
disabled |
GamutByValue |
color by each sampled value |
GamutByValueMultiply |
as above, multiplied with the original value |
GamutBySum |
color the final ray-traced value |
GamutBySumMultiply |
as above, multiplied with the original value |
| Property | Effect |
|---|---|
Details |
Ray-march step density (steps ≈ Slices × Details). Higher = finer, smoother, slower. |
Dithering |
Per-pixel ray-start jitter that breaks step banding into fine noise (default True). |
RayStop |
Alpha value at which a ray terminates early (default 0.95). Raise toward 0.99 for fewer hard terminations. |
LinearFiltering |
Trilinear filtering of the 3D texture (smooth vs. blocky). |
MipMaps |
Mip-map minification (can introduce "lines" with linear filtering). |
TextureInterpolation |
Sampling of the front/back-face position textures. |
Detailsis the main quality/performance dial.1–2is a good range for medical data; higher only when you zoom in close.
// Slice the volume with a clipping plane
Vol.ClippingPlane := TPlaneF.Create(0, 0, -1, -0.2);
// Skip a front offset (X) and shorten the back (Y) of every ray
Vol.RayLimits := Point(2, 4);
IntensityMode / AlphaIntensityMode (TRayCastDistanceMethod) modulate the sampled value or alpha along the ray — for example to fade far samples (rcdInvLinear) or focus on a band (rcdFocused with IntensityFocus / IntensityExp). RayIntensityTexture / RayAlphaIntensityTexture drive these from a 1D texture when the mode is rcdTexture.
To move the camera into the volume (essential for fog / clouds), enable two-sided rendering:
Vol.RenderInside := True;
The ray marcher then restarts the ray at the camera position while it is inside the box, and the medium correctly composites over the scene. This costs performance (both faces are rasterized), so leave it off for solid objects you only look at from outside.
Sizes / DataType changes in BeginUpdate / EndUpdate.UseLighting. Translucent medium → SetEmissionAbsorptionBlend.LinearFiltering for smooth interpolation; keep Dithering on to hide step banding.Details to trade quality vs. performance; start low and raise only when needed.TGorillaVolumetricNoise is a ready-to-use cloud / smoke / fog body. It is a subclass of TGorillaVolumetricMesh that fills its own 3D texture with fractal (FBM) Perlin noise and renders it as a physically based emission-absorption medium you can also fly through.
You get a believable volumetric cloud from a handful of properties — no data files, no shader code.
Like any volumetric mesh, it needs the front/back face passes (see the Volumetric Mesh guide). After that, a cloud is three lines:
uses
Gorilla.Volumetric.Noise,
Gorilla.Controller.Passes.Face;
var Cloud := TGorillaVolumetricNoise.Create(GorillaViewport1);
Cloud.Parent := GorillaViewport1;
Cloud.SetSize(1, 1, 1);
// face passes (see the Volumetric Mesh guide)
Cloud.FrontFaceRenderPass := FFrontFace;
Cloud.BackFaceRenderPass := FBackFace;
FFrontFace.AllowControl(Cloud);
FBackFace.AllowControl(Cloud);
Cloud.ApplyPreset(vnpClouds); // done — a puffy cloud
The component already sets sensible defaults in its constructor: 64³ resolution, RenderInside := True (so you can fly through it), lighting off (fog is an emission-absorption medium, not a lit surface) and the emission-absorption blend.
ApplyPreset loads a complete set of shaping parameters. You can still fine-tune individual properties afterwards.
TGorillaVolumetricNoisePreset |
Look |
|---|---|
vnpClouds |
Puffy cumulus clouds (billowy noise, rounded blob, medium coverage). Default. |
vnpSmoke |
Denser, more filled smoke body — good base for animated smoke. |
vnpFog |
Thin, evenly distributed haze (smooth noise, low density, little edge fade). |
Cloud.ApplyPreset(vnpSmoke);
Cloud.Density := 2.0; // then tweak to taste
All shaping properties rebuild the 3D texture automatically when changed.
| Property | Type | Description |
|---|---|---|
Frequency |
Single |
Base noise scale — how many noise cycles span the volume. Higher = smaller, more numerous features. |
Octaves |
Integer |
Number of FBM octaves summed for detail. More = finer wisps, slower to generate. |
Persistence |
Single |
Amplitude falloff per octave (0–1). Lower = smoother, higher = rougher. |
Lacunarity |
Single |
Frequency growth per octave (usually ~2.0). |
Coverage |
Single |
Cloud coverage 0–1. 1 keeps the whole body; lower values carve it into separate puffs. |
EdgeFalloff |
Single |
Border fade 0–1. Fades density toward the volume border so the body is a rounded blob, not a filled cube. |
Billowy |
Boolean |
Use abs() noise for the puffy cauliflower cumulus / smoke look (default True). Off = smooth haze. |
Density |
Single |
Overall opacity of the medium (see below). |
Seed |
LongWord |
Random seed of the underlying Perlin generator. |
Cloud.Frequency := 3.0;
Cloud.Octaves := 5;
Cloud.Coverage := 0.6; // fewer, more separated puffs
Cloud.EdgeFalloff := 0.6; // softer border
Cloud.Billowy := True;
Density is not baked into the voxel data — it is the absorption strength of the physically based Beer-Lambert blend, applied at render time. This is what keeps a dense cloud smooth instead of forming hard saturation "shells" / step terraces when you look at it from inside.
Cloud.Density := 2.5; // denser, still smooth
Because Density only rebuilds the (cheap) blend function and not the volume data, it is safe to change every frame — you can even animate it.
The absorption is resolution-independent: a cloud at
vms32x32x32looks comparably dense to one atvms64x64x64for the sameDensity.
RenderInside is True by default, so the camera can move inside the cloud and the medium composites correctly over the rest of the scene. Nothing extra to do — just move the camera in.
Advance Offset over time and call Regenerate to make the noise drift like moving smoke:
procedure TForm1.OnAnimationTick(Sender: TObject);
begin
FCloud.Offset := FCloud.Offset + Point3D(0, 0.02, 0.05);
FCloud.Regenerate; // re-samples the volume, uploads the new data
end;
Regenerate re-samples the whole volume on the CPU, so it is the expensive part of animation. To keep it affordable:
Cloud.Sizes := vms32x32x32).Density (opacity) is cheap and does not require Regenerate.The density stored per voxel is built as:
Octaves of Perlin noise summed with Persistence and Lacunarity, base scale Frequency. Billowy uses abs(noise).The stored voxel value is a smooth 0..1 gradient. Opacity comes at render time from the emission-absorption blend scaled by Density. This separation (gradient data + render-time absorption) is what removes the terracing artifacts that a naïve "bake density into the data + linear blend" approach produces.
Coverage, EdgeFalloff and Density.Density controls opacity cheaply and safely (no volume rebuild) — use it as your main dial.vms32x32x32 and update on a timer, not every frame; the GPU render stays cheap, only the CPU re-sampling is costly.RenderInside on for fly-through fog; keep UseLighting off (a cloud has no lit surface — lit clouds need light-marching, a separate feature).The Gorilla3D render pass system provides a flexible multi-pass rendering pipeline for applying advanced visual effects to your 3D scene. Each render pass operates on the scene or on previously rendered textures, producing output that can be chained into subsequent passes.
All render passes inherit from TGorillaRenderPassController, which manages FBO (Frame Buffer Object) allocation, shader compilation, and integration with the viewport's rendering loop. Passes are categorized into two types:
TRenderPassType.Pre) -- Execute before the main scene render. They typically re-render scene objects into an off-screen buffer (e.g., shadow maps, reflections, environment maps, voxelization).TRenderPassType.Post) -- Execute after the main scene render. They read the rendered image and apply full-screen effects (e.g., FXAA, bokeh, SSAO compositing, underwater).Passes use two rendering strategies:
Unit: Gorilla.Controller.Passes.FXAA
Class: TGorillaRenderPassFXAA
Type: Post-pass, RectToFBO, 1 iteration
FXAA (Fast Approximate Anti-Aliasing) smooths jagged edges in the final rendered image using a luminance-based edge detection algorithm. It operates as an internal render pass and is typically managed by the deferred composite system.
| Method | Description |
|---|---|
SetCompositeInputTexture |
Assigns the input texture from the composite pass |
GetFinalOutputTexture |
Returns the anti-aliased output texture |
var
LPass: TGorillaRenderPassFXAA;
begin
LPass := TGorillaRenderPassFXAA.Create(nil);
LPass.Viewport := GorillaViewport1;
LPass.Enabled := True;
end;
Note: FXAA is typically activated automatically when using the deferred rendering pipeline. Manual setup is rarely needed.
Unit: Gorilla.Controller.Passes.SMStoreDepth
Class: TGorillaRenderPassSMStoreDepth
Type: Pre-pass, RenderListToFBO
Renders the scene depth from a light's perspective into a shadow map texture. The viewport size defaults to 1024x1024 with OverwriteViewportSize = True.
| Property | Type | Default | Description |
|---|---|---|---|
Light |
TLight |
nil | The light source for shadow projection |
| Property | Type | Default | Description |
|---|---|---|---|
DepthMethod |
TDepthMethod |
dmDefault |
Depth calculation method: dmDefault, dmMVPPosZ, dmModelViewPosZ |
| Property | Type | Description |
|---|---|---|
MapSize |
Integer |
Shadow map resolution |
BiasMatrix |
TMatrix3D |
Light-space bias matrix for shadow lookup |
DefaultDepth |
Single |
Default depth value for clear |
Unit: Gorilla.Controller.Passes.VSMStoreDepth
Class: TGorillaRenderPassVSMStoreDepth
Type: Pre-pass, RenderListToFBO
Stores both depth and depth-squared (moments) into an RG16F texture, enabling soft shadow edges through variance-based filtering. The shader computes moment1 = depth and moment2 = depth * depth with a partial derivative bias.
| Property | Type | Default | Description |
|---|---|---|---|
Light |
TLight |
nil | The light source for shadow projection |
Unit: Gorilla.Controller.Passes.VSMBlur
Class: TGorillaRenderPassVSMBlur
Type: Pre-pass, RectToFBO, PingPong mode, 2 iterations
Blurs the variance shadow map to produce soft shadow edges. Uses ping-pong rendering between two FBOs with a default blur amount of 5.
| Property | Type | Description |
|---|---|---|
VSMStoreDepth |
TGorillaRenderPassVSMStoreDepth |
The VSM depth pass to blur (via GetInputPass/SetInputPass) |
Unit: Gorilla.Controller.Passes.ScreenSpaceShadows
Class: TGorillaRenderPassScreenSpaceShadows
Type: Post-pass, RectToFBO, internal render pass
Computes shadows in screen space using ray marching from each pixel toward each light source. Supports up to 8 lights via a Uniform Buffer Object (UBO).
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TGorillaRenderPassController |
nil | Position G-buffer input |
Normals |
TGorillaRenderPassController |
nil | Normals G-buffer input |
ShadowStrength |
Single |
4.0 | Shadow intensity multiplier |
NumSamples |
Integer |
32 | Number of ray march samples |
SampleStep |
Single |
0.1 | Step size for ray marching |
Unit: Gorilla.Controller.Passes.SSAO
Class: TGorillaRenderPassSSAO
Type: Post-pass, RectToFBO, internal render pass
Computes ambient occlusion in screen space using a 128-sample hemisphere kernel and a 4x4 noise texture for randomized sampling. Transfers kernel data efficiently via a UBO (SSAOShaderData).
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TGorillaRenderPassController |
nil | Position G-buffer input |
Normals |
TGorillaRenderPassController |
nil | Normals G-buffer input |
Radius |
Single |
1.0 | Sampling hemisphere radius |
Bias |
Single |
0.5 | Depth comparison bias |
NoiseScale |
TPointF |
(1, 1) | Noise texture tiling scale |
var
LPass: TGorillaRenderPassSSAO;
begin
LPass := TGorillaRenderPassSSAO.Create(nil);
LPass.Viewport := GorillaViewport1;
LPass.Position := MyPositionPass;
LPass.Normals := MyNormalsPass;
LPass.Radius := 1.5;
LPass.Bias := 0.25;
LPass.Enabled := True;
end;
Note: The unit also defines
TGorillaRenderPassEmbeddedSSAO, which is the variant used internally by the deferred composite system.
Unit: Gorilla.Controller.Passes.Voxelize
Class: TGorillaRenderPassVoxelize
Type: Pre-pass, RenderListToFBO
Converts scene geometry into a 3D voxel texture for use in voxel cone tracing. Generates 6 LOD levels and supports up to 8 lights (VOXEL_MAX_LIGHTS = 8).
| Property | Type | Default | Description |
|---|---|---|---|
VoxelSize |
Integer |
-- | Voxel grid resolution (32..512, multiples of 32) |
FocalLength |
Single |
-- | Focal length for voxel projection |
| Property | Type | Description |
|---|---|---|
VoxelCenter |
TPoint3D |
Center of the voxel grid |
BiasMatrix |
TMatrix3D |
Voxel-space transformation matrix |
GetTexture3D |
Function | Returns the 3D voxel texture |
The unit also defines
TGorillaRenderPassEmbeddedVoxelizefor internal use by the deferred pipeline.
Unit: Gorilla.Controller.Passes.GlobalIllumination
Class: TGorillaRenderPassGlobalIllum
Type: Post-pass, RectToFBO, internal render pass
Computes indirect lighting using voxel cone tracing. Traces shadow cones, reflection cones, and light scattering cones through the voxelized scene. Supports up to 8 lights via UBO.
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TGorillaRenderPassController |
nil | Position G-buffer input |
Normals |
TGorillaRenderPassController |
nil | Normals G-buffer input |
VoxelGeometry |
TGorillaRenderPassController |
nil | Voxelization pass providing 3D texture |
ShadowStrength |
Single |
0.4 | Indirect shadow intensity |
ReflectionStrength |
Single |
0.0 | Indirect reflection intensity |
The unit also defines
TGorillaRenderPassEmbeddedGlobalIllumfor internal deferred pipeline use.
Unit: Gorilla.Controller.Passes.GlobalIllumBlur
Class: TGorillaRenderPassGlobalIllumBlur
Type: Post-pass, extends TGorillaRenderPassBlur, internal render pass
Blurs the global illumination output to reduce noise. Default blur amount is 1.
| Property | Type | Description |
|---|---|---|
GlobalIllumPass |
TGorillaRenderPassGlobalIllum |
The GI pass to blur |
UpdateTexture |
Method | Updates the input texture reference |
Unit: Gorilla.Controller.Passes.Reflection
Class: TGorillaRenderPassReflection
Type: Pre-pass, RenderListToFBO
Renders a mirrored view of the scene for planar reflective surfaces. Uses a mirror matrix computed via ray-plane intersection, with clip planes to prevent rendering below the mirror surface.
| Property | Type | Default | Description |
|---|---|---|---|
Camera |
TCamera |
nil | Scene camera |
Target |
TControl3D |
nil | Object to exclude from reflection (the mirror itself) |
MirrorPosition |
TPoint3D |
(0,0,0) | Position of the mirror plane |
MirrorNormal |
TPoint3D |
(0,-1,0) | Normal vector of the mirror plane |
MirrorSize |
Single |
10 | Size of the mirror surface |
var
LReflection: TGorillaRenderPassReflection;
begin
LReflection := TGorillaRenderPassReflection.Create(nil);
LReflection.Viewport := GorillaViewport1;
LReflection.Camera := Camera1;
LReflection.Target := MirrorPlane1;
LReflection.MirrorPosition := Point3D(0, 0, 0);
LReflection.MirrorNormal := Point3D(0, -1, 0);
LReflection.MirrorSize := 15;
LReflection.Enabled := True;
end;
Unit: Gorilla.Controller.Passes.Refraction
Class: TGorillaRenderPassRefraction
Type: Pre-pass, RenderListToFBO
Renders the scene as seen through a refractive surface, using clip planes to render only geometry on one side of the surface.
| Property | Type | Default | Description |
|---|---|---|---|
SurfacePosition |
TPoint3D |
(0,0,0) | Position of the refractive surface |
SurfaceNormal |
TPoint3D |
(0,1,0) | Normal of the refractive surface |
SurfaceCutOff |
Single |
0 | Cut-off distance for clipping |
ClippingEnabled |
Boolean |
True | Enable/disable clip plane |
| Property | Type | Description |
|---|---|---|
OutputDepthTexture |
Texture | Depth texture output for refraction calculations |
Unit: Gorilla.Controller.Passes.Environment
Class: TGorillaRenderPassEnvironment
Type: Pre-pass, RenderListToFBO, 6 iterations (one per cube face)
Renders the scene into a 6-face cubemap texture for environment reflections. Each face is rendered from the environment position looking in the corresponding axis direction.
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TPoint3D |
-- | Center position for environment capture |
IsDynamic |
Boolean |
False | Re-render every frame if True |
Target |
TControl3D |
nil | Object to exclude from environment |
UseEmbeddedLight |
Boolean |
True | Use built-in light for environment rendering |
CenterOffsetFront |
Single |
-- | Per-face offset for front |
CenterOffsetBack |
Single |
-- | Per-face offset for back |
CenterOffsetLeft |
Single |
-- | Per-face offset for left |
CenterOffsetRight |
Single |
-- | Per-face offset for right |
CenterOffsetTop |
Single |
-- | Per-face offset for top |
CenterOffsetBottom |
Single |
-- | Per-face offset for bottom |
| Property | Type | Description |
|---|---|---|
Camera |
TCamera |
Internal camera used for rendering |
EmbeddedLight |
TLight |
Built-in light for environment |
MapSize |
Integer |
Cubemap face resolution (default 128) |
CubeMap |
Texture | The generated cubemap texture |
| Method | Description |
|---|---|
InvalidateEnvironment |
Forces re-rendering of the cubemap |
SetCenterOffsets(AValue) |
Sets all 6 face offsets to the same value |
SetCenterOffsets(F,B,L,R,T,Bo) |
Sets each face offset individually |
var
LEnvMap: TGorillaRenderPassEnvironment;
begin
LEnvMap := TGorillaRenderPassEnvironment.Create(nil);
LEnvMap.Viewport := GorillaViewport1;
LEnvMap.Position := Point3D(0, 2, 0);
LEnvMap.IsDynamic := False;
LEnvMap.Target := ReflectiveSphere1;
LEnvMap.Enabled := True;
end;
Unit: Gorilla.Controller.Passes.Bokeh
Class: TGorillaRenderPassBokeh
Type: Post-pass, RectToFBO
Simulates camera depth of field with bokeh blur shapes. Supports pentagon-shaped bokeh, chromatic aberration, vignetting, and auto-focus. Requires a depth pass as input.
| Property | Type | Default | Description |
|---|---|---|---|
FocalDepth |
Single |
10 | Distance to the focal plane |
FocalLength |
Single |
75 | Lens focal length |
Vignette |
Single |
16 | Vignette intensity |
VignetteFade |
Single |
24 | Vignette fade distance |
FrustumNearFar |
TPointF |
(1, 100) | Camera frustum near/far planes |
BlurSamples |
Integer |
4 | Blur sample count (clamped 1..16) |
BlurRings |
Integer |
4 | Blur ring count (clamped 1..16) |
ShowFocus |
Boolean |
False | Visualize the focus plane |
AutoFocus |
Boolean |
True | Auto-focus on center of screen |
BokehType |
TGorillaBokehType |
btDefault |
Bokeh style: btDefault, btGlow |
Unit: Gorilla.Bokeh
A design-time convenience component that wraps TGorillaRenderPassCustomDepth and TGorillaRenderPassBokeh together. Drop it onto a viewport to enable depth of field.
var
LBokeh: TGorillaBokeh;
begin
LBokeh := TGorillaBokeh.Create(GorillaViewport1);
LBokeh.Viewport := GorillaViewport1;
LBokeh.FocalDepth := 15;
LBokeh.FocalLength := 50;
LBokeh.BlurSamples := 6;
LBokeh.BlurRings := 6;
LBokeh.AutoFocus := True;
LBokeh.Enabled := True;
end;
Unit: Gorilla.Controller.Passes.CustomBlur
Class: TGorillaRenderPassBlur
Type: Post-pass, RectToFBO
Base class for all blur render passes. Supports multiple blur algorithms and ping-pong rendering for iterative blurring.
| Property | Type | Default | Description |
|---|---|---|---|
BlurType |
TPassBlurType |
-- | Blur algorithm: RadialBlur, FastBlur, GaussianBlur |
BlurMode |
TPassBlurMode |
-- | Direction: Horizontal, Vertical |
BlurAmount |
Single |
-- | Blur strength |
Exposure |
Single |
-- | Exposure adjustment |
Note:
FastBlurmay produce unexpected artefacts on some NVIDIA GPUs.
Unit: Gorilla.Controller.Passes.EmissiveBlur
Class: TGorillaRenderPassEmissiveBlur
Type: Extends TGorillaRenderPassBlur, internal render pass
Blurs the emissive channel from the deferred rendering G-buffer to produce bloom/glow effects.
| Property | Type | Description |
|---|---|---|
EmissiveTexture |
Texture | The emissive G-buffer texture to blur |
Unit: Gorilla.Controller.Passes.PostFX
Class: TGorillaRenderPassPostFX
Type: Post-pass, RectToFBO
Allows custom GLSL post-processing shaders. You provide a surface shader function that processes each fragment. The pass provides access to G-buffer textures and time information via a UBO.
| Property | Type | Default | Description |
|---|---|---|---|
SurfaceShader |
TStrings |
nil | Custom GLSL shader code |
MaskTexture |
TBitmap |
nil | Optional mask texture |
| Uniform | Description |
|---|---|
_RenderedTexture |
The main rendered scene texture |
_MaskTexture |
User-supplied mask texture |
_AlphaTexture |
Alpha G-buffer channel |
_PositionTexture |
Position G-buffer channel |
_NormalsTexture |
Normals G-buffer channel |
_EmissiveTexture |
Emissive G-buffer channel |
The _TimeInfo vec4 uniform provides:
X = start time (always 0)Y = current time in seconds, relative to the start (pass creation or ResetTime)Z = previous frame timeW = delta timeYour custom shader must implement:
vec3 SurfaceShader(inout TLocals DATA)
| Method | Description |
|---|---|
ResetTime |
Restarts the internal time counter (all _TimeInfo values start at 0 again) |
UpdateShader |
Recompiles the shader after changing SurfaceShader |
var
LPostFX: TGorillaRenderPassPostFX;
begin
LPostFX := TGorillaRenderPassPostFX.Create(nil);
LPostFX.Viewport := GorillaViewport1;
LPostFX.SurfaceShader.Text :=
'vec3 SurfaceShader(inout TLocals DATA) {' + sLineBreak +
' vec3 col = DATA.Color.rgb;' + sLineBreak +
' float gray = dot(col, vec3(0.299, 0.587, 0.114));' + sLineBreak +
' return vec3(gray);' + sLineBreak +
'}';
LPostFX.UpdateShader;
LPostFX.Enabled := True;
end;
Unit: Gorilla.Controller.Passes.Underwater
Class: TGorillaRenderPassUnderwater
Type: Post-pass, RectToFBO
A procedural underwater visual effect using ray marching and caustics simulation with time-based animation. Reads the position G-buffer from the deferred composite to determine which fragments are below the water surface (Y < 0).
Unit: Gorilla.Controller.Passes.Composite
Class: TGorillaRenderPassComposite
Type: Post-pass, RectToFBO
Combines two render pass outputs using a configurable blending method.
| Property | Type | Default | Description |
|---|---|---|---|
Method |
TCompositeMethod |
-- | Blend operation: Add, Subtract, Multiply, Divide, Mix, Input1, Input2 |
BlendFactor |
Single |
-- | Blending factor for Mix method |
| Method | Description |
|---|---|
SetInput2Pass |
Assigns the second input render pass |
Unit: Gorilla.Controller.Passes.Deferred.Composite
Class: TGorillaRenderPassDeferredComposite
Type: Post-pass
The central compositing pass for the deferred rendering pipeline. Combines all G-buffer channels (albedo, position, normals, emissive, etc.) with lighting, shadows, SSAO, global illumination, and other effects into the final image.
| Constant | Value | Description |
|---|---|---|
ALL |
$00 | All layers |
ALBEDO |
$01 | Opaque albedo |
TRANSLUCENT_ALBEDO |
$02 | Translucent albedo |
ALPHA |
$04 | Alpha channel |
DEPTH |
$08 | Depth buffer |
POSITION |
$10 | World-space position |
NORMAL |
$20 | World-space normals |
EMISSIVE |
$40 | Emissive channel |
COMPS |
$80 | Components channel |
AMBIENT |
$100 | Ambient channel |
SPECULAR |
$200 | Specular channel |
SSS |
$1000 | Subsurface scattering |
SSAO |
$2000 | SSAO |
| Property | Description |
|---|---|
AlbedoTexture |
Opaque albedo G-buffer |
TranslucentAlbedoTexture |
Translucent albedo G-buffer |
AlphaTexture |
Alpha G-buffer |
PositionTexture |
Position G-buffer |
NormalsTexture |
Normals G-buffer |
EmissiveTexture |
Emissive G-buffer |
SSSTexture |
Subsurface scattering G-buffer |
SSAOTexture |
SSAO G-buffer |
ComponentsTexture |
Material components G-buffer |
AmbientTexture |
Ambient lighting G-buffer |
SpecularTexture |
Specular lighting G-buffer |
| Property | Type | Description |
|---|---|---|
Saturation |
TPoint3D |
Saturation: X=opaque, Y=translucent, Z=composite |
EmissiveBlur |
-- | Emissive bloom blur control |
GlobalFlags |
-- | Global rendering flags |
SSSFlags |
-- | Subsurface scattering flags |
SSAOFlags |
-- | SSAO flags |
SSRFlags |
-- | Screen-space reflection flags |
The Gorilla3D Dialogue System provides a multi-level, event-driven dialogue framework for building interactive conversations in games. It supports branching dialogues with questions, answers, flow nodes, character definitions, timed events, and full serialization to JSON.
| Class | Description |
|---|---|
TGorillaDialogueSystem |
Main component managing dialogues and characters |
TGorillaDialogue |
A single dialogue (conversation) |
TGorillaDialogueItem |
A node in the dialogue tree (question, answer, or flow) |
TGorillaDialogueItemEvent |
An event attached to a dialogue item |
TGorillaDialogueCharacter |
A character participating in dialogues |
| Kind | Description |
|---|---|
Question |
A decision point — displays text and waits for player choice |
Answer |
An option the player can select |
Flow |
A chain element connecting questions and answers |
Reference |
A redirect to another dialogue item |
Events can be attached to dialogue items and triggered at specific moments:
| Kind | Description |
|---|---|
Text |
Display text on screen |
Image |
Show an image |
Audio |
Play an audio file |
Video |
Play a video |
Animation |
Start an animation |
Method |
Execute a published method via RTTI |
ObjProperty |
Set an object property |
Redirect |
Jump to another item |
Timer |
Start a timeout counter |
Misc |
Custom user-defined event |
| Trigger | Description |
|---|---|
OnBegin |
Executed when the item is displayed |
OnEnd |
Executed when the item is hidden |
OnTimeout |
Executed when a timer expires |
TGorillaDialogueSystem onto your formvar
DlgSys: TGorillaDialogueSystem;
begin
DlgSys := TGorillaDialogueSystem.Create(Self);
// Load a dialogue from file
// Use Gorilla.Utils.Dialogue.Reader to load JSON files
end;
A typical dialogue tree looks like this:
Dialogue: "Guard Conversation"
├── Question: "What do you want?"
│ ├── Answer: "I need to pass" → Flow → Question: "Do you have a permit?"
│ │ ├── Answer: "Yes" → [end]
│ │ └── Answer: "No" → [redirect to start]
│ └── Answer: "Nothing, sorry" → [end]
└── Events:
├── OnBegin: Text "A guard approaches you"
└── OnBegin: Audio "guard_greeting.wav"
Each dialogue item can have multiple events:
// Events are configured per item
// Event triggers: OnBegin, OnEnd, OnTimeout
// Event kinds: Text, Image, Audio, Video, Animation, Method, ObjProperty, Redirect, Timer, Misc
The dialogue system supports:
TGorillaDialogueVariables): Store TObject references by name for cross-dialogue stateTGorillaDialogueParameters): Store dynamic key-value pairs for item configurationCharacters represent speakers in the dialogue:
// Characters are managed in the TGorillaDialogueCharacterCollection
// Each character has an identifier and can be linked to dialogue items
| Event | Type | Description |
|---|---|---|
OnStartDialogue |
TOnStartDialogue |
Dialogue begins, provides initial items |
OnStopDialogue |
TOnStopDialogue |
Dialogue ends |
OnPauseDialogue |
TOnPauseDialogue |
Dialogue is paused |
OnBeginDialogueItem |
TOnBeginDialogueItem |
An item is displayed (with available choices) |
OnEndDialogueItem |
TOnEndDialogueItem |
An item is dismissed |
OnBeginItemEvent |
TOnBeginDialogueItemEvent |
An event starts (can set AHandled) |
OnEndItemEvent |
TOnEndDialogueItemEvent |
An event finishes |
OnSkippedDialogue |
TOnSkippedDialogue |
Player skipped dialogue |
OnSkipAvailability |
TOnSkipAvailability |
Notification if skip is available |
OnBeginItemTimeout |
TOnBeginItemTimeout |
Timeout counter starts |
OnEndItemTimeout |
TOnEndItemTimeout |
Timeout expired |
The dialogue system uses JSON for serialization:
Gorilla.Utils.Dialogue.Reader — Loads dialogues from JSONGorilla.Utils.Dialogue.Writer — Saves dialogues to JSONDialogues can also be managed via the Assets Manager as DIALOGUE asset type.
OnTimeout for timed choices (e.g., "respond in 5 seconds")DIALOGUE asset packagesAudio eventsThe Gorilla3D Inventory System provides a flexible, template-based item management framework for games. It supports item groups, templates, collectables, manufacturing/crafting, upgrade/downgrade chains, dependencies, multi-language names, and full XML serialization.
| Class | Description |
|---|---|
TGorillaInventory |
Main inventory component |
TGorillaInventoryGroup |
Category of items (weapons, keys, potions, etc.) |
TGorillaInventoryItemTemplate |
Blueprint/prototype for collectible items |
TGorillaInventoryCollectable |
An actual collected item instance |
TGorillaInventoryManufacturer |
Crafting system for combining items |
TGorillaInventoryManufacturingProcess |
A crafting recipe |
The inventory follows a template-instance pattern:
| State | Description |
|---|---|
None |
No action |
Allowed |
Collection permitted |
Collected |
Successfully collected |
QuantityExceeded |
Max quantity reached |
Disabled |
Item template is disabled |
NotFound |
Template not found |
Missing |
Missing dependency |
uses Gorilla.Utils.Inventory;
var
Inventory: TGorillaInventory;
begin
Inventory := TGorillaInventory.Create(Self);
end;
Groups categorize your items:
// Groups are collections within the inventory
// Example groups: Weapons, Armor, Consumables, Keys, Notes
Templates define what items look like and how they behave:
| Property | Type | Description |
|---|---|---|
Id |
String | Unique identifier |
Name |
TGorillaInventoryLanguageMap | Multi-language display name |
Enabled |
Boolean | Whether the item can be collected |
Group |
TGorillaInventoryGroup | Category |
MaxQuantity |
Integer | Maximum stack size |
Weight |
Single | Item weight |
MaxWeight |
Single | Maximum weight |
IsPooled |
Boolean | Whether instances are pooled |
Parameters |
TGorillaInventoryParameters | Custom key-value parameters |
ImageIndex |
Integer | Index in a TImageList for UI |
UpgradeItem |
TGorillaInventoryItemTemplate | Next tier upgrade |
DowngradeItem |
TGorillaInventoryItemTemplate | Previous tier downgrade |
Dependency |
TGorillaInventoryDependencyList | Required items for collection |
// Templates are prototypes - build collectables from them
var LCollectable := SomeTemplate.Build();
Templates can require other items to be present before collection:
// Add a dependency: need 2x "Key" to collect "Treasure"
TreasureTemplate.AddDependency('Key', 2);
// Create an upgrade chain: Sword → BetterSword → BestSword
SwordTemplate.UpgradeItem := BetterSwordTemplate;
BetterSwordTemplate.UpgradeItem := BestSwordTemplate;
BestSwordTemplate.DowngradeItem := BetterSwordTemplate;
Collectables are instances of templates that represent actual items in the player's inventory:
| Property | Type | Description |
|---|---|---|
Id |
String | Unique identifier |
Name |
TGorillaInventoryLanguageMap | Display name |
Parameters |
TGorillaInventoryParameters | Custom parameters |
Data |
TValue | Runtime data (not serialized) |
The manufacturing system allows combining items:
| Class | Description |
|---|---|
TGorillaInventoryManufacturer |
Contains crafting processes |
TGorillaInventoryManufacturingProcess |
A single recipe |
TGorillaInventoryIngredient |
An ingredient in a recipe |
| State | Description |
|---|---|
Undefined |
Not started |
Processing |
Currently crafting |
Completed |
Crafting finished |
Failed |
Crafting failed |
The inventory system serializes to XML:
// Save to XML
Inventory.ToXml(ParentXmlElement);
// Load from XML
Inventory.FromXml(XmlNode, LoadingCache);
Multi-language support is built-in via TGorillaInventoryLanguageMap — each name can have translations for different languages.
The inventory can also be managed through the Assets Manager as INVENTORY asset type.
Data property is transient — use Parameters for persistent custom dataImageIndex with a TImageList for inventory UI iconsThe Gorilla3D Skill System provides a hierarchical skill tree framework for games. Skills are organized in groups, support leveling with interpolation, async leveling processes, multi-language names, and full XML serialization.
| Class | Description |
|---|---|
TGorillaSkillSystem |
Main component managing skill groups |
TGorillaSkillGroup |
A category of skills |
TGorillaSkill |
A single skill with level, value, and sub-skills |
TGorillaSkillProcess |
An async leveling-up process |
Skills form a hierarchy: Groups contain Skills, and Skills can contain sub-skills (since TGorillaSkill extends TGorillaSkillGroup). This allows building complex skill trees.
SkillSystem
├── Group: "Combat"
│ ├── Skill: "Swordsmanship" (Level 3, Value 1.5)
│ │ ├── Sub-Skill: "Parry" (Level 1)
│ │ └── Sub-Skill: "Riposte" (Level 0, Locked)
│ └── Skill: "Archery" (Level 2, Value 1.2)
└── Group: "Magic"
└── Skill: "Fireball" (Level 5, Value 3.0)
uses Gorilla.Utils.SkillSystem;
var
SkillSys: TGorillaSkillSystem;
begin
SkillSys := TGorillaSkillSystem.Create(Self);
end;
Groups organize skills into categories:
var LGroup := SkillSys.AddGroup(); // creates a TGorillaSkillGroup
LGroup.Name := 'Combat';
LGroup.Enabled := True;
function AddSkill(): TGorillaSkill;
function FindSkillByName(const ASkillName: String): TGorillaSkill;
function FindSkillByGUID(const AGUID: TGUID): TGorillaSkill;
procedure GetActivatedSkills(var AMap: TGorillaSkillMap);
Each skill has these key properties:
| Property | Type | Default | Description |
|---|---|---|---|
Enabled |
Boolean | — | Whether the skill is unlocked |
Activated |
Boolean | False | Whether the skill is currently active |
Value |
Single | 1.0 | Main skill value (used for game effects) |
Factor |
Single | 1.0 | Interpolation factor for level calculations |
Interpolation |
TGorillaSkillLevelInterpolation | Linear | How value scales with level |
Level |
Integer | 0 | Current skill level |
MaxLevel |
Integer | — | Maximum achievable level |
LevelingTime |
Integer | — | Time required to level up (ms) |
Icon |
Integer | — | Index in a TImageList |
Name |
String | — | Display name (current language) |
Names[lang] |
String | — | Multi-language name access |
GUID |
TGUID | auto | Unique identifier |
Position |
TPointF | — | Flow chart position (for editor) |
The value of a skill changes with its level according to the interpolation method:
| Interpolation | Description |
|---|---|
LinearInterpolation |
Value = BaseValue + Level * Factor |
LogarithmicInterpolation |
Logarithmic growth curve |
ExponentialInterpolation |
Exponential growth curve |
ExponentialMinus1Interpolation |
Exponential minus 1 curve |
Skills support asynchronous leveling (e.g., training takes time):
// Start leveling up (targets first sub-skill)
var LProcess := SomeSkill.StartLevelingUp();
// Start leveling toward a specific sub-skill
var LProcess := SomeSkill.StartLevelingUp(TargetSubSkill);
TGorillaSkillProcess manages the async leveling operation.
The system validates skill switching — ensuring that leveling constraints (like required sub-skills being activated) are respected.
Skills serialize to and from XML:
// Save
SkillSys.ToXml(ParentXmlElement);
// Load
SkillSys.FromXml(XmlNode);
The skill system integrates with the Assets Manager as SKILLS asset type.
Enabled := False for locked skills; unlock via game logicActivated to track which skills the player has chosen to useMaxLevel to cap skill progressionLevelingTime for time-gated skill upgradesGUID for reliable cross-references instead of namesGorilla3D includes a grid-based pathfinding system with an A* algorithm implementation. The system supports static and dynamic obstacles, configurable obstacle margins, and integrates with the 3D scene for navigation of characters and NPCs.
| Class | Description |
|---|---|
TGorillaPathfindingAlgorithm |
Abstract base for pathfinding algorithms (obstacle and agent management) |
TGorillaPathfindingAStar |
A* pathfinding implementation (in Gorilla.Utils.Pathfinding.AStar) |
TGorillaPathfindingAStar (or custom algorithm) onto your viewportAgent property to the character/NPC that needs to navigateuses Gorilla.Utils.Pathfinding, Gorilla.Utils.Pathfinding.AStar;
var
Pathfinder: TGorillaPathfindingAStar;
begin
Pathfinder := TGorillaPathfindingAStar.Create(Self);
Pathfinder.Parent := GorillaViewport1;
Pathfinder.Agent := CharacterModel;
end;
Obstacles are 3D controls that block pathfinding. Each obstacle has a bounding box and can be static (optimized) or dynamic (recalculated each query).
// Static obstacle (never moves - better performance)
Pathfinder.AddObstacle(WallMesh, True);
// Dynamic obstacle (moves at runtime)
Pathfinder.AddObstacle(MovingPlatform, False);
// With explicit bounding box
Pathfinder.AddObstacle(SomeObject, CustomBounds, True);
// Remove a specific obstacle
Pathfinder.RemoveObstacle(WallMesh);
// Remove all obstacles
Pathfinder.ClearObstacles();
// Reset computed grid rectangles (force recalculation)
Pathfinder.ResetObstacles();
// Get obstacle count
var Count := Pathfinder.CountObstacles();
Add a buffer zone around obstacles to prevent the agent from clipping:
Pathfinder.ObstacleMargin := Point3D(0.5, 0, 0.5); // half-unit margin on X and Z
| Field | Type | Description |
|---|---|---|
Control |
TControl3D | The visual component acting as obstacle |
IsStatic |
Boolean | If true, bounding box is computed once |
Bounds |
TBoundingBox | Current bounding box |
Computed |
Boolean | Whether grid rect has been calculated |
GridRect |
TRectF | Computed grid coordinates |
Use the OnUpdate event to provide custom bounding boxes:
Pathfinder.OnUpdate := procedure(const AControl: TControl3D; out ABounds: TBoundingBox)
begin
// Return custom bounds for this obstacle
ABounds.Min := Point3D(-1, 0, -1);
ABounds.Max := Point3D(1, 2, 1);
end;
The A* implementation (Gorilla.Utils.Pathfinding.AStar) extends the base algorithm with grid-based pathfinding. It finds the shortest path from the agent's position to a target while avoiding obstacles.
// The pathfinder uses the Agent property to determine the start position
var AgentPos := Pathfinder.AgentPosition; // returns (0,0,0) if no agent set
ResetObstacles() when the scene layout changes significantlyOnUpdate event for obstacles with complex shapes that need custom bounding boxesAutomatic switching between skeletal animations, driven by input or by your own state variables.
Component: TGorillaAnimationController
Unit: Gorilla.Animation.Controller
A character usually consists of one mesh and many animation clips - idle, run,
jump, hit, die. Playing them by hand means calling PlayAnimation() from every
place that can change the character state, and keeping track of which clip is allowed
to follow which.
TGorillaAnimationController replaces that with a small state machine: you declare
transitions ("from clip A to clip B, when X happens"), and afterwards you only
dispatch what happened. The controller decides whether a transition matches the
currently playing clip and performs the switch.
Key features:
A -> B when <condition> instead of scattered playback callsTGorillaPhysicsCharacterController feeds its state in for youTGorillaAnimationController (Model, DefaultAnimation)
└─ Layers : TGorillaAnimationTransitionLayerCollection
└─ TGorillaAnimationTransitionLayer ("Layer0", "Layer1", ...)
└─ Transitions : TGorillaAnimationTransitionCollection
└─ TGorillaAnimationTransition (AnimationFrom -> AnimationTo)
The controller does not own the animations. It works on the TGorillaAnimationManager
of the linked TGorillaModel, and switching means setting
Model.AnimationManager.Current and starting that animation.
A dispatch always runs through every layer, and every layer evaluates against the animation that is current at that moment.
TGorillaModel onto your viewport and load a character into itTGorillaAnimationController onto the formModel property to the model componentDefaultAnimation to the ID of the clip that should play initiallyuses
Gorilla.Animation, Gorilla.Animation.Controller;
const
CHARACTER_MODEL = 'c.dae';
CHARACTER_IDLE = 'c-idle.dae';
CHARACTER_RUN = 'c-run.dae';
procedure TForm1.SetupCharacter();
var
LPckg : TGorillaAssetsPackage;
LPath : String;
LAnim : TGorillaAnimation;
LLay : TGorillaAnimationTransitionLayer;
begin
LPckg := GorillaAssetsManager1.AddEmptyPackage('Cache');
LPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))
+ IncludeTrailingPathDelimiter('assets');
// 1) load the model and the additional animation clips
GorillaModel1.LoadFromFile(LPckg, LPath + CHARACTER_MODEL, []);
LAnim := GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_IDLE, []);
GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_RUN, []);
LAnim.Start();
// 2) link the model, then set the default animation
GorillaAnimationController1.Model := GorillaModel1;
GorillaAnimationController1.DefaultAnimation := CHARACTER_IDLE;
// 3) create a layer and declare the transitions
LLay := GorillaAnimationController1.AddLayer('Layer0');
LLay.AddTransition('idle > run', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
end;
Order matters: assign
ModelbeforeDefaultAnimation. SettingDefaultAnimationresolves the clip through the model's animation manager, makes it the current animation and starts it right away. Without a model the assignment is remembered as a string but nothing is started.
Transitions reference animations by ID, not by object. The ID is the one the
animation manager registered the clip under - for clips added with
AddAnimationFromFile() that is the file name, e.g. c-idle.dae. Declaring the IDs
as constants keeps the transition table readable:
const
MODEL_ANIM_IDLE = 'c-idle.dae';
MODEL_ANIM_HIT1 = 'c-hit1.dae';
References are resolved lazily against Model.AnimationManager. A transition that
names a clip which is not loaded yet stays unresolved and simply never triggers, so
load all clips before (or at least right after) declaring the transitions.
A TGorillaAnimationTransition answers three questions:
| Question | Properties |
|---|---|
| From where to where? | AnimationFrom, AnimationTo |
| When? | DetectionKind plus HotKey / States or Variable / Value |
| How? | Mode, Loop |
TGorillaAnimationTransitionDetectionKind selects what a transition listens to:
| Value | Triggered by | Evaluated properties |
|---|---|---|
tkHotKeyAndStates |
A character controller hotkey plus the active character states | HotKey, States |
tkCustom |
A named variable and its value | Variable, Value |
You do not normally set DetectionKind yourself - the AddTransition() overload you
choose sets it for you.
State matching is a subset test. The transition fires when all states listed in
States are contained in the dispatched state set; the dispatched set may contain
more. States := [] therefore matches any state, and the hotkey alone decides.
Values are compared as strings. Value stores TValue.ToString(), so the integer
1 and the string '1' are the same condition.
TGorillaAnimationTransitionMode defines how the switch happens:
| Mode | Behaviour |
|---|---|
tmImmediatly |
The destination clip becomes current and starts right away, cutting the running clip |
tmSequentially |
The running clip is set to non-looping and plays to its end; the destination clip starts afterwards |
tmBlend |
Reserved for cross-fading. Not implemented yet - currently behaves like tmSequentially |
OffsetAnimationFrom, OffsetAnimationTo and Duration describe the blend window for
tmBlend. They are stored and serialized, but have no effect until blending is
implemented.
The engine does have a crossfade, but it lives on
TGorillaAnimationManagerand is triggered byPlayAnimation(). The controller switches by assigningAnimationManager.Current, which bypasses it. See Animation Playback Control for the blend settings and for a pattern that combines the controller's transition table with crossfading.
Use
tmImmediatlyfor responsive movement (idle and run must react on the same frame) andtmSequentiallywhen a clip must not be interrupted, e.g. a reload or an attack wind-up.
Loop applies to the destination clip:
Loop = true - the destination clip repeats until another transition switches awayLoop = false - the destination clip plays once; when it ends the controller
re-evaluates the transitions (see One-Shot Animations)Both TGorillaAnimationController and TGorillaAnimationTransitionLayer offer
AddTransition(). The controller variant takes the layer name as first argument and
requires the layer to exist already.
// hotkey + states variant
LLay.AddTransition('idle > run', IDLE, RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
// custom variable variant
LLay.AddTransition('idle > hit1', IDLE, HIT1, false,
'anim', 1,
TGorillaAnimationTransitionMode.tmImmediatly);
Transitions can be looked up and removed again:
LTr := GorillaAnimationController1.FindTransition('Layer0', 'idle > run');
LTr := GorillaAnimationController1.FindTransition('Layer0', IDLE, RUN);
GorillaAnimationController1.DeleteTransition('Layer0', 'idle > run');
GorillaAnimationController1.DeleteTransition('Layer0', IDLE, RUN);
A model with a dozen clips produces dozens of transitions. Layers group them so each group stays readable - for example one layer for "starting to move", one for "coming back to rest", one for combat.
LLay := GorillaAnimationController1.AddLayer('Movement');
// ...
if GorillaAnimationController1.LayerExists('Movement') then
GorillaAnimationController1.RemoveLayer('Movement');
AddLayer() returns the existing layer if the name is already in use, so calling it
twice never produces duplicates.
How layers interact: a dispatch is forwarded to every layer in collection order. Each layer looks at the current animation and may switch it - which means a later layer already sees the result of an earlier one. Within a single layer the first matching transition wins and evaluation stops.
Design your layers so that only one of them can match a given situation. In the
physics demo this is done by making the leave transitions depend on
UnknownHotKey + fpIdle, which cannot be true while a movement hotkey is dispatched.
Nothing happens until you dispatch. All four overloads exist on the controller, on a single layer, and on the layer collection:
procedure DispatchInput(ADispatcher : TGorillaAnimationDispatcher); overload;
procedure DispatchInput(AHotKey : TGorillaCharacterControllerHotKey;
AStates : TGorillaCharacterControllerStates); overload;
procedure DispatchInput(AVariable : String; AValue : String); overload;
procedure DispatchInput(AVariable : String; AValue : TValue); overload;
The last dispatch is remembered in the controller's DispatchState property and is
replayed automatically when a one-shot clip ends.
Use this when the trigger is game logic rather than input - a hit, a spell, a phase change:
procedure TForm2.Button2Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 1);
end;
Any TValue-compatible value works; it is compared by its string representation.
Use this when animation should follow character movement:
GorillaAnimationController1.DispatchInput(
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving]);
TGorillaCharacterControllerHotKey and TGorillaCharacterControllerState are declared
in Gorilla.Controller.Input.Types and are the same values a first- or third-person
controller reports.
TGorillaPhysicsCharacterController dispatches for you. Link both components and the
character's movement drives the animations without a single line of playback code:
GorillaPhysicsCharacterController1.Model := GorillaModel1;
GorillaPhysicsCharacterController1.Controller := GorillaThirdPersonController1;
GorillaPhysicsCharacterController1.AnimationController := GorillaAnimationController1;
Every character state change is forwarded as
AnimationController.DispatchInput(AHotKey, AStates). Both Model and
AnimationController must be assigned, otherwise the dispatch is skipped.
A transition with Loop = false and Mode = tmImmediatly starts the destination clip
once. When it finishes, the controller sets that clip back to looping and re-runs the
last dispatch against the transitions. This is how a character returns from a one-shot
clip: you declare the way back with the same condition.
// out: idle -> hit1, plays once
FLayer1.AddTransition('idle > hit1', IDLE, HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
// back: when hit1 has finished, the same dispatch ('anim' = 1) is replayed,
// now with hit1 as current animation - so this one matches and loops idle
FLayer1.AddTransition('hit1 > idle', HIT1, IDLE, true,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
Without the second transition the character would stay in its final hit pose.
In tmSequentially mode the mechanism is different: the running clip is set to
non-looping and the destination starts when it ends, so no replay is needed.
From the AnimationController demo: one rest-pose model plus three clips, switched by a custom variable from two buttons.
const
MODEL_ANIM_NONE = 'c.dae';
MODEL_ANIM_IDLE = 'c-idle.dae';
MODEL_ANIM_HIT1 = 'c-hit1.dae';
MODEL_ANIM_HIT2 = 'c-hit2.dae';
procedure TForm2.FormCreate(Sender: TObject);
var
LPath : String;
LPckg : TGorillaAssetsPackage;
LOpts : TGorillaLoadOptions;
begin
LPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))
+ IncludeTrailingPathDelimiter('assets');
LPckg := GorillaAssetsManager1.AddEmptyPackage('TempPackage');
LOpts := TGorillaLoadOptions.Create(LPath + MODEL_ANIM_NONE, LPckg);
GorillaModel1.LoadFromFile(LOpts);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_IDLE);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_HIT1);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_HIT2);
AddCustomTransitions();
end;
procedure TForm2.AddCustomTransitions();
begin
GorillaAnimationController1.DefaultAnimation := MODEL_ANIM_IDLE;
FLayer1 := GorillaAnimationController1.AddLayer('Layer1');
// hit 1: play once, then return to looping idle
FLayer1.AddTransition('idle > hit1', MODEL_ANIM_IDLE, MODEL_ANIM_HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit1 > idle', MODEL_ANIM_HIT1, MODEL_ANIM_IDLE, true,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
// hit 2: same pattern
FLayer1.AddTransition('idle > hit2', MODEL_ANIM_IDLE, MODEL_ANIM_HIT2, false,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit2 > idle', MODEL_ANIM_HIT2, MODEL_ANIM_IDLE, true,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
// allow interrupting one hit with the other
FLayer1.AddTransition('hit2 > hit1', MODEL_ANIM_HIT2, MODEL_ANIM_HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit1 > hit2', MODEL_ANIM_HIT1, MODEL_ANIM_HIT2, false,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 1);
end;
procedure TForm2.Button3Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 2);
end;
Note the pairs: every out transition (Loop = false) has a matching back
transition using the same variable value, because the value is replayed when the
one-shot clip ends.
The demo links GorillaAnimationController1.Model to GorillaModel1 at design time,
which is why the code never assigns Model itself.
See demos/AnimationController.
From the PhysicsCharacterControllerDemo: no manual dispatch at all - the physics character controller feeds the animation controller, and two layers split "start moving" from "stop moving".
const
CHARACTER_MODEL = 'c.dae';
CHARACTER_IDLE = 'c-idle.dae';
CHARACTER_RUN = 'c-run.dae';
procedure TForm1.DoCreateCharacter();
var
LPath : String;
LAnim : TGorillaAnimation;
LLay : TGorillaAnimationTransitionLayer;
begin
FPackage := GorillaAssetsManager1.AddEmptyPackage('Cache');
LPath := GetAssetsPath();
GorillaModel1.LoadFromFile(FPackage, LPath + CHARACTER_MODEL, []);
LAnim := GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_IDLE, []);
GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_RUN, []);
LAnim.Start();
GorillaAnimationController1.DefaultAnimation := CHARACTER_IDLE;
// layer 0: any movement key while moving -> run
LLay := GorillaAnimationController1.AddLayer('Layer0');
LLay.AddTransition('idle > run-forward', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-backward', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveBackward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-left', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveLeft,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-right', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveRight,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
// layer 1: no key, character idle -> back to idle clip
LLay := GorillaAnimationController1.AddLayer('Layer1');
LLay.AddTransition('run > idle', CHARACTER_RUN, CHARACTER_IDLE, true,
TGorillaCharacterControllerHotKey.UnknownHotKey,
[TGorillaCharacterControllerState.fpIdle],
TGorillaAnimationTransitionMode.tmImmediatly);
end;
The Layer0 transitions cannot fire while the character is idle (no movement hotkey is
dispatched), and the Layer1 transition cannot fire while a movement hotkey is
dispatched - the two layers are mutually exclusive by construction.
The demo declares the Layer1 transition once per movement direction. That is optional:
all four use the identical condition (UnknownHotKey + fpIdle), so a single
transition is enough. As in the other demo, Model and the link from
GorillaPhysicsCharacterController1.AnimationController are set at design time.
See demos/PhysicsCharacterControllerDemo.
The whole setup - linked model, default animation, layers and transitions - serializes to JSON:
GorillaAnimationController1.SaveToFile('character.animctrl');
// ...
GorillaAnimationController1.LoadFromFile('character.animctrl', FPackage);
Stream variants (SaveToStream / LoadFromStream) and the raw JSON level
(ToJSON / FromJSON) are available as well.
On loading, the controller tries to reconnect the model in this order:
TGorillaModel whose Source equals the stored file nameIf the model cannot be restored, or an animation file listed in the JSON is missing, an
exception is raised. Pass a TGorillaAssetsPackage to LoadFromFile / LoadFromStream
so auto-loaded models and textures end up in the package you expect.
With the design package installed, the controller's context menu offers Transition
Editor: a flow-chart view of the layers, the animations they reference and the
transitions between them. The node positions are stored per layer (UIPosition) and
serialized with the rest of the setup, so a hand-arranged graph survives save and load.
Nothing switches at all.
Check in this order: is Model assigned, is DefaultAnimation a valid ID and did it
actually start, are the transition IDs spelled exactly like the registered animation
IDs, and are you dispatching?
A transition only works the first time. A non-looping destination clip needs a way back. Add the reverse transition, see One-Shot Animations.
Transitions added later do not trigger. For hotkey detection, the collection builds an internal lookup map on first use. After adding or changing transitions at runtime, rebuild it:
LLay.Transitions.UpdateHashMap();
FindTransition(<name>) returns nil although the transition exists.
The by-name lookup searches that same map. Call UpdateHashMap() first, or look the
transition up by animation pair with FindTransition(AFrom, ATo), which always scans
the collection.
The wrong transition fires.
Transitions from the same animation with the same hotkey share one lookup bucket and are
tested in collection order - the first one whose states are a subset of the dispatched
states wins. Declare the more specific transition (larger States set) before the
general one.
Enabled = False and it still switches.
The inherited Enabled property does not gate transitions - dispatching works
regardless. Stop feeding dispatches (or clear the layers) if you want to freeze the
state machine.
Two layers fight over the same clip. Remember that layers run in order and each sees the result of the previous one. Make the conditions mutually exclusive.
They are used in the transitions, in DefaultAnimation and in the JSON. A typo in a
string fails silently.
Model then DefaultAnimation then layers and transitions. Every step after the first
resolves references through the model's animation manager.
Movement, combat, emotes. Keep each layer small enough to read at a glance and make the conditions of different layers mutually exclusive.
Loop = false always needs a matching transition back, triggered by the same condition.
tmImmediatly for MovementMovement has to react on the same frame. Reserve tmSequentially for clips that must
play out completely.
tmBlend as tmSequentiallyCross-fading is not implemented yet. Do not rely on OffsetAnimationFrom,
OffsetAnimationTo or Duration having a visible effect.
For player characters, link TGorillaPhysicsCharacterController.AnimationController
instead of dispatching hotkeys by hand.
A dispatch walks all layers. Use a few well-chosen variables rather than one variable per animation.
Version: 1.1 (Bytecode Version: 0x00010001)
Last Updated: December 2025
Copyright: 2017-2025 Eric Berger, gorilla3d.de Gorilla3D Framework
GorillaScript is a scripting language designed for the Gorilla3D Framework that provides a Pascal/Delphi-based syntax with native Delphi interoperability. It is a compiled, bytecode-interpreted language that allows embedding scripting capabilities into Delphi applications.
GorillaScript is designed to provide a balance between performance and flexibility for scripting scenarios within the Gorilla3D Framework.
It prioritizes:
GorillaScript consists of three main components:
Parser (TGorillaScriptParserDelphi)
Gorilla.Script.Parser.Delphi.pasCompiler (TGorillaScriptCompiler)
Gorilla.Script.Compiler.pasExecutor (TGorillaScriptExecutor)
Gorilla.Script.Executor.pasSource Code (.pas)
↓
Parser (Lexer + Syntax Analysis)
↓
Abstract Syntax Tree (AST)
↓
Compiler (Code Generation)
↓
Bytecode Stream
↓
Executor (VM Interpretation)
↓
Execution Result
The TGorillaScriptEngine component orchestrates all scripting activities:
TGorillaScriptLibraryBinderStack:
GORILLA_SCRIPT_MAX_STACKSIZE)TGorillaScriptStackValue containing a reference and TValueCall Stack:
GORILLA_SCRIPT_MAX_CALLSTACK)Heap:
GORILLA_SCRIPT_MAX_HEAPSIZE)GorillaScript uses Pascal/Delphi syntax:
Case Sensitivity: Case-insensitive for keywords and identifiers Comments:
// comment{ comment } or (* comment *){$DEFINE SYMBOL}Statement Terminator: Semicolon (;)
A GorillaScript program follows standard Delphi unit structure:
program Gorilla3DTest;
uses
System.SysUtils, FMX.UI, Gorilla3DTest.App;
procedure Main();
var LApp : TGorillaApp;
begin
// this script is used in keep-alive mode
// the created script object will be destroyed automatically
// when the executor will be destroyed.
LApp := TGorillaApp.Create();
end;
begin
Main();
end.
WARNING: Currently it is necessary to declare at least one global function that needs to be called. At this stage of development the program itself does not have an stack context. Therefor we need to call a global function first.
The included Gorill3DTest.App unit looks like this:
unit Gorilla3DTest.App;
interface
uses
System.SysUtils, System.Math,
FMX.OS, FMX.UI, FMX.Types, FMX.Forms, FMX.StdCtrls, FMX.Objects3D, Gorilla.DefTypes,
Gorilla.Viewport, Gorilla.Camera, Gorilla.Light, Gorilla.Model, Gorilla.Controller.Input,
Gorilla.Material.Lambert, Gorilla.Material.Bumpmap;
const
GORILLA_CAPTION : String = 'Gorilla3D Scripting 3D Demo';
type
TMyClass = class(TObject)
public
Tag : String;
end;
TGorillaApp = class
protected
FWindow : TForm;
FViewport : TGorillaViewport;
FCenter : TControl3D;
FCamera : TGorillaCamera;
FLight : TGorillaLight;
FCube : TGorillaCube;
FSphere : TGorillaSphere;
FPlane : TGorillaPlane;
FModel : TGorillaModel;
FMaterial1 : TGorillaLambertMaterialSource;
FMaterial2 : TGorillaBumpMapMaterialSource;
FTimer : TTimer;
FInput : TGorillaInputController;
FSinCurve : Double;
procedure DoOnKeyUp(ASender : TObject; AKeyCode : Integer);
procedure DoOnTimer(ASender : TObject);
public
property Viewport : TGorillaViewport read FViewport;
property Camera : TGorillaCamera read FCamera;
property Light : TGorillaLight read FLight;
property Cube : TGorillaCube read FCube;
property Sphere : TGorillaSphere read FSphere;
property Plane : TGorillaPlane read FPlane;
property Timer : TTimer read FTimer;
constructor Create(); override;
end;
implementation
constructor TGorillaApp.Create();
var LForm : TForm;
LTexPath : String;
LTest : TMyClass;
LTest2 : TObject;
LOpts : TGorillaLoadOptions;
begin
inherited Create();
LTest := TMyClass.Create() as TObject;
LTest.Tag := 'MyTestClass';
LTest2 := (LTest as TObject);
System.WriteLn(LTest.Tag);
LForm := TUI.GetMainForm();
Self.FSinCurve := 0.0;
Self.FWindow := LForm;
Self.FWindow.Caption := GORILLA_CAPTION;
// create viewport
Self.FViewport := TGorillaViewport.Create(LForm);
Self.FViewport.Parent := LForm;
// create dummy and camera
Self.FCenter := TDummy.Create(Self.FViewport) as TControl3D;
Self.FCenter.Parent := Self.FViewport;
Self.FCamera := TGorillaCamera.Create(Self.FCenter);
Self.FCamera.Parent := Self.FCenter;
Self.FCamera.Target := Self.FCenter;
Self.FCamera.Position.Point := TPoint3D.Create(0, -10, -50);
Self.FViewport.Camera := Self.FCamera;
Self.FViewport.UsingDesignCamera := false;
/// Overloaded native methods are not detectable for the RTTI, therefore we
/// use LoadNewModelFromOptions instead of LoadNewModelFromFile in this
/// demo here.
{ $DEFINE TEST_STRUCT_CALL}
{$IFDEF TEST_STRUCT_CALL}
LOpts := TGorillaLoadOptions.Create('\delphi\projects\wax\lib\gorilla\source\demos\assets\models\suzanne.gltf', nil, nil);
Self.FModel := TGorillaModel.LoadNewModelFromOptions(Self.FViewport, LOpts);
{$ELSE}
// create and load a model from file
Self.FModel := TGorillaModel.LoadNewModelFromFile(Self.FViewport, nil,
'\delphi\projects\wax\lib\gorilla\source\demos\assets\models\suzanne.gltf', []);
{$ENDIF}
Self.FModel.Parent := Self.FViewport;
Self.FModel.Position.Point := TPoint3D.Create(5, -2, 0);
Self.FModel.RotationAngle.X := 180;
Self.FModel.Scale.Point := TPoint3D.Create(2, 2, 2);
// create light source
Self.FLight := TGorillaLight.Create(Self.FViewport);
Self.FLight.Parent := Self.FViewport;
Self.FLight.Position.Point := TPoint3D.Create(0, -20, 0);
Self.FLight.LightType := TLightType.Spot;
Self.FLight.RotationAngle.X := -90;
Self.FLight.SpotExponent := 0.25;
Self.FLight.SpotCutOff := 60;
// create cube and sphere
Self.FCube := TGorillaCube.Create(Self.FViewport);
Self.FCube.Parent := Self.FViewport;
Self.FCube.Scale.Point := TPoint3D.Create(5, 5, 5);
Self.FMaterial1 := TGorillaLambertMaterialSource.Create(Self.FCube);
Self.FMaterial1.Parent := Self.FCube;
{$IFDEF MSWINDOWS}
LTexPath := '..\assets\textures\';
{$ELSE}
LTexPath := TOS.GetDocumentsPath();
{$ENDIF}
Self.FMaterial1.Texture.LoadFromFile(LTexPath + 'crate1_diffuse.jpg');
Self.FCube.MaterialSource := Self.FMaterial1;
Self.FSphere := TGorillaSphere.Create(Self.FCube);
Self.FSphere.Parent := Self.FCube;
Self.FSphere.Position.Point := TPoint3D.Create(-3, -1, 0);
Self.FMaterial2 := TGorillaBumpMapMaterialSource.Create(Self.FSphere);
Self.FMaterial2.Parent := Self.FSphere;
{$IFDEF MSWINDOWS}
LTexPath := LTexPath + 'bump\';
{$ENDIF}
Self.FSphere.MaterialSource := Self.FMaterial2;
Self.FPlane := TGorillaPlane.Create(Self.FViewport);
Self.FPlane.Parent := Self.FViewport;
Self.FPlane.RotationAngle.X := -90;
Self.FPlane.SetSize(100, 100, 1);
Self.FPlane.MaterialSource := Self.FMaterial1;
// create a timer for animation
Self.FTimer := TTimer.Create(Self.FViewport);
Self.FTimer.Parent := Self.FViewport;
Self.FTimer.Interval := 16;
Self.FTimer.OnTimer := @Self.DoOnTimer;
end;
procedure TGorillaApp.DoOnKeyUp(ASender : TObject; AKeyCode : Integer);
begin
TUI.ShowInfo('Taste gedrückt = ' + AKeyCode.ToChar());
end;
procedure TGorillaApp.DoOnTimer(ASender : TObject);
var LY, LX : Double;
begin
// update window caption with FPS for checking performance
Self.FWindow.Caption := GORILLA_CAPTION + ' ' + Self.FViewport.FPS.ToString() + ' FPS';
// animate 3D elements
Self.FViewport.BeginUpdate();
try
Self.FSinCurve := Self.FSinCurve + 0.1;
LY := TMath.Sin(Self.FSinCurve);
LX := TMath.Cos(Self.FSinCurve);
Self.FCube.Position.Point := TPoint3D.Create(0, LY * 2, 0);
Self.FCube.RotationAngle.Y := Self.FCube.RotationAngle.Y + 1;
Self.FSphere.RotationAngle.Y := Self.FSphere.RotationAngle.Y - 1;
Self.FLight.Position.Point := TPoint3D.Create(LX * 5, -10, LY * 3);
Self.FModel.RotationAngle.Y := Self.FModel.RotationAngle.Y + 1;
finally
Self.FViewport.EndUpdate();
end;
end;
end.
var
MyInteger: Integer;
MyString: String;
MyBoolean: Boolean;
MyObject: TMyClass;
MyArray: TArray;
const
MAX_VALUE = 100;
APP_NAME = 'MyApp';
PI_VALUE = 3.14159;
Arithmetic Operators:
+ (Addition)- (Subtraction)* (Multiplication)/ (Division)div (Integer division)mod (Modulo)Comparison Operators:
= (Equality)<> (Inequality)< (Less than)<= (Less than or equal)> (Greater than)>= (Greater than or equal)Logical Operators:
and (Boolean AND)or (Boolean OR)xor (Boolean XOR)not (Boolean NOT)Bitwise Operators:
and (Bitwise AND)or (Bitwise OR)xor (Bitwise XOR)shl (Shift left)shr (Shift right)Special Operators:
@ (Address of)in (Set membership)as (Type cast)is (Type check)GorillaScript supports standard Delphi primitive types:
Integer Types:
ShortInt / Int8: 8-bit signed integerByte / UInt8: 8-bit unsigned integerSmallInt / Int16: 16-bit signed integerWord / UInt16: 16-bit unsigned integerInteger / LongInt / Int32: 32-bit signed integerCardinal / LongWord / UInt32: 32-bit unsigned integerInt64: 64-bit signed integerUInt64: 64-bit unsigned integerFloating-Point Types:
Single: 32-bit floating-pointDouble: 64-bit floating-pointBoolean Types:
Boolean: Standard boolean typeString Types:
String: Unicode string (UnicodeString)String Helper Methods:
str.ToInteger() - Convert string to integerstr.ToInt64() - Convert string to 64-bit integerstr.ToSingle() - Convert string to single precision floatstr.ToDouble() - Convert string to double precision floatstr.ToBoolean() - Convert string to booleanstr.ToValue() - Convert string to TValueNumeric Type Helpers:
All numeric types (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double) provide:
.ToString() - Convert to string representation.ToChar() - Convert to character representation.ToString() for "True"/"False" representationSpecial Types:
Pointer: Generic pointer typeTValue: Variant-like type for dynamic typingTMethod: Method pointer typeArrays:
GorillaScript provides a powerful TArray type with rich helper methods. Arrays can hold mixed types (strings, numbers, booleans) in the same array.
var LArr1 : TArray;
begin
// Create array with size
LArr1 := TArray.Create(5);
// Mixed-type storage
LArr1[0] := 'abc'; // String
LArr1[1] := 123.25; // Double
LArr1[2] := true; // Boolean
LArr1[4] := LArr1[0]; // Copy element
// Display array
System.WriteLn(LArr1.ToString()); // [abc, 123.25, True, (empty), abc]
end;
TArray Helper Methods:
Construction & Info:
TArray.Create(size) - Create array with specified sizearr.Length() - Get array lengtharr.IsEmpty() - Check if array is emptyarr.High() - Get highest indexarr.Low() - Get lowest index (always 0)Element Access:
arr[index] - Read/write element at indexarr.First() - Get first elementarr.Peek() - Get last elementModification:
arr.SetLength(newSize) - Resize arrayarr.Push(item) - Add item to endarr.Pop() - Remove last itemarr.Delete(index, count) - Delete elementsSlicing & Copying:
arr.Slice(count) - Get slice from startarr.Reduce(count) - Reduce array sizearr.Copy(start, count) - Copy rangeConversion:
arr.ToString() - Convert to string representationarr.ToValue() - Convert to TValueRecords (Structs):
type
TMyRecord = record
Field1: Integer;
Field2: String;
end;
Sets:
type
TMyEnum = (meOne, meTwo, meThree);
TMySet = set of TMyEnum;
var
MySet: TMySet;
begin
MySet := [meOne, meThree];
if meTwo in MySet then
// ...
end;
Enumerations:
type
TColor = (clRed, clGreen, clBlue);
var
MyColor: TColor;
begin
MyColor := clRed;
end;
Classes follow standard Delphi object-oriented syntax:
type
TMyClass = class(TObject)
private
FValue: Integer;
protected
procedure DoProtectedWork;
public
constructor Create;
destructor Destroy; override;
procedure PublicMethod;
property Value: Integer read FValue write FValue;
end;
Visibility Specifiers:
private: Accessible only within the classprotected: Accessible within the class and descendantspublic: Accessible everywherepublished: Public with RTTI (for native classes)type
IMyInterface = interface
['{GUID}']
procedure DoSomething;
function GetValue: Integer;
end;
TMyClass = class(TInterfacedObject, IMyInterface)
public
procedure DoSomething;
function GetValue: Integer;
end;
type
TComponentName = String;
TCallback = procedure(ASender: TObject) of object;
if Condition then
Statement
else if AnotherCondition then
AnotherStatement
else
DefaultStatement;
// Block form
if Condition then
begin
Statement1;
Statement2;
end
else
begin
Statement3;
Statement4;
end;
GorillaScript supports advanced case statements with integers, floats, and strings. Ranges are supported for all types.
Integer Case:
case Value of
0: Statement1;
1, 2, 3: Statement2; // Multiple values
4..10: Statement3; // Range
11..20, 25, 30..35: Statement4; // Mixed ranges and values
else
DefaultStatement;
end;
String Case:
case StringValue of
'Hello': Statement1;
'Hallo'..'Hulu': Statement2; // String range (alphabetical)
'World': Statement3;
else
DefaultStatement;
end;
Float Case:
case FloatValue of
1225.70: Statement1;
1225.749..1225.7501: Statement2; // Float range
else
DefaultStatement;
end;
Block Form:
case Value of
0:
begin
Statement1;
Statement2;
end;
1:
begin
Statement3;
end;
end;
Standard For Loop:
// For-to loop
for i := 0 to 10 do
Statement;
// For-downto loop
for i := 10 downto 0 do
Statement;
// Block form
for i := 0 to Count - 1 do
begin
Statement1;
Statement2;
end;
Performance Note: For loops are currently slow due to bytecode interpretation overhead on each iteration. See Section 10.1 for details.
Status: Fully Implemented
While loops are implemented using general bytecode operations (JUMP, JUMP_ON_ZERO):
while Condition do
Statement;
// Block form
while Condition do
begin
Statement1;
Statement2;
end;
// With break and continue
while Condition do
begin
if ShouldSkip then
Continue;
if ShouldStop then
Break;
ProcessItem;
end;
Implementation: The compiler generates a condition check followed by a conditional jump. The loop body is executed, then an unconditional jump returns to the condition check.
Status: Fully Implemented
Repeat-until loops are implemented using general bytecode operations:
repeat
Statement1;
Statement2;
until Condition;
// With break and continue
repeat
if ShouldSkip then
Continue;
if ShouldStop then
Break;
ProcessItem;
until Condition;
Implementation: The loop body is executed first, then the condition is checked. A conditional jump returns to the start if the condition is false. This ensures the body executes at least once.
// Try-Except
try
RiskyOperation;
except
on E: Exception do
HandleException(E);
end;
// Try-Finally
try
AllocateResource;
UseResource;
finally
FreeResource;
end;
// Try-Except-Finally
try
RiskyOperation;
except
on E: ESpecificException do
HandleSpecific(E);
on E: Exception do
HandleGeneral(E);
end;
for i := 0 to 100 do
begin
if ShouldSkip(i) then
Continue;
if ShouldStop(i) then
Break;
ProcessItem(i);
end;
procedure MyProcedure(Param1: Integer; Param2: String);
begin
// Implementation
end;
function MyFunction(Param1: Integer): String;
begin
Result := IntToStr(Param1);
end;
Value Parameters (default):
procedure Process(Value: Integer);
Var Parameters (by reference):
procedure Modify(var Value: Integer);
begin
Value := Value + 1;
end;
Out Parameters:
procedure GetValues(out Value1: Integer; out Value2: String);
begin
Value1 := 42;
Value2 := 'Hello';
end;
Const Parameters:
procedure Display(const Value: String);
begin
// Value cannot be modified
WriteLn(Value);
end;
function Calculate(A, B: Integer): Integer; overload;
begin
Result := A + B;
end;
function Calculate(A, B: Double): Double; overload;
begin
Result := A + B;
end;
Virtual Methods:
type
TBaseClass = class
procedure DoWork; virtual;
end;
TDerivedClass = class(TBaseClass)
procedure DoWork; override;
end;
Abstract Methods:
type
TAbstractClass = class
procedure DoWork; virtual; abstract;
end;
Static Methods:
type
TMyClass = class
class procedure StaticMethod; static;
end;
type
TMyClass = class(TObject)
private
FField: Integer;
procedure PrivateMethod;
protected
procedure ProtectedMethod;
public
constructor Create; overload;
constructor Create(AValue: Integer); overload;
destructor Destroy; override;
procedure PublicMethod;
function GetValue: Integer;
property Field: Integer read FField write FField;
end;
constructor TMyClass.Create;
begin
inherited Create;
FField := 0;
end;
constructor TMyClass.Create(AValue: Integer);
begin
inherited Create;
FField := AValue;
end;
destructor TMyClass.Destroy;
begin
// Cleanup
inherited;
end;
Read/Write Properties:
type
TMyClass = class
private
FValue: Integer;
public
property Value: Integer read FValue write FValue;
end;
Getter/Setter Methods:
type
TMyClass = class
private
FValue: Integer;
function GetValue: Integer;
procedure SetValue(AValue: Integer);
public
property Value: Integer read GetValue write SetValue;
end;
type
TBaseClass = class(TObject)
public
procedure BaseMethod;
end;
TDerivedClass = class(TBaseClass)
public
procedure DerivedMethod;
procedure BaseMethod; override;
end;
type
IMyInterface = interface
['{GUID-HERE}']
procedure InterfaceMethod;
end;
TMyClass = class(TInterfacedObject, IMyInterface)
public
procedure InterfaceMethod;
end;
implementation
procedure TMyClass.InterfaceMethod;
begin
// Implementation
end;
var
MyObject: TMyClass;
begin
// Create object
MyObject := TMyClass.Create;
try
MyObject.DoWork;
finally
// Destroy object
MyObject.Free;
end;
end;
GorillaScript provides seamless integration with native Delphi code through the RTTI system. Native classes, interfaces, records, enums, and sets can be registered and used directly in scripts.
Native classes are registered with the engine and become available in scripts:
// In Delphi host code
Engine.RegisteredClasses.Add(TMyNativeClass);
After registration, the class is available in scripts:
// In script
var
MyObject: TMyNativeClass;
begin
MyObject := TMyNativeClass.Create;
MyObject.NativeMethod;
MyObject.Free;
end;
// In Delphi host code
Engine.RegisteredEnums.Add(
TGorillaScriptRegisteredType.From(
'MyUnit.TMyEnum',
TypeInfo(TMyEnum)
)
);
// In Delphi host code
Engine.RegisteredStructs.Add(
TGorillaScriptRegisteredType.From(
'MyUnit.TMyRecord',
TypeInfo(TMyRecord)
)
);
// In Delphi host code
Engine.RegisteredInterfaces.Add('MyUnit.IMyInterface');
Native methods are called through RTTI with automatic type conversion:
Native events can be assigned to script methods:
// In script
procedure TMyForm.ButtonClick(Sender: TObject);
begin
ShowMessage('Button clicked!');
end;
procedure TMyForm.FormCreate(Sender: TObject);
begin
Button1.OnClick := @Self.ButtonClick;
end;
Event handlers are wrapped by TGorillaScriptObjectEventHandler which dispatches calls from native code to script methods.
The following types are automatically available in all scripts:
Primitive Types: String, Int8, ShortInt, UInt8, Byte, Int16, SmallInt, UInt16, Word, Integer, LongInt, Cardinal, LongWord, Int32, UInt32, Int64, UInt64, Single, Double, Boolean, Pointer, TValue, TMethod
Base Classes: TObject, TInterfacedObject, IInterface, TComponentName
Special Types: TShader, TVertexShader, TPixelShader, System, TCustomAttribute, NATIVE, GLSL, UNIFORM, ATTRIBUTE, VARYING
Pre-registered units available without explicit "uses" clause:
System: Core system functionsSystem.SysUtils: String and utility functionsSystem.Math: Mathematical functionsSystem.Math.Vectors: Vector operationsSystem.Types: Standard typesSystem.Classes: Component streamingSystem.UITypes: UI-related typesFile Format:
0xDEADBABE0x00010001 (Major: 1, Minor: 1)Instruction Format:
OPERATION [OPERANDS...] DELIMITER
The VM supports the following operation categories:
Control Flow:
GS_BC_NONE: No operationGS_BC_DELIM: Command delimiterGS_BC_HALT: Stop executionGS_BC_RETURN: Return from functionGS_BC_JUMP: Unconditional jumpGS_BC_JUMP_ON_ZERO: Jump if top of stack is zeroGS_BC_JUMP_ON_NOTZERO: Jump if top of stack is non-zeroStack Operations:
GS_BC_GET_STACKVALUE: Pop value from stackGS_BC_SET_STACKVALUE: Push value to stackGS_BC_COPY: Duplicate top stack valueGS_BC_COPYTOP: Copy stack topGS_BC_PUSH: Push valueGS_BC_POP: Pop valueArithmetic Operations:
GS_BC_ADD: AdditionGS_BC_SUB: SubtractionGS_BC_MUL: MultiplicationGS_BC_DIV: DivisionGS_BC_MOD: ModuloGS_BC_POW: PowerGS_BC_INC: IncrementGS_BC_DEC: DecrementComparison Operations:
GS_BC_LT: Less thanGS_BC_LEQ: Less than or equalGS_BC_GT: Greater thanGS_BC_GEQ: Greater than or equalGS_BC_EQ: EqualGS_BC_NEQ: Not equalLogical Operations:
GS_BC_NOT: Boolean NOTGS_BC_AND: Boolean ANDGS_BC_OR: Boolean ORGS_BC_XOR: Boolean XORBitwise Operations:
GS_BC_BITAND: Bitwise ANDGS_BC_BITOR: Bitwise ORGS_BC_BITXOR: Bitwise XORGS_BC_SHL: Shift leftGS_BC_SHR: Shift rightObject Operations:
GS_BC_GET_TYPE: Get type informationGS_BC_GET_METHOD: Get method pointerGS_BC_GET_FIELD: Get field valueGS_BC_SET_FIELD: Set field valueGS_BC_GET_CONST: Get constant valueGS_BC_GET_NATIVE_PROPERTY: Get native propertyGS_BC_SET_NATIVE_PROPERTY: Set native propertyGS_BC_CALL: Call methodGS_BC_READ_ACC_ARR: Array read accessGS_BC_WRITE_ACC_ARR: Array write accessGS_BC_ISTYPE: Type checkGS_BC_AS: Type castGS_BC_ADDRESSOF: Get addressGS_BC_IN: Set membership testGS_BC_NEWSET: Create new setControl Structures:
GS_BC_FOR_LOOP: For loop (has dedicated handler)GS_BC_WHILE_LOOP: While loop marker (implemented via JUMP/JUMP_ON_ZERO)GS_BC_REPEAT_LOOP: Repeat loop marker (implemented via JUMP/JUMP_ON_ZERO)GS_BC_CASE: Case statementGS_BC_TRY: Try blockGS_BC_EXCEPT: Except blockGS_BC_FINALLY: Finally blockGS_BC_RANGECHECK: Range checkInterpreter Loop:
Method Dispatch:
Stack Frame: Each function call creates a stack frame containing:
The executor uses a lookup table (FByteCodes) to map bytecode operations to handler procedures, avoiding case statement overhead:
// Faster than case statement
LProc := FByteCodes[ABC];
LProc(AContext, AByteCode);
Critical Performance Issue: For Loops
For loops currently exhibit significant performance degradation compared to native Delphi code. This is due to the execution model where each loop iteration interprets bytecode through the __DoExecByteCode() function.
Benchmark Data:
Root Cause Analysis:
From Gorilla.Script.Executor.pas (lines 638-797):
procedure TGorillaScriptExecutor.DoForLoop(...);
begin
// Comment on line 720-721:
// "The following code was just an experiment for optimizing loops in
// scripting, but did not result in the expected performance yet."
Exit; // Loop optimization disabled
// Experimental optimization code follows but is never executed
...
while LLoopRunning do
begin
repeat
AByteCode.Read(LBC, SizeOf(LBC));
if LBC = GS_BC_JUMP then
// Handle jump
else
__DoExecByteCode(LBC); // ← Performance bottleneck
until LLoopBreak;
end;
end;
Performance Impact: Each loop iteration requires:
Workarounds:
Execution Speed:
Memory Usage:
Optimization Tips:
Severity: High Status: Known issue, workaround required
When writing code inside a class method, you must explicitly qualify member access with Self. even when already in the self context:
Incorrect (will not work):
type
TMyClass = class
private
FValue: Integer;
public
procedure SetValue(AValue: Integer);
end;
procedure TMyClass.SetValue(AValue: Integer);
begin
FValue := AValue; // ← ERROR: FValue not resolved
end;
Correct (required workaround):
procedure TMyClass.SetValue(AValue: Integer);
begin
Self.FValue := AValue; // ← Must use "Self."
end;
Impact: Affects all field, property, and method access within class methods.
Workaround: Always prefix member access with Self. in class methods.
Severity: High Status: Known issue, optimization attempt failed
For loops are significantly slower than native Delphi code due to bytecode interpretation overhead. See Section 10.1 for details.
Generic types are supported only for pre-defined native types like TArray<T>. User-defined generic types are not supported.
Inline assembly (asm blocks) is not supported and will cause compilation errors.
Compiler directives support is limited:
{$DEFINE}, {$IFDEF}, {$ENDIF} are supportedCustom attributes beyond basic system attributes may not be accessible in scripts.
The Variant type has limited support. Use TValue for dynamic typing instead.
Thread-safe mode adds significant performance overhead (~600ms per million iterations). For single-threaded scenarios, disable with:
// In source code, remove {$DEFINE THREADSAFE}
Hard-coded memory limits:
These limits require recompilation to change.
Error messages may not always provide accurate line numbers or context, especially for complex expressions.
Limited debugging capabilities:
Pointer arithmetic is not supported. Pointers can be stored and passed but not manipulated.
Direct memory access functions (like Move, FillChar) may have limited or no support.
No support for calling external DLLs directly. Must be wrapped in native Delphi code first.
| Opcode | Name | Description |
|---|---|---|
| 0 | GS_BC_NONE | No operation |
| 1 | GS_BC_DELIM | Statement delimiter |
| 2 | GS_BC_HALT | Stop execution |
| 3 | GS_BC_RETURN | Return from function |
| 5 | GS_BC_JUMP | Unconditional jump |
| 6 | GS_BC_JUMP_ON_ZERO | Conditional jump (zero) |
| 7 | GS_BC_JUMP_ON_NOTZERO | Conditional jump (non-zero) |
| 8 | GS_BC_GET_STACKVALUE | Pop stack value |
| 9 | GS_BC_SET_STACKVALUE | Push stack value |
| 10 | GS_BC_ADD | Addition |
| 11 | GS_BC_SUB | Subtraction |
| 12 | GS_BC_MUL | Multiplication |
| 13 | GS_BC_DIV | Division |
| 14 | GS_BC_MOD | Modulo |
| 15 | GS_BC_POW | Power |
| 16 | GS_BC_LT | Less than |
| 17 | GS_BC_LEQ | Less than or equal |
| 18 | GS_BC_GT | Greater than |
| 19 | GS_BC_GEQ | Greater than or equal |
| 20 | GS_BC_EQ | Equal |
| 21 | GS_BC_NEQ | Not equal |
| 22 | GS_BC_NOT | Boolean NOT |
| 23 | GS_BC_AND | Boolean AND |
| 24 | GS_BC_OR | Boolean OR |
| 25 | GS_BC_XOR | Boolean XOR |
| 26 | GS_BC_BITAND | Bitwise AND |
| 27 | GS_BC_BITOR | Bitwise OR |
| 28 | GS_BC_BITXOR | Bitwise XOR |
| 29 | GS_BC_SHL | Shift left |
| 30 | GS_BC_SHR | Shift right |
| 31 | GS_BC_INC | Increment |
| 32 | GS_BC_DEC | Decrement |
| 33 | GS_BC_ADDRESSOF | Get address |
| 34 | GS_BC_IN | Set membership |
| 35 | GS_BC_AS | Type cast |
| 40 | GS_BC_COPY | Copy stack value |
| 41 | GS_BC_COPYTOP | Copy top of stack |
| 42 | GS_BC_RANGECHECK | Range check |
| 43 | GS_BC_TRY | Try block |
| 44 | GS_BC_EXCEPT | Except block |
| 45 | GS_BC_FINALLY | Finally block |
| 46 | GS_BC_FOR_LOOP | For loop (dedicated handler) |
| 47 | GS_BC_WHILE_LOOP | While loop marker (uses JUMP ops) |
| 48 | GS_BC_REPEAT_LOOP | Repeat loop marker (uses JUMP ops) |
| 49 | GS_BC_CASE | Case statement |
| 50 | GS_BC_GET_TYPE | Get type information |
| 51 | GS_BC_GET_METHOD | Get method pointer |
| 52 | GS_BC_GET_FIELD | Get field value |
| 53 | GS_BC_SET_FIELD | Set field value |
| 54 | GS_BC_GET_CONST | Get constant value |
| 55 | GS_BC_GET_NATIVE_PROPERTY | Get native property |
| 56 | GS_BC_SET_NATIVE_PROPERTY | Set native property |
| 64 | GS_BC_CALL | Call method |
| 65 | GS_BC_READ_ACC_ARR | Array read |
| 66 | GS_BC_WRITE_ACC_ARR | Array write |
| 67 | GS_BC_ISTYPE | Type check |
| 68 | GS_BC_NEWSET | Create set |
Issue: "Field not found in class method"
Self.Issue: "Script runs slowly with loops"
Issue: "Stack overflow error"
Issue: "Out of stack space"
Issue: "Cannot access native class member"
Engine.RegisteredClasses.Add(TMyClass)Self. prefix)Core Files:
Gorilla.Script.pas: Main engine componentGorilla.Script.Parser.Delphi.pas: Delphi syntax parserGorilla.Script.Compiler.pas: Bytecode compilerGorilla.Script.Executor.pas: Bytecode interpreterGorilla.Script.ByteCode.pas: Bytecode definitionsGorilla.Script.Types.pas: Type systemGorilla.Script.Entities.pas: AST entitiesLibrary Files:
Gorilla.Script.Libraries.pas: Library systemGorilla.Script.Lib.*.pas: Standard library modulesEnd of Specification
Comprehensive input handling for keyboard, mouse, and gamepad devices.
Component: TGorillaInputController
The Gorilla Input Polling System provides high-performance, asynchronous input handling for games and interactive applications. Unlike traditional event-driven input, this system continuously monitors input devices and allows you to define complex input combinations (HotKeys) and sequences.
Key Features:
TGorillaInputController component onto your formEnabled property to TrueSupported property to enable desired devices:Keyboard - Enable keyboard inputMouse - Enable mouse inputGamePad - Enable gamepad inputExample:
// Enable all devices
GorillaInputController1.Supported := [Keyboard, Mouse, GamePad];
GorillaInputController1.Enabled := True;
var
LController: TGorillaInputController;
begin
LController := TGorillaInputController.Create(Self);
LController.Supported := [Keyboard, Mouse, GamePad];
LController.Enabled := True;
end;
A HotKey is a combination of inputs that triggers an action when activated or deactivated. You can combine up to 4 inputs per device (keyboard, mouse, gamepad) in a single HotKey.
HotKeys consist of:
TGorillaInputController componentHotKeys property in Object Inspector[...] to open the collection editorName property (e.g., "Jump", "Fire", "Sprint")Combinations propertyKind to device type (Keyboard, Mouse, GamePad)Code to the input code constantExample: Jump HotKey (Spacebar)
HotKey: "Jump"
Combinations:
Item[0]:
Kind: Keyboard
Code: GORILLA_INPUT_KEY_SPACE
TriggerOnActivate: True
Example: Aim + Shoot HotKey (Right Mouse + Left Mouse)
HotKey: "AimAndShoot"
Combinations:
Item[0]:
Kind: Mouse
Code: GORILLA_INPUT_MOUSE_RBUTTON
Item[1]:
Kind: Mouse
Code: GORILLA_INPUT_MOUSE_LBUTTON
TriggerOnActivate: True
LockTime: 100
var
LHotKey: TGorillaHotKeyItem;
begin
// Add HotKey
LHotKey := GorillaInputController1.AddHotKey('Jump');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_SPACE);
LHotKey.TriggerOnActivate := True;
LHotKey.OnTriggered := OnJumpTriggered;
end;
procedure TForm1.OnJumpTriggered(const AItem: TGorillaHotKeyItem;
const ACurrentInput: TGorillaHotKeyRaw; const AMode: TGorillaInputMode);
begin
if AMode = Activated then
Player.Jump();
end;
Multi-Device HotKey Example:
// Ctrl + E + Left Mouse Click for special attack
LHotKey := GorillaInputController1.AddHotKey('SpecialAttack');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_CTRL_LEFT);
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_E);
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
LHotKey.TriggerOnActivate := True;
LHotKey.LockTime := 500; // Half-second cooldown
TriggerOnActivate:
TriggerOnDeactivate:
Both Modes:
True to trigger on press AND release// Charge shot: Hold to charge, release to fire
LHotKey := GorillaInputController1.AddHotKey('ChargeShot');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
LHotKey.TriggerOnActivate := True; // Start charging
LHotKey.TriggerOnDeactivate := True; // Release shot
LHotKey.OnTriggered := OnChargeShotTriggered;
procedure TForm1.OnChargeShotTriggered(const AItem: TGorillaHotKeyItem;
const ACurrentInput: TGorillaHotKeyRaw; const AMode: TGorillaInputMode);
begin
if AMode = Activated then
Player.StartCharge()
else if AMode = Deactivated then
Player.ReleaseShot();
end;
Lock Time prevents rapid re-triggering of HotKeys:
LHotKey := GorillaInputController1.AddHotKey('Attack');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
LHotKey.LockTime := 250; // 250ms cooldown between attacks
Use Cases:
Sequences detect ordered combinations of HotKeys (like fighting game combos). You can chain up to 16 HotKeys in a sequence.
Sequences consist of:
TGorillaInputController componentSequences property in Object Inspector[...] to open the collection editorName property (e.g., "Combo1", "CheatCode")HotKeys propertyHotKeyName to the name of an existing HotKeySensitivity (default: 500ms)Example: Konami Code
Sequence: "KonamiCode"
Sensitivity: 500
HotKeys:
Item[0]: HotKeyName = "ArrowUp"
Item[1]: HotKeyName = "ArrowUp"
Item[2]: HotKeyName = "ArrowDown"
Item[3]: HotKeyName = "ArrowDown"
Item[4]: HotKeyName = "ArrowLeft"
Item[5]: HotKeyName = "ArrowRight"
Item[6]: HotKeyName = "ArrowLeft"
Item[7]: HotKeyName = "ArrowRight"
Item[8]: HotKeyName = "KeyB"
Item[9]: HotKeyName = "KeyA"
var
LHK1, LHK2, LHK3: TGorillaHotKeyItem;
LSeq: TGorillaInputSequenceItem;
begin
// Create individual HotKeys
LHK1 := GorillaInputController1.AddHotKey('Punch');
LHK1.AddInput(Keyboard, GORILLA_INPUT_KEY_P);
LHK1.TriggerOnActivate := True;
LHK2 := GorillaInputController1.AddHotKey('Punch');
LHK2.AddInput(Keyboard, GORILLA_INPUT_KEY_P);
LHK2.TriggerOnActivate := True;
LHK3 := GorillaInputController1.AddHotKey('Kick');
LHK3.AddInput(Keyboard, GORILLA_INPUT_KEY_K);
LHK3.TriggerOnActivate := True;
// Create Sequence: Punch-Punch-Kick
LSeq := GorillaInputController1.AddSequence('Combo1', [LHK1, LHK2, LHK3]);
LSeq.Sensitivity := 500;
LSeq.OnTriggered := OnCombo1Triggered;
end;
procedure TForm1.OnCombo1Triggered(const ASequence: TGorillaInputSequenceItem);
begin
Player.PerformCombo('Triple Strike');
end;
Sensitivity defines the maximum time between HotKey activations in a sequence:
| Sensitivity | Description | Use Case |
|---|---|---|
| 100-300ms | Very strict | Fast-paced fighting combos |
| 300-500ms | Normal | General combo inputs |
| 500-1000ms | Relaxed | Cheat codes, accessibility |
| 1000ms+ | Very relaxed | Discovery mechanics |
Default: 500ms (defined by GORILLA_INPUT_SEQUENCE_SENSITIVITY)
Available Keys:
// Letters
GORILLA_INPUT_KEY_A to GORILLA_INPUT_KEY_Z
// Numbers
GORILLA_INPUT_KEY_0 to GORILLA_INPUT_KEY_9
// Arrows
GORILLA_INPUT_KEY_ARROW_LEFT
GORILLA_INPUT_KEY_ARROW_UP
GORILLA_INPUT_KEY_ARROW_RIGHT
GORILLA_INPUT_KEY_ARROW_DOWN
// Special keys
GORILLA_INPUT_KEY_SPACE
GORILLA_INPUT_KEY_RETURN
GORILLA_INPUT_KEY_ESCAPE
GORILLA_INPUT_KEY_BACKSPACE
GORILLA_INPUT_KEY_DELETE
GORILLA_INPUT_KEY_TAB
GORILLA_INPUT_KEY_PAUSE
// Modifiers
GORILLA_INPUT_KEY_SHIFT_LEFT
GORILLA_INPUT_KEY_SHIFT_RIGHT
GORILLA_INPUT_KEY_CTRL_LEFT
GORILLA_INPUT_KEY_CTRL_RIGHT
GORILLA_INPUT_KEY_ALT
GORILLA_INPUT_KEY_ALTGR
// Symbols
GORILLA_INPUT_KEY_PLUS
GORILLA_INPUT_KEY_MINUS
GORILLA_INPUT_KEY_DOT
GORILLA_INPUT_KEY_COMMA
// ... and many more
| Constant | Char | Decimal |
|---|---|---|
| GORILLA_INPUT_KEY_A | 'A' | 65 |
| GORILLA_INPUT_KEY_B | 'B' | 66 |
| GORILLA_INPUT_KEY_C | 'C' | 67 |
| GORILLA_INPUT_KEY_D | 'D' | 68 |
| GORILLA_INPUT_KEY_E | 'E' | 69 |
| GORILLA_INPUT_KEY_F | 'F' | 70 |
| GORILLA_INPUT_KEY_G | 'G' | 71 |
| GORILLA_INPUT_KEY_H | 'H' | 72 |
| GORILLA_INPUT_KEY_I | 'I' | 73 |
| GORILLA_INPUT_KEY_J | 'J' | 74 |
| GORILLA_INPUT_KEY_K | 'K' | 75 |
| GORILLA_INPUT_KEY_L | 'L' | 76 |
| GORILLA_INPUT_KEY_M | 'M' | 77 |
| GORILLA_INPUT_KEY_N | 'N' | 78 |
| GORILLA_INPUT_KEY_O | 'O' | 79 |
| GORILLA_INPUT_KEY_P | 'P' | 80 |
| GORILLA_INPUT_KEY_Q | 'Q' | 81 |
| GORILLA_INPUT_KEY_R | 'R' | 82 |
| GORILLA_INPUT_KEY_S | 'S' | 83 |
| GORILLA_INPUT_KEY_T | 'T' | 84 |
| GORILLA_INPUT_KEY_U | 'U' | 85 |
| GORILLA_INPUT_KEY_V | 'V' | 86 |
| GORILLA_INPUT_KEY_W | 'W' | 87 |
| GORILLA_INPUT_KEY_X | 'X' | 88 |
| GORILLA_INPUT_KEY_Y | 'Y' | 89 |
| GORILLA_INPUT_KEY_Z | 'Z' | 90 |
| GORILLA_INPUT_KEY_0 | '0' | 48 |
| GORILLA_INPUT_KEY_1 | '1' | 49 |
| GORILLA_INPUT_KEY_2 | '2' | 50 |
| GORILLA_INPUT_KEY_3 | '3' | 51 |
| GORILLA_INPUT_KEY_4 | '4' | 52 |
| GORILLA_INPUT_KEY_5 | '5' | 53 |
| GORILLA_INPUT_KEY_6 | '6' | 54 |
| GORILLA_INPUT_KEY_7 | '7' | 55 |
| GORILLA_INPUT_KEY_8 | '8' | 56 |
| GORILLA_INPUT_KEY_9 | '9' | 57 |
| GORILLA_INPUT_KEY_ARROW_LEFT | #37 | 75 |
| GORILLA_INPUT_KEY_ARROW_UP | #38 | 72 |
| GORILLA_INPUT_KEY_ARROW_RIGHT | #39 | 77 |
| GORILLA_INPUT_KEY_ARROW_DOWN | #40 | 80 |
| GORILLA_INPUT_KEY_SPACE | ' ' | 32 |
| GORILLA_INPUT_KEY_EXCL | '!' | 33 |
| GORILLA_INPUT_KEY_QUOTE | '“' | 34 |
| GORILLA_INPUT_KEY_HASH | '#' | 35 |
| GORILLA_INPUT_KEY_PERCENT | '%' | 37 |
| GORILLA_INPUT_KEY_STAR | '*' | 42 |
| GORILLA_INPUT_KEY_PLUS | '+' | 43 |
| GORILLA_INPUT_KEY_COMMA | ',' | 44 |
| GORILLA_INPUT_KEY_MINUS | '-' | 45 |
| GORILLA_INPUT_KEY_DOT | '.' | 46 |
| GORILLA_INPUT_KEY_DIV | '/' | 47 |
| GORILLA_INPUT_KEY_PARA | '§' | 167 |
| GORILLA_INPUT_KEY_DOLLAR | '$' | 36 |
| GORILLA_INPUT_KEY_EURO | '€' | 128 |
| GORILLA_INPUT_KEY_AT | '@' | 64 |
| GORILLA_INPUT_KEY_AND | '&' | 38 |
| GORILLA_INPUT_KEY_BACKSLASH | '\' | 92 |
| GORILLA_INPUT_KEY_BRACKETOPEN | '(' | 40 |
| GORILLA_INPUT_KEY_BRACKETCLOSE | ')' | 41 |
| GORILLA_INPUT_KEY_EQUAL | '=' | 61 |
| GORILLA_INPUT_KEY_QUESTION | '?' | 63 |
| GORILLA_INPUT_KEY_TILDE | '~' | 126 |
| GORILLA_INPUT_KEY_UNDERSCORE | '_' | 95 |
| GORILLA_INPUT_KEY_COLON | ':' | 58 |
| GORILLA_INPUT_KEY_SEMICOLON | ';' | 59 |
| GORILLA_INPUT_KEY_BAR | | | 124 |
| GORILLA_INPUT_KEY_TAGOPEN | '<' | 60 |
| GORILLA_INPUT_KEY_TAGCLOSE | '>' | 62 |
| GORILLA_INPUT_KEY_SHIFT_BACKSPACE | #8 | 8 |
| GORILLA_INPUT_KEY_SHIFT_TAB | #9 | 9 |
| GORILLA_INPUT_KEY_LINEFEED | #$0A | 10 |
| GORILLA_INPUT_KEY_RETURN | #$0D | 13 |
| GORILLA_INPUT_KEY_ESCAPE | #$1B | 27 |
| GORILLA_INPUT_KEY_DELETE | #$7F | 127 |
| GORILLA_INPUT_KEY_SHIFT_CAPS | #20 | 20 |
| GORILLA_INPUT_KEY_SHIFT_LEFT | #160 | 160 |
| GORILLA_INPUT_KEY_SHIFT_RIGHT | #161 | 161 |
| GORILLA_INPUT_KEY_CTRL_LEFT | #162 | 162 |
| GORILLA_INPUT_KEY_CTRL_RIGHT | #163 | 163 |
| GORILLA_INPUT_KEY_ALT | #164 | 164 |
| GORILLA_INPUT_KEY_ALTGR | #165 | 165 |
WASD Movement Example:
// Forward
LHotKey := GorillaInputController1.AddHotKey('MoveForward');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_W);
LHotKey.TriggerOnActivate := True;
LHotKey.TriggerOnDeactivate := True;
LHotKey.OnTriggered := OnMoveForward;
// Sprint (Shift + W)
LHotKey := GorillaInputController1.AddHotKey('Sprint');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_SHIFT_LEFT);
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_W);
LHotKey.TriggerOnActivate := True;
LHotKey.TriggerOnDeactivate := True;
Available Buttons:
// Buttons
GORILLA_INPUT_MOUSE_LBUTTON // Left button
GORILLA_INPUT_MOUSE_RBUTTON // Right button
GORILLA_INPUT_MOUSE_MBUTTON // Middle button (wheel click)
GORILLA_INPUT_MOUSE_X1BUTTON // Extra button 1
GORILLA_INPUT_MOUSE_X2BUTTON // Extra button 2
// Double-clicks
GORILLA_INPUT_MOUSE_LBUTTON_DBLCLK
GORILLA_INPUT_MOUSE_RBUTTON_DBLCLK
GORILLA_INPUT_MOUSE_MBUTTON_DBLCLK
GORILLA_INPUT_MOUSE_X1BUTTON_DBLCLK
GORILLA_INPUT_MOUSE_X2BUTTON_DBLCLK
// Events
GORILLA_INPUT_MOUSE_WHEEL // Mouse wheel
GORILLA_INPUT_MOUSE_POSITION // Mouse position (persistent)
| Constant | Index | Value |
|---|---|---|
| GORILLA_INPUT_MOUSE_POSITION | 0 | $100001 |
| GORILLA_INPUT_MOUSE_LBUTTON | 1 | $100002 |
| GORILLA_INPUT_MOUSE_LBUTTON_DBLCLK | 2 | $100003 |
| GORILLA_INPUT_MOUSE_RBUTTON | 3 | $100004 |
| GORILLA_INPUT_MOUSE_RBUTTON_DBLCLK | 4 | $100005 |
| GORILLA_INPUT_MOUSE_MBUTTON | 5 | $100006 |
| GORILLA_INPUT_MOUSE_MBUTTON_DBLCLK | 6 | $100007 |
| GORILLA_INPUT_MOUSE_X1BUTTON | 7 | $100008 |
| GORILLA_INPUT_MOUSE_X1BUTTON_DBLCLK | 8 | $100009 |
| GORILLA_INPUT_MOUSE_X2BUTTON | 9 | $10000A |
| GORILLA_INPUT_MOUSE_X2BUTTON_DBLCLK | 10 | $10000B |
| GORILLA_INPUT_MOUSE_WHEEL | 11 | $10000C |
Shoot and Reload Example:
// Left click to shoot
LHotKey := GorillaInputController1.AddHotKey('Shoot');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
LHotKey.TriggerOnActivate := True;
// Right click to aim
LHotKey := GorillaInputController1.AddHotKey('Aim');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_RBUTTON);
LHotKey.TriggerOnActivate := True;
LHotKey.TriggerOnDeactivate := True;
// R key to reload
LHotKey := GorillaInputController1.AddHotKey('Reload');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_R);
LHotKey.TriggerOnActivate := True;
Supported Controllers:
Maximum GamePads:
Available Buttons:
// D-Pad
GORILLA_INPUT_GAMEPAD_DPAD_UP
GORILLA_INPUT_GAMEPAD_DPAD_DOWN
GORILLA_INPUT_GAMEPAD_DPAD_LEFT
GORILLA_INPUT_GAMEPAD_DPAD_RIGHT
// Face buttons
GORILLA_INPUT_GAMEPAD_BUTTON_A
GORILLA_INPUT_GAMEPAD_BUTTON_B
GORILLA_INPUT_GAMEPAD_BUTTON_X
GORILLA_INPUT_GAMEPAD_BUTTON_Y
// Shoulder buttons
GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT // LB
GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT // RB
// System buttons
GORILLA_INPUT_GAMEPAD_STARTBUTTON // Start/Menu
GORILLA_INPUT_GAMEPAD_MODEBUTTON // Xbox/Guide button
GORILLA_INPUT_GAMEPAD_BACKBUTTON // Back/View
// Thumbsticks (press)
GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT
GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT
// Triggers (persistent, 0-255)
GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT // LT
GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT // RT
// Thumbstick positions (persistent, -32768 to +32767)
GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_LEFT
GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_RIGHT
// Connection events
GORILLA_INPUT_GAMEPAD_CONNECTED
GORILLA_INPUT_GAMEPAD_DISCONNECTED
| Constant | Index | Value |
|---|---|---|
| GORILLA_INPUT_GAMEPAD_CONNECTED | $1000 | $200001 |
| GORILLA_INPUT_GAMEPAD_DISCONNECTED | $1001 | $200002 |
| GORILLA_INPUT_GAMEPAD_DPAD_UP | 0 | $200003 |
| GORILLA_INPUT_GAMEPAD_DPAD_DOWN | 1 | $200004 |
| GORILLA_INPUT_GAMEPAD_DPAD_LEFT | 2 | $200005 |
| GORILLA_INPUT_GAMEPAD_DPAD_RIGHT | 3 | $200006 |
| GORILLA_INPUT_GAMEPAD_START_BUTTON | 4 | $200007 |
| GORILLA_INPUT_GAMEPAD_MODEBUTTON | 5 | $200008 |
| GORILLA_INPUT_GAMEPAD_BACKBUTTON | 6 | $200009 |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT | 7 | $20000A |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT | 8 | $20000B |
| GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT | 9 | $20000C |
| GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT | 10 | $20000D |
| GORILLA_INPUT_GAMEPAD_BUTTON_A | 11 | $20000E |
| GORILLA_INPUT_GAMEPAD_BUTTON_B | 12 | $20000F |
| GORILLA_INPUT_GAMEPAD_BUTTON_X | 13 | $200011 |
| GORILLA_INPUT_GAMEPAD_BUTTON_Y | 14 | $200012 |
| GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT | $100 | $200020 |
| GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT | $101 | $200021 |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_LEFT | $200 | $200030 |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_RIGHT | $201 | $200031 |
GamePad HotKeys Example:
// Jump with A button
LHotKey := GorillaInputController1.AddHotKey('GamePadJump');
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_BUTTON_A);
LHotKey.TriggerOnActivate := True;
// Sprint with left thumbstick press + forward movement
LHotKey := GorillaInputController1.AddHotKey('GamePadSprint');
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT);
LHotKey.TriggerOnActivate := True;
// Aim with LT, shoot with RT
LHotKey := GorillaInputController1.AddHotKey('GamePadAimShoot');
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT);
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT);
LHotKey.TriggerOnActivate := True;
Persistent messages provide continuous feedback for analog inputs like mouse position, gamepad triggers, and thumbsticks.
| Message-Code | Description | DataType |
|---|---|---|
| GORILLA_INPUT_MOUSE_POSITION | $100001 | latest mouse position |
| GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT | $200020 | gamepad left trigger value |
| GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT | $200021 | gamepad right trigger value |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_LEFT | $200030 | gamepad left thumbstick position |
| GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_RIGHT | $200031 | gamepad right thumbstick position |
var
LMessage: TGorillaInputMessage;
LPos: TPoint;
begin
// Get last mouse position
if GorillaInputController1.GetLastMousePosition(LPos) then
begin
// LPos.X, LPos.Y contain screen coordinates
Camera.RotateBy(LPos.X * 0.01, LPos.Y * 0.01);
end;
// Alternative: Get raw message
if GorillaInputController1.GetPersistentMessage(Mouse,
GORILLA_INPUT_MOUSE_POSITION, LMessage) then
begin
LPos := LMessage.Data.AsType<TPoint>;
end;
end;
var
LTriggers: TPoint;
begin
// Get both trigger values (0-255 each)
if GorillaInputController1.GetLastGamePadTriggers(LTriggers) then
begin
// LTriggers.X = Left trigger (0-255)
// LTriggers.Y = Right trigger (0-255)
Car.SetAcceleration(LTriggers.Y / 255.0);
Car.SetBraking(LTriggers.X / 255.0);
end;
end;
var
LThumbstick: TPointF;
begin
// Get left thumbstick position (-1.0 to +1.0)
if GorillaInputController1.GetLastGamePadThumbstickPosLeft(LThumbstick) then
begin
// LThumbstick.X = Horizontal (-1.0 to +1.0)
// LThumbstick.Y = Vertical (-1.0 to +1.0)
Player.Move(LThumbstick.X, LThumbstick.Y);
end;
// Get right thumbstick for camera
if GorillaInputController1.GetLastGamePadThumbstickPosRight(LThumbstick) then
begin
Camera.Rotate(LThumbstick.X * 2.0, LThumbstick.Y * 2.0);
end;
end;
For direct input handling without HotKeys:
procedure TForm1.FormCreate(Sender: TObject);
begin
GorillaInputController1.OnKeyDown := OnKeyDown;
GorillaInputController1.OnKeyUp := OnKeyUp;
GorillaInputController1.OnMouseDown := OnMouseDown;
GorillaInputController1.OnMouseUp := OnMouseUp;
GorillaInputController1.OnMouseMove := OnMouseMove;
GorillaInputController1.OnGamePadButtonDown := OnGamePadButtonDown;
GorillaInputController1.OnGamePadButtonUp := OnGamePadButtonUp;
end;
procedure TForm1.OnKeyDown(ASender: TObject; AKeyCode: Integer);
begin
if AKeyCode = GORILLA_INPUT_KEY_ESCAPE then
ShowMenu();
end;
procedure TForm1.OnMouseMove(ASender: TObject;
AStates: TGorillaMouseStates; APos: TPointF);
begin
// Handle mouse movement
Cursor.Position := APos;
end;
procedure TForm1.OnGamePadButtonDown(ASender: TObject;
AState: TGorillaInputCode; AButtons: TGorillaGamePadButtons);
begin
if TGorillaGamePadButton.ButtonA in AButtons then
Player.Jump();
end;
| Platform | Keyboard | Mouse | GamePad | Notes |
|---|---|---|---|---|
| Windows | ✓ | ✓ | ✓ (XInput) | Low-level hooks for keyboard/mouse |
| Linux | ✓ | ✓ | ✓ (SDL2) | Requires SDL2 library |
| Android | ✓ | ✓ | ✓ | Touch events mapped to mouse |
By default, the input controller uses low-level hooks on Windows for better performance:
// Enabled by default
GorillaInputController1.HighPerformanceHooks := True;
// Disable during debugging (makes debugging faster)
{$IFDEF DEBUG}
GorillaInputController1.HighPerformanceHooks := False;
{$ENDIF}
When to disable:
WARNING: On Windows platform in many cases high performance hooks debugging is getting very slow, because low level hooks have a 1000ms timeout by default and hooks not getting paused during debugging.
This leads to lagging mouse and keyboard input. Of course you can deactivate HighPerformanceHooks meanwhile, but you could also edit the registry lik this:
Since v1.1.16.+ Linux support is available for input polling. Gamepad/joystick handling is solved by using SDL2.
sudo apt-get install libsdl2-2.0-0
sudo dnf install SDL2
You can expose Windows USB devices to WSL2, but it's complicated: https://learn.microsoft.com/windows/wsl/connect-usb#attach-a-usb-device
winget install usbipd
Restart PowerShell with admin-rights!
List devices and get the busid of your gamepad/joystick:
usbipd list
Attach gamepad to WSL2:
usbipd attach --wsl --busid <busid>
Check USB devices on WSL2:
lsusb
NOTICE: USBUtils needed:
sudo apt install usbutils
Remove gamepad from WSL2:
usbipd detach --busid <busid>
This requires WSL2 and is experimental for gamepads.
Control how often input handlers poll for new inputs:
var
LHandler: TGorillaInputHandler;
begin
// Get keyboard handler
LHandler := GorillaInputController1.GetHandler(Keyboard);
if Assigned(LHandler) then
LHandler.Sensitivity := 5; // Poll every 5ms (faster)
end;
Default: 10ms (GORILLA_INPUT_HANDLER_SENSITIVITY)
Guidelines:
All operations are thread-safe:
// Good
AddHotKey('PlayerJump');
AddHotKey('WeaponReload');
AddSequence('SuperCombo');
// Bad
AddHotKey('HK1');
AddHotKey('Input2');
AddSequence('Seq1');
// Prevent spam
LHotKey := AddHotKey('Attack');
LHotKey.LockTime := 250; // Match animation duration
// Desktop game - keyboard + mouse only
GorillaInputController1.Supported := [Keyboard, Mouse];
// Console game - gamepad only
GorillaInputController1.Supported := [GamePad];
{$IFDEF DEBUG}
GorillaInputController1.HighPerformanceHooks := False;
{$ENDIF}
// Charge shot
LHotKey.TriggerOnActivate := True; // Start charge
LHotKey.TriggerOnDeactivate := True; // Release
{$IFDEF MSWINDOWS}
// Windows-specific code
{$ENDIF}
{$IFDEF LINUX}
// Linux-specific code
{$ENDIF}
The Gorilla3D Particle System provides powerful tools for creating stunning visual effects like fire, smoke, rain, explosions, and more. This guide covers everything you need to know about creating, customizing, and optimizing particle effects in your games and applications.
The particle system supports:
The simplest way to create particles is to drop a TGorillaParticleEmitter component onto your viewport:
var
LEmitter: TGorillaParticleEmitter;
begin
LEmitter := TGorillaParticleEmitter.Create(Self);
LEmitter.Parent := GorillaViewport1;
LEmitter.Camera := Camera1;
LEmitter.EmitParticles := 10;
LEmitter.MaxParticles := 1000;
LEmitter.Start();
end;
Gorilla3D includes pre-configured emitters for common effects:
| Emitter | Description |
|---|---|
| TGorillaFireParticleEmitter | Realistic fire effects with flames and optional smoke |
| TGorillaSmokeParticleEmitter | Various smoke styles (4 different textures) |
| TGorillaRainParticleEmitter | Rain with droplets and splash effects |
| TGorillaSnowParticleEmitter | Falling snow with spiral movement |
| TGorillaEruptionParticleEmitter | Volcanic eruption with lava particles |
| TGorillaExplosionParticleEmitter | Explosion with expanding particles |
| TGorillaSpotParticleEmitter | Spot/splash effects |
| TGorillaWaterfallParticleEmitter | Cascading water effect |

Fire Effect Example:
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
LFire.Camera := Camera1;
LFire.Kind := TGorillaFireParticleKind.Torch;
LFire.Start();
end;
Each particle is a lightweight record containing:
TGorillaParticle = record
Position : TPoint3D; // Current 3D position
Velocity : TPoint3D; // Movement vector
Color : TAlphaColorF;// RGBA color
Size : Single; // Current size
Angle : Single; // Rotation angle
Weight : Single; // Particle weight (affects gravity)
Age : Single; // Current age (seconds)
Life : Single; // Lifetime (seconds)
Growth : Single; // Size change per frame
end;
Emitters create and manage particles. The base class TGorillaParticleEmitter provides:
Influencers manipulate particle behavior at runtime:
Presets define randomization ranges for particle properties:
// TParticlePreset: Single value randomization
property ParticleSize: TParticlePreset;
// TParticleVectorPreset: 3D vector randomization
property ParticlePosition: TParticleVectorPreset;
property ParticleVelocity: TParticleVectorPreset;
Example:
// Size between 16-32 pixels
LEmitter.ParticleSize.Preset(16, 32, 1, false);
// Velocity: up with some horizontal spread
LEmitter.ParticleVelocity.Preset(0, 50, 1000, Point3D(1, -10, 1), [axX, axY, axZ]);
Position Preset:
// Random spawn area
LEmitter.ParticlePosition.RangeX.Preset(-100, 100, 100, true);
LEmitter.ParticlePosition.RangeY.Preset(0, 0, 100, false);
LEmitter.ParticlePosition.RangeZ.Preset(-100, 100, 100, true);
LEmitter.ParticlePosition.Direction.Point := Point3D(1, 1, 1);
Velocity Preset:
// Upward movement
LEmitter.ParticleVelocity.Direction.Point := Point3D(0, -1, 0);
LEmitter.ParticleVelocity.RangeY.Preset(100, 200, 1000, false);
Size & Growth:
// Start size
LEmitter.ParticleSize.Preset(32, 64, 1, false);
// Growth (shrinking particles)
LEmitter.ParticleGrowth.Preset(-10, -5, 1000, false);
Angle & Rotation:
// Random initial angle
LEmitter.ParticleAngle.Preset(0, 360, 1, false);
// Auto-rotation in shader
LEmitter.AutoRotation := 0.5;
Lifetime:
// 2-5 seconds lifetime
LEmitter.ParticleLifeTime.Preset(2000, 5000, 1000, false);
Weight:
// Affects gravity influence
LEmitter.ParticleWeight.Preset(1, 10, 10, false);
Basic Emission:
LEmitter.EmitParticles := 10; // Emit 10 particles per interval
LEmitter.MaxParticles := 1000; // Maximum 1000 active particles
LEmitter.EmitTime := 16; // Update every 16ms (~60 FPS)
LEmitter.AutoEmit := True; // Emit automatically
Limited Duration:
// Emit for 5 seconds then stop
LEmitter.MaxAutoEmitTime := 5000;
LEmitter.AutoEmit := True;
LEmitter.Start();
Manual Emission:
// Disable auto-emit
LEmitter.AutoEmit := False;
LEmitter.Start();
// Emit manually (e.g., on mouse click)
procedure TForm1.ViewportClick(Sender: TObject);
var
LPos: TPoint3D;
begin
LPos := Get3DPosition(Mouse.X, Mouse.Y);
LEmitter.EmitParticle(LPos);
end;
Blending:
// Additive blending (bright fire/explosions)
LEmitter.BlendFunc := TBlendEquationFunc.befAdd;
LEmitter.BlendSource := TBlendFactor.bfOne;
LEmitter.BlendDest := TBlendFactor.bfOne;
// Alpha blending (smoke/fog)
LEmitter.BlendFunc := TBlendEquationFunc.befAdd;
LEmitter.BlendSource := TBlendFactor.bfSrcAlpha;
LEmitter.BlendDest := TBlendFactor.bfOneMinusSrcAlpha;
Particle Fading:
// Fade particle edges to prevent clipping artifacts
LEmitter.ParticleFade := 2.5;
Debug Visualization:
LEmitter.ShowBounds := True; // Show bounding box
The default influencer that applies velocity to position:
// Automatically created with every emitter
// Applies: Position += Velocity * DeltaTime
Creates spiral/helical motion (great for snowflakes):
var
LSpiral: TGorillaSpiralParticleInfluencer;
begin
LSpiral := TGorillaSpiralParticleInfluencer.Create(LEmitter);
LSpiral.Emitter := LEmitter;
LSpiral.Spirals := 10; // Number of spirals in lifetime
LSpiral.Enabled := True;
end;
Simulates falling particles:
var
LGravity: TGorillaGravityParticleInfluencer;
begin
LGravity := TGorillaGravityParticleInfluencer.Create(LEmitter);
LGravity.Emitter := LEmitter;
LGravity.Force.Point := Point3D(0, 9.81, 0); // Earth gravity (m/s²)
LGravity.Ratio := 0.01; // Power multiplier
LGravity.Enabled := True;
end;
Creates wind zones affecting particles:
var
LWind: TGorillaWindParticleInfluencer;
begin
LWind := TGorillaWindParticleInfluencer.Create(LEmitter);
LWind.Emitter := LEmitter;
LWind.Origin.Point := Point3D(0, 0, 0);
LWind.Size.Point := Point3D(50, 20, 20);
LWind.Force.Point := Point3D(-8.0, 0, 0); // Beaufort scale (m/s)
LWind.Enabled := True;
end;
Beaufort Wind Scale:
| Speed (m/s) | Description |
|---|---|
| 0.0 - 0.2 | Calm |
| 0.3 - 1.6 | Light air |
| 1.6 - 3.4 | Light breeze |
| 5.5 - 8.0 | Moderate breeze |
| 13.9 - 17.2 | Strong breeze |
| 32.7+ | Hurricane |
Creates gravitational attraction to a point:
var
LTractor: TGorillaTraktorInfluencer;
begin
LTractor := TGorillaTraktorInfluencer.Create(LEmitter);
LTractor.Emitter := LEmitter;
LTractor.Center := Point3D(0, 0, 0);
LTractor.Radius := 50;
LTractor.Acceleration := 0.25;
LTractor.Enabled := True;
end;
Particles follow a predefined 3D path:
var
LTrail: TGorillaTrailedParticleInfluencer;
begin
LTrail := TGorillaTrailedParticleInfluencer.Create(LEmitter);
LTrail.Emitter := LEmitter;
// Define path points
LTrail.Path.MoveTo3D(Point3D(0, 0, 0));
LTrail.Path.LineTo3D(Point3D(10, 5, 0));
LTrail.Path.CurveTo3D(Point3D(20, 10, 5), Point3D(15, 7, 2));
LTrail.Enabled := True;
end;
Interpolate between start and end colors:
var
LColor: TGorillaColoredParticleInfluencer;
begin
LColor := TGorillaColoredParticleInfluencer.Create(LEmitter);
LColor.Emitter := LEmitter;
LColor.StartColor := TAlphaColorRec.Blue;
LColor.EndColor := TAlphaColorRec.Red;
LColor.Enabled := True;
end;
Apply random colors to particles:
var
LRandColor: TGorillaRandomColorParticleInfluencer;
begin
LRandColor := TGorillaRandomColorParticleInfluencer.Create(LEmitter);
LRandColor.Emitter := LEmitter;
LRandColor.Enabled := True;
end;
Simple collision with spheres, cubes, or meshes:
var
LObstacle: TGorillaObstacleInfluencer;
begin
LObstacle := TGorillaObstacleInfluencer.Create(LEmitter);
LObstacle.Emitter := LEmitter;
LObstacle.Kind := TParticleObstacleKind.Sphere;
LObstacle.Center := Point3D(0, 0, 0);
LObstacle.Radius := 5;
LObstacle.Surface := TParticleObstacleSurface.Reflect;
LObstacle.Acceleration := 9.81;
LObstacle.Elasticity := 0.1;
LObstacle.Enabled := True;
end;
Obstacle Types:
Sphere - Spherical collision volumeCube - Box collision volumeMesh - Custom mesh collision (experimental)Surface Modes:
Flow - Particles flow around obstacleReflect - Particles bounce off surfaceFull physics engine integration (requires Q3 / JOLT Physics package):
var
LPhysics: TGorillaPhysicsInfluencer;
begin
LPhysics := TGorillaPhysicsInfluencer.Create(LEmitter);
LPhysics.Emitter := LEmitter;
LPhysics.Physics := GorillaPhysicsSystem1;
LPhysics.Restitution := 0.1; // Bounciness
LPhysics.Density := 0.00001;
LPhysics.Enabled := True;
end;

The following example shows how to interact on particle collision. This examples has a rain emitter and when the particles collide with anything else than another particle, a splashing effect should happen. The splashing is solved again by a particle emitter component. This example uses the Q3 Physics engine.
uses
[...]
Gorilla.Material.Particle,
Gorilla.Particle.Emitter,
Gorilla.Particle.Influencer,
Gorilla.Particle.Rain,
Gorilla.Particle.Spot,
Gorilla.Physics,
Gorilla.Physics.Q3.Body;
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
protected
FViewport : TGorillaViewport;
FCamera : TGorillaCamera;
FPhysics : TGorillaPhysicsSystem;
FParticles : TGorillaRainParticleEmitter;
FInfluencer : TGorillaPhysicsInfluencer;
FSplashes : TGorillaSpotParticleEmitter;
procedure DoOnGorillaPhysicsNotifyContact(const AContact : Pointer {PQ3ContactConstraint};
const AOffset, ANormal : TPoint3D; const ABodyA, ABodyB : TGorillaPhysicsBody);
[...]
end;
[...]
procedure TForm1.DoOnGorillaPhysicsNotifyContact(const AContact : Pointer {PQ3ContactConstraint};
const AOffset, ANormal : TPoint3D; const ABodyA, ABodyB : TGorillaPhysicsBody);
begin
// collision detected - create splashes on particle-sphere/box/terrain/mesh collision
// not on particle-particle collision (too much)
if (PTypeInfo(TQ3Body(ABodyA).UserDataType) = TypeInfo(PGorillaParticle))
and (PTypeInfo(TQ3Body(ABodyB).UserDataType) = TypeInfo(PGorillaParticle)) then
Exit;
if (PTypeInfo(TQ3Body(ABodyA).UserDataType) = TypeInfo(PGorillaParticle)) then
FSplashes.EmitParticle(
PGorillaParticle(TQ3Body(ABodyA).UserData)^.Position
)
else if (PTypeInfo(TQ3Body(ABodyB).UserDataType) = TypeInfo(PGorillaParticle)) then
FSplashes.EmitParticle(
PGorillaParticle(TQ3Body(ABodyB).UserData)^.Position
);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
[...]
// create physics system with contact callback function to display splashes
FPhysics := TGorillaPhysicsSystem.Create(FViewport);
FPhysics.OnBeginContact := DoOnGorillaPhysicsNotifyContact;
// create rain particle emitter
FParticles := TGorillaRainParticleEmitter.Create(FViewport);
FParticles.Parent := FViewport;
FParticles.Camera := FCamera;
FParticles.EmitParticles := 25;
// preconfigure particles
FParticles.Colored.StartColor := TAlphaColorF.Create( TAlphaColorRec.Blue );
FParticles.Colored.EndColor := TAlphaColorF.Create( TAlphaColorRec.Blueviolet );
FParticles.ParticleSize.Preset(20, 20, 1, false);
FParticles.ParticleGrowth.Preset(0, 0, 1, false);
FParticles.Colored.Enabled := false;
FParticles.Wind.Enabled := false;
// create a physics influencer
FInfluencer := TGorillaPhysicsInfluencer.Create(FParticles);
FInfluencer.Emitter := FParticles;
// link to physics system component
FInfluencer.Physics := FPhysics;
FInfluencer.Enabled := true;
// another particle emitter to simulate rain drop splashes when they hit an obstacle
FSplashes := TGorillaSpotParticleEmitter.Create(FViewport);
FSplashes.Parent := FViewport;
FSplashes.Camera := FCamera;
FSplashes.LoadTexture('splash.png');
// Activate physics
FPhysics.Active := true;
// Activate rain particle emitter
FParticles.Start();
FParticles.Splashes.Stop(); // BUGFIX: in some cases sub-emitters rendering black
// Active splash emitter
FSplashes.Start();
end;
Animate particles using texture atlases:
var
LMaterial: TGorillaParticleMaterialSource;
begin
LMaterial := TGorillaParticleMaterialSource.Create(Self);
LMaterial.IsSpriteSheet := True;
LMaterial.SpriteSheetRowCount := 4;
LMaterial.SpriteSheetColCount := 4;
LMaterial.FrameWidth := 256;
LMaterial.FrameHeight := 256;
LMaterial.Duration := 1.5; // Animation duration
LMaterial.Texture.LoadFromFile('explosion_spritesheet.png');
LEmitter.MaterialSource := LMaterial;
end;
Helper Method:
LEmitter.LoadTexture(
'explosion.png', // Filename
64, // Particle size
True, // Is sprite sheet
4, 4, // Rows, columns
256, 256 // Frame width/height
);
Reuse expired particles for better performance:
LEmitter.Reuse := True; // Enable caching (default)
// Clear cached particles
LEmitter.ClearUnused();
// Clear all particles
LEmitter.Clear();
Process particles on background thread:
LEmitter.Async := True; // Enable async mode
LEmitter.EmitTime := 16;
LEmitter.Start();
// Access the thread
if Assigned(LEmitter.Thread) then
ShowMessage('Async thread running');
Note: Async mode is recommended for particle systems with > 5000 particles or complex influencers.
Of course you can use the power of Firemonkey to control particle emission by mouse interaction. In the following example, we setup a raw emitter with our own particle material. By the viewport MouseUp, MouseDown and MoveMove events we can detect mouse events. This demo should emit particles every time the mouse is pressed and move. By this we can "draw" particles.

var
FParticles : TGorillaParticleEmitter;
procedure TForm1.FormCreate(Sender: TObject);
var LParticleMat : TParticleMaterialSource;
LColorInfl : TGorillaColoredParticleInfluencer;
begin
// create the particle material shader
LParticleMat := TParticleMaterialSource.Create(FGorilla);
LParticleMat.Parent := FGorilla;
LParticleMat.UseTexture := false;
LParticleMat.IsTextureAtlas := false;
// create particle emitter for spraying effect
FParticles := TGorillaParticleEmitter.Create(FGorilla);
FParticles.Parent := FGorilla;
// connect particle shader and emitter
LParticleMat.Emitter := FParticles;
// limit number of particles
FParticles.EmitParticles := 100;
FParticles.MaxParticles := 10000;
// disable auto emittance, becaus we want only to emit on mouse click
FParticles.AutoEmit := false;
// enable particle caching
FParticles.Reuse := true;
// randomize particle properties
// 1) random position of particles
FParticles.ParticlePosition.Preset(0, 0, 1000, Point3D(1, 1, 1), [axX, axY, axZ]);
// 2) random velocity of particles
FParticles.ParticleVelocity.Preset(5, 10, 1000, Point3D(1, 2, 1), [axX, axY, axZ]);
FParticles.ParticleVelocity.RangeY.Negative := false;
// 3) the rest of properties
FParticles.ParticleSize.Preset(2, 3, 1, false);
FParticles.ParticleAngle.Preset(0, 360, 1, false);
FParticles.ParticleWeight.Preset(1, 1, 1, false);
FParticles.ParticleGrowth.Preset(0, 0, 1, false);
FParticles.ParticleLifeTime.Preset(500, 5000, 1000, false);
// create a color influencer for a starting and end color
LColorInfl:= TGorillaColoredParticleInfluencer.Create(FParticles);
LColorInfl.StartColor := TAlphaColorF.Create(0, 1, 0, 1);
LColorInfl.EndColor := TAlphaColorF.Create(0, 0, 1, 0);
end;
var
FLatest : TPointF;
FMouseMove : Boolean = false;
FClickPt : TPoint3D;
procedure TForm1.DoOnViewportMouseUp(ASender : TObject; AButton : TMouseButton;
AShift : TShiftState; X, Y : Single);
begin
FMouseMove := false;
end;
procedure TForm1.DoOnViewportMouseDown(ASender : TObject; AButton : TMouseButton;
AShift : TShiftState; X, Y : Single);
var I : Integer;
begin
if (ssLeft in AShift) then
begin
FMouseMove := true;
FLatest := PointF(X, Y);
// emit particles at mouse position
FClickPt := FGorilla.ScreenToWorld(Point(round(X), round(Y)));
for I := 0 to (FParticles.EmitParticles - 1) do
FParticles.EmitParticle(FClickPt);
end;
end;
procedure TForm1.DoOnViewportMouseMove(ASender : TObject; AShiftState : TShiftState;
X, Y : Single);
var lDiff : TPointF;
I : Integer;
lOrigin : TPoint3D;
begin
if (ssLeft in AShiftState) then
begin
// emit particles at mouse position
FClickPt := FGorilla.ScreenToWorld(Point(round(X), round(Y)));
for I := 0 to (FParticles.EmitParticles - 1) do
FParticles.EmitParticle(FClickPt);
end;
if FMouseMove then
begin
FLatest := PointF(X, Y);
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// on some constellations you will need an interval to update the viewport
FGorilla.Invalidate();
end;
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
LFire.Camera := Camera1;
LFire.Kind := TGorillaFireParticleKind.Default; // or Alternative, Torch
LFire.Start();
// Optional: Access smoke component
LFire.Smoke.Visible := True;
end;
var
LRain: TGorillaRainParticleEmitter;
begin
LRain := TGorillaRainParticleEmitter.Create(Self);
LRain.Parent := GorillaViewport1;
LRain.Camera := Camera1;
LRain.Width := 100;
LRain.Height := 50;
LRain.Depth := 100;
LRain.SpawnSize := 0.05; // 5% from top
LRain.Start();
// Configure wind
LRain.Wind.Force.Point := Point3D(-5, 0, 0);
// Enable splashes
LRain.Splashes.Visible := True;
end;
var
LSnow: TGorillaSnowParticleEmitter;
begin
LSnow := TGorillaSnowParticleEmitter.Create(Self);
LSnow.Parent := GorillaViewport1;
LSnow.Camera := Camera1;
LSnow.Width := 100;
LSnow.Height := 50;
LSnow.Depth := 100;
LSnow.Start();
end;
var
LExplosion: TGorillaExplosionParticleEmitter;
begin
LExplosion := TGorillaExplosionParticleEmitter.Create(Self);
LExplosion.Parent := GorillaViewport1;
LExplosion.Camera := Camera1;
LExplosion.MaxAutoEmitTime := 1000; // 1 second burst
LExplosion.Start();
end;
MaxParticles based on target hardware// 60 FPS updates
LEmitter.EmitTime := 16;
// 30 FPS updates (better performance)
LEmitter.EmitTime := 33;
// Always enable for performance
LEmitter.Reuse := True;
Influencer.Enabled := False// Enable for > 5000 particles
if LEmitter.MaxParticles > 5000 then
LEmitter.Async := True;
Always link emitter to active camera for proper sorting:
LEmitter.Camera := GorillaViewport1.Camera;
// Continuous effect
LEmitter.MaxAutoEmitTime := 0; // Infinite
LEmitter.ParticleLifeTime.Preset(2000, 4000, 1000, False);
// One-time effect (explosion)
LEmitter.MaxAutoEmitTime := 1000; // 1 second
LEmitter.ParticleLifeTime.Preset(500, 1500, 1000, False);
Force particle update independently of timer:
LEmitter.ForceUpdate();
LEmitter.OnStart := OnEmitterStart;
LEmitter.OnStop := OnEmitterStop;
LEmitter.OnEmitted := OnParticleEmitted;
LEmitter.OnDispose := OnParticleDispose;
LEmitter.OnProcess := OnAutoEmitProcess;
// Stop emitter
LEmitter.Stop();
// Clear all particles
LEmitter.Clear();
// Remove influencers
LEmitter.ClearInfluencers();
LEmitter.Visible := TrueLEmitter.Start() was calledMaxParticles > 0MaxParticlesEmitTime intervalAsync := TrueReuse := TrueLEmitter.Camera := Camera1Influencer.Enabled := TrueInfluencer.Emitter := LEmitterThe Gorilla3D Terrain System provides powerful tools for creating realistic landscapes in your 3D applications. This guide covers everything you need to know about creating, customizing, and optimizing terrain in your games and simulations.
The terrain system offers three main components:
The simplest way to create terrain is to drop a TGorillaTerrain component onto your viewport:
var
LTerrain: TGorillaTerrain;
begin
LTerrain := TGorillaTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Width := 100;
LTerrain.Height := 20;
LTerrain.Depth := 100;
LTerrain.SetXYResolution(256, 256);
end;
Heightmaps are grayscale images where pixel brightness determines terrain height.
var
LHeightMap: TBitmap;
begin
LHeightMap := TBitmap.Create;
try
LHeightMap.LoadFromFile('terrain_heightmap.png');
LTerrain.HeightMap := LHeightMap;
LTerrain.RebuildTerrain;
finally
LHeightMap.Free;
end;
end;
You can load heightmaps directly in the IDE:
HeightMap property[...] button to open the bitmap editorBenefits of Design-Time Loading:
Note: After loading a heightmap at design-time, click the viewport to refresh the display.
Resolution defines the number of vertices in your terrain grid. Higher resolution means more detail but requires more memory and processing power.
Recommended Resolutions:
// Set resolution using property
LTerrain.Resolution := Point(256, 256);
// Or set X and Y separately
LTerrain.ResolutionX := 256;
LTerrain.ResolutionY := 256;
// Or use the method
LTerrain.SetXYResolution(256, 256);
Important: Android has a maximum of 65,536 indices per mesh. Keep resolutions below 256×256 for mobile platforms.
Enable static buffering to upload terrain data directly to GPU memory:
LTerrain.StaticBuffering := True; // Default
// or use (1st parameter is for static buffering)
LTerrain.RebuildTerrain(True, False);
Note: Static buffering improves rendering performance but prevents showing debug visualizations (grid/vertices).
Reduce vertex count while maintaining visual quality:
// Automatic decimation during rebuild
LTerrain.AutoDecimate := True;
LTerrain.RebuildTerrain;
// Manual decimation with custom parameters
LTerrain.RebuildTerrain(False, False); // Keep mesh data in memory
LTerrain.Decimate(0.2, 3.0, 0.0001);
LTerrain.StaticBuffering := True; // Upload to GPU after decimation
Decimation Parameters:
Generate realistic terrain without heightmap images using procedural algorithms.
Creates smooth rolling hills:
var
LAlgorithm: THillRandomTerrain;
begin
LAlgorithm := THillRandomTerrain.Create;
try
LAlgorithm.Size := 9; // Grid size (2^9+1 = 513x513)
LAlgorithm.Hills := 20; // Number of hills
LAlgorithm.MinRadius := 10; // Minimum hill radius
LAlgorithm.MaxRadius := 100; // Maximum hill radius
LTerrain.RandomTerrain(LAlgorithm);
finally
LAlgorithm.Free;
end;
end;
// Or use the simple version
LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Hill);
Popular algorithm for realistic terrain with valleys and peaks:
var
LAlgorithm: TDiamondSquareTerrain;
begin
LAlgorithm := TDiamondSquareTerrain.Create;
try
LAlgorithm.Size := 9; // Grid size
LAlgorithm.MSeed := 1000; // Random seed
LTerrain.RandomTerrain(LAlgorithm);
finally
LAlgorithm.Free;
end;
end;
Smooth, natural-looking terrain with configurable interpolation:
var
LAlgorithm: TPerlinNoiseTerrain;
begin
LAlgorithm := TPerlinNoiseTerrain.Create;
try
LAlgorithm.Size := 7;
LAlgorithm.Intensity := 0.25;
LAlgorithm.Interpolation := TPerlinNoiseInterpolation.Cosine;
LAlgorithm.DiamondSquareFactor := 0.75;
LAlgorithm.DiamondSquareEnabled := True;
LTerrain.RandomTerrain(LAlgorithm);
finally
LAlgorithm.Free;
end;
end;
Interpolation Types:
Linear - Fast, sharp edgesCosine - Smooth, natural (default)Cubic - Very smooth, slowerCreates flat elevated areas surrounded by lower terrain:
var
LAlgorithm: TPlateauTerrain;
begin
LAlgorithm := TPlateauTerrain.Create;
try
LAlgorithm.Size := 9;
LAlgorithm.Plateaus := 3; // Number of plateaus
LAlgorithm.MinSize := 50; // Minimum radius
LAlgorithm.MaxSize := 250; // Maximum radius
LAlgorithm.MinHeight := 0.25; // Minimum height factor
LAlgorithm.MaxHeight := 1.0; // Maximum height factor
LAlgorithm.Inverted := False; // True for lowlands instead
LTerrain.RandomTerrain(LAlgorithm);
finally
LAlgorithm.Free;
end;
end;
Particle-based terrain with smooth deformation:
var
LAlgorithm: TBrownianTerrain;
begin
LAlgorithm := TBrownianTerrain.Create;
try
LAlgorithm.Size := 9;
LAlgorithm.Particles := 3000; // More = more detail, slower
LAlgorithm.MinHeight := 0.01;
LAlgorithm.MaxHeight := 0.05;
LTerrain.RandomTerrain(LAlgorithm);
finally
LAlgorithm.Free;
end;
end;
You can generate procedural terrain directly in the IDE without writing code:
TGorillaTerrain component onto your viewportBenefits:
Customization: The design-time generators use default parameters. For fine-tuned control, use the runtime approach with custom algorithm properties.

Smooth heightmaps that are lower resolution than your terrain grid:
LTerrain.Smoothing := 5; // Range: 0-20, higher = smoother
Smoothing applies blur iterations to the heightmap before generating vertices. Set to 0 to disable.
Render both front and back faces of terrain triangles:
LTerrain.TwoFace := True;
Note: Keep this False (default) for better performance. Only enable if you need to see terrain from below.
Visualize terrain structure during development:
// Show vertex points
LTerrain.ShowVertices := True;
LTerrain.VerticeColor := TAlphaColorRec.Yellow;
// Show polygon grid
LTerrain.ShowGrid := True;
Important: Debug visualization only works when StaticBuffering := False. Disable in production builds.
Use BeginUpdate/EndUpdate to batch property changes:
LTerrain.BeginUpdate;
try
LTerrain.Width := 200;
LTerrain.Height := 50;
LTerrain.Resolution := Point(512, 512);
LTerrain.Smoothing := 10;
finally
LTerrain.EndUpdate; // Rebuilds once
end;
The planting feature allows you to automatically populate terrain with vegetation, rocks, or other objects. It's an instancing system that adjusts models to follow terrain topology.
The planting algorithm:
Important: All submeshes inside the source model are treated equally when creating instances.
Configure planting directly in the IDE:

The planting algorithm is straight forward and treats all submeshes inside the source model equaly on creating instances. Therefore it can produce unexpected results.
The source model should contain a flat hierarchy without or less transformation of sub-meshes.
NOTICE: The applied instance transformation is absolute and not relative to the source model.
The algorithm will create instances for all meshes inside the selected template / source model.
Basically the algorithm splits the terrain into cells for more realistic placement.
| Setting | Description |
|---|---|
| Clear Instances | Clears all previously available instances in the source. |
| Minimum Scale | If “Random Scaling” is activated, this is the lowest limit for scaling. |
| Instance Scale | A basis scaling of each instance (will be multiplied with source scale if “Apply Source Transformation” is activated. |
| Space | Adjustment between cell-center and source size. |
| Padding | Increasing this value will compress cells for planting. Objects will be placed closer together. |
| Random Y-Rotation | This is not suitable for all kind of source models. Depending on the internal transformation of submeshes. |
| Random Scaling | This will randomly scale instances with limitations given by “Minimum Scale”. |
| Apply Random Grid-Offset | Terrain is splitted into equal size grid cells. To produce a more realistic look, you can add some random offset to the cell-center. |
| Apply Source Transformation | It will apply the transformation of the owner model. This is not suitable for all kind of models, depending on the internal transformation of submeshes. |
| Count | The number of instances that should be created. This should be adjusted to the GPU you are using and the outcome you expect. |

Create planetary terrain with TGorillaSphereTerrain:
var
LSphereTerrain: TGorillaSphereTerrain;
begin
LSphereTerrain := TGorillaSphereTerrain.Create(Self);
LSphereTerrain.Parent := GorillaViewport1;
LSphereTerrain.Width := 50;
LSphereTerrain.Height := 50;
LSphereTerrain.Depth := 50;
LSphereTerrain.SetXYResolution(512, 512);
LSphereTerrain.HeightScale := 0.1; // Controls deformation amount
// Load heightmap for planet surface
LSphereTerrain.HeightMap := MyPlanetHeightMap;
LSphereTerrain.RebuildTerrain;
end;
The sphere terrain uses the same algorithms as planar terrain but deforms a sphere surface instead of a flat plane.
TGorillaCVLODTerrain provides level-of-detail optimization for large terrains. It stands for Camera-View-Level-Of-Detail-Terrain.
var
LLODTerrain: TGorillaCVLODTerrain;
begin
LLODTerrain := TGorillaCVLODTerrain.Create(Self);
LLODTerrain.Parent := GorillaViewport1;
LLODTerrain.Camera := Camera1; // Required for distance calculations
LLODTerrain.Width := 500;
LLODTerrain.Height := 50;
LLODTerrain.Depth := 500;
LLODTerrain.SetXYResolution(256, 256);
// LOD configuration
LLODTerrain.CurrentLOD := 0; // 0 = highest detail
LLODTerrain.LODLevels := 4; // Number of detail levels
LLODTerrain.ClusterSize := 32; // Vertices per cluster
LLODTerrain.CameraMovementThreshold := 5.0; // Update sensitivity
LLODTerrain.UpdateInterval := 100; // Update frequency (ms)
LLODTerrain.RebuildTerrain;
end;
Note: The LOD clustering system is experimental. For best results, use the CurrentLOD property to test different detail levels.
Apply materials to terrain using material sources:
var
LMaterial: TGorillaLambertMaterialSource;
begin
LMaterial := TGorillaLambertMaterialSource.Create(Self);
LMaterial.Diffuse := 'grass_texture.png';
LMaterial.Normal := 'grass_normal.png';
LTerrain.MaterialSource := LMaterial;
end;
Texture coordinates are automatically generated based on terrain position (0,0 to 1,1).
Create custom procedural terrain by extending TRandomTerrainAlgorithm:
type
TMyCustomTerrain = class(TRandomTerrainAlgorithm)
protected
procedure Generate;
public
function GetHeightMap: TBitmap; override;
end;
procedure TMyCustomTerrain.Generate;
var
x, y: Integer;
begin
FWidth := 513;
FHeight := 513;
SetLength(FData, FWidth);
for x := 0 to FWidth - 1 do
begin
SetLength(FData[x], FHeight);
for y := 0 to FHeight - 1 do
begin
// Your custom height calculation
FData[x][y] := YourHeightFunction(x, y); // Range 0.0 to 1.0
end;
end;
end;
function TMyCustomTerrain.GetHeightMap: TBitmap;
begin
Generate;
Result := inherited GetHeightMap; // Converts FData to bitmap
end;
StaticBuffering for terrains that don't changeTwoFace unless absolutely neededThe Gorilla3D Arena is the multiplayer building block: a set of components that let several devices find each other on a network, agree on who is taking part, and play a turn based game together — without writing a line of socket code.
It sits on RTL App Tethering (System.Tether) and adds what an actual
application needs on top of it: a role, a message envelope, a member list,
seating and turn order — and the handful of repairs without which two devices
on an ordinary Wi-Fi never find each other at all.
Three layers, each usable on its own. Pick the one that matches how much you want done for you.
TGorillaArenaMatch seating, turn order, host authority, state sync
| uses IGorillaArenaRules
v
TGorillaArenaSession role, transport, member list, one message channel
| TGorillaArenaMessage envelopes
v
TGorillaArenaManager pairing, profiles, users, mirrored entities
|
v
System.Tether RTL App Tethering (UDP discovery + TCP transport)
Both TGorillaArenaSession and TGorillaArenaMatch are components: drop one on
a form, wire its events in the object inspector, and the network half of a
multiplayer application is done.
Beside that stack sits the lobby directory, a small PHP endpoint that takes the place of reading an IP address out to somebody over the phone. It is optional and independent of everything above.
| Page | Content |
|---|---|
| Arena Manager | TGorillaArenaManager: pairing, profiles, the user list, and mirrored entities |
| Session | TGorillaArenaSession: roles, transport, members, messages, and the network repairs |
| Match | TGorillaArenaMatch: seating, whose turn it is, host authority, state synchronisation |
| Rules | IGorillaArenaRules: writing the rules a match is played by |
| Lobby Directory | TGorillaArenaDirectory and the PHP endpoint behind it: pick a session from a list instead of typing an address |
| You want | Use |
|---|---|
| Objects mirrored between devices over App Tethering, your own protocol on top | TGorillaArenaManager (not on Linux) |
| A group that finds each other and exchanges messages you define | TGorillaArenaSession |
| A turn based game — cards, dice, board | TGorillaArenaMatch |
Each one is a descendant of the one above it, so moving up a layer later costs
nothing: the properties and events of the lower layer stay exactly where they
were. Users, Items, Myself and their events come from
TGorillaArenaCustomManager and are there on every layer and every platform -
see Session.
| Platform | Arena | Note |
|---|---|---|
| Windows | Yes | |
| Android | Yes | Needs a multicast lock and, from API 31, the Bluetooth permission — both handled by TGorillaArenaSession |
| macOS / iOS | Yes | |
| Linux | Yes | Always over the Arena's own transport, atDirect - App Tethering has no Linux implementation |
App Tethering (atNetwork, atBluetooth) and the Arena's own transport
(atDirect) do not see each other. As soon as one participant runs Linux,
every device has to use atDirect - it is available on Windows, Android and
macOS as well. Only the raw TGorillaArenaManager does not exist on Linux;
sessions, matches, the lobby directory, users and items do. See
Session.
| Unit | Content |
|---|---|
Gorilla.Arena.Manager |
TGorillaArenaManager — tethering, pairing, users (not on Linux) |
Gorilla.Arena.Base |
TGorillaArenaCustomManager — users, items, Myself and their events, on every platform |
Gorilla.Arena.Net |
The Arena's own transport: UDP discovery, TCP to the host (atDirect) |
Gorilla.Arena.Entity |
TGorillaArenaEntity — an object mirrored to every participant |
Gorilla.Arena.User |
TGorillaArenaUser — a participant, with colour and position |
Gorilla.Arena.Session |
TGorillaArenaSession — role, transport, members, messaging |
Gorilla.Arena.Match |
TGorillaArenaMatch — seating, turns, host authority |
Gorilla.Arena.Directory |
TGorillaArenaDirectory — publishing a session to a lobby list, and joining one from it |
Gorilla.Arena.Rules |
IGorillaArenaRules, members, seating, scoreboard |
Gorilla.Arena.Message |
The wire envelope and the sequence gate |
Gorilla.Arena.JSONWrap |
The JSON backed object entities are built on |
Gorilla.Arena.Utils |
Colour and point conversion helpers |
A complete turn based game, minus the rules:
uses
Gorilla.Arena.Rules, Gorilla.Arena.Session, Gorilla.Arena.Match;
// --- setting up -----------------------------------------------------------
FMatch := TGorillaArenaMatch.Create(Self);
FMatch.MessageResource := 'MyGame'; // both sides need the same name
FMatch.AppVersion := 1; // raise it when a payload changes shape
FMatch.RulesComponent := MyRules1; // a TGorillaArenaRules on the form
FMatch.OnMembersChanged := MembersChanged; // somebody arrived or left
FMatch.OnMatchChanged := MatchChanged; // the state or the turn moved
FMatch.OnRemoteMove := RemoteMove; // somebody else moved
FMatch.OnNotice := Notice; // something to tell the user
// --- one device opens, the others join ------------------------------------
FMatch.OpenSession('Anna');
FMatch.JoinSession('Ben');
// --- playing --------------------------------------------------------------
FMatch.StartMatch(); // host only
if FMatch.IsMyTurn() then
begin
LMove := TJSONObject.Create();
LMove.AddPair('card', 'Q');
FMatch.SubmitMove(LMove); // takes ownership
end;
What to draw comes from Participants(), Scoreboard(), Headline(),
TurnMemberName() and InMatch.
The Arena ships with the GAMEPACKAGE edition of Gorilla3D. Install the package and the three components are on the tool palette under Gorilla3D Arena.
The units are compiled with GAME_PACKAGE, because the Arena is part of that
edition. On Linux Gorilla.Arena.Manager is left out and not registered - it
is App Tethering through and through; every other unit is in the package on
every platform. Gorilla.Arena.Net only needs Indy, which the package requires
everywhere. For tethering the requires clause adds tethering on every
platform but Linux, and IndyIPServer on Windows and macOS.
atDirect)TGorillaArenaManager is the bottom layer of the Arena: it wraps RTL App
Tethering, pairs the devices, keeps the list of who is connected, and mirrors
entities between them.
Most applications never touch it directly — Session and Match descend from it and do the work. Use it on its own when you want the mirrored-object model and your own protocol on top.
The manager owns a TTetheringManager and a TTetheringAppProfile, both
created for you and both disabled until Join(). Around them it adds:
ConnectRemoteProfiles closes that gap.IGorillaArenaUser, kept in
step through the UserList resource.Two names, and they are not the same thing:
| Property | |
|---|---|
Id |
Stable identity inside the group. Defaults to a fresh GUID and is meant to stay put for the manager's lifetime. Set it before Join() to carry an identity over from somewhere else. |
DisplayName |
What other participants read. Free text, need not be unique. |
Target names the group to join. Set it before Join(); changing it while
joined disconnects and reconnects.
FManager := TGorillaArenaManager.Create(Self);
FManager.DisplayName := 'Anna';
FManager.Join();
try
// Myself exists from here on
ShowMessage(FManager.Myself.GUIDStr);
finally
FManager.Leave();
end;
Join() raises OnStatusChanged with Pending, brings tethering up, creates
the local user, and reports Joined. Leave() reports None.
| Property | |
|---|---|
Joined / Active |
True once Join() brought the manager up — with or without anybody else |
HasPeers |
True when at least one remote manager is actually paired |
Opening a table and waiting is a normal state, so Joined deliberately does
not depend on a partner being there. Ask HasPeers for that.
Users is a TGorillaArenaUserList, keyed by GUID. Myself is your own entry
and exists only between Join() and Leave().
LEnum := FManager.Users.GetEnumerator();
try
while LEnum.MoveNext() do
Memo1.Lines.Add(LEnum.Current.Value.Id);
finally
FreeAndNil(LEnum);
end;
UpdateUsers() asks every remote profile for its user list and raises
OnUserEvent with Update for each.CleanupUsers() drops users whose profile is gone and raises OnUserEvent
with Remove.To use a user class of your own, call SetUserClass() before joining:
FManager.SetUserClass(TMyArenaUser);
An entity is an object that exists on every device. Descend from
TGorillaArenaEntity and give each property a getter and setter that go
through GetJSONProperty / SetJSONProperty — no field declarations needed,
the JSON document is the storage.
type
TCard = class(TGorillaArenaEntity)
protected
function GetSuit() : String;
procedure SetSuit(const AValue : String);
published
property Suit : String read GetSuit write SetSuit;
end;
function TCard.GetSuit() : String;
begin
Result := GetJSONProperty('Suit').AsString().DeQuotedString('"');
end;
procedure TCard.SetSuit(const AValue : String);
begin
SetJSONProperty('Suit', AValue);
end;
Changing a property updates the local resource, which the other side mirrors. When you change several at once, wrap them — otherwise every single assignment goes on the wire:
LCard.BeginUpdate();
try
LCard.Suit := 'hearts';
LCard.Value := 12;
LCard.Group := 'hand';
finally
LCard.EndUpdate();
LCard.Submit();
end;
| Method | |
|---|---|
BeginUpdate / EndUpdate |
Hold back updates while several properties change |
Submit |
Update the local resource and push the whole entity to everybody |
Changed |
Update the local resource only |
| Event | |
|---|---|
OnStatusChanged |
None, Pending or Joined |
OnUserEvent |
Somebody was Added, Removed or Updated |
OnMessage |
Log output — see Log() and DoOutputMessage |
OnError |
Problems in plain text. Everything here also goes to OnMessage |
Broadcast(AResource, AData) sends a string to a named resource on every
connected profile — not to profiles discovery has merely seen.
Greeting(AMessage) is a broadcast to the built-in Greeting resource.
On a machine with more than one IPv4 subnet — a VPN client, a virtual switch,
a second card — the RTL multicast adapter writes the literal placeholder
MULTIHOMED into its connection string instead of an address. Everybody who
answers a discovery then opens a TCP connection to the host "MULTIHOMED",
which resolves nowhere. Nobody finds anybody, and no error is visible.
EnsureBindAddress works around it by setting TTetheringManager.BindToAddress
when the machine has two or more subnets. Which card it picks is a heuristic:
the ordinary home and office ranges first, then anything else routable, and
the carrier grade NAT range 100.64/10 last, because that is where VPN clients
such as Tailscale live.
Set BindToAddress yourself to take the guess out, or override
PickBindAddress. Note that TGorillaArenaSession already overrides it to
return an empty string — see Session for why
that is the better answer for a broadcast based session.
SetupDefaultProfile is the extension point for declaring resources of your
own:
procedure TMyManager.SetupDefaultProfile();
var LRes : TLocalResource;
begin
inherited;
LRes := FAppProfile.Resources.Add();
LRes.Name := 'MyChannel';
LRes.OnResourceReceived := MyChannelReceived;
end;
It is deliberately not called from the constructor: a virtual method called
out of a constructor runs before the constructor of the descendant that
overrides it, so the override would see its own fields still empty. The manager
runs it on the first Join() instead.
The manager is not synchronized. It relies on the tethering manager delivering
its events on the main thread, which is what TTetheringManager.SynchronizeEvents
does and what it defaults to. Switch that off and every handler runs on a
worker thread, and guarding the user and item lists becomes your job.
The only work the manager does off the main thread by itself is
RequestRemoteResourcesAsync, and that one hands its result back through
TThread.Queue.
TGorillaArenaSession is a group of devices that found each other, know who is
there, and can send each other messages. Drop it on a form, call OpenSession
on one device and JoinSession on the others — discovery, pairing, connecting
the profiles, the member list and one message channel are all done for you.
Turn taking is not in here; that is Match, which descends from this class.
FSession := TGorillaArenaSession.Create(Self);
FSession.MessageResource := 'MyGame';
FSession.AppVersion := 1;
FSession.OpenSession('Anna'); // one device
FSession.JoinSession('Ben'); // the others
FSession.JoinSession('Ben', '192.168.1.14'); // ... when discovery is blocked
FSession.CloseSession();
OpenSession reports the address it is reachable at through OnNotice —
worth showing, because it is what somebody types in when the automatic search
comes up empty. LocalAddress() returns the same value.
On Android both calls first ask for the Bluetooth permission and only then do
their work, so do not assume the session is up when the call returns. Wait
for OnMembersChanged or OnNotice.
The third form of JoinSession takes a host directly — an address or a manager
name. It is the way out on networks that isolate their clients from each other,
such as guest Wi-Fi with AP isolation. The Lobby Directory
exists so that players do not have to type it.
| Value | |
|---|---|
asrOffline |
Not in a session at all |
asrHost |
Opened the session; keeps the state and decides everything |
asrClient |
Joined somebody else's session |
Role, and the shortcuts IsHost and IsOffline, tell you where you stand.
Members() returns everybody the session knows about, yourself included:
type
TGorillaArenaMember = record
Id : String; // stable identity, handed out by the session
Name : String; // what the others read
Here : Boolean; // false once somebody left mid match
end;
MyId() is your own id — empty until you opened or joined. MemberName(AId)
resolves an id, MemberCount counts them. OnMembersChanged fires whenever
the list moves.
One channel carries everything, named by MessageResource. Every message is a
JSON envelope with a version, a type, its sender, a sequence number and a free
form payload:
LMsg := FSession.NewMessage('chat');
LMsg.SetStr('text', 'well played');
FSession.SendMessage(LMsg); // takes ownership
Anything the framework does not recognise arrives at OnAppMessage:
procedure TForm1.AppMessage(const ASender : TObject;
AMessage : TGorillaArenaMessage; var AHandled : Boolean);
begin
if AMessage.MsgType = 'chat' then
begin
Memo1.Lines.Add(FSession.MemberName(AMessage.From) + ': '
+ AMessage.GetStr('text'));
AHandled := true;
end;
end;
The message is borrowed — it is freed as soon as the handler returns.
Two things are filtered out before any of that: your own broadcast coming back to you, and anything the sequence gate has already seen. Tethering does not promise ordering across resources and may deliver a resource twice, so every sender numbers its own messages upwards and anything not newer is dropped.
Exactly one transport at a time:
| Value | Carried by | Platforms |
|---|---|---|
atNetwork |
App Tethering, UDP broadcast over the local network | Windows, Android, macOS, iOS |
atBluetooth |
App Tethering, RFCOMM to a device already paired at operating system level | Windows, Android, macOS |
atDirect (default) |
The Arena's own transport (Gorilla.Arena.Net): UDP discovery, one TCP connection per client to the host |
Windows x86/x64/ARM64EC, Linux x64, Android 32/64, macOS x64/ARM64 |
The two worlds do not see each other. A device on atDirect neither finds
nor is found by one on tethering. As soon as one participant runs Linux — where
atDirect is the only transport and is used whatever Transport says — every
device has to be set to atDirect.
FMatch.Transport := TGorillaArenaTransport.atDirect;
FMatch.OpenSession('Anna'); // host
FMatch.JoinSession('Ben'); // first host of this app that answers
FMatch.JoinSession('Ben', '192.168.1.14'); // that machine, no discovery
FMatch.JoinSession('Ben', 'box.local:47812'); // host name with port
FMatch.JoinSession('Ben', 'Anna'); // the host called Anna
DirectPort (47810 — when it is taken,
the next nine are tried) and answers discovery on UDP DiscoveryPort
(47811). Every client holds exactly one connection, to the host, which
relays what a client sends to everybody else. The member list is the host's
roster.MULTIHOMED problem, nothing to choose by hand.MessageResource is the application key: a
host ignores discovery requests of other applications and refuses their
connections with a notice saying why.CheckSynchronize.DirectPort (+9) and UDP DiscoveryPort
open inbound. Windows asks the first time a host opens.For atNetwork and atBluetooth this is a choice and not a set, and the
reason is structural: every allowed
adapter runs a discovery of its own, so both devices find each other more than
once and start a profile connection per find — and then sit in
TTetheringAppProfile.Connect waiting for an answer the other one cannot give,
because it is waiting itself. On Android the system kills the app for not
responding.
Bluetooth is the way out when the network is not one: a guest Wi-Fi that isolates its clients, a firewall in the way, or no Wi-Fi at all. It only ever reaches devices already paired at operating system level, and its search costs seconds per paired device.
Transport is read when a session is opened or joined, so changing it while
one is running does nothing until the next one.
Users, Items, Myself, OnUserEvent and OnItemEvent come from
TGorillaArenaCustomManager (Gorilla.Arena.Base) and are the same on every
platform and every transport.
// Myself exists once a session is open, and is shared by itself
FMatch.Myself.Position := Point3D(1, 0, 2); // everybody sees it
// several changes, one message
FMatch.Myself.BeginUpdate();
try
FMatch.Myself.Position := LPos;
FMatch.Myself.Color := LColor;
finally
FMatch.Myself.EndUpdate();
end;
// items of your own
TGorillaArenaEntity.RegisterEntityClass(TSword); // once, on every device
LSword := TSword.Create(FMatch);
LSword.Id := 'Excalibur';
LSword.Power := 5;
FMatch.AddItem(LSword); // everybody gets a TSword with Power = 5
LSword.Power := 7; // ... and this change
FMatch.RemoveItem(LSword); // ... and this
On atDirect:
| Rule | |
|---|---|
| Ownership | Whoever creates an entity owns it — its SourceProfile is the owner's member id. Only the owner sends it; a copy changed elsewhere stays local, and an entity claimed by somebody else is dropped |
| Changes | Every property change is sent as the whole entity; BeginUpdate/EndUpdate collapse a batch into one message |
| Late arrivals | Get the current state of every entity from every owner |
| Leaving | Takes the entities along — the others see Remove for that participant's user and items |
| Classes | Found by QualifiedName. Register your own with TGorillaArenaEntity.RegisterEntityClass on every device; an unknown class arrives as a plain TGorillaArenaEntity and says so in the log |
| Scope | Entities belong to the session: closing it clears Users and Items. Add items after OpenSession/JoinSession |
On tethering the entities keep doing what they always did — shared resources
and Item/Update streams through the app profile.
| Property | Default | |
|---|---|---|
MessageResource |
ArenaMessage |
Name of the channel. Both sides need the same one — give each application its own |
AppVersion |
1 |
Version of your payloads. Two devices with different versions refuse to talk and say so |
EnvPrefix |
ARENA |
Prefix of the environment variables below |
LogTag |
Arena |
What platform log lines are prefixed with |
Transport |
atDirect |
See above. Was atNetwork before Linux support — an application that relied on that default and wants tethering has to set it now |
SearchInterval |
4000 |
Milliseconds between two searches |
SearchWindow |
3000 |
How long one search listens |
SearchMaxTries |
15 |
How many searches before giving up |
DirectPort |
47810 |
atDirect: TCP port of the host. The next nine are tried when it is taken |
DiscoveryPort |
47811 |
atDirect: UDP port of the discovery. The same on every device |
| Event | |
|---|---|
OnNotice |
Something worth telling the user, in plain text |
OnMembersChanged |
Somebody arrived or left |
OnAppMessage |
A message no layer of the framework knew what to do with |
OnStatusChanged |
Pending when a session starts, Joined once it is up, None when it closes |
OnUserEvent |
A user was added, changed or removed |
OnItemEvent |
An item was added, changed or removed — ours or somebody else's |
The manager's own OnStatusChanged, OnUserEvent, OnMessage and OnError
stay free for you: the session overrides the protected DoStatusChanged,
DoUserEvent and DoErrorMessage methods instead of hooking its own events.
Override these in a descendant; each one is called with the member list already up to date.
| Method | |
|---|---|
DoSessionStarting |
A role was just taken, before the network comes up — throw away what the last session left behind |
DoSessionReady |
The session is up, with or without anybody else |
DoMemberArrived |
Somebody joined |
DoMemberGone |
Somebody left |
DispatchMessage |
Act on a message; return False for one you do not know |
Transmit |
The only place the session touches the network — override it to test the layers above without one |
RebuildMembers |
Rebuild the member list; likewise a test seam |
Note when overriding
DoStatusChangedorDoUserEventyourself: checkFDestroyingand leave at once when it is set. The manager reports its own teardown through them, and by then nothing may act any more.
Five things that are invisible from the outside and each of which makes a session simply never come up:
Discovery that keeps trying. The RTL searches once, for three seconds, at the moment of joining, and never again. Whether the answer arrives inside that window is luck on Wi-Fi — a phone whose radio is in power save, an access point that holds a broadcast back, a device started a little later. The session repeats the search every few seconds until somebody is there, and gives up after about a minute rather than keeping the radio busy for the whole game.
Who connects to whom. Both devices discover each other in the same moment,
and the inherited version has each of them call Connect on the other. One of
the two is refused, the refusal tears the pair down again — "lost
communication" — and the user lists never line up. A refusal is harmless only
when it means the other side got there first, and the one thing that says so is
ConnectedProfiles: Connect records a profile there on its own success and
nowhere else, and an incoming connection never appears in this side's list.
So the session asks. If the profile is connected, it goes on to fetch the user
list, without which the member list stays empty while messages are visibly
arriving. If it is not, the connection simply failed, and the search repeat
tries it again — reading that case as the harmless one is what used to leave a
side connected, receiving messages, and alone at its own table.
The passive side of a pairing. The RTL discovers the other end's profiles, and with them its user list, only for the side that pairs actively. Its own repair for the other side — the reverse connect — misfires, because that handler starts by looking up a profile this side has never discovered. Whoever ends up passive is then connected and receiving messages with a member list of one, and a host in that position can never start the match; with a direct join by address, or one out of the lobby directory, that is always the host. The search repeat therefore also asks a paired manager for its profiles again, connects to a profile it knows but is not connected to, and asks who is there. All three are no-ops once they have taken, and the repeat stops as soon as somebody is found.
The Android multicast lock. Android hands multicast to an app only while it
holds a WifiManager multicast lock. Without one the Wi-Fi stack drops the
discovery packets before the app ever sees them — a session opened on the phone
is invisible to everybody, and one opened elsewhere stays invisible to the
phone. The lock is taken when a session opens and dropped when it closes, not
held for the life of the application, because it stops the Wi-Fi chip from
filtering in power save and costs battery.
The bind address. The manager picks one address on a machine with several
and binds tethering to it. On Windows that is what keeps a session from ever
being found: discovery goes out as a limited broadcast to 255.255.255.255,
and a socket bound to one address does not receive those — only a socket on
0.0.0.0 does. The session therefore overrides PickBindAddress to return an
empty string and lets the RTL bind every card, which is the case it was written
for. <PREFIX>_BIND still overrides everything.
App Tethering has no Linux implementation — it needs System.Bluetooth, which
does not exist there. On Linux the session derives from
TGorillaArenaCustomManager instead of TGorillaArenaManager, and every
session runs over atDirect, whatever Transport says (atBluetooth adds a
notice). Sessions, matches, the lobby directory, users and items work as on
every other platform.
The properties the tethering manager publishes elsewhere — Id,
DisplayName, Target, AllowedAdapters, BindToAddress — are published on
Linux under the same names, so a form designed on Windows loads unchanged. A
form unit that lists Gorilla.Arena.Manager in its uses (the IDE adds it for
the ancestor of the session) has to put it in {$IFNDEF LINUX}.
The Gorilla3D package carries every Arena unit on Linux except
Gorilla.Arena.Manager.
Three environment variables, all prefixed with EnvPrefix:
| Variable | |
|---|---|
<PREFIX>_LOG |
Names a file to trace into |
<PREFIX>_BIND |
Names the network card by hand, overriding everything |
<PREFIX>_ADAPTERS |
Names the tethering adapters |
<PREFIX>_ADAPTERS takes names separated by semicolons or |, never by
commas: TTetheringManager.SetAllowedAdapters splits on those two only, an
unknown name matches no adapter, and the manager then registers none, listens
on nothing, and fails silently. The names are Network (plain UDP broadcast,
the RTL default), Network_V4 (multicast, despite the name) and Bluetooth.
Everything also goes to the platform log — adb logcat on Android, where there
is no console and no environment to point a variable at.
TGorillaArenaMatch is a Session in which everybody takes turns.
It adds seating, turn order, host authority and state synchronisation — the
half of a turn based game that is the same whether it is cards, dice or a
board.
What is left for the application is the rules, what a move contains, and the user interface.
Whoever opened the session owns the only rules instance that decides anything.
The others keep one of their own purely to render the state the host ships
them — they never see SubmitTurn.
host client
---- ------
rules.SubmitTurn(seat, move) <----- move
rules.StateToJSON() -----> rules.StateFromJSON()
rules.CurrentSeat() -----> turn
The consequence worth knowing: a client's rules object is a renderer. Its
CurrentSeat and Finished are never asked; what it shows comes entirely from
the state the host sent.
Host only:
FMatch.StartMatch(); // the linked rules
FMatch.StartMatch('poker'); // built through OnCreateRules
StartMatch builds the rules, checks that enough members are present
(MinMembers), fixes the seating, resets the rules, and sends everybody a
start message. Too few members, or an id nothing can build, produces a notice
and nothing else.
if FMatch.IsMyTurn() then
begin
LMove := TJSONObject.Create();
LMove.AddPair('card', 'Q');
FMatch.SubmitMove(LMove); // takes ownership; may be nil
end;
On the host that goes straight into the rules. On a client it travels to the
host, who decides and ships the result back. Either way SubmitMove does
nothing unless it really was your turn.
IsMyTurn is false again the moment you have moved, and stays false until the
host says otherwise — a repeated turn message does not put you back on.
IsMyTurn() |
It is our turn and we have not moved yet |
TurnSeat() |
Seat of whoever is on turn, or -1 |
TurnMemberName() |
Their name, or '' |
InMatch |
True while a match is running |
The seating is fixed when the match starts and does not change again.
Somebody who leaves keeps their seat and their score and is marked
Here := False; the rules are told through MemberLeft and decide what that
means — skipping their turn, or ending a match nobody is left in.
SeatOf(AId) resolves an id to a seat. Participants() is what to list:
| Situation | What it returns |
|---|---|
| A match is running | The seating |
| Before one, on a client | The roster the host sent |
| Otherwise | Whoever the session has found |
On a client the host's list beats what the local user list has caught up with — the host owns the session. A list the client is not itself in is ignored: that is one the host put together before it had heard of the newcomer, and taking it would drop them out of their own lobby until the next one arrives.
Three ways, tried in this order:
// 1. the event
FMatch.OnCreateRules := CreateRules;
procedure TForm1.CreateRules(const ASender : TObject; const AId : String;
out ARules : IGorillaArenaRules);
begin
ARules := MyGameRegistry.Build(AId); // nil for an id you do not have
end;
// 2. a component on the form
FMatch.RulesComponent := MyRules1;
// 3. set directly, for one fixed set of rules
FMatch.Rules := TMyRules.Create();
Or override CreateRules in a descendant to build them some other way. See
Rules for what to implement.
The framework does not know what your game needs on top of the roster. Four hooks put it there and read it back:
| Host side | Client side | |
|---|---|---|
DoDecorateStart |
DoApplyStart |
Anything the match needs to know once, at the start |
DoDecorateTurn |
DoApplyTurn |
Anything that belongs on every turn message |
procedure TMyMatch.DoDecorateStart(AMsg : TGorillaArenaMessage);
begin
inherited;
AMsg.SetInt('dice', FDiceCount);
end;
procedure TMyMatch.DoApplyStart(AMsg : TGorillaArenaMessage);
begin
inherited;
FDiceCount := AMsg.GetInt('dice', 2);
end;
DoRemoteMove is the other half: somebody else moved, and this is where you
show it.
procedure TMyMatch.DoRemoteMove(const AName : String;
const AMove : TJSONObject);
begin
inherited; // raises OnRemoteMove
// AMove is borrowed and may be nil
end;
Participants() |
Everybody, in the order they should be listed |
Scoreboard() |
The rules' scoreboard, or empty outside a match |
Headline() |
One line above it — "Round 2 of 3" |
RulesId |
Id of the rules in play |
HostId |
Id of whoever is hosting |
| Event | |
|---|---|
OnMatchChanged |
The state, the turn or the outcome moved |
OnRemoteMove |
Somebody else moved |
OnCreateRules |
Build the rules behind an id |
plus everything the session already offers — OnMembersChanged, OnNotice,
OnAppMessage.
Seven message types, all handled for you:
| Type | Direction | |
|---|---|---|
hello |
client → host | I am here, this is my name |
lobby |
host → all | Who is in, and which rules are selected |
start |
host → all | The match begins |
turn |
host → all | It is this member's turn |
state |
host → all | The state after a move |
over |
host → all | The match ended |
move |
client → host | What I did on my turn |
Two details that only show up in practice:
Turns are numbered. The host re-sends the current turn whenever somebody says hello — and the session layer greets more than once per join. Without a number on it, a player who had already moved would be told to move again, and would play the whole thing out a second time for nothing.
A newcomer mid match is caught up. Their hello gets the lobby, the
current state, and the running turn marked as a repeat rather than a new one.
Two people open a session and then find each other. Rather than leaving both convinced they are in charge, the lower id keeps it and the other switches to client with a notice. An arbitrary rule, but the same one on both devices, which is the only property that matters.
IGorillaArenaRules is what a Match is played by. It is the one
part the framework cannot supply: the framework knows that people take turns,
your rules know what a turn does.
Nothing in the unit knows about tethering or FireMonkey, which is what makes a set of rules testable on its own — without a network and without a form.
IGorillaArenaRules = interface(IInterface)
function GetRulesInfo() : TGorillaArenaRulesInfo;
procedure Reset(const AMembers : TGorillaArenaMembers);
function CurrentSeat() : Integer;
procedure SubmitTurn(const ASeat : Integer; const AMove : TJSONObject);
procedure MemberLeft(const ASeat : Integer);
function Finished() : Boolean;
function StateToJSON() : TJSONObject;
procedure StateFromJSON(const AState : TJSONObject);
function Headline() : String;
function Scoreboard() : TGorillaArenaScoreboard;
end;
GetRulesInfo describes the rules without playing them — this is what a lobby
lists:
| Field | |
|---|---|
Id |
Stable key. It travels on the wire, so never translate it |
Name |
What the lobby shows |
Description |
One line under the name |
MinMembers |
Fewer than this and the match will not start |
MaxMembers |
More than this are not seated. 0 means no limit |
Both implement the interface and bring the seating with them; pick by how the rules come into existence.
| Class | |
|---|---|
TGorillaArenaRules |
A component — drop it on the form and point TGorillaArenaMatch.RulesComponent at it |
TGorillaArenaCustomRules |
Reference counted, built on demand — for a registry of several games |
They give you Reset and MemberLeft already done, plus two helpers:
NextPresentSeat(AFrom) |
The next seat that is still occupied, or -1 when nobody is left |
PresentCount() |
How many are still here |
Members is the seating as an array.
A game in which everybody plays one card per round, highest wins:
type
THighCardRules = class(TGorillaArenaRules)
protected
FSeat : Integer;
FScore : TArray<Integer>;
FRound : Integer;
public
function GetRulesInfo() : TGorillaArenaRulesInfo; override;
procedure Reset(const AMembers : TGorillaArenaMembers); override;
function CurrentSeat() : Integer; override;
procedure SubmitTurn(const ASeat : Integer;
const AMove : TJSONObject); override;
function Finished() : Boolean; override;
function StateToJSON() : TJSONObject; override;
procedure StateFromJSON(const AState : TJSONObject); override;
function Headline() : String; override;
function Scoreboard() : TGorillaArenaScoreboard; override;
end;
function THighCardRules.GetRulesInfo() : TGorillaArenaRulesInfo;
begin
Result.Id := 'highcard';
Result.Name := 'High Card';
Result.Description := 'One card each, highest takes the round';
Result.MinMembers := 2;
Result.MaxMembers := 6;
end;
procedure THighCardRules.Reset(const AMembers : TGorillaArenaMembers);
begin
inherited; // fills the seating
SetLength(FScore, Length(AMembers));
FSeat := 0;
FRound := 1;
end;
function THighCardRules.CurrentSeat() : Integer;
begin
if Finished() then
Result := -1
else
Result := FSeat;
end;
procedure THighCardRules.SubmitTurn(const ASeat : Integer;
const AMove : TJSONObject);
var LCard : Integer;
begin
LCard := 0;
if Assigned(AMove) and (AMove.GetValue('card') is TJSONNumber) then
LCard := (AMove.GetValue('card') as TJSONNumber).AsInt;
Inc(FScore[ASeat], LCard);
FSeat := NextPresentSeat(ASeat);
if FSeat <= 0 then // back at the top: a round is done
Inc(FRound);
end;
function THighCardRules.Finished() : Boolean;
begin
Result := (FRound > 3) or (PresentCount() < 2);
end;
StateToJSON / StateFromJSON carry FScore, FSeat and FRound;
Scoreboard turns them into rows.
Reset is handed the seating in the order the members are to play, and that
order does not change again for the match. A member who leaves keeps their seat
so the scoreboard can still show what they scored; MemberLeft marks them, and
NextPresentSeat skips them from then on.
CurrentSeat must return -1 once the match is over, and Finished must
agree with it. The host asks Finished first: when it says yes, an over
message goes out and no turn is announced.
Watch for the case where everybody has left. NextPresentSeat returns -1
rather than spinning, and PresentCount() < 2 is usually the right thing to
put into Finished.
A move is a TJSONObject your application builds and reads; the framework only
carries it. It may be nil for rules that need no payload — check before
reading.
The move reaches the rules only on the host. Whatever a client needs to see
of it must travel in the state, or through OnRemoteMove if it is only
decoration.
StateToJSON produces everything a client needs to render, and the caller owns
the result. StateFromJSON applies what the host sent, and does not take
ownership — copy out what you keep.
function THighCardRules.StateToJSON() : TJSONObject;
var LArr : TJSONArray;
LVal : Integer;
begin
Result := TJSONObject.Create();
LArr := TJSONArray.Create();
for LVal in FScore do
LArr.Add(LVal);
Result.AddPair('score', LArr);
Result.AddPair('seat', TJSONNumber.Create(FSeat));
Result.AddPair('round', TJSONNumber.Create(FRound));
end;
Keep it small: it goes out after every single move.
TGorillaArenaScoreRow = record
Name : String;
Score : Integer; // the number that decides the ranking
Detail : String; // free text next to it
Current : Boolean; // marks the member whose turn it is
Gone : Boolean; // marks a member who left
end;
Headline() is the line above it. Both are pure presentation and are asked on
every device, including the clients, which is why they have to work off the
state alone.
Because the rules touch neither tethering nor FireMonkey, a console program is enough:
LRules := THighCardRules.Create(nil);
SetLength(LMembers, 2);
LMembers[0].Id := '{a}'; LMembers[0].Name := 'Anna'; LMembers[0].Here := true;
LMembers[1].Id := '{b}'; LMembers[1].Name := 'Ben'; LMembers[1].Here := true;
LRules.Reset(LMembers);
Assert(LRules.CurrentSeat() = 0);
LMove := TJSONObject.Create();
try
LMove.AddPair('card', TJSONNumber.Create(10));
LRules.SubmitTurn(0, LMove);
finally
FreeAndNil(LMove);
end;
Assert(LRules.CurrentSeat() = 1);
The layer above can be exercised without a network too — see
Session, where Transmit and RebuildMembers
are virtual for exactly this purpose.
Asking a player to read an IP address out to somebody over the phone is a poor thing to ask. The lobby directory replaces it: the host publishes the session it just opened, everybody else reads a list of what is open and picks one.
Two halves — a small PHP endpoint you host, and the TGorillaArenaDirectory
component that talks to it. Both are optional; a session works without either.
host directory client
---- --------- ------
OpenSession()
Publish() --register--> lobby file
<--id, token--
(every minute) --update----> refreshed
:
list <--list------ Refresh()
(no address) ---------> OnLobbies
:
address <--join------ JoinLobby()
-----------> JoinSession(addr)
... <--------------- tethering connects -----------> ...
Withdraw() --unregister-> deleted
The listing carries no address. Only join hands one out, and the component
feeds it straight into the session without letting it near the application.
uses
Gorilla.Arena.Session, Gorilla.Arena.Directory;
FDirectory := TGorillaArenaDirectory.Create(Self);
FDirectory.Endpoint := 'https://example.com/arena/';
FDirectory.Session := FSession; // or FMatch
FDirectory.OnLobbies := LobbiesArrived;
FDirectory.OnPublished := TablePublished;
FDirectory.OnJoined := TableJoined;
FDirectory.OnError := DirectoryError;
Every call goes out on a background thread and answers on the main thread, so
nothing here blocks the user interface. Busy is true while a request is in
flight.
Open the session first, then publish it:
FSession.OpenSession(PlayerName());
FDirectory.Publish('Anna''s table', 'beat', 'evenings');
From then on the component keeps the registration alive by itself — the
directory drops anything it has not heard from for a few minutes.
BeatInterval sets how often, and the default of a minute is well inside that
window.
procedure TFormMain.TablePublished(const ASender : TObject;
const AId, APublicAddress : String);
begin
FLblStatus.Text := 'Your table is listed';
// Worth showing: it is what somebody types in when the directory is
// unreachable for them.
FLblAddress.Text := APublicAddress;
end;
A fourth argument makes the table need a password. It is listed either way,
marked Locked:
FDirectory.Publish('Private round', 'beat', '', 'thePassword');
Call Withdraw() when the session closes. Without it the table lingers in the
list until it goes stale and people try to join something that is not there:
procedure TFormMain.CloseTable();
begin
FDirectory.Withdraw();
FSession.CloseSession();
end;
Update() pushes a change straight away rather than waiting for the next
heartbeat — worth it right after the player count or the state visibly changed.
The heartbeat reads both off the linked session by itself.
FDirectory.JoinLobby(LSelectedId, PlayerName());
FDirectory.JoinLobby(LSelectedId, PlayerName(), LPassword); // if Locked
That asks the directory where the table is and hands the answer to
Session.JoinSession. OnJoined confirms it — with the table's name, and
deliberately not with its address.
JoinLobby needs Session to be assigned; without one it reports the error
no_session rather than doing nothing.
FDirectory.Refresh();
procedure TFormMain.LobbiesArrived(const ASender : TObject;
const ALobbies : TGorillaArenaLobbies);
var LLobby : TGorillaArenaLobby;
begin
FList.Clear();
for LLobby in ALobbies do
FList.Add(Format('%s — %s (%d/%d)%s',
[LLobby.Name, LLobby.Host, LLobby.Players, LLobby.Max,
IfThen(LLobby.Locked, ' 🔒', '')]));
end;
| Field | |
|---|---|
Id |
Opaque handle — the only thing JoinLobby needs |
Name, Host, Game, Note |
What to show |
Players, Max |
How many are in, how many fit (0 = unsaid) |
Locked |
Needs a password |
Started |
The match is already running |
Age, Seen |
Seconds since it opened, and since it was last heard from |
RefreshInterval refreshes on a timer. Switch it on while the list is on
screen and off again when it is not — it is a network request per tick, on
somebody's mobile data:
FDirectory.RefreshInterval := 10; // seconds; 0 turns it off
Everything reports through OnError with a code you can branch on and a
message you can show.
| Code | |
|---|---|
no_endpoint |
Endpoint was never set |
unreachable |
No network, no DNS, or the server is down |
bad_answer |
Something answered, but not this API |
not_found |
The table is no longer open |
locked |
Wrong or missing password |
too_many |
This address already has as many tables as it may |
rate_limited |
Too many requests — wait a moment |
no_session |
JoinLobby without a Session |
Without an OnError handler the message goes to OnNotice instead, so a
failure is never silent.
The endpoint lives in <gorilla>\source\lib\arena\server. PHP 7.4 or newer, no
database, no dependencies — one JSON file per lobby.
index.php, config.php, .htaccess and the data/ folder.secret in config.php to something random and private:
php -r "echo bin2hex(random_bytes(32));"data/ writable.Endpoint is then the URL of index.php.
Move the storage out of the document root if you can — set storage_dir to
something like /var/lib/arena-lobbies. The shipped data/.htaccess refuses
HTTP access, but that only works on Apache with AllowOverride on.
The full API, its error codes and every setting are documented in
server/README.md.
The listing never carries an address, and TGorillaArenaLobby has no field
that could hold one. Only join hands one out — one table at a time, rate
limited, and only while that table is open. So an address is never on public
display and cannot be swept out of a listing.
It does reach the program that is joining, and it has to: a direct connection cannot be made to an address you do not have. Somebody who joins and watches their own network traffic can therefore see where they connected. Hiding it from them as well would need a relay carrying the game traffic, which is a different piece of software.
Three things reduce what is exposed in the meantime:
hash_hmac(id, secret), so knowing an id — they are all public — is not
enough to guess the file that holds its address.password_hash. A leaked file does not let anybody take over a table.Two clocks, and the shorter one wins:
lobby_ttl (default 300 s) |
How long a table stays listed without a heartbeat |
lobby_max_lifetime (2 days) |
The hard cap: past this it is gone however faithfully it was refreshed |
Expired tables are never served, and their files are deleted by a sweep that runs on roughly one request in ten.
The directory knows a host by the address its request came from — on a home
network that is the router, not the host. Somebody on the same network who
connects to it reaches the outside of their own router, which refuses unless
it forwards the port and loops it back inside ("NAT loopback"); few home
routers do. The symptom is Connection refused for a table that is plainly
listed.
So Publish — and every refresh after it — also reports the host's LAN
addresses (Session.LocalAddresses, private IPv4 only, best first), and the
server hands those out instead, but only to a joiner whose public address is
the host's own: somebody already on that network. JoinLobby passes all of
them to the session as a:port;b:port, and the session tries them in turn, so
a virtual adapter (WSL, Hyper-V, VirtualBox, a VPN) that happens to be listed
first costs a few seconds, not the join.
Needs the updated index.php on the server; an older server simply keeps
handing out the public address.
The directory only passes an address along; it does not make the host
reachable. Two devices on the same network are fine, and so is a host with a
public address and the game port forwarded (TCP DirectPort, 47810 by
default; for App Tethering the tethering ports). Behind a plain consumer NAT
with nothing forwarded the connection will not come up — the directory will
have done its job and the join will still fail.
Say so in the user interface rather than leaving people guessing: a join that succeeds at the directory and then goes quiet is otherwise indistinguishable from a slow one.
php -S 127.0.0.1:8777 -t <gorilla>\source\lib\arena\server
tests\directorycheck.dpr in the Tumble & Roll example exercises the whole
client against a running endpoint — publishing, listing, updating, locked
tables, withdrawal and the error paths:
directorycheck http://127.0.0.1:8777/
The Gorilla3D audio building block covers everything a game needs to be heard: a backend independent audio manager, two interchangeable drivers (FMOD and OpenAL), a ready-made playlist component, and two speech modules that sit on top of the stack — Text-to-Speech for talking characters and Speech-to-Text for voice input.
Everything is layered on the abstract TGorillaAudioManager. The speech modules
never talk to FMOD or OpenAL directly — they only use the backend independent
interface, so switching the driver does not touch a line of their code.
TGorillaTextToSpeech TGorillaSpeechToText TGorillaAudioPlaylist
(characters, lipsync) (microphone, commands) (tracks, shuffle)
| | |
+-------------+-------------+-------------+-------------+
| |
TGorillaAudioManager (abstract) — sounds, channels, listener
| |
+-------------+ +-------------+
| |
TGorillaFMODAudioManager TGorillaOpenALManager
(FMOD Core API) (OpenAL Soft + EFX)
Beside this stack there is the old TGorillaLegacyAudioManager, a thread based
wrapper around the FMX TMediaPlayer. It is kept for simple "play a jingle"
scenarios and for projects migrating from earlier Gorilla3D versions — see
Audio Manager.
| Page | Content |
|---|---|
| Audio Manager | The backend independent API: sound items, channels, the 3D listener, Update(), and the legacy manager |
| FMOD Driver | TGorillaFMODAudioManager: channel groups, DSP effects, 3D reverb, geometry occlusion, licensing |
| OpenAL Driver | TGorillaOpenALManager: sources, buffers, EFX effects, distance models, codecs |
| Audio Playlist | TGorillaAudioPlaylist: track list, shuffle, loop, auto-advance |
| Text-to-Speech | TGorillaTextToSpeech with the Piper backend, visemes and lipsync |
| Speech-to-Text | TGorillaSpeechToText with the whisper.cpp and Vosk backends, voice commands |
| FMOD | OpenAL | |
|---|---|---|
| 3D spatialization | Yes | Yes |
| DSP effect chains | Yes (full DSP graph) | EFX effects (reverb, chorus, echo, distortion, flanger, compressor) |
| Channel groups / buses | Yes | Channels grouping several sounds |
| Geometry based occlusion | Yes | No |
| 3D reverb zones | Yes | Reverb effect slots only |
| Streaming | Yes | Yes |
| Built-in codecs | Very broad (MP3, OGG, WAV, FLAC, MOD, MIDI, …) | WAV, plus MP3 and OGG Vorbis through the bundled decoders |
| Licensing | Commercial product, free below a revenue threshold | Open source (LGPL / ISC depending on build) |
| Redistribution | FMOD libraries must be shipped with the app | OpenAL Soft libraries must be shipped or installed |
Rule of thumb: take FMOD when the sound design is a feature of the game — buses, effect chains, occlusion. Take OpenAL when you want positional audio without a commercial dependency.
Both drivers can even be used side by side in one application, since every component that consumes audio takes its manager through a property.
| Platform | Legacy manager | FMOD | OpenAL | TTS (Piper) | STT (whisper.cpp / Vosk) |
|---|---|---|---|---|---|
| Windows | Yes | Yes | Yes | Yes | Yes |
| macOS | Yes | Yes | Yes | Yes | Yes |
| Linux | Limited | — | Yes | Yes | Yes |
| Android | Yes | Yes (via JNI) | — | HTTP mode only | Library mode only |
| iOS | Yes | Yes | — | HTTP mode only | Library mode only |
The mobile restriction of the speech modules comes from process spawning: Piper
and whisper-cli are external executables, which mobile platforms do not allow.
Their library and HTTP modes are unaffected.
| Unit | Content |
|---|---|
Gorilla.Audio.Manager |
TGorillaAudioManager, TGorillaSoundItem, TGorillaLegacyAudioManager |
Gorilla.Audio.FMOD* |
FMOD driver, system, sounds, channels, channel groups, DSP, reverb, geometry |
Gorilla.Audio.OpenAL* |
OpenAL driver, loader, API bindings, MP3 and OGG decoders |
Gorilla.Audio.Playlist |
TGorillaAudioPlaylist |
Gorilla.Audio.TTS* |
Speech synthesis, speakers, visemes, phonemizers, Piper backend |
Gorilla.Audio.STT* |
Speech recognition, capture, voice activity detection, whisper.cpp and Vosk backends |
uses
Gorilla.Audio.Manager, Gorilla.Audio.OpenAL;
var
LAudio : TGorillaOpenALManager;
LSound : TGorillaSoundItem;
begin
LAudio := TGorillaOpenALManager.Create(Self);
LAudio.Parent := GorillaViewport1;
LSound := LAudio.LoadSoundItemFromFile('sounds/explosion.wav');
LAudio.PlaySound(LSound);
// call once per frame, drives streaming and 3D updates
LAudio.Update();
end;
TGorillaAudioManager is the backend independent heart of the audio building
block. It is an abstract TFmxObject — you never instantiate it directly, you
drop one of its two implementations on the form and program against the base
class. Everything built on top of the audio stack (playlist, text-to-speech,
speech-to-text) only knows this base class, which is what makes the driver
exchangeable.
| Class | Unit | Purpose |
|---|---|---|
TGorillaAudioManager |
Gorilla.Audio.Manager |
Abstract manager, the API everything else uses |
TGorillaSoundItem |
Gorilla.Audio.Manager |
Abstract single sound, a TCollectionItem |
TGorillaChannelItem |
Gorilla.Audio.Manager |
Abstract playback channel |
TGorillaAudioEffectItem |
Gorilla.Audio.Manager |
Abstract effect slot |
TGorillaLegacyAudioManager |
Gorilla.Audio.Manager |
Old TMediaPlayer based manager, thread driven |
TGorillaFMODAudioManager |
Gorilla.Audio.FMOD |
FMOD implementation |
TGorillaOpenALManager |
Gorilla.Audio.OpenAL |
OpenAL implementation |
Both implementations are design-time components, so the usual way is to drop them onto the form. At runtime they are created like any other FMX component:
uses
Gorilla.Audio.Manager, Gorilla.Audio.OpenAL;
var LAudio : TGorillaAudioManager;
begin
LAudio := TGorillaOpenALManager.Create(Self);
TGorillaOpenALManager(LAudio).Parent := GorillaViewport1;
From here on the code can stay on the TGorillaAudioManager type. Swapping the
driver later is a one line change.
A TGorillaSoundItem is one loaded piece of audio. It is a collection item, so
sounds can be pre-configured at design-time through the Object Inspector and are
owned and released by their manager.
| Member | Description |
|---|---|
FileName |
Path of the audio file |
PlaybackPosition |
Current position in milliseconds (read-only) |
PlaybackLength |
Total length in milliseconds (read-only) |
IsPlaying() |
True while audible |
Play() / Pause() / Resume() / Stop() |
Playback control |
LoadFromStream(AStream) |
Fills an item created with CreateSoundItem() |
On top of that every item carries the backend independent 3D interface:
| Method | Description |
|---|---|
Supports3DAudio() |
True when the driver can place this sound in space |
Set3DAudio(AEnabled) |
Switches positional playback on — before loading the data |
SetWorldPosition(APosition) |
Moves the sound in world space |
Set3DDistance(AMin, AMax) |
Distance range the sound is attenuated in |
SetPlaybackVolume(AVolume) |
Gain, 0.0 silent … 1.0 unchanged |
SetPlaybackPitch(APitch) |
Pitch, 1.0 unchanged, 2.0 one octave up |
The base class implements these as no-ops, so a driver only overrides what it really supports. This is the interface the text-to-speech module uses to make a character's voice come out of the character.
var LSound : TGorillaSoundItem;
begin
// from a file
LSound := LAudio.LoadSoundItemFromFile('sounds/explosion.wav');
// from a stream - read completely into memory
LSound := LAudio.LoadSoundItemFromStream(LFileStream);
// from a memory stream - can be streamed continuously
LSound := LAudio.LoadSoundItemFromStream(LMemoryStream);
// look a sound up again
LSound := LAudio.GetSoundItemByFilename('sounds/explosion.wav');
// drop everything
LAudio.ClearSounds();
end;
The LoadSoundFrom...() overloads without Item in their name do the same but
return nothing — use them when the sound is only ever addressed by index.
Some settings are evaluated while the audio data is created and cannot be changed afterwards — FMOD decides about 3D handling when the sound is created, for example. For those cases the item is created empty, configured, and filled afterwards:
var LSound : TGorillaSoundItem;
begin
LSound := LAudio.CreateSoundItem('guard_voice');
if Assigned(LSound) then
begin
LSound.Set3DAudio(true);
LSound.Set3DDistance(1.0, 40.0);
LSound.LoadFromStream(LWaveStream);
end
else
// driver does not support it, fall back
LSound := LAudio.LoadSoundItemFromStream(LWaveStream);
end;
CreateSoundItem() returns nil when the driver cannot do the two step
creation, so a caller always needs the fallback shown above.
LAudio.PlaySound(LSound); // by item
LAudio.PlaySound(0); // by index
LSound.Play();
LSound.Pause();
LSound.Resume();
LSound.Stop();
if LSound.IsPlaying then
ShowMessage(Format('%d / %d ms',
[LSound.PlaybackPosition, LSound.PlaybackLength]));
LAudio.StopAllChannels();
LAudio.ClearAllChannels();
Positional audio needs two things: sounds that have a position, and a listener
that has one too. The sound side is the item interface shown above, the listener
side is driver specific — FMOD offers ListenerTarget to follow a TControl3D
automatically, OpenAL offers ListenerPosition, ListenerOrientation and
ListenerVelocity. See FMOD Driver and OpenAL Driver.
LSound.Set3DAudio(true);
LSound.Set3DDistance(2.0, 50.0); // full volume up to 2 units, silent at 50
LSound.SetWorldPosition(Torch.AbsolutePosition.Point);
LSound.SetPlaybackVolume(0.8);
Keep the listener in sync every frame, otherwise the panning lags behind the camera.
A channel is a playing instance of a sound. The base class exposes only the two global operations, because the two drivers model channels quite differently:
| Method | Description |
|---|---|
StopAllChannels() |
Stops everything currently audible |
ClearAllChannels() |
Stops and releases all channels |
For categories (music, SFX, voice) use the driver specific grouping: FMOD channel groups or OpenAL channels.
procedure TForm1.GorillaViewport1Render(Sender : TObject; ...);
begin
FAudio.Update();
end;
Update() refills streaming buffers, retires finished channels and applies
listener changes. FMOD can do this on its own — AutoUpdate with
AutoUpdateInterval (33 ms by default) runs an internal thread. When you drive
the manager yourself, switch AutoUpdate off so the work happens at a defined
point in your frame.
| Event | Fired when |
|---|---|
OnUpdate |
Update() was called; synchronized with the main thread when the auto-update thread triggered it |
OnListenerUpdated |
The listener position or orientation changed |
TGorillaLegacyAudioManager is a TThread descendant that keeps one FMX
TMediaPlayer per audio file. It is simple, needs no external library at all,
and is not built for performance. A global instance called AudioManager is
created by the unit.
uses Gorilla.Audio.Manager;
// cache files first, that is much faster than loading them one by one
AudioManager.BeginCaching();
AudioManager.Add(1, 'sounds/explosion.wav');
AudioManager.Add(2, 'sounds/background.mp3');
AudioManager.Add(3, 'sounds/footstep.wav', 0.5); // 50% volume
AudioManager.EndCaching();
AudioManager.Play(1); // once
AudioManager.Play(2, TGorillaAudioMode.Loop, 0.3); // looped, 30% volume
AudioManager.Pause(2); // pause / resume toggle
AudioManager.Stop(1);
AudioManager.PauseAll();
AudioManager.StopAll();
AudioManager.Mute := true;
| Property | Default | Description |
|---|---|---|
LoopCheckInterval |
100 | Interval in ms at which finished loops are restarted |
QueueTimeout |
250 | Time in ms the worker waits for a queue event |
Mute |
False | Mutes every cached file at once |
Limitations worth knowing before you pick it:
TMediaPlayer per file — memory use grows quickly with the number of soundsempty.mp3 in the temp directory during initialization; if that
fails, playback is not possibleUse it for tools, prototypes and menu clicks. Everything else belongs on FMOD or OpenAL.
TGorillaAudioManager, not against the concrete driver — it
keeps the driver exchangeable and lets the speech modules work either wayUpdate() once per frame, or leave FMOD's AutoUpdate onCreateSoundItem())TGorillaFMODAudioManager implements the Gorilla3D audio manager on top of the
FMOD Core API. It is the richer of the two drivers: channel groups, DSP
effect chains, 3D reverb zones and geometry based occlusion are all available,
and FMOD brings its own broad set of codecs.
| Unit | Content |
|---|---|
Gorilla.Audio.FMOD |
TGorillaFMODAudioManager, TGorillaFMODSoundItem, channel groups, effects |
Gorilla.Audio.FMOD.System |
FMOD system initialization and global settings |
Gorilla.Audio.FMOD.Sound |
Sound handles |
Gorilla.Audio.FMOD.Channel |
Channel handling |
Gorilla.Audio.FMOD.ChannelGroup |
Channel group handling |
Gorilla.Audio.FMOD.SoundGroup |
Sound groups |
Gorilla.Audio.FMOD.DSP |
Digital signal processing effects |
Gorilla.Audio.FMOD.Reverb3D |
3D reverb zones |
Gorilla.Audio.FMOD.Geometry |
Geometry based occlusion |
Gorilla.Audio.FMOD.Custom |
Hooks for custom FMOD extensions |
Android.JNI.FMOD |
JNI bridge used on Android |
uses
Gorilla.Audio.Manager, Gorilla.Audio.FMOD;
var LAudio : TGorillaFMODAudioManager;
begin
LAudio := TGorillaFMODAudioManager.Create(Self);
LAudio.Parent := GorillaViewport1;
LAudio.AutoUpdate := true; // internal update thread
LAudio.AutoUpdateInterval := 33; // ms
end;
| Property | Default | Description |
|---|---|---|
AutoUpdate |
True | Runs an internal thread calling Update() |
AutoUpdateInterval |
33 | Interval of that thread in ms |
Sounds |
— | Design-time collection of TGorillaFMODSoundItem |
ChannelGroups |
— | Design-time collection of channel groups |
ListenerPosition |
— | Position of the listener |
ListenerVelocity |
— | Listener velocity, drives the Doppler effect |
ListenerForward |
— | Listener forward direction |
ListenerUp |
— | Listener up direction |
ListenerTarget |
— | A TControl3D the listener follows automatically |
ListenerUpdateInterval |
— | How often the target is polled |
AutoUpdateListenerForward |
— | Whether the forward vector follows the target too |
Read-only helpers: SystemObject (the raw IGorillaFMODSystem for anything the
component does not wrap), SoundRefs[], ChannelGroupRefs[] and IsPlaying.
TGorillaFMODSoundItem derives from TGorillaSoundItem and adds the full FMOD
channel feature set:
| Property | Description |
|---|---|
FileName |
Audio file to load |
Mode |
Mode2D or Mode3D — evaluated when the sound is created |
ChannelGroup |
Name of the group the sound plays in |
Loop, LoopCount |
Looped playback, -1 = endless |
AutoStart |
Starts automatically once the manager is loaded |
Volume, Pitch, Mute, Frequency |
Basic channel settings; a negative frequency plays non-streamed sounds backwards |
Priority |
0 (most important) … 256, default 128 — decides who gets dropped when channels run out |
PositionInMilliseconds |
Seek position |
VolumeRamp |
Smooths abrupt volume changes |
LowPassGain |
Gain of the low pass applied by occlusion and reverb |
FadeIn, FadeOut |
Fade durations |
AntiFatigue, AntiFatigueLevel |
Tiny random volume variation, so a sample repeated over and over stops sounding identical |
FadeInMinVol … FadeOutMaxVol |
Range the anti-fatigue variation works in |
Position3D, Velocity3D |
3D placement of the sound |
MinMax3DDistance |
Distance range for attenuation |
Cone3DSettings |
Inner angle, outer angle and outer volume of a directional sound |
Delay, DelayDSPClockStart, DelayDSPClockEnd |
Sample accurate scheduling |
Effects |
Collection of DSP effects attached to this sound |
OnPlay, OnPause, OnStop |
Playback events |
var LSound : TGorillaFMODSoundItem;
begin
LSound := LAudio.Sounds.Add();
LSound.FileName := 'sounds/torch.wav';
LSound.Mode := TGorillaFMODSoundMode.Mode3D;
LSound.ChannelGroup := 'SFX';
LSound.Loop := true;
LSound.LoopCount := -1;
LSound.AntiFatigue := true;
LSound.MinMax3DDistance := Position(1, 30);
end;
Mode decides whether FMOD creates a 2D or a 3D sound and is read while the
sound is created — set it before the audio data is loaded. That is exactly why
CreateSoundItem() exists, see Audio Manager.
Channel groups are the FMOD way of building buses: music, SFX, voice. A sound is assigned to a group by name, and the group controls volume, muting and effects for everything inside it at once.
var LGroup : TGorillaFMODChannelGroupItem;
begin
LGroup := LAudio.ChannelGroups.Add();
LGroup.DisplayName := 'SFX';
// later on, through the FMOD interface
LAudio.ChannelGroupRefs['SFX'].SetVolume(0.4);
end;
The simplest setup links the listener to the camera and lets the manager do the rest:
LAudio.ListenerTarget := Camera1;
LAudio.AutoUpdateListenerForward := true;
LAudio.ListenerUpdateInterval := 33;
Without a target, set the four listener vectors yourself, or use
Set3DListener() for the complete attribute set in one call. OnListenerUpdated
fires whenever the listener changed.
Gorilla.Audio.FMOD.DSP wraps the FMOD DSP units — reverb, echo, chorus,
distortion, compressor, parametric EQ, pitch shifter and the rest of the FMOD
catalogue. Effects are attached per sound through its Effects collection, and
AttachEffects() / DetachEffects() on the sound item switch the whole chain on
and off.
For everything the component does not wrap, go through SystemObject and use
the FMOD API directly.
Gorilla.Audio.FMOD.Reverb3D defines reverb zones in 3D space: a position, an
inner and an outer radius and a reverb preset. As the listener moves through the
world, FMOD blends between the zones automatically — a cave sounds like a cave
without a single line of gameplay code.
Gorilla.Audio.FMOD.Geometry feeds polygons into FMOD's occlusion engine.
Sounds behind a wall are then attenuated and low-pass filtered by the geometry
instead of being audible through it. Use a very coarse version of the level
geometry — occlusion meshes are a budget item, not a copy of the render mesh.
FMOD has to be updated regularly, otherwise 3D positions, streaming and virtual
voices go stale. Either leave AutoUpdate on and let the internal thread do it,
or switch it off and call Update() in your render loop:
LAudio.AutoUpdate := false;
// ...
procedure TForm1.GorillaViewport1Render(Sender : TObject; ...);
begin
LAudio.Update();
end;
The FMOD binaries ship with Gorilla3D under <installation>\lib\fmod\. Two
variants exist:
| Library | Purpose |
|---|---|
fmodL / fmodL64 |
Logging build, verbose diagnostics — the default |
fmod / fmod64 |
Productive build, no logging |
Switch to the productive build at the very start of your application, before the first manager is created:
// in the .dpr file
TGorillaFMODAudioManager.UseProductiveLibrary := true;
For design-time support the logging DLL has to be copied into the IDE binary folder, see Installation.
FMOD itself is a commercial product of Firelight Technologies. It is free below a revenue threshold, but it always requires registration and attribution — check the current terms before shipping:
| Platform | Support |
|---|---|
| Windows | 32 and 64 bit |
| macOS | Yes |
| iOS | Yes |
| Android | Yes, through the JNI bridge in Android.JNI.FMOD |
| Linux | Not supported by this driver — use OpenAL |
Mode and the 3D distances before the audio data is loadedPriority so important sounds survive when the channel limit is reachedAntiFatigue for footsteps, impacts and other frequently repeated samplesUseProductiveLibrary in release buildsTGorillaOpenALManager implements the Gorilla3D audio manager on top of
OpenAL Soft. It is the open source alternative to FMOD: positional audio,
distance models, sound cones, Doppler and the EFX effect extension — without a
commercial dependency, and it is the only driver available on Linux.
| Unit | Content |
|---|---|
Gorilla.Audio.OpenAL |
TGorillaOpenALManager, sounds, channels, effects |
Gorilla.Audio.OpenAL.Loader |
Loading WAV, OGG and MP3 into audio buffers |
Gorilla.Audio.OpenAL.API |
Low level OpenAL and EFX bindings |
Gorilla.Audio.MP3.API |
MP3 decoding through libmpg123 |
Gorilla.Audio.OGG.API |
OGG Vorbis decoding through libogg / libvorbis |
uses
Gorilla.Audio.Manager, Gorilla.Audio.OpenAL;
var LAudio : TGorillaOpenALManager;
begin
LAudio := TGorillaOpenALManager.Create(Self);
LAudio.Parent := GorillaViewport1;
if not LAudio.InitializeOpenAL() then
raise Exception.Create('No OpenAL device available');
end;
Initialized tells you whether device and context are up. ShutdownOpenAL()
releases everything again — it is called on destruction anyway.
| Property | Description |
|---|---|
Sounds |
Collection of TGorillaOpenALSoundItem (the OpenAL buffers) |
Channels |
Collection of TGorillaOpenALChannelItem (the OpenAL sources) |
Effects |
Collection of TGorillaOpenALEffectItem (EFX effect slots) |
ListenerPosition |
Position of the listener |
ListenerVelocity |
Listener velocity, drives the Doppler effect |
ListenerOrientation |
Six-component vector: forward and up |
DopplerFactor |
Multiplier of the Doppler effect, default 1.0 |
Initialized |
True once device and context exist (read-only) |
A TGorillaOpenALSoundItem is an OpenAL buffer plus the source settings applied
when it is played:
| Property | Description |
|---|---|
FileName |
Audio file to load |
Loaded |
True once the buffer holds data (read-only) |
Format |
TStreamFormat — mono/stereo, sample rate, bit depth (read-only) |
Streaming |
Streams from disk instead of loading the file completely |
Position, Velocity |
3D placement of the sound |
Volume, Pitch, Looping |
Basic playback settings |
DistanceModel |
dmInverse, dmLinear or dmExponent |
ReferenceDistance |
Distance up to which no attenuation happens |
MaxDistance |
Distance the attenuation stops at |
RolloffFactor |
How quickly the sound fades with distance |
ConeInnerAngle, ConeOuterAngle, ConeOuterGain |
Directional sound cone |
PlaybackPosition, PlaybackLength |
Position and length in ms (read-only) |
var LSound : TGorillaOpenALSoundItem;
begin
LSound := LAudio.Sounds.Add();
LSound.DisplayName := 'torch';
LSound.FileName := 'sounds/torch.wav';
LSound.Looping := true;
LSound.Position := Point3D(4, 1, -2);
LSound.ReferenceDistance := 2;
LSound.MaxDistance := 30;
LSound.LoadBuffer();
// or load everything configured at design time in one go
LAudio.LoadAllSounds();
end;
Lookup helpers: Sounds.FindByName(), Sounds.FindByFileName(),
GetSoundItemByFilename(). LoadBufferFromStream() fills a buffer from a
stream, UnloadBuffer() releases it.
In this driver a channel is a named group of sounds that are played, paused and positioned together — the OpenAL counterpart to an FMOD channel group.
var LChannel : TGorillaOpenALChannelItem;
begin
LChannel := LAudio.Channels.Add();
LChannel.Name := 'SFX';
LChannel.Volume := 0.4;
LAudio.AddSoundToChannel('SFX', 'torch');
LAudio.AddSoundToChannel('SFX', 'footstep');
LAudio.PlayChannel('SFX');
LAudio.PauseChannel('SFX');
LAudio.ResumeChannel('SFX');
LAudio.StopChannel('SFX');
if LAudio.GetChannelState('SFX') = psPlaying then
...;
end;
Further channel operations: RemoveSoundFromChannel(), ClearChannelSounds(),
ChannelHasSound(), GetChannelSoundCount(), StopAllChannels() and
ClearAllChannels(). Channel states are psInitial, psPlaying, psPaused
and psStopped.
Playing single sounds works as well and returns the channel the sound landed in:
LChannel := LAudio.PlaySound('torch');
LChannel := LAudio.PlaySoundItem(LSound);
The EFX extension is exposed through effect slots. Each slot has a type and can be applied to a channel:
| Effect type | |
|---|---|
etNone |
No effect |
etReverb |
Room reverb |
etChorus |
Chorus |
etEcho |
Echo / delay |
etDistortion |
Distortion |
etFlanger |
Flanger |
etCompressor |
Compressor |
var LEffect : TGorillaOpenALEffectItem;
begin
LEffect := LAudio.Effects.Add();
LEffect.Name := 'CaveReverb';
LEffect.EffectType := etReverb;
LEffect.Enabled := true;
LAudio.ApplyEffectToChannel('SFX', 'CaveReverb');
end;
EFX requires an OpenAL implementation that supports it. OpenAL Soft does; some vendor drivers do not.
LAudio.SetListenerWorldPosition(Camera1.AbsolutePosition.Point);
LAudio.ListenerOrientation := TVector6D.Create(
LForward.X, LForward.Y, LForward.Z,
LUp.X, LUp.Y, LUp.Z);
LAudio.ListenerVelocity := LPlayerVelocity;
LAudio.DopplerFactor := 1.0;
TVector6D packs the two vectors OpenAL expects: the first three components are
the forward ("at") vector, the last three the up vector. TVector6D.Default
returns the standard orientation.
Unlike FMOD there is no automatic listener target — update the listener from your camera every frame.
| Model | Behaviour |
|---|---|
dmInverse |
Inverse distance attenuation — the physically plausible default |
dmLinear |
Linear falloff between reference and maximum distance, reaches true silence |
dmExponent |
Exponential falloff, useful for a dramatic close-up effect |
The model works together with ReferenceDistance, MaxDistance and
RolloffFactor. A common mistake is leaving ReferenceDistance at its default
while working in a scene scaled in centimetres — the sound is then attenuated
long before it should be.
| Format | Decoder |
|---|---|
| WAV (PCM) | Built in |
| OGG Vorbis | ogg / vorbis / vorbisfile libraries |
| MP3 | libmpg123 |
LoadAudioFile() in Gorilla.Audio.OpenAL.Loader picks the decoder by file
extension, so LoadSoundItemFromFile() handles all three transparently.
procedure TForm1.GorillaViewport1Render(Sender : TObject; ...);
begin
LAudio.Update();
end;
Update() refills streaming buffers and retires finished sources. Without it,
streamed sounds stop after their first buffer.
The OpenAL binaries ship with Gorilla3D under <installation>\lib\OpenAL\.
| File | Purpose |
|---|---|
openal32.dll (Windows), libopenal.so / .dylib |
The OpenAL implementation |
oalinst.exe |
OpenAL Soft installer, for systems without a system-wide OpenAL |
libmpg123-0.dll |
MP3 decoding |
ogg.dll, vorbis.dll, vorbisfile.dll, vorbisenc.dll |
OGG Vorbis decoding |
Deploy the libraries next to your executable, or run oalinst.exe once during
installation. On Linux, OpenAL is usually available through the distribution
package manager (libopenal1).
Upstream sources:
InitializeOpenAL() — a missing device is a normal case,
not an exceptionStreaming for music and long ambiences, leave it off for short effectsReferenceDistance / MaxDistance to the scale of your sceneListenerVelocity only when you actually want Doppler, otherwise it
produces surprising pitch shiftsTGorillaAudioPlaylist is a non-visual component that plays a list of audio
tracks — with shuffle, loop and automatic advance to the next track. It works
headless, so it fits a background music system just as well as a media player
UI.
| Class | Description |
|---|---|
TGorillaAudioPlaylist |
The component: track list, playback, shuffle, loop |
TGorillaPlaylistCollection |
The owned collection of tracks |
TPlaylistItem |
One track — Name and FilePath |
TAudioDriver |
FMOD or OpenAL |
The playlist does not implement audio playback itself; it drives a
TGorillaFMODAudioManager or a TGorillaOpenALManager. Either link an existing
manager from your form, or let the playlist create one internally on first
playback.
uses Gorilla.Audio.Playlist;
var LPlaylist : TGorillaAudioPlaylist;
begin
LPlaylist := TGorillaAudioPlaylist.Create(Self);
LPlaylist.Driver := TAudioDriver.OpenAL;
LPlaylist.Volume := 0.6;
LPlaylist.AddToPlaylist('music/menu.ogg');
LPlaylist.AddToPlaylist('music/battle.ogg');
LPlaylist.AddToPlaylist('music/credits.ogg');
LPlaylist.LoopMode := true;
LPlaylist.AutoPlayNext := true;
LPlaylist.Play();
end;
Because Items is a published collection, the same list can be filled at
design-time through the Object Inspector's collection editor.
// let the playlist create and own a manager
LPlaylist.Driver := TAudioDriver.FMOD;
// or link a manager that already exists on the form
LPlaylist.Driver := TAudioDriver.OpenAL;
LPlaylist.OpenALManager := GorillaOpenALManager1;
A manager linked through FMODManager / OpenALManager stays owned by the form;
one created by the playlist is released with it. CreateAudioHandler() and
DestroyAudioHandler() control that instance explicitly, and the read-only
FMOD / OpenAL properties give access to whichever manager is currently in
use.
Link an existing manager whenever the rest of your game already uses one — running two audio devices side by side wastes voices and complicates mixing.
LIndex := LPlaylist.AddToPlaylist('music/boss.ogg');
LPlaylist.RemoveFromPlaylist(2);
LPlaylist.MovePlaylistItem(3, 0);
LPlaylist.ClearPlaylist();
LItem := LPlaylist.GetPlaylistItem(0);
ShowMessage(LItem.Name + ' -> ' + LItem.FilePath);
Caption := Format('%d tracks, now playing %s',
[LPlaylist.PlaylistCount, LPlaylist.CurrentTrackName]);
AddToPlaylist() derives the display name from the file name. Setting
FilePath on an item updates that name as well, so a track list stays readable
without extra work.
Audio can also be loaded directly, bypassing the list — useful for a one-off stinger:
LPlaylist.LoadAudio('music/intro.ogg');
LPlaylist.LoadAudio(LMemoryStream);
LPlaylist.Play();
LPlaylist.Pause();
LPlaylist.Stop();
LPlaylist.PlayItem(2);
LPlaylist.PlayNext();
LPlaylist.PlayPrevious();
if LPlaylist.IsPlaying then ...;
if LPlaylist.IsPaused then ...;
LPos := LPlaylist.GetPlaybackPosition(); // ms
LLen := LPlaylist.GetPlaybackLength(); // ms
LPlaylist.SetPlaybackPosition(30000); // seek to 0:30
| Property | Effect |
|---|---|
ShuffleMode |
Plays the list in a random order; the order is regenerated whenever the list changes |
LoopMode |
Starts over at the first track after the last one |
AutoPlayNext |
Advances to the next track when one finishes |
Shuffle works on a permutation, not on a random pick per track — every track is played once before any repeats.
By default the component polls playback on an internal timer and advances on its
own. When an external timer or your render loop already drives the audio, switch
that off and call UpdatePlayback() instead:
LPlaylist.AutoUpdate := false;
// ...
procedure TForm1.RenderTimer(Sender : TObject);
var LFinished : Boolean;
LPos : UInt32;
begin
LPos := LPlaylist.UpdatePlayback(LFinished);
ProgressBar1.Value := LPos;
if LFinished then
LPlaylist.PlayNext();
end;
UpdatePlayback() returns the current position in milliseconds and reports
through its out parameter whether the track has ended. The component latches the
actual start of playback, so a track is never reported as finished during the
start-up window.
| Event | Fired when |
|---|---|
OnPlaylistChanged |
Tracks were added, removed, moved or edited |
OnTrackChanged |
A different track became current |
OnPlaybackFinished |
The current track ended |
OnStateChanged |
Playing / paused / stopped changed |
| Property | Default | Description |
|---|---|---|
Items |
— | The track collection, editable at design-time |
Driver |
FMOD |
Audio backend to use |
FMODManager |
— | Existing FMOD manager to drive |
OpenALManager |
— | Existing OpenAL manager to drive |
AutoUpdate |
True | Polls playback and advances on its own |
AutoPlayNext |
True | Continues with the next track automatically |
ShuffleMode |
False | Random play order |
LoopMode |
False | Restart after the last track |
Volume |
— | Playback volume, 0.0 … 1.0 |
Read-only: Playlist, PlaylistCount, CurrentIndex, CurrentTrackName,
FMOD, OpenAL.
AutoUpdate on unless something else already drives the audio each frameOnTrackChanged to update a "now playing" label instead of pollingLoopMode with AutoPlayNextDynamic character speech: text goes in, spoken 3D audio plus a lipsync timeline
comes out. TGorillaTextToSpeech sits on top of the audio stack and never
touches an audio API itself — which is why it works with FMOD and OpenAL alike.
The speech engine is not part of the Gorilla3D distribution. Piper and its voice models are downloaded separately, see Getting Piper.
TGorillaTextToSpeech component: characters, queue, cache, lipsync
|
+-- TGorillaTTSEngine exchangeable backend (Piper, ...)
|
+-- TGorillaAudioManager playback (OpenAL / FMOD)
Speak() does not block. Synthesis runs on a worker thread, playback starts as
soon as the audio is ready, and several sentences per character are spoken in
order.
| Unit | Content |
|---|---|
Gorilla.Audio.TTS |
Request, result, abstract TGorillaTTSEngine, engine registry |
Gorilla.Audio.TTS.Speaker |
TGorillaTextToSpeech, TGorillaTTSSpeaker, cache, worker thread |
Gorilla.Audio.TTS.Piper |
Piper backend (process or HTTP mode) |
Gorilla.Audio.TTS.Visemes |
Viseme set, timeline, phonemizer, estimator |
Gorilla.Audio.TTS.Espeak |
Phonemizer using the espeak-ng library (preferred) |
Gorilla.Audio.TTS.Utils |
Process runner, RIFF/WAVE tools, amplitude envelope |
Piper is a local neural text-to-speech system — no cloud, no account, no per-request cost. It consists of an executable and one voice model per voice. Both are obtained from the Piper project, not from Gorilla3D.
| Source | |
|---|---|
| Project | https://github.com/rhasspy/piper |
| Releases | https://github.com/rhasspy/piper/releases |
The backend was tested against rhasspy/piper 1.2.0, whose command line
matches the default CommandTemplate. Archives are available for Windows amd64,
Linux x86_64 / aarch64 / armv7l and macOS x64 / aarch64.
Unpack the archive next to your application. You get a folder piper/
containing piper.exe (respectively piper) and the espeak-ng-data folder.
Voices are not contained in the executable archives and have to be downloaded separately:
| Source | |
|---|---|
| Voice models | https://huggingface.co/rhasspy/piper-voices |
| Listen before downloading | https://rhasspy.github.io/piper-samples/ |
Every voice consists of two files that belong together:
de_DE-thorsten-medium.onnx
de_DE-thorsten-medium.onnx.json
The .json holds the model configuration, including the sample rate and the
speaker list of multi-speaker models. A model without its .json cannot be
used.
The Piper archives already ship espeak-ng.dll (libespeak-ng.so.1 /
libespeak-ng.dylib), which the phonemizer picks up automatically. Only when
you want the phonemizer without Piper — or a newer version — fetch it from
https://github.com/espeak-ng/espeak-ng.
Piper is MIT licensed, espeak-ng is GPL. The voice models carry their own licenses (mostly CC-BY or public domain) — check the license of every voice you ship. Since none of it is redistributed by Gorilla3D, the obligations are between you and the respective project.
uses
Gorilla.Audio.Manager, Gorilla.Audio.OpenAL,
Gorilla.Audio.TTS, Gorilla.Audio.TTS.Speaker, Gorilla.Audio.TTS.Piper;
var LPiper : TGorillaPiperEngine;
begin
LPiper := TGorillaPiperEngine.Create(Self);
LPiper.ExecutablePath := 'C:\tools\piper\piper.exe'; // or just 'piper' (PATH)
LPiper.ModelDirectory := 'C:\tools\piper\voices'; // scanned for *.onnx
LPiper.DefaultVoice := 'de_DE-thorsten-medium';
GorillaTextToSpeech1.AudioManager := GorillaOpenALManager1;
GorillaTextToSpeech1.Engine := LPiper;
end;
With the standard layout you can skip all of that: when ExecutablePath and
ModelDirectory are left empty, the engine searches next to the application for
piper\piper.exe, piper.exe and Piper\piper\piper.exe, and for the voice
folders piper\voices, voices and models.
GetVoices() then lists everything it found; multi-speaker models report each
speaker separately as model.onnx#3. ResolveExecutable() tells you which
executable would actually be called — an empty result means Piper was not found.
If your Piper version expects a different command line, only CommandTemplate
needs adjusting. Placeholders: %EXE%, %MODEL%, %OUTPUT%, %LENGTH_SCALE%,
%NOISE_SCALE%, %NOISE_W%, %SENTENCE_SILENCE%, %SPEAKER%,
%ESPEAK_DATA%, %CUDA%.
| Property | Default | Description |
|---|---|---|
Mode |
pmProcess |
Spawn the executable, or talk to an HTTP server |
ExecutablePath |
— | Path or bare name of the Piper executable |
ModelPath |
— | Model used when nothing else names one |
ModelDirectory |
— | Folder scanned for *.onnx |
EspeakDataPath |
— | Only needed when Piper cannot find its espeak data |
CommandTemplate |
see above | Command line of the executable |
Timeout |
30000 | Milliseconds a single synthesis may take |
NoiseW |
0.8 | Variation of the phoneme lengths |
CudaEnabled |
False | Adds --cuda to the command line |
ServerUrl |
http://127.0.0.1:5000 |
Base address in HTTP mode |
HttpPath |
— | Resource path appended to ServerUrl |
Instead of spawning a process per sentence, the engine can talk to a running Piper HTTP server. This is the only mode available on mobile platforms, and it is the better choice when many characters speak at once, because the model stays loaded:
LPiper.Mode := pmHttp;
LPiper.ServerUrl := 'http://127.0.0.1:5000';
var LSpeaker : TGorillaTTSSpeaker;
begin
TTS.AudioManager := GorillaOpenALManager1;
TTS.Engine := GorillaPiperEngine1;
LSpeaker := TTS.AddSpeaker('Guard', 'de_DE-thorsten-medium');
LSpeaker.Target := GuardModel; // the voice comes out of the model
LSpeaker.Pitch := 0.92; // same model, different character
LSpeaker.Spatial := true;
TTS.Speak('Guard', 'Halt! Who goes there?');
end;
A character is addressed by name, so gameplay code never needs a reference to
the speaker object. FindSpeaker() returns it when you do.
TTS.Speak(LSpeaker, 'Move along.'); // already resolved speaker
LSpeaker.Stop(); // stop and clear this character's queue
LSpeaker.Pause();
LSpeaker.Resume();
TTS.StopAll(); // silence everybody
With Speaker.Interrupt := true a new sentence cuts off the running one instead
of queueing behind it — the right setting for combat barks, the wrong one for
dialogue.
| Property | Description |
|---|---|
Name |
The name the character is addressed by |
VoiceId |
Piper model name or path; empty uses the engine's default voice |
SpeakerId |
Speaker index inside a multi-speaker model, -1 = default |
Language |
Language of the text, drives phonemization |
Rate |
Speaking rate, 1.0 normal, 1.2 = 20 % faster |
Pitch |
Playback pitch, 1.0 unchanged |
Volume |
Playback gain |
Expressiveness |
Amount of variation in the generated voice, 0..1 |
SentenceSilence |
Pause between two sentences in seconds |
Enabled |
A disabled speaker silently drops every Speak() |
Spatial |
Plays the voice at the position of Target instead of centred |
Interrupt |
New sentence cuts off the running one |
Target |
The TControl3D the voice is emitted from |
Offset |
Mouth offset relative to the target's origin |
MinDistance, MaxDistance |
Distance range the voice is attenuated in |
Read-only state: IsSpeaking, QueueLength, Current, PlaybackTime,
Viseme, VisemeWeights, VisemeWeight[], WordIndex.
Deriving several characters from a single voice model is mostly a matter of
Pitch and Rate — two guards at 0.92 and 1.06 are perceived as two people.
During playback every speaker reports its current mouth state:
procedure TForm1.OnViseme(ASender : TObject; const ASpeaker : TGorillaTTSSpeaker;
const AViseme : TGorillaVisemeKind; const AWeights : TGorillaVisemeWeights);
var LKind : TGorillaVisemeKind;
begin
for LKind := Low(TGorillaVisemeKind) to High(TGorillaVisemeKind) do
GuardModel.SetMorphTargetWeight(GORILLA_VISEME_NAMES[LKind], AWeights[LKind]);
end;
The viseme set follows the Oculus/Meta LipSync standard
(sil PP FF TH DD kk CH SS nn RR aa E I O U), which most character assets ship
as blend shapes. For cartoon rigs, GorillaVisemeToMouthShape() maps onto the
Preston Blair chart A..H.
The weights are already blended (co-articulation) and always sum to 1.0.
OnWord additionally reports word boundaries, for subtitles for example.
Piper does not report phoneme times, so the timeline is estimated:
Three implementations exist and are chosen by priority — the first available one wins:
| Priority | Implementation | Note |
|---|---|---|
| 100 | TGorillaEspeakLibPhonemizer |
espeak-ng library directly, real IPA, no process start |
| 50 | TGorillaEspeakPhonemizer |
espeak-ng as a command line tool |
| 0 | TGorillaRuleBasedPhonemizer |
Grapheme approximation for DE/EN, always available |
The library variant activates automatically as soon as
Gorilla.Audio.TTS.Piper is used, because the Piper releases ship
espeak-ng.dll. It is architecture bound: the official archives are 64 bit,
so a Win32 build falls back to the rule-based phonemizer.
Custom implementations plug in through IGorillaPhonemizer plus
GorillaRegisterPhonemizer() (with a priority), or hard-wired through
GorillaSetDefaultPhonemizer().
Character speech repeats a lot — greetings, hints, combat barks. CacheEnabled
serves anything already known without synthesis latency; with CacheDirectory
the cache survives a restart of the program (WAV plus .vis files).
| Property | Default | Description |
|---|---|---|
CacheEnabled |
True | Reuse the audio of sentences spoken before |
CacheDirectory |
— | Folder for the persistent cache; empty = memory only |
CacheCapacity |
64 | Number of sentences kept in memory |
ClearCache() empties the memory cache, PurgeCache() deletes the files as
well.
Both the component and each speaker expose the same set — use the component level for a global subtitle system, the speaker level for one character.
| Event | Fired when |
|---|---|
OnSpeechStart |
A sentence became audible |
OnSpeechFinished |
A sentence finished playing |
OnViseme |
The dominant mouth shape changed |
OnWord |
The spoken word changed |
OnError |
A sentence could not be spoken |
Playback and lipsync are advanced by Update(). AutoUpdate (on by default,
UpdateInterval 16 ms) does that from an internal timer; switch it off to drive
the component from your own render loop.
type
TMyEngine = class(TGorillaTTSEngine)
protected
function DoSynthesize(const ARequest : TGorillaTTSRequest;
const AResult : TGorillaTTSResult) : Boolean; override;
public
class function GetEngineName() : String; override;
end;
initialization
TGorillaTTSEngineRegistry.RegisterEngine(TMyEngine);
DoSynthesize only has to call AResult.SetWave(<RIFF/WAVE stream>). The
viseme timeline is estimated automatically afterwards — if the backend reports
real phoneme times, it fills AResult.Visemes itself and the estimation is
skipped.
Backends that are not thread safe override IsThreadSafe with false; their
calls are then serialized.
The engine is selected either through the Engine property or through
EngineName (a string such as 'Piper'), in which case the component creates
the instance itself.
| Mode | Windows | Linux | macOS | Android/iOS |
|---|---|---|---|---|
Piper pmProcess |
Yes | Yes | Yes | No (no process spawning) |
Piper pmHttp |
Yes | Yes | Yes | Yes |
3D positioning is implemented for OpenAL and FMOD. The module creates the sound
item through TGorillaAudioManager.CreateSoundItem(), configures it and loads
the audio data afterwards — necessary because FMOD evaluates the 3D mode while
creating the sound.
There is no Piper library: piper_phonemize.dll only exports C++-mangled
functions with std::vector / std::string parameters, and the actual VITS
inference lives inside piper.exe. The only usable parts of the archives are
espeak-ng.dll (see Phonemizers) and, in principle,
onnxruntime.dll — whose C API would require reimplementing the whole Piper
inference.
| Symptom | Cause |
|---|---|
ResolveExecutable() returns empty |
Piper not found — set ExecutablePath |
GetVoices() returns nothing |
ModelDirectory wrong, or the .onnx.json files are missing |
| Speech is audible but the mouth does not move | Blend shape names do not match GORILLA_VISEME_NAMES |
| Lipsync is coarse | Rule-based phonemizer active — check the espeak-ng library, and the bitness of your build |
| Voice is not positional | Spatial off, Target unassigned, or the driver reports Supports3DAudio() = false |
| First sentence is late, later ones are instant | Normal — the cache is doing its job; pre-warm on level load |
| Nothing at all on Android/iOS | pmProcess is unavailable there, use pmHttp |
Pitch/Rate instead of one voice model per NPCInterrupt for barks, queueing for dialogueTarget so voices are attenuated with distance like every other soundOnError — a missing model is a normal runtime conditionVoice input: microphone in, recognized text and voice commands out.
TGorillaSpeechToText records through the audio driver already present in your
scene, cuts the stream into utterances, hands them to a recognizer on a worker
thread and raises the result on the main thread.
The recognition engines are not part of the Gorilla3D distribution. whisper.cpp and Vosk — their libraries, executables and models — are downloaded separately, see Getting whisper.cpp and Getting Vosk.
microphone
|
IGorillaAudioCapture capture backend (OpenAL / FMOD)
|
IGorillaVAD voice activity detection, cuts out utterances
|
TGorillaSTTEngine recognition (whisper.cpp / Vosk)
|
TGorillaSpeechToText queue, events, voice command matching
Two threads are involved: a capture thread that drains the recording device at a
raised priority — a device that is not drained in time silently overwrites its
own ring buffer — and a worker thread doing the recognition. Events are queued
and raised by Update() on the main thread, so a handler may safely touch the
scene.
| Unit | Content |
|---|---|
Gorilla.Audio.STT |
Request, result, abstract TGorillaSTTEngine, engine registry |
Gorilla.Audio.STT.Listener |
TGorillaSpeechToText, voice commands, threads |
Gorilla.Audio.STT.Capture |
IGorillaAudioCapture plus the OpenAL, FMOD and null backends |
Gorilla.Audio.STT.VAD |
IGorillaVAD, the energy based detector and the registry |
Gorilla.Audio.STT.Whisper |
whisper.cpp backend (library or command line) |
Gorilla.Audio.STT.Vosk |
Vosk backend (streaming, grammar capable) |
Gorilla.Audio.STT.Utils |
Sample buffers, resampling, wave file helpers |
| whisper.cpp | Vosk | |
|---|---|---|
| Engine name | Whisper |
Vosk |
| Accuracy | Very high | Good |
| Streaming / partial results | No | Yes |
| Grammar (restrict to phrases) | No (uses the phrases as a prompt) | Yes |
| Language auto detection | Yes | No — one model per language |
| Word timings | Yes | Yes |
| Latency | Recognizes after the utterance ended | Reports while the user is still speaking |
| Model size | 75 MB (tiny) … 3 GB (large) | 50 MB (small) … 2 GB |
Rule of thumb: Vosk for voice commands that have to react immediately, whisper.cpp when the text itself matters — dictation, subtitles, free-form input. The listener component works with both, so this is a one-property decision.
whisper.cpp is a local implementation of OpenAI's Whisper model — no cloud, no account. You need two things: the binaries and a model file.
| Source | |
|---|---|
| Project | https://github.com/ggml-org/whisper.cpp |
| Releases | https://github.com/ggml-org/whisper.cpp/releases |
The engine can use either of two paths, controlled by Mode:
| Mode | What it needs |
|---|---|
wmLibrary |
The shared library whisper.dll (Windows), libwhisper.so / libwhisper.so.1 (Linux), libwhisper.dylib (macOS) |
wmProcess |
The command line tool whisper-cli (older builds: main) |
wmAuto |
Library when it loads, otherwise the command line tool — the default |
The release archives contain both. Put them next to your application or
somewhere on the system library / search path; LibraryPath and
ExecutablePath override the search when you keep them elsewhere.
| Source | |
|---|---|
| GGML models | https://huggingface.co/ggerganov/whisper.cpp/tree/main |
| Download script | models/download-ggml-model.sh in the whisper.cpp repository |
Models are single files named ggml-<size>.bin:
| File | Size | Note |
|---|---|---|
ggml-tiny.bin |
~75 MB | Fast, noticeably weaker |
ggml-base.bin |
~142 MB | Good compromise for voice commands |
ggml-small.bin |
~466 MB | Clearly better for free text |
ggml-medium.bin |
~1.5 GB | |
ggml-large-v3.bin |
~3 GB | Best quality, slowest |
The .en variants (ggml-base.en.bin) are English-only and better at English
than their multilingual counterpart of the same size.
Point the engine at them:
LWhisper.ModelDirectory := 'C:\tools\whisper\models'; // scanned for ggml-*.bin
LWhisper.ModelPath := 'base'; // -> ggml-base.bin
ModelPath accepts an absolute path, a file name inside ModelDirectory, or a
bare size name such as base or small.en. RefreshModels() rescans the
folder, GetModels() returns what was found, and LibraryAvailable() /
ResolveExecutable() tell you what the engine would actually use.
| Property | Default | Description |
|---|---|---|
Mode |
wmAuto |
How whisper.cpp is reached |
LibraryPath |
— | Path of the shared library |
ExecutablePath |
— | Path of whisper-cli |
ModelPath |
— | Model to recognize with |
ModelDirectory |
— | Folder scanned for ggml-*.bin |
CommandTemplate |
see below | Command line used in wmProcess |
Threads |
0 | 0 uses half the cores, leaving room for the render loop |
Timeout |
60000 | Milliseconds a single recognition may take |
UseGPU |
False | Only with a GPU build of the library |
MaxSegmentLength |
0 | Characters per segment, 0 = no limit (useful for subtitles) |
SplitOnWord |
True | Keeps words intact when splitting |
Temperature |
— | 0 is deterministic, the right choice for voice commands |
NoSpeechThreshold |
— | Probability above which a segment is discarded as silence |
Command line placeholders: %EXE%, %MODEL%, %INPUT%, %OUTPUT%,
%LANGUAGE%, %THREADS%, %TRANSLATE%, %PROMPT%, %JSONFULL%.
UseGPU is off by default on purpose: a Vulkan build of whisper.cpp shares the
device with the Gorilla3D Vulkan renderer, and whether that is collision free is
unverified.
whisper.cpp is MIT licensed, the models are released by OpenAI under MIT as well. You still distribute them yourself — Gorilla3D ships neither.
Vosk is a streaming recognizer: it reports partial results while the user is still speaking, and it can be restricted to a fixed phrase list, which raises the hit rate for voice commands dramatically.
| Source | |
|---|---|
| Project | https://alphacephei.com/vosk/ |
| Libraries (releases) | https://github.com/alphacep/vosk-api/releases |
| Models | https://alphacephei.com/vosk/models |
You need the shared library libvosk.dll (Windows), libvosk.so (Linux) or
libvosk.dylib (macOS), plus one model per language. A Vosk model is a
directory, not a file — vosk-model-small-de-0.15 for example. Unpack it and
point the engine at it:
LVosk.ModelDirectory := 'C:\tools\vosk'; // scanned for vosk-model-*
LVosk.ModelPath := 'vosk-model-small-de-0.15';
| Property | Default | Description |
|---|---|---|
LibraryPath |
— | Path of libvosk; empty searches next to the app and on the library path |
ModelPath |
— | Model directory to recognize with |
ModelDirectory |
— | Folder scanned for vosk-model-* directories |
MaxAlternatives |
0 | Number of alternative readings, 0 = best only |
LogLevel |
-1 | -1 silences the Vosk logging, 0 reports warnings and errors |
PartialWords |
False | Word timings in intermediate results as well |
Vosk is Apache-2.0 licensed; the models carry their own licenses.
uses
Gorilla.Audio.Manager, Gorilla.Audio.OpenAL,
Gorilla.Audio.STT, Gorilla.Audio.STT.Listener, Gorilla.Audio.STT.Whisper;
var LWhisper : TGorillaWhisperEngine;
begin
LWhisper := TGorillaWhisperEngine.Create(Self);
LWhisper.ModelDirectory := 'C:\tools\whisper\models';
LWhisper.ModelPath := 'base';
STT.AudioManager := GorillaOpenALManager1;
STT.Engine := LWhisper;
STT.Language := 'de';
STT.Mode := smPushToTalk;
STT.Active := true;
end;
AudioManager may be left empty — the component then uses the first manager
owned by the same form. Engine may be left empty too, in which case
EngineName ('Whisper', 'Vosk', or empty for the first registered backend)
decides which engine the component creates internally.
| Property | Default | Description |
|---|---|---|
Active |
False | Starts and stops recording |
Mode |
smContinuous |
How the component decides when to record |
Device |
— | Recording device out of GetDevices(); empty = system default |
SampleRate |
16000 | Leave it there — the recognizers work on 16 kHz |
Language |
— | e.g. de; empty asks the engine to detect it (whisper.cpp only) |
Prompt |
— | Context hint, e.g. the proper names of your game world |
Translate |
False | Lets the engine translate the result into English |
PartialResults |
False | Intermediate results while speaking (streaming engines only) |
UseGrammar |
False | Hands the command phrases to the engine as a grammar |
CommandThreshold |
0.75 | Similarity a phrase needs to fire its command |
AutoUpdate |
True | Drives Update() from an internal timer |
UpdateInterval |
16 | Interval of that timer in ms |
PollInterval |
20 | Interval the capture thread polls the device with |
MaxQueueLength |
8 | Utterances that may wait for the recognizer |
| Mode | Behaviour |
|---|---|
smPushToTalk |
Records between BeginListen() and EndListen(); the release triggers the recognition. The most reliable mode in a noisy room |
smContinuous |
Records permanently, the detector cuts the stream into utterances |
smSingleShot |
Records until exactly one utterance was found, then stops |
// push to talk, e.g. from a key handler
procedure TForm1.FormKeyDown(...);
begin
if Key = vkT then STT.BeginListen();
end;
procedure TForm1.FormKeyUp(...);
begin
if Key = vkT then STT.EndListen();
end;
// "say the name of your character now"
STT.Listen(); // switches to smSingleShot and activates
STT.Stop(); // stop and discard everything not recognized yet
In smPushToTalk everything between the two calls is one utterance and the
voice activity detector is bypassed. In the other modes BeginListen() only
switches recording on — the detector then decides where an utterance starts and
ends, so EndListen() has nothing to trigger.
For a game the raw text is rarely the goal. A command bundles the synonyms a player might use under one name the application reacts to:
var LCmd : TGorillaSTTCommand;
begin
LCmd := STT.Commands.Add('Attack', ['angriff', 'attackieren', 'greif an']);
LCmd.Threshold := 0.8; // stricter than the component default
STT.Commands.Add('Follow', ['folge mir', 'komm mit']);
STT.UseGrammar := true; // Vosk: restrict the recognizer to these phrases
end;
procedure TForm1.STTCommand(ASender : TObject;
const ACommand : TGorillaSTTCommand; const AConfidence : Single;
const AResult : TGorillaSTTResult);
begin
if ACommand.Name = 'Attack' then
Guard.Attack();
end;
| Member | Description |
|---|---|
Name |
The name reported by OnCommand |
Phrases |
The phrases that trigger it, one per line |
Enabled |
A disabled command is never matched |
Threshold |
Similarity needed; 0 uses the component's CommandThreshold |
Tag |
Free for application use |
Match(AText) |
Best similarity of any phrase, 1.0 for a literal hit |
UseGrammar hands all phrases of all enabled commands to the engine. With a
grammar capable engine (Vosk) that raises the hit rate dramatically, at the
price of no longer understanding anything else — perfect for a command-only
mode, wrong for a chat window. Engines without grammar support (whisper.cpp) get
the phrases as a context prompt instead.
Matching can also be done manually, e.g. for text that came from somewhere else:
if STT.MatchCommand('greif an', LCmd, LConfidence) then ...;
procedure TForm1.STTResult(ASender : TObject; const AResult : TGorillaSTTResult);
var LWord : TGorillaSTTWord;
begin
Memo1.Lines.Add(AResult.Text);
for LWord in AResult.Words do
Memo1.Lines.Add(Format(' %s %.2f - %.2f (%.0f%%)',
[LWord.Text, LWord.StartTime, LWord.EndTime, LWord.Confidence * 100]));
end;
| Member | Description |
|---|---|
Text |
The recognized sentence |
Words |
Word timings, empty when the backend does not report them |
Alternatives |
Alternative readings, empty when none were requested |
Language |
The language the engine detected or was told to use |
Confidence |
Overall confidence, 0..1 |
IsPartial |
True for an intermediate result; always followed by a final one |
EngineName |
Which backend produced it |
Duration, StartTime |
Length and position of the utterance in seconds |
WordCount, IsEmpty |
Convenience |
The result is owned by the component and invalid after the handler returned — copy what you need.
The detector decides where an utterance begins and ends. The built-in one is
energy based and adapts to the noise floor; it registers itself under the name
Energy, and VADName picks a different one if you registered your own.
| Property | Default | Description |
|---|---|---|
Threshold |
0.012 | Absolute level a frame has to exceed |
NoiseMultiplier |
2.5 | Factor applied to the tracked noise floor |
MinSpeechDuration |
0.25 s | Shorter utterances are discarded as a click or a cough |
MinSilenceDuration |
0.6 s | Pause that ends an utterance |
PreRollDuration |
0.3 s | Audio kept in front of the detected speech, so the plosive of the first word survives |
MaxSegmentDuration |
15 s | Emergency brake for a speaker who never pauses |
MaxZeroCrossingRate |
0.42 | Above this, a loud frame is treated as noise |
NoiseAdaption |
0.05 | How quickly the noise floor follows the input |
The effective threshold is the larger of Threshold and
NoiseFloor * NoiseMultiplier, which is what lets the detector work in a room
with a fan running. Reach the instance through ActiveVAD() while the component
is active.
MinSilenceDuration is the tuning knob that matters most: too short cuts
sentences apart at every breath, too long adds latency to every result.
Recording goes through the audio driver already in your scene:
| Backend | Name |
|---|---|
| OpenAL capture | OpenAL |
| FMOD record | FMOD |
| Null device | None |
ComboBox1.Items.AddStrings(STT.GetDevices());
STT.Device := ComboBox1.Text;
ActiveCapture() returns the backend in use while active. It reports health
data worth logging during development — captured frames, startup latency, and
the share of real time the device actually delivers. A driver that silently
drops samples is the most confusing failure of the whole subsystem: recording
"works", the level meter moves, and the recognizer returns nonsense because it
is fed audio with holes in it.
// synchronous, does not touch the capture layer at all
LResult := STT.RecognizeFile('test\utterance.wav');
try
Memo1.Lines.Add(LResult.Text);
STT.DispatchResult(LResult); // run it through the voice command matching too
finally
LResult.Free();
end;
SaveLastSegment() writes exactly what the recognizer was handed last into a
wave file — with smPushToTalk, BeginListen(), a few spoken words and
EndListen(), that is the fastest way to find out whether a recognition problem
is a capture problem.
| Event | Fired when |
|---|---|
OnSpeechStart |
The detector found the start of speech |
OnSpeechEnd |
An utterance ended |
OnPartial |
Intermediate result of a streaming engine |
OnResult |
An utterance was recognized |
OnCommand |
The recognized text matched a command — fires after OnResult |
OnError |
Recording or recognition failed |
State for a UI: IsListening, IsSpeaking, Level (0..1, ready for a level
meter) and DroppedSegments. Anything above zero in DroppedSegments means
the engine is too slow for the mode — use a smaller model, or switch to
push-to-talk.
Events are queued by the worker threads and raised by Update(). AutoUpdate
does that on a timer; switch it off to call Update() from your render loop.
| Windows | Linux | macOS | Android/iOS | |
|---|---|---|---|---|
| Capture (OpenAL / FMOD) | Yes | Yes | Yes | Yes |
whisper.cpp wmLibrary |
Yes | Yes | Yes | Yes |
whisper.cpp wmProcess |
Yes | Yes | Yes | No (no process spawning) |
| Vosk | Yes | Yes | Yes | Yes |
On mobile platforms use the library mode. Also remember that recording needs a microphone permission in the app manifest.
| Symptom | Cause |
|---|---|
IsAvailable() false |
Library or model not found — check LibraryFile(), GetModels() |
| "whisper-cli could not be found" | Neither library nor executable resolved; set ExecutablePath |
| Level meter moves, text is nonsense | The device drops samples — check the capture health data, raise PollInterval sensitivity |
| Sentences are cut in half | MinSilenceDuration too short |
| Nothing is recognized in a quiet room | Threshold too high, or the wrong Device |
| Every cough is recognized | MinSpeechDuration too low |
DroppedSegments grows |
Engine too slow — smaller model, fewer threads elsewhere, or push-to-talk |
| No partial results | PartialResults only works with a streaming engine (Vosk) |
| Commands never fire | CommandThreshold too strict, or the phrases do not match the language of the model |
ggml-base.bin and only go bigger when the text quality is
actually the problemTemperature := 0 for voice commandsPrompt with the proper names of your game world — it noticeably
improves the spelling of unusual wordsDroppedSegments during development, log it in release buildsActive onGorilla3D includes a built-in physics engine for realistic simulation of rigid body dynamics, collision detection, and constraints. The framework supports two physics backends: the built-in Q3 Physics Engine and the JOLT Physics Engine, selectable at design-time or runtime.
The physics system (TGorillaPhysicsSystem) is the central component that:
TGorillaPhysicsSystem onto your viewportActive := TrueGravity (default: (0, 9.81, 0) — downward in FMX Y-up)Colliders collection in the Object InspectorStep() from a timer (recommended interval: 33ms for ~30 Hz)var
Physics: TGorillaPhysicsSystem;
begin
Physics := TGorillaPhysicsSystem.Create(Self);
Physics.Parent := GorillaViewport1;
Physics.Driver := TGorillaPhysicsDriverType.Q3Physics;
Physics.Gravity := Point3D(0, 9.81, 0);
Physics.Accuracy := 10;
Physics.Active := True;
end;
// In a timer (33ms interval):
procedure TForm1.Timer1Timer(Sender: TObject);
begin
GorillaPhysicsSystem1.Step();
end;
| Driver | Enum Value | Description |
|---|---|---|
| Q3 Physics | Q3Physics |
Built-in lightweight physics engine. Supports the full set of collider shapes (box, sphere, capsule, cylinder, cone, convex hull, mesh, terrain) and joint types. |
| JOLT Physics | JOLTPhysics |
External high-performance physics engine. Same collider and joint coverage as Q3, tuned for large/complex scenes. |
| Custom | CustomPhysics |
Register your own physics driver implementation. |
Physics.Driver := TGorillaPhysicsDriverType.JOLTPhysics;
| Collider | Q3 | JOLT | Method |
|---|---|---|---|
| Box | Yes | Yes | AddBoxCollider |
| Sphere | Yes | Yes | AddSphereCollider |
| Capsule | Yes | Yes | AddCapsuleCollider |
| Cylinder | Yes | Yes | AddCylinderCollider |
| Cone | Yes | Yes | AddConeCollider |
| Convex Hull | Yes | Yes | AddConvexHullCollider |
| Mesh | Yes | Yes | AddMeshCollider (experimental) |
| Terrain | Yes | Yes | AddTerrainCollider |
| Particle | Yes | Yes | AddParticleCollider (used internally by particle system) |
Before adding a collider, create a TGorillaColliderSettings record to configure the body:
var
Settings: TGorillaColliderSettings;
begin
// Create settings for a dynamic body
Settings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eDynamicBody);
// Physics material
Settings.Data.Friction := 0.4;
Settings.Data.Restitution := 0.3; // bounciness
Settings.Data.Density := 1.0;
Settings.Data.Sensor := False; // True = trigger only, no physical response
// Lock axes
Settings.LockRotAxisX := False;
Settings.LockRotAxisY := False;
Settings.LockRotAxisZ := False;
// Damping
Settings.LinearDamping := 0.0;
Settings.AngularDamping := 0.05;
// Velocity limits
Settings.MaxLinearVelocity := Point3D(100, 100, 100);
Settings.MaxAngularVelocity := Point3D(100, 100, 100);
// Collision layers (bodies only collide within the same layer)
Settings.Layers := 1;
// Sleep optimization
Settings.AllowSleep := True;
Settings.Active := True;
end;
| Type | Enum | Description |
|---|---|---|
| Static | eStaticBody |
Does not move. Use for floors, walls, terrain. |
| Dynamic | eDynamicBody |
Fully simulated. Responds to forces, gravity, and collisions. |
| Kinematic | eKinematicBody |
Moved by code, not by physics. Pushes dynamic bodies but is not pushed back. |
var Settings: TGorillaColliderSettings;
begin
// Floor (static)
Settings := TGorillaColliderSettings.Create(eStaticBody);
Settings.Data.Friction := 0.6;
GorillaPhysicsSystem1.AddBoxCollider(FloorPlane, Settings);
// Falling crate (dynamic)
Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.Data.Restitution := 0.2;
GorillaPhysicsSystem1.AddBoxCollider(CrateModel, Settings);
// Custom size override
GorillaPhysicsSystem1.AddBoxCollider(SomeControl, Settings, Point3D(2, 2, 2));
end;
Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.Data.Restitution := 0.8; // bouncy ball
GorillaPhysicsSystem1.AddSphereCollider(BallMesh, Settings); // auto-detect radius
GorillaPhysicsSystem1.AddSphereCollider(BallMesh, Settings, 1.5); // explicit radius
Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.LockRotAxisX := True;
Settings.LockRotAxisZ := True; // keep upright
GorillaPhysicsSystem1.AddCapsuleCollider(CharacterModel, Settings, 0.5, 1.8);
Settings := TGorillaColliderSettings.Create(eStaticBody);
GorillaPhysicsSystem1.AddTerrainCollider(GorillaTerrain1, Settings);
GorillaPhysicsSystem1.RemoveCollider(CrateModel);
Joints connect two bodies together. Configure them via the Joints collection at design-time or add them programmatically.
Both physics backends now support the full set of joint types. The original
eight joints were joined by the JOLT-parity constraints (Point, Distance,
Cone, SwingTwist, SixDOF) and the coupling constraints (Gear,
RackAndPinion, Pulley) — these are now implemented natively in both the
Q3 and the JOLT backend, so a scene behaves the same regardless of the driver.
| Joint | Description | Q3 | JOLT |
|---|---|---|---|
Fixed |
Locks two bodies together rigidly | Yes | Yes |
BallAndSocket |
Free rotation around a point (shoulder, hip) | Yes | Yes |
Hinge |
Rotation on one axis (door, wheel) | Yes | Yes |
LimitedHinge |
Hinge with angle limits (finger, knee) | Yes | Yes |
Prismatic |
Sliding on one axis (sliding door, elevator) | Yes | Yes |
StiffSpring |
Soft spring that maintains a distance between bodies | Yes | Yes |
Magnet |
Attracts one body toward another based on mass | Yes | Yes |
Buoyancy |
Simulates floating on a fluid surface | Yes | Yes |
Point |
Point-to-point pin (equivalent to BallAndSocket) | Yes | Yes |
Distance |
Keeps two anchors a fixed distance apart (rigid rope) | Yes | Yes |
Cone |
Pin whose swing is limited to a cone | Yes | Yes |
SwingTwist |
Swing cone + twist limit (ragdoll joints) | Yes | Yes |
SixDOF |
Per-axis translation / rotation limits | Yes | Yes |
RackAndPinion |
Couples a pinion's rotation to a rack's translation | Yes | Yes |
Gear |
Couples two bodies' rotation (meshed gears) | Yes | Yes |
Pulley |
Rope of fixed total length over two pulley points | Yes | Yes |
Backend notes
- Buoyancy is a soft, per-step effect rather than a hard constraint. It uses
ControlAas the floating body andControlBas the fluid-surface anchor. In the Q3 backend it is a spring + damper along the up-axis; in the JOLT backend it is applied through JOLT's native buoyancy, which integrates the actually submerged volume of the body's shape (so it also yields a righting torque).Stiffness/Dampingare re-purposed per backend — see the note below.- Gear, RackAndPinion and Pulley are coupling constraints: set
Ratio(transmission ratio). For Gear/RackAndPinion under JOLT, also wire the two sub-joints (the hinges/slider) viaConstraintA/ConstraintBso JOLT can correct positional drift.- For Buoyancy the
Stiffnessfield is the buoyancy strength (Q3) or the buoyancy factor (JOLT:1= neutral,> 1floats, clamped to2), andDampingis the fluid drag in both backends.
Joints can be motorized:
| Motor | Description |
|---|---|
NoMotor |
No motor |
RotationMotor |
Constant rotation |
AngularVelocityMotor |
Angular velocity drive |
PositionMotor |
Drive toward a position |
LinearVelocityMotor |
Constant linear velocity |
VelocityMotor |
Combined angular + linear velocity |
A Buoyancy joint makes a body float on a fluid. It uses two bodies:
ControlA is the floating body, ControlB is a (usually static, invisible)
anchor placed at the fluid surface — its height defines where the body floats.
The "liquid" itself is normally just a semi-transparent, collider-less volume so
the body can actually submerge into it.
var
LSurface, LFloat: TGorillaCube;
LJoint: TGorillaPhysicsJointPrefab;
LSettings: TGorillaColliderSettings;
begin
// Invisible STATIC anchor at the water surface (y = -5; negative Y = up).
LSurface := TGorillaCube.Create(Self);
LSurface.Parent := GorillaViewport1;
LSurface.SetSize(0.4, 0.1, 0.4);
LSurface.Position.Point := Point3D(0, -5, 0);
LSurface.Visible := False;
LSettings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eStaticBody);
GorillaPhysicsSystem1.AddBoxCollider(LSurface, LSettings);
// The floating body (starts submerged; buoyancy lifts it to the surface).
LFloat := TGorillaCube.Create(Self);
LFloat.Parent := GorillaViewport1;
LFloat.SetSize(1.5, 1.5, 1.5);
LFloat.Position.Point := Point3D(0, -3, 0);
LSettings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eDynamicBody);
GorillaPhysicsSystem1.AddBoxCollider(LFloat, LSettings);
// The buoyancy joint: A = floating body, B = surface anchor.
LJoint := GorillaPhysicsSystem1.Joints.Add as TGorillaPhysicsJointPrefab;
LJoint.JointType := TGorillaPhysicsJointType.Buoyancy;
LJoint.ControlA := LFloat; // floating body
LJoint.ControlB := LSurface; // fluid-surface anchor
LJoint.AnchorA.Point := Point3D(0, 0, 0);
LJoint.AnchorB.Point := Point3D(0, 0, 0);
// Stiffness / Damping are interpreted per backend:
// Q3 : Stiffness = spring strength (0 -> mass-based default), Damping = drag
// JOLT : Stiffness = buoyancy factor (0 -> default 1.2, > 1 floats, max 2),
// Damping = fluid drag
LJoint.Stiffness := 0; // 0 -> sensible per-backend default
LJoint.Damping := 0.5;
end;
Under JOLT the effect is applied through JOLT's native buoyancy, which integrates the actually submerged volume of the collider shape — so a body pushed under water not only bobs back up but also rights itself if it entered at an angle.
Apply physics effects to bodies at runtime:
// Apply an impulse (instant push)
GorillaPhysicsSystem1.RemoteBodyImpulse(CrateModel, Point3D(0, -10, 0));
// Apply a continuous force
GorillaPhysicsSystem1.RemoteBodyForce(CrateModel, Point3D(5, 0, 0));
// Set velocity directly (useful for character controllers)
GorillaPhysicsSystem1.RemoteBodyVelocity(CharacterCtrl, Point3D(0, 0, 3));
// Set angular velocity
GorillaPhysicsSystem1.RemoteBodyAngularVelocity(WheelMesh, Point3D(5, 0, 0));
// Apply angular impulse at a point
GorillaPhysicsSystem1.RemoteBodyAngularImpulse(CrateModel,
Point3D(0, 10, 0), Point3D(1, 0, 0));
// Teleport a body (override physics position)
GorillaPhysicsSystem1.RemoteBodyTransform(CrateModel,
Point3D(0, -5, 0), Point3D(0, 0, 0));
GorillaPhysicsSystem1.OnBeginContact := procedure(ASender: TObject;
const ABody1, ABody2: TGorillaPhysicsBody)
begin
// Two bodies started colliding
end;
GorillaPhysicsSystem1.OnEndContact := procedure(ASender: TObject;
const ABody1, ABody2: TGorillaPhysicsBody)
begin
// Two bodies stopped colliding
end;
Settings.OnBeginContact := procedure(ASender: TObject;
const AOffset, ANormal: TPoint3D; ABody1, ABody2: TGorillaPhysicsBody)
begin
// This specific collider started a contact
end;
Settings.OnEndContact := procedure(ASender: TObject;
const AOffset, ANormal: TPoint3D; ABody1, ABody2: TGorillaPhysicsBody)
begin
// This specific collider ended a contact
end;
GorillaPhysicsSystem1.OnBeginStep := HandleBeginStep; // before simulation
GorillaPhysicsSystem1.OnEndStep := HandleEndStep; // after simulation
GorillaPhysicsSystem1.OnBeginUpdate := HandleBeginUpdate; // before body sync
GorillaPhysicsSystem1.OnEndUpdate := HandleEndUpdate; // after body sync
Use the Colliders collection property to define colliders at design-time. Each TGorillaPhysicsColliderPrefab links a TControl3D to a collider type and settings. They are automatically registered when the physics system activates.
The Joints collection works similarly for design-time joint configuration.
Enable threaded physics computation for better performance:
GorillaPhysicsSystem1.Async := True;
// When accessing bodies from the main thread, block first:
GorillaPhysicsSystem1.Block();
try
GorillaPhysicsSystem1.RemoteBodyImpulse(SomeBody, Point3D(0, -5, 0));
finally
GorillaPhysicsSystem1.Unblock();
end;
TGorillaPhysicsCharacterController (in Gorilla.PhysicsCharacterController) provides a physics-driven character that works with the physics system for ground detection, slopes, and collision response.
Step() at a fixed interval (33ms recommended) for stable simulationStep() from a timer, not from the render loopBlock()/Unblock() when accessing bodies in async modeData.Sensor := True) for trigger volumes that detect overlap without physical responseRenderColliders := True to visualize all collider shapesThe Gorilla.Animation unit provides a comprehensive animation system for Gorilla3D, supporting skeletal/joint animation, vertex (mesh) animation, and property-based keyframe animation. It extends FireMonkey's animation framework with 3D-specific functionality and synchronization mechanisms.
The animation system is built on a hierarchical structure:
TGorillaAnimationManager clip registry, playback, crossfade
└─ TGorillaAnimation one clip ("Walk", "c-run.dae")
└─ Skeleton : TSkeletonKeyAnimation clock + tick for all interpolators
└─ Interpolators : TPropertyKeyAnimation (abstract base)
├─ TPoint3DKeyAnimation
├─ TVector3DKeyAnimation
├─ TQuaternion3DKeyAnimation
├─ TTransformationKeyAnimation
└─ TCoordinateKeyAnimation
TGorillaRenderClock (Delphi 13+) drives scene animations from the renderer
TPoint3DAnimation simple start/stop TPoint3D animation
Class inheritance:
TCustomPropertyAnimation (FMX)
├─ TPropertyKeyAnimation
│ ├─ TPoint3DKeyAnimation / TVector3DKeyAnimation / TQuaternion3DKeyAnimation
│ ├─ TTransformationKeyAnimation / TCoordinateKeyAnimation
│ └─ TSkeletonKeyAnimation
└─ TPoint3DAnimation
TFmxObject → TGorillaAnimation
TComponent → TGorillaAnimationManager
Abstract base class for all keyframe-based animations in Gorilla3D.
Inheritance: TCustomPropertyAnimation → TPropertyKeyAnimation
Platforms: All Gorilla3D supported platforms
Interfaces: IDuplicatable
| Property | Type | Description |
|---|---|---|
| QualifiedName | String | Qualified identifier from definition import. |
| Elements | TReferencedComponentList | Hashmap of linked components. |
| Def | TObject | Linked Gorilla3D definition structure. |
| TransitionTime | Single | Latest computed normalized time (read-only). |
| Property | Type | Default | Description |
|---|---|---|---|
| Keys | TKeys | - | Collection of keyframes. |
| StartFromCurrent | Boolean | False | Start animation from current property value. |
| AnimationType | TAnimationType | In | Easing type: In, Out, InOut. |
| AutoReverse | Boolean | False | Reverse playback at end. |
| Enabled | Boolean | False | Enable/disable animation. |
| Delay | Single | 0.0 | Delay before starting (seconds). |
| Duration | Single | - | Total animation duration (required). |
| Interpolation | TInterpolationType | Linear | Interpolation algorithm. |
| Inverse | Boolean | False | Start from end to beginning. |
| Loop | Boolean | False | Repeat animation continuously. |
| PropertyName | String | - | Target property name (supports dot notation). |
| Trigger / TriggerInverse | String | - | Standard FMX trigger expressions. |
| Event | Type | Description |
|---|---|---|
| OnProcess | TNotifyEvent | Fired on every processed animation step. |
| OnFinish | TNotifyEvent | Fired when a non-looping animation reaches its end. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Stop(); override;
Stops the animation and clears internal caches.
procedure AddElements(const AElements: TReferencedComponentList);
Applies animation to multiple components.
Parameters:
AElements - List of components to animateExample:
var
Elements: TReferencedComponentList;
begin
Elements := TReferencedComponentList.Create();
Elements.AddOrSetValue(Cube1, True);
Elements.AddOrSetValue(Sphere1, True);
Animation.AddElements(Elements);
end;
procedure AddElement(const AElement: TComponent; const AValue: Boolean);
Applies animation to a single component.
Parameters:
AElement - Component to animateAValue - Enable flag (typically True)Example:
Animation.AddElement(Cube1, True);
procedure LoadFromInterpolatorDef(ADef: TCustomDef); virtual; abstract;
Loads animation from a definition structure. Must be implemented by derived classes.
Parameters:
ADef - Definition object (TPoint3DInterpolatorDef, TVector3DInterpolatorDef, etc.)procedure ResetCaching();
Resets animation values manipulated during caching.
procedure ProcessCachingTick(time, deltaTime: Single);
Processes animation tick during caching operations.
Parameters:
time - Current animation timedeltaTime - Time since last tickprocedure Transform(const AMat: TMatrix3D); virtual; abstract;
Transforms all keyframe data by a matrix (e.g., for mirroring).
Parameters:
AMat - Transformation matrix to applyExample:
var
MirrorMatrix: TMatrix3D;
begin
MirrorMatrix := TMatrix3D.CreateScaling(Point3D(-1, 1, 1));
Animation.Transform(MirrorMatrix);
end;
procedure CaptureBlendSnapshot(const ABlendList: TGorillaBlendList); virtual;
Captures the current property values of all targets into ABlendList. Used by
TGorillaAnimationManager to take the "from-pose" when a crossfade starts. The base
implementation does nothing; TPoint3DKeyAnimation, TVector3DKeyAnimation,
TQuaternion3DKeyAnimation and TTransformationKeyAnimation override it.
TCoordinateKeyAnimation (vertex animation) does not take part in crossfading.
Keyframe animation for TPoint3D properties (Position, Rotation, Scale).
Inheritance: TPropertyKeyAnimation → TPoint3DKeyAnimation
Platforms: All Gorilla3D supported platforms
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from TPoint3DInterpolatorDef.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all keyframe points by matrix.
var
Anim: TPoint3DKeyAnimation;
Key: TPoint3DKey;
begin
Anim := TPoint3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Position.Point';
Anim.Duration := 2.0;
Anim.Loop := True;
Anim.AddElement(Cube1, True);
Key := TPoint3DKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[Cube1] := Point3D(0, 0, 0);
Key := TPoint3DKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[Cube1] := Point3D(10, 5, 0);
Anim.Start();
end;
Keyframe animation for TVector3D properties.
Inheritance: TPropertyKeyAnimation → TVector3DKeyAnimation
Platforms: All Gorilla3D supported platforms
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from TVector3DInterpolatorDef.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all keyframe vectors by matrix.
Keyframe animation for quaternion-based rotations.
Inheritance: TPropertyKeyAnimation → TQuaternion3DKeyAnimation
Platforms: All Gorilla3D supported platforms
Features:
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from TQuaternion3DInterpolatorDef.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all keyframe quaternions by matrix.
var
Anim: TQuaternion3DKeyAnimation;
Key: TQuaternion3DKey;
Quat: TQuaternion3D;
begin
Anim := TQuaternion3DKeyAnimation.Create(Self);
Anim.PropertyName := 'RotationAngle';
Anim.Duration := 3.0;
Anim.AddElement(Cube1, True);
Quat := TQuaternion3D.Create(Vector3D(0, 0, 0));
Key := TQuaternion3DKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[Cube1] := Quat;
Quat := TQuaternion3D.Create(Vector3D(0, 180, 0));
Key := TQuaternion3DKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[Cube1] := Quat;
Anim.Start();
end;
Keyframe animation for TMatrix3D transformations (primarily skeletal animation).
Inheritance: TPropertyKeyAnimation → TTransformationKeyAnimation
Platforms: All Gorilla3D supported platforms
Use Cases:
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from TTransformationInterpolatorDef.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all keyframe matrices by matrix.
var
Anim: TTransformationKeyAnimation;
Key: TTransformationKey;
Matrix: TMatrix3D;
begin
Anim := TTransformationKeyAnimation.Create(Self);
Anim.PropertyName := 'LocalMatrix';
Anim.AddElement(Joint1, True);
Matrix := TMatrix3D.CreateTranslation(Point3D(0, 0, 0));
Key := TTransformationKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Value[Joint1] := Matrix;
Matrix := TMatrix3D.CreateTranslation(Point3D(0, 5, 0)) *
TMatrix3D.CreateRotationY(DegToRad(45));
Key := TTransformationKey(Anim.Keys.Add);
Key.Time := 1.0;
Key.Value[Joint1] := Matrix;
Anim.Start();
end;
Keyframe animation for vertex positions (mesh morphing).
Inheritance: TPropertyKeyAnimation → TCoordinateKeyAnimation
Platforms: All Gorilla3D supported platforms
Use Cases:
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from TMeshInterpolatorDef.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all keyframe vertices by matrix.
var
Anim: TCoordinateKeyAnimation;
Key: TCoordinateKey;
Vertices: TPoint3DDynArray;
begin
Anim := TCoordinateKeyAnimation.Create(Self);
Anim.PropertyName := 'Data.Vertices';
Anim.Duration := 2.0;
Anim.AddElement(CustomMesh1, True);
SetLength(Vertices, CustomMesh1.Data.VertexBuffer.Length);
// ... populate vertices array
Key := TCoordinateKey(Anim.Keys.Add);
Key.Time := 0.0;
Key.Vertices[CustomMesh1] := Vertices;
// ... add more keys
Anim.Start();
end;
Container for synchronized animation of multiple property key animations.
Inheritance: TPropertyKeyAnimation → TSkeletonKeyAnimation
Platforms: All Gorilla3D supported platforms
Purpose:
| Property | Type | Description |
|---|---|---|
| Interpolators | TGorillaPropertyKeyAnimationList | Collection of grouped property animations (read-only). |
| Paused | Boolean | Pause/resume the skeleton. Delphi 13+ only - use it instead of the inherited Pause, which is occupied by TGorillaRenderClock. |
| Property | Type | Default | Description |
|---|---|---|---|
| AutoRepaint | Boolean | True | Automatically call Repaint() after each ProcessAnimation(). |
A new skeleton is created with Loop = True and Duration = 2. Its
LoadFromInterpolatorDef does nothing - the skeleton is only a grouping animation,
TGorillaAnimation.LoadFromAnimationDef fills it.
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure LoadFromInterpolatorDef(ADef: TCustomDef); override;
Loads from animation definition.
procedure AddInterpolator(AInter: TPropertyKeyAnimation);
Adds and enables an interpolator.
Important: Use this method instead of Interpolators.Add() to properly initialize the interpolator.
Parameters:
AInter - Property key animation to addExample:
var
SkeletonAnim: TSkeletonKeyAnimation;
JointAnim: TTransformationKeyAnimation;
begin
SkeletonAnim := TSkeletonKeyAnimation.Create(Self);
JointAnim := TTransformationKeyAnimation.Create(Self);
JointAnim.PropertyName := 'LocalMatrix';
JointAnim.AddElement(Joint1, True);
// ... configure JointAnim
SkeletonAnim.AddInterpolator(JointAnim);
SkeletonAnim.Start();
end;
procedure Reset();
Resets all child interpolators to starting position by calling ProcessTick(0, 0).
procedure SetSpeed(const ASpeed: Single);
Sets animation speed for all child interpolators.
Parameters:
ASpeed - Factor applied to the duration of every child interpolatorImportant: The implementation is Duration := Duration * ASpeed on every interpolator.
It is therefore a duration factor (2.0 = twice as long = half speed), it is
relative and cumulative, and it does not change the skeleton's own Duration. See
Playback Speed for an absolute rate.
Example:
SkeletonAnim.SetSpeed(0.5); // interpolators take half as long
procedure Start(); override;
procedure Stop(); override;
Start/stop the skeleton. The child interpolators are not started themselves - the skeleton copies its own clock into each of them on every tick, which keeps all joints synchronous.
On Delphi 13+ Start hands a skeleton that actually started to TGorillaRenderClock
and Stop gives it back. A start that does not take (invisible parent control, zero
duration) is not handed over.
procedure SeekTo(const ATime: Single);
Puts the play head at ATime (seconds) without computing a pose. The evaluation is
left to the next ordinary tick, so jumping into a clip right after Start does not pay
for a second skeleton evaluation. A pending start delay is cleared as well, because the
delay branch of FMX TAnimation.ProcessTick would otherwise put the clock back to zero.
Parameters:
ATime - Absolute position in seconds, 0 .. DurationExample:
LAnim.Skeleton.SeekTo(0.5 * LAnim.Skeleton.Duration); // half way through the clip
See Seeking to an Exact Position.
procedure ProcessAnimationRemote(ATime, ADeltaTime: Single);
Manually process an animation tick (external control, caching, design-time previews).
It calls ProcessCachingTick on every interpolator and therefore also works on a
stopped or paused skeleton. The step is relative: each call advances by ADeltaTime
from where the interpolators currently are.
Parameters:
ATime - Current animation timeADeltaTime - Time delta since last tickAt design time the interpolators only advance while the global
GorillaDesignTimeAnimationEnabled is True.
procedure Transform(const AMat: TMatrix3D); override;
Transforms all child interpolators by matrix.
Parameters:
AMat - Transformation matrixHigh-level animation instance representing a complete animation (e.g., "Walk", "Run").
Inheritance: TFmxObject → TGorillaAnimation
Platforms: All Gorilla3D supported platforms
Interfaces: IDuplicatable
| Property | Type | Description |
|---|---|---|
| Def | TAnimationDef | Associated animation definition (read-only). |
| Id | String | Registered animation identifier (read-only). |
| Skeleton | TSkeletonKeyAnimation | Skeleton helper interpolator holding sub-interpolators (read-only). |
| IsRunning | Boolean | True if animation is playing (read-only). |
| IsPaused | Boolean | True if animation is paused (read-only). Reads Skeleton.Paused on Delphi 13+, Skeleton.Pause before. |
| FrameCount | Integer | Number of frames of the cache grid, set by LoadFromAnimationDef (read-only). |
| FrameRate | Integer | Frames per second of the cache grid - a build constant, not the source clip's frame rate (read-only). |
| InPlace | Boolean | Removes the horizontal root motion from the clip, so the character animates on the spot. Acts on the definition, therefore on every instance sharing it. Assigning it discards cached frames without rebuilding them - see SetInPlace. |
| HasRootMotion | Boolean | True if the clip carries a measurable horizontal root motion. Valid before InPlace is set as well (read-only). |
| Property | Type | Description |
|---|---|---|
| UseTransform | Boolean | Enable/disable TransformMatrix application. |
| TransformMatrix | TMatrix3D | Transformation matrix for animated vertices. |
| Manager | TGorillaAnimationManager | Owner AnimationManager component. |
| Source | String | Animation file source path. |
constructor Create(AOwner: TComponent); override;
Standard constructor.
constructor CreateEx(const AManager: TGorillaAnimationManager); virtual;
Creates animation with linked manager.
Parameters:
AManager - Parent animation managerdestructor Destroy(); override;
procedure LoadFromAnimationDef(ADef: TAnimationDef); virtual;
Loads animation from definition structure.
Parameters:
ADef - Animation definition from model importExample:
var
Animation: TGorillaAnimation;
begin
Animation := TGorillaAnimation.CreateEx(Manager);
Animation.LoadFromAnimationDef(ModelDef.Animations[0]);
end;
procedure Start(); virtual;
Enables the skeleton and makes this clip the manager's Current one. Does not
crossfade and does not stop the previously current clip - use
TGorillaAnimationManager.PlayAnimation for that.
procedure Stop(); virtual;
Disables the skeleton. FMX advances the clip to its final frame first.
procedure StopAtCurrent(); virtual;
Stops the animation without advancing it to its final frame - the joints keep the values of the last tick. The crossfade uses it to keep the visible pose as its "from-pose"; use it whenever a clip should freeze where it is.
procedure Reset(); virtual;
Ticks all interpolators at time 0 (see TSkeletonKeyAnimation.Reset).
procedure SetSpeed(const ASpeed: Single);
Delegates to TSkeletonKeyAnimation.SetSpeed.
Parameters:
ASpeed - Factor for the interpolator durations (> 1 = slower, cumulative)function HasCachedFrames(): Boolean;
True while this clip can be drawn from baked frames, i.e. its definition finished
caching (TAnimationDef.BufferingState = Ready).
procedure SetFixedCacheFrame(AFrameNr: Integer);
Sets a fixed frame number for cache debugging.
Parameters:
AFrameNr - Frame number to displayprocedure UnsetFixedCacheFrame();
Deactivates fixed frame rendering.
function GetCurrentCachedFrame(const AMeshDef: TMeshDef): TMeshBufferObject;
Returns current mesh buffer object if caching is active.
Parameters:
AMeshDef - Mesh definitionReturns: Cached mesh buffer for current frame, or nil
The frame number is Round(FrameCount * Skeleton.TransitionTime), or the fixed frame
set by SetFixedCacheFrame.
procedure SetInPlace(const AValue: Boolean; const ARebuildCache: Boolean); overload;
Sets InPlace and, with ARebuildCache, bakes the clip again in the same call. Without
the rebuild a clip that was loaded with caching flags loses its baked frames and is drawn
from the mesh's static buffer - the character stands in its bind pose while the animation
reports IsRunning = True.
Parameters:
AValue - Take the horizontal root motion out of the clip (True) or put it back (False)ARebuildCache - Bake the clip again afterwards. Costs what the initial caching cost, which is why it is not what assigning the InPlace property does. Does nothing for a clip that was never cached - an uncached clip is skinned live and shows the change immediately.The frames are baked from the model this animation belongs to. Baking plays the clip once to sample it and stops it afterwards; a clip that was running is restarted through the manager.
Example:
var LAnim : TGorillaAnimation;
begin
LAnim := GorillaModel1.AnimationManager.GetAnimation('c-run.dae');
// model was loaded with caching flags
LAnim.SetInPlace(True, True);
// drive the character with the motion the clip no longer applies
LOffset := LAnim.RootMotionAt(LAnim.Skeleton.NormalizedTime);
end;
function RootMotionAt(const ANormTime: Single): TPointF;
The horizontal motion InPlace took out, at a normalised position 0..1 of the clip,
relative to its first frame and in model units. X is the world X component, Y the
world Z one.
function RootMotionTotal(): TPointF;
function RootMotionPeak(): Single;
Total motion from the first to the last frame, and the largest distance from the start reached anywhere in the clip.
Central manager for all animations associated with a 3D model or character.
Inheritance: TComponent → TGorillaAnimationManager
Platforms: All Gorilla3D supported platforms
Interfaces: IDuplicatable
A TGorillaModel creates its manager automatically. When you create one yourself, the
owner passed to the constructor must be a TGorillaMesh (or a descendant such as
TGorillaModel) - the constructor casts it and assigns it to Mesh.
The manager owns its animations: removing an entry from Animations or calling
Clear frees the TGorillaAnimation instance.
| Property | Type | Description |
|---|---|---|
| Mesh | TObject | Associated mesh/model object (the owner). |
| Animations | TGorillaAnimationMap | Hashmap of id-to-animation relationships (read-only). Enumerating it yields the hash order - use GetAnimationNames / GetSortedAnimations for a stable order. |
| Current | TGorillaAnimation | Currently active animation instance. Reading it while none is set returns (and stores) GetFirstAnimation. Assigning a different one stops the previous clip without crossfading. |
| BlendActive | Boolean | True while a crossfade is in progress (read-only). |
| Property | Type | Default | Description |
|---|---|---|---|
| CurrentAnimationName | String | - | Id of the current animation. Assigning calls PlayAnimation(Value). |
| BlendEnabled | Boolean | True | Master switch for crossfading in PlayAnimation. |
| BlendDuration | Single | 0.25 | Base crossfade length in seconds; 0 disables blending. |
| BlendUseSmoothStep | Boolean | True | Smoothstep easing instead of a linear ramp. |
| BlendAdaptive | Boolean | True | Scale the fade by the largest angular distance between both poses, clamped to [BlendDuration, BlendMaxDuration]. |
| BlendMaxDuration | Single | 0.6 | Upper bound for the adaptive duration in seconds. |
See Crossfading Between Animations.
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Clear(); virtual;
Cancels a running crossfade, resets Current and removes (and frees) all animations.
function GetAnimationNames(): TArray<String>;
Returns the ids of all animations, sorted in natural order: runs of digits are compared by their numeric value, everything else case-insensitively.
Returns: Sorted snapshot of the ids. A dynamic array - nothing to free. Empty if the manager holds no animations.
Ordering rules:
Walk2 before Walk10 (digit runs compared numerically, any length, no overflow)idle and Idle sort together (case-insensitive); ids that differ in case only are
ordered case-sensitively, so the result is always deterministic2 before 02 (equal value: fewer leading zeros first)Example:
var LName : String;
begin
ComboBox1.Clear();
for LName in GorillaModel1.AnimationManager.GetAnimationNames() do
ComboBox1.Items.Add(LName);
end;
function GetSortedAnimations(): TArray<TGorillaAnimation>;
Returns all animation instances in the same natural order as GetAnimationNames.
Returns: Sorted snapshot. The array needs no freeing; the instances are still owned by the manager - do not free them.
Example:
var LAnim : TGorillaAnimation;
begin
for LAnim in GorillaModel1.AnimationManager.GetSortedAnimations() do
Memo1.Lines.Add(Format('%s: %.2f s', [LAnim.Id, LAnim.Skeleton.Duration]));
end;
function GetFirstAnimation(): TGorillaAnimation;
Returns the first animation in natural id order (see GetAnimationNames) - not
necessarily the first one that was added.
Returns: First animation or nil
function GetLastAnimation(): TGorillaAnimation;
Returns the last animation in natural id order (see GetAnimationNames) - not
necessarily the last one that was added.
Returns: Last animation or nil
function GetAnimation(const AId: String = ''): TGorillaAnimation; overload;
Returns animation by identifier.
Parameters:
AId - Animation identifier (exact, case-sensitive key = TGorillaAnimation.Id, f.e.
the file name archer.dae)Returns: Animation instance or nil. An empty AId is looked up like any other key
and normally returns nil - use Current for the current animation.
Fallback: If no animation has this id, the component name of the animation
(TGorillaAnimation.Name) is compared, case-insensitive. Component names can not contain
dots or dashes, so the animation with the id archer-idle.dae is named archer_idle_dae -
both strings find it. AddAnimation checks the exact id only.
Prefer
IdoverName: when you fill a list (f.e. a combobox) to play animations from, useTGorillaAnimation.IdorGetAnimationNames().Idis the key the manager stores,Nameis only the derived component name.
Example:
var
WalkAnim: TGorillaAnimation;
begin
WalkAnim := Manager.GetAnimation('Walk');
if Assigned(WalkAnim) then
WalkAnim.Start();
end;
function GetAnimation(const ADef: TAnimationDef): TGorillaAnimation; overload;
Returns animation by definition.
Parameters:
ADef - Animation definitionReturns: Animation instance or nil
function AddAnimation(const AId: String; const AAnimation: TGorillaAnimation): TGorillaAnimation;
Adds animation to manager.
Parameters:
AId - Unique identifierAAnimation - Animation instanceReturns: Added animation, or existing animation if AId already exists
Example:
var
Animation: TGorillaAnimation;
begin
Animation := TGorillaAnimation.CreateEx(Manager);
Animation.LoadFromAnimationDef(AnimDef);
Manager.AddAnimation('Walk', Animation);
end;
function PlayAnimation(const AId: String): TGorillaAnimation; overload;
Plays animation by identifier.
Parameters:
AId - Animation identifier, resolved like GetAnimation(AId) - the component name
works as fallbackReturns: Playing animation or nil if not found
Behavior:
BlendEnabled is set with BlendDuration > 0, the current pose is captured, the old
clip is stopped with StopAtCurrent and the new one fades in. Otherwise the old clip
is stopped and the new one started (hard switch).Example:
Manager.PlayAnimation('Run');
function PlayAnimation(const AAnim: TGorillaAnimation): TGorillaAnimation; overload;
Plays specific animation instance.
Parameters:
AAnim - Animation instanceReturns: Playing animation, nil if AAnim is nil
Same switching and crossfade behaviour as the id overload.
function PlayNextAnimation(): TGorillaAnimation;
Plays the animation that follows the current one in natural id order
(see GetAnimationNames). Goes through PlayAnimation, so it crossfades.
Returns:
function PlayPreviousAnimation(): TGorillaAnimation;
Plays the animation that precedes the current one in natural id order, through
PlayAnimation.
Returns:
Example:
// registered ids: 'Walk10', 'Idle', 'Walk2'
Manager.PlayAnimation('Idle');
Manager.PlayNextAnimation(); // Walk2
Manager.PlayNextAnimation(); // Walk10
Manager.PlayNextAnimation(); // Idle (wrap-around)
Manager.PlayPreviousAnimation(); // Walk10
Changed behaviour: earlier builds walked the
Animationshashmap, i.e. an unpredictable order that could change whenever animations were added. All navigation routines (GetFirstAnimation,GetLastAnimation,PlayNextAnimation,PlayPreviousAnimation) and theCurrentfallback now follow the naturally sorted ids.
procedure ResetToBindPose(); virtual;
Stops all animations and returns the model to its bind pose (the unanimated pose).
Stop leaves the last pose of the clip and Reset jumps to the first frame of the clip -
neither is the bind pose.
Current stays assigned; PlayAnimation starts from the bind pose afterwards.Also available as TGorillaModel.ResetToBindPose().
procedure CancelBlend();
Aborts a running crossfade. The joints keep their current values, the new animation continues normally.
procedure ApplyBlendIfActive();
Mixes the captured from-pose into the values the running clip just wrote. Called by
TSkeletonKeyAnimation on every tick while BlendActive is set - no need to call it
yourself.
class function ForceStep(AMinDeltaTime: Double = 0.01): Boolean;
Forces animation update outside FMX message loop.
Parameters:
AMinDeltaTime - Minimum time since last update (default: 0.01 seconds)Returns: True if step was forced, False if skipped
Delphi 13+: FMX no longer has an animation thread to step. ForceStep only answers
whether AMinDeltaTime has passed and records the time - it does not advance anything.
Scene animations are advanced by TGorillaRenderClock at the start of each rendered
frame instead. Using the result as a rate gate keeps working unchanged.
Example:
// In rendering loop or timer
if TGorillaAnimationManager.ForceStep(0.01) then
Viewport.EndUpdate()
else
Viewport.EndUpdateWithoutInvalidate();
Simple property animation for TPoint3D without keyframes.
Inheritance: TCustomPropertyAnimation → TPoint3DAnimation
Platforms: All Gorilla3D supported platforms
| Property | Type | Default | Description |
|---|---|---|---|
| StartValue | TPosition3D | - | Starting point. |
| StopValue | TPosition3D | - | Ending point. |
| StartFromCurrent | Boolean | False | Start from current property value. |
| AnimationType | TAnimationType | In | Easing type. |
| AutoReverse | Boolean | False | Reverse at end. |
| Enabled | Boolean | False | Enable/disable. |
| Delay | Single | 0.0 | Start delay. |
| Duration | Single | 0.2 | Animation duration. |
| Interpolation | TInterpolationType | Linear | Interpolation type. |
| Inverse | Boolean | False | Reverse direction. |
| Loop | Boolean | False | Loop playback. |
| PropertyName | String | - | Target property. |
| Trigger / TriggerInverse | String | - | Standard FMX triggers. |
| OnProcess / OnFinish | TNotifyEvent | - | Standard FMX animation events. |
On Delphi 13+ Start / Stop hand the animation to and from TGorillaRenderClock,
because it moves scene content.
var
Anim: TPoint3DAnimation;
begin
Anim := TPoint3DAnimation.Create(Self);
Anim.Parent := Cube1;
Anim.PropertyName := 'Position.Point';
Anim.StartValue.Point := Point3D(0, 0, 0);
Anim.StopValue.Point := Point3D(10, 5, 0);
Anim.Duration := 2.0;
Anim.Loop := True;
Anim.Start();
end;
Delphi 13+ only (CompilerVersion >= 37.0).
Keeps the animations that drive scene content on the renderer's clock instead of FMX's display link.
Why: Delphi 13 replaced the FMX animation thread with IFMXDisplayLinkService, and
that service drops a tick whenever a paint is still pending. With a busy renderer
(switching on global illumination is enough) a paint is pending almost always, so poses
advanced in irregular lumps while the image advanced evenly - walk cycles stuttered.
Up to Delphi 12 ForceStep avoided this; on Delphi 13 the clock is put at the frame
instead.
How: TSkeletonKeyAnimation.Start and TPoint3DAnimation.Start hand a running
animation over. The clock holds the FMX Pause flag for it, so the display link leaves
it alone, and drops the flag for exactly one ProcessTick per rendered frame. Delay,
loop, auto-reverse and OnFinish therefore behave as before. A single step is capped at
0.25 s, so one long frame (loading, resize, breakpoint) does not teleport animations.
Because Pause is occupied, the pause state lives in the clock - use
TSkeletonKeyAnimation.Paused / TGorillaAnimation.IsPaused, not Skeleton.Pause.
2D interface animations are not affected and stay with FMX.
| Method | Description |
|---|---|
TakeOver(AAnim) |
Put a running animation under the render clock. |
Release(AAnim) |
Give it back to FMX, restoring its own pause state. Called on Stop and on destruction; Tick also releases animations that stopped otherwise (StopAtCurrent, Enabled := False, a finished clip). |
IsPaused(AAnim) |
Pause state of an animation (falls back to Pause if it is not under the clock). |
SetPaused(AAnim, AValue) |
Pause or resume an animation. |
Tick(): Boolean |
Advance all animations by the elapsed time. Called by TGorillaViewport at the start of each rendered frame - do not call it yourself. |
Single keyframe for TPoint3D animation.
Inheritance: TKey → TPoint3DKey
| Property | Type | Description |
|---|---|---|
| Value[Index: TComponent] | TPoint3D | Point value for specific component. |
procedure SetDefaultValue(AValue: TPoint3D);
function GetDefaultValue(): TPoint3D;
Single keyframe for TVector3D animation.
Inheritance: TKey → TVector3DKey
| Property | Type | Description |
|---|---|---|
| Value[Index: TComponent] | TVector3D | Vector value for specific component. |
Single keyframe for quaternion animation.
Inheritance: TKey → TQuaternion3DKey
| Property | Type | Description |
|---|---|---|
| Value[Index: TComponent] | TQuaternion3D | Quaternion value for specific component. |
Single keyframe for matrix transformation.
Inheritance: TKey → TTransformationKey
| Property | Type | Description |
|---|---|---|
| Value[Index: TComponent] | TMatrix3D | Matrix value for specific component. |
Single keyframe for vertex positions.
Inheritance: TKey → TCoordinateKey
| Property | Type | Description |
|---|---|---|
| Vertices[Index: TComponent] | TPoint3DDynArray | Vertex array for specific component. |
TGorillaInterpolatorList = TDictionary<String, TPropertyKeyAnimation>;
Hashmap of identifier-to-animation pairs.
TGorillaAnimationMap = TDictionary<String, TGorillaAnimation>;
Hashmap of identifier-to-TGorillaAnimation pairs.
TElementPoints = TDictionary<TComponent, TPoint3D>;
Component-to-Point3D hashmap for keys.
TElementVectors = TDictionary<TComponent, TVector3D>;
Component-to-Vector3D hashmap for keys.
TElementQuaternions = TDictionary<TComponent, TQuaternion3D>;
Component-to-Quaternion3D hashmap for keys.
TElementMatrices = TDictionary<TComponent, TMatrix3D>;
Component-to-Matrix3D hashmap for keys.
TGorillaPropertyKeyAnimationList = TObjectList<TPropertyKeyAnimation>;
Type of TSkeletonKeyAnimation.Interpolators (created without item ownership).
TElementVertices = class(TDictionary<TComponent, TVertexDataMap>);
Component-to-vertex-data hashmap.
TGorillaBlendEntryKind = (bekPoint3D, bekVector3D, bekQuaternion3D, bekMatrix3D);
TGorillaBlendList = TObjectList<TGorillaBlendEntry>;
Crossfade structures. A TGorillaBlendEntry holds one captured property value
(component, instance, RTTI property, kind, snapshot value and the offset that is decayed
over the blend). IsEulerRotation marks Euler rotations in degrees, which are blended
along the shortest arc. The list owns its entries.
TElementCoordinates = TDictionary<TComponent, TPoint3DDynArray>;
Component-to-vertex-array hashmap for keys.
| Variable | Default | Description |
|---|---|---|
GorillaDesignTimeAnimationEnabled |
False | Lets ProcessCachingTick advance animations of components in design state. Set it only while driving a design-time preview through ProcessAnimationRemote. |
GorillaSkipJointsWhenCached |
False | Skips the per-joint evaluation while a clip is drawn from baked frames. Saves CPU for crowds, but joint transforms, attachments, IK, joint-based bounds and the crossfade freeze at the last full evaluation. |
gOneInterpolator |
False | Internal debugging switch. |
Synchronization: Use TSkeletonKeyAnimation to group related animations for synchronized playback without timing offsets.
Performance: Up to Delphi 12, use ForceStep() in rendering loops to avoid FMX timer jitter. From Delphi 13 on, TGorillaRenderClock keeps poses and frames in step automatically.
Caching: Complex vertex animations benefit from frame caching to reduce CPU load.
Property Names: Supports dot notation for nested properties (e.g., "Position.Point.X").
Multiple Elements: Single animation can control multiple components with different values per keyframe.
Interpolation: All animations support standard FireMonkey interpolation types (Linear, Quadratic, Cubic, etc.).
Transform Matrices: Animations can be transformed (mirrored, scaled) by applying matrices to all keyframes.
AutoRepaint: Disable AutoRepaint on TSkeletonKeyAnimation for manual viewport control and better performance.
Memory Management: Always properly stop and free animations to prevent memory leaks.
Thread Safety: Animation updates occur on the main thread - via the FMX animation timer up to Delphi 12, via TGorillaRenderClock and the display link from Delphi 13 on.
Order of Animations: Animations is a hashmap without a defined order. Everything that needs an order - GetFirstAnimation, GetLastAnimation, PlayNextAnimation, PlayPreviousAnimation - uses the natural id order of GetAnimationNames.
Crossfading: Only PlayAnimation (and therefore CurrentAnimationName, PlayNextAnimation and PlayPreviousAnimation) crossfades. Start() on an animation and assigning Current switch hard.
The Gorilla.AssetsManager unit provides the asset management system for Gorilla3D. Assets (models, textures, audio, etc.) are organized in groups within ZIP-based packages. The system supports 10 built-in asset types, subgroups, JSON metadata, and caching for fast access.
| Constant | Value | Description |
|---|---|---|
GORILLA_ASSETS_MODEL |
0 | 3D models |
GORILLA_ASSETS_TEXTURE |
1 | Textures/images |
GORILLA_ASSETS_AUDIO |
2 | Audio files |
GORILLA_ASSETS_VIDEO |
3 | Video files |
GORILLA_ASSETS_MISC |
4 | Miscellaneous |
GORILLA_ASSETS_DIALOGUE |
5 | Dialogue data |
GORILLA_ASSETS_INVENTORY |
6 | Inventory data |
GORILLA_ASSETS_SCRIPT |
7 | Script files |
GORILLA_ASSETS_PREFAB |
8 | Prefab data |
GORILLA_ASSETS_SKILLS |
9 | Skill system data |
GORILLA_PACKAGE_VERSION = '1.3' — Current package format version.
| Value | Description |
|---|---|
LowQuality |
Low quality assets |
MediumQuality |
Medium quality assets |
HighQuality |
High quality assets |
ExcellentQuality |
Excellent quality assets |
Note: Currently reserved for future use.
| Value | Description |
|---|---|
StrictFileName |
Match full filename (not just extension) |
Cached |
Cache asset data in memory |
| Value | Description |
|---|---|
asUndef |
Undefined state |
asLoading |
Currently loading |
asLoaded |
Loaded successfully |
asStoring |
Currently storing |
asStored |
Stored successfully |
TPersistent
└── TGorillaAsset
├── TGorillaTextureAsset
├── TGorillaModelAsset
├── TGorillaAudioAsset
└── ... (other asset types)
TOwnedCollection
└── TGorillaAssetsGroupCollection
TComponent
└── TGorillaAssetsManager
Base class for all assets.
| Property | Type | Description |
|---|---|---|
Group |
TGorillaAssetsGroup |
Parent asset group |
Id |
TGorillaGUID |
Unique identifier |
Filename |
String |
Original filename |
Extension |
String |
File extension |
Cached |
Boolean |
Whether data is buffered in memory |
IsStandalone |
Boolean |
Asset without group reference |
State |
TAssetState |
Current loading/storing state |
| Property | Type | Description |
|---|---|---|
SubGroups |
TGorillaAssetsGroupCollection |
Nested asset groups (e.g., textures within a model) |
| Method | Description |
|---|---|
GetGroupId() |
Returns the group ID (abstract, per asset type) |
GetGroupDescr() |
Returns the group description (abstract) |
GetSupportedExtensions() |
Returns supported file extensions (abstract) |
IsExtensionSupported(AExt) |
Check if extension is supported |
GetSupportedAssetClass(AExt) |
Find asset class by extension |
ImportFromFile(AGroup, AFilename, AFlags) |
Import asset from file into group |
ImportFromStream(AGroup, AFilename, AStream, AFlags) |
Import asset from stream (abstract) |
UpdateInArchive() |
Re-store asset in ZIP archive |
GetSize() |
Returns asset size in bytes |
ToJSON() |
Serialize to JSON |
FromJSON(AValue) |
Deserialize from JSON |
AddSubGroup(AClass) |
Add or get sub-group by asset class |
RemoveSubGroup(AIdx/ADescr) |
Remove sub-group |
GetSubGroup(AIdx/ADescr) |
Get sub-group |
FindSubAsset(AFilename, AStrictFilename) |
Find asset in sub-groups |
AddSubAssetFromFile(AFilename) |
Add or find asset from file |
Stores texture/image data as TBitmap. Supports BMP, JPG, JPEG, DDS, GIF, PNG, TIF, TIFF, TGA.
| Property | Type | Description |
|---|---|---|
Bitmap |
TBitmap |
Buffered bitmap image |
CachedBitmap |
TGorillaTextureBitmap |
Cached GPU texture bitmap |
OriginalFilename |
String |
Original file path before import |
Stores 3D model data as TModelDef. Supports OBJ, G3D, DAE, FBX, GLTF, STL, X3D, Babylon, PLY, SKP, and more. Models are saved as G3D inside packages.
Main component for managing asset packages.
| Method | Description |
|---|---|
AddPackage(AName) |
Create a new asset package |
RemovePackage(AName) |
Remove a package |
GetPackage(AName) |
Get package by name |
LoadFromFile(AFilename) |
Load package from ZIP file |
SaveToFile(AFilename) |
Save package to ZIP file |
The Gorilla.Camera unit provides camera components for controlling the view in Gorilla3D scenes. It includes the main camera component TGorillaCamera and the smooth camera controller TGorillaSmoothCameraController for interactive camera navigation.
Extended camera component inheriting from FireMonkey's TCamera with additional functionality for Gorilla3D rendering.
Inheritance: TCamera → TGorillaCamera
Platforms: All Gorilla3D supported platforms
| Property | Type | Access | Description |
|---|---|---|---|
| Def | TCameraDef | Read | Access to the camera definition object containing camera parameters. |
| UpdateNeeded | Boolean | Read | Indicates whether the camera needs to be updated. |
| PerspectiveMatrix | TMatrix3D | Read | Not implemented — reading this property raises an exception. Use GetProjectionMatrix() instead, which honours ProjectionMode. |
| Property | Type | Description |
|---|---|---|
| FOV | Single | Get or set the field of view angle in degrees. Only used while ProjectionMode is cpPerspective — except by sky boxes, which keep rendering through a perspective frustum built from this angle. |
| ProjectionMode | TGorillaCameraProjection | Perspective, orthographic or isometric projection. Default cpPerspective. |
| OrthoHeight | Single | Height of the visible area in world units, for orthographic and isometric cameras. The orthographic counterpart of FOV — smaller values zoom in. Default 10. |
| OrthoWidth | Single | Width of the visible area in world units. 0 (the default) derives the width from OrthoHeight and the viewport aspect ratio. |
| IsometricPreset | TGorillaIsometricPreset | Camera angles used while ProjectionMode is cpIsometric. Default ipTrueIsometric. Selecting a preset mirrors its angles into IsometricYaw / IsometricPitch. |
| IsometricYaw | Single | Azimuth of the isometric view in degrees, around the world Y axis. Only read while IsometricPreset is ipCustom. |
| IsometricPitch | Single | Elevation of the isometric view in degrees above the horizon; positive values look down. Only read while IsometricPreset is ipCustom. |
| AutoIsometricOrientation | Boolean | When True (the default) the camera re-orients itself whenever an isometric setting changes. Turn it off to keep manual control of RotationAngle. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
Standard lifecycle methods.
procedure AssignFrom(Src: TPersistent);
Copy camera settings from another persistent object.
procedure LoadFromDefinition(const ADef: TCameraDef); virtual;
Load camera settings from a camera definition object.
procedure Update(); virtual;
Update the camera state.
function IsOrthographic(): Boolean;
True while the camera renders through a box frustum, which is the case for both cpOrthographic and cpIsometric.
function GetProjectionSettings(): TGorillaProjectionSettings; virtual;
The projection this camera wants the context to rasterise through. Single source of truth: the viewport hands this to the main context, and the render pass controller hands it to every pass that renders through a context of its own. TGorillaProjectionSettings is declared in Gorilla.Context.Types.
function GetProjectionMatrix(const AViewWidth, AViewHeight: Single;
const ANear, AFar: Single): TMatrix3D; virtual;
Builds this camera's projection matrix for a viewport of the given pixel size. A perspective camera returns exactly the matrix the context would have computed on its own.
procedure ApplyIsometricOrientation(); virtual;
Points the camera down the isometric axis described by IsometricYaw and IsometricPitch. With a Target assigned the camera is placed on that axis through the target, keeping its current distance, because a target makes TCamera ignore rotation. Call this manually after changing the angles while AutoIsometricOrientation is off.
procedure GetIsometricAngles(out AYaw, APitch: Single); virtual;
Yaw (azimuth around the world Y axis) and pitch (elevation above the horizon, positive looks down) belonging to the active IsometricPreset. ipCustom returns the camera's current angles.
Interactive camera controller providing smooth, impulse-based camera navigation. This component is a TDummy that contains a camera and controls it through physics-like impulses.
Inheritance: TDummy → TGorillaSmoothCameraController
Platforms: All Gorilla3D supported platforms
| Property | Type | Access | Description |
|---|---|---|---|
| Impulse | TPoint3D | Read/Write | Current impulse for rotation around Y-axis (X), moving up/down (Y), and zooming (Z). |
| ShiftImpulse | TPoint3D | Read/Write | Current impulse for shifting on X, Y, and Z axes. |
| Property | Type | Description |
|---|---|---|
| Types | TGorillaSmoothCameraControlTypes | Enable or disable control types: rotation, movement, zooming, and shifting. |
| Property | Type | Description |
|---|---|---|
| ImpulseLimitRotate | Single | Maximum input value for rotation impulse. |
| ImpulseLimitUpAndDown | Single | Maximum input value for up/down movement impulse. |
| ImpulseLimitZoom | Single | Maximum input value for zoom impulse. |
| Property | Type | Description |
|---|---|---|
| IntensityRotate | Single | Intensity (sensitivity) of camera rotation. |
| IntensityUpAndDown | Single | Intensity (sensitivity) of camera up/down movement. |
| IntensityZoom | Single | Intensity (sensitivity) of camera zoom. |
| Property | Type | Description |
|---|---|---|
| DampingRotate | Single | Damping factor for rotation impulse. Higher = slower decay. |
| DampingUpAndDown | Single | Damping factor for up/down movement impulse. |
| DampingZoom | Single | Damping factor for zoom impulse. |
| Property | Type | Description |
|---|---|---|
| LimitRotationMin | Single | Minimum rotation angle around Y-axis. |
| LimitRotationMax | Single | Maximum rotation angle around Y-axis. |
| LimitUpAndDownMin | Single | Minimum position on Y-axis for up/down movement. While orbiting: minimum pitch of the camera (rotation around X) in degrees; a range of less than 360 is not wrapped round. |
| LimitUpAndDownMax | Single | Maximum position on Y-axis for up/down movement. While orbiting: maximum pitch of the camera (rotation around X) in degrees. |
| LimitZoomMin | Single | Minimum zoom distance on Z-axis. |
| LimitZoomMax | Single | Maximum zoom distance on Z-axis. |
| Property | Type | Description |
|---|---|---|
| ShiftImpulseLimit | Single | Maximum shift impulse value. |
| ShiftDamping | Single | Damping factor for shifting impulse. |
| ShiftIntensity | Single | Intensity (sensitivity) of shifting on X, Y, and Z axes. |
| ShiftOnGround | Boolean | Shift over the ground instead of along the view: forward/backward and left/right shifting move the controller level, whatever the camera's pitch. Shifting up and down is unaffected. Default: False. |
| Property | Type | Description |
|---|---|---|
| Camera | TCamera | Link to the camera component to control. Controller does nothing if no camera is linked. |
| Viewport | TControl | Link to viewport for automatic mouse event registration. If not linked, you must call control methods manually. |
| Property | Type | Description |
|---|---|---|
| ShowController | Boolean | Show/hide a cube rendered at the controller position (for debugging). |
| Interval | Integer | Internal update interval in milliseconds. |
| Enabled | Boolean | Enable or disable the controller. |
| Orbiting | Boolean | Enable orbiting navigation mode where camera rotates around the controller instead of the controller rotating. |
| NavigationProfile | TGorillaCameraNavigationProfile | Choose between preset navigation profiles (Default, Orbit, InvOrbit, Blender, Sketchfab). |
| Property | Type | Description |
|---|---|---|
| Shifting | TCameraShiftState | Input controls to allow shifting (default: right mouse button). |
| ShiftUp | TCameraShiftState | Input controls to allow shifting upwards (default: Shift + right mouse button). |
| Zooming | TCameraShiftState | Input controls to allow zooming (default: mouse wheel). |
| Rotation | TCameraShiftState | Input controls to allow rotation (default: left mouse button). |
| Property | Type | Description |
|---|---|---|
| OnBeforeModify | TOnCameraControllerEvent | Callback event before a control type is modified. |
| OnAfterModify | TOnCameraControllerEvent | Callback event after a control type was modified. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Standard lifecycle methods.
procedure AddImpulse(AOfs: TPointF); virtual;
Add rotation impulse (AOfs.X) and up/down movement impulse (AOfs.Y).
procedure AddXImpulse(AAngle: Single); virtual;
Add rotation impulse around Y-axis.
procedure AddYImpulse(AAngle: Single); virtual;
Add up/down movement impulse.
procedure Zoom(AStrength: Single = 1); virtual;
Zoom in or out. Positive values zoom in, negative values zoom out. Under an orthographic or isometric camera this scales the camera's OrthoHeight instead of moving it — moving an orthographic camera along its view axis does not change the image, it only shifts the scene inside the near/far range.
function GetOrthographicCamera(out ACamera: TGorillaCamera): Boolean; virtual;
Returns the linked camera when it renders orthographically, so zoom handling can branch on it.
procedure ApplyOrthographicZoom(const ACamera: TGorillaCamera;
const AStep: Single); virtual;
Applies one zoom step to an orthographic camera. AStep is the distance the camera would have travelled along its view axis in a perspective setup; positive values zoom in. Scaling is multiplicative, so a step feels the same at any zoom level, and the result is clamped so a long scroll can neither collapse the view box nor blow it up beyond recovery.
procedure Shift(AOfs: TPoint3D); virtual;
Move the camera controller on X, Y, and Z axes.
procedure SetPositionAndAngle(const APos: TPoint3D; const AAngle: TPoint3D);
Set the controller to a specific position and angle.
Projection a TGorillaCamera renders through.
Values:
cpPerspective - View pyramid built from FOV. The default; distant objects get smaller.cpOrthographic - View box built from OrthoHeight / OrthoWidth. Objects keep their size regardless of distance.cpIsometric - cpOrthographic plus a fixed camera orientation taken from IsometricPreset. Isometry is not a projection of its own; it is what you get when you look at an orthographic scene down one particular axis.Ready-made camera angles used while ProjectionMode is cpIsometric.
Values:
ipTrueIsometric - Azimuth 45°, elevation 35.264° (ArcTan(1 / Sqrt(2))). The view direction becomes (1, 1, 1) normalised, so all three world axes are foreshortened equally.ipDimetric2To1 - Azimuth 45°, elevation 26.565° (ArcTan(0.5)). Strictly dimetric, but it is what most tile engines mean by "isometric" — a unit cube lands on whole pixel counts.ipMilitary - Azimuth 45°, elevation 45°. Military / cavalier style top-down view.ipCustom - Uses IsometricYaw and IsometricPitch.Enumeration defining types of camera controls.
Values:
scctRotateX - Rotation around X-axisscctRotateY - Rotation around Y-axisscctMoveY - Movement on Y-axis (up/down)scctZoom - Zoom in/outscctShiftX - Shift on X-axisscctShiftY - Shift on Y-axisscctShiftZ - Shift on Z-axisSet of TGorillaSmoothCameraControlType values.
Enumeration of preset navigation profiles.
Values:
cnpDefault - No orbiting, rotation by LMB, shifting xz-axes by RMB, shifting xy-axes by Shift+RMB, zooming by mouse wheelcnpOrbit - With orbiting, rotation by RMB, shifting xy-axes by LMB, shifting xz-axes by Shift+LMB, zooming by mouse wheelcnpInvOrbit - With orbiting, rotation by LMB, shifting xy-axes by RMB, shifting xz-axes by Shift+RMB, zooming by mouse wheelcnpBlender - Blender-like navigation: with orbiting, rotation by Ctrl+RMB, shifting xy-axes by Ctrl+LMB, shifting xz-axes by Shift+LMB, zooming by mouse wheelcnpSketchfab - Sketchfab-like navigation: with orbiting, rotation by LMB, shifting xy-axes by RMB, shifting xz-axes by Shift+RMB, move-forward by mouse wheel, zoom by Ctrl+mouse wheelMouse and keyboard state items for input control.
Values:
cssShift - Shift key pressedcssAlt - Alt key pressedcssCtrl - Ctrl key pressedcssLeft - Left mouse buttoncssRight - Right mouse buttoncssMiddle - Middle mouse buttoncssDouble - Double-clickcssTouch - Touch inputcssPen - Pen inputcssCommand - Command key (macOS)cssHorizontal - Horizontal scrollingcssMouseWheel - Mouse wheelSet of TCameraShiftStateItem values.
Event callback for camera controller modifications.
TOnCameraControllerEvent = procedure(
ASender: TObject;
AType: TGorillaSmoothCameraControlType;
var AValue: Single
) of object;
Parameters:
ASender - The controller triggering the eventAType - Type of control being modifiedAValue - Current value (can be modified in the event handler)INITIAL_CAMERA_ZOFFSET = -1.0;
Default Z-offset for camera positioning.
GORILLA_ISOMETRIC_YAW = 45.0;
GORILLA_ISOMETRIC_PITCH = 35.2643896827547;
GORILLA_DIMETRIC_PITCH = 26.5650511770780;
GORILLA_MILITARY_PITCH = 45.0;
The angles behind TGorillaIsometricPreset, exposed for use elsewhere. GORILLA_ISOMETRIC_PITCH is ArcTan(1 / Sqrt(2)) in degrees, GORILLA_DIMETRIC_PITCH is ArcTan(0.5).
Camera Reference: Always set the Camera property of TGorillaSmoothCameraController to link it to a camera component.
Viewport Integration: Set the Viewport property for automatic mouse event handling. Without this, you must manually call AddImpulse(), Zoom(), and Shift().
Impulse System: The controller uses a physics-like impulse system with damping. Impulses gradually decrease over time based on damping settings.
Orbiting Mode: In orbiting mode, the camera rotates around the controller position rather than rotating in place. This is useful for object inspection.
Navigation Profiles: Use preset profiles for familiar navigation schemes from other 3D applications (Blender, Sketchfab, etc.).
Limits: Set min/max limits to constrain camera movement within specific bounds.
Projection Modes: ProjectionMode only takes effect on the camera that actually renders. TGorillaViewport.UsingDesignCamera defaults to True, and while it is on the viewport renders through its own design camera — set it to False after assigning Viewport.Camera.
Orthographic Zoom: Change OrthoHeight to zoom an orthographic camera. Moving it along its view axis does not change the image.
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.
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;
| 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. |
TGorillaGraphicsBackend = (
gbDefault, // platform default: OpenGL / OpenGL ES
gbOpenGL, // explicitly select OpenGL / OpenGL ES
gbVulkan // explicitly select Vulkan (Windows, Linux, Android)
);
Description of a single physical GPU as reported by the operating system. Filled by GetGpuAdapters.
| 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.
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 = array of TGorillaGpuAdapterInfo;
Result of GetHybridGraphicsState — the render / display constellation of the system.
| 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)
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;
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;
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.
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.
DisplayAdapterName falls back to GetActiveDisplayAdapterName() 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
IDXGIFactory5 / IDXGIFactory6 are not declared by the Delphi RTL (which stops at Winapi.DXGI1_4) and are declared inside this unit. Only the vtable layout matters; the inherited chain up to IDXGIFactory4 is complete in the RTL.EnumDisplayDevices and IDXGIAdapter.EnumOutputs are 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).TFileStream loop. sysfs reports a size of one page (4096) for every attribute while the actual read returns far fewer bytes, so TStringList.LoadFromFile / TFile.ReadAllText raise. Missing attributes are the normal case and never travel as an exception, so the debugger does not stop on every probe.dxgi.dll is delay loaded by the RTL; a missing library is caught and simply reported as "no enumeration available".HMONITOR handles inside the EnumDisplayMonitors callback; all further work happens outside, so no Delphi exception can travel through user32 frames.NativeUInt for every C unsigned 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 on BadRROutput / BadRRCrtc (monitor unplugged between two requests).NSScreen.localizedName and CGDisplayModeGetPixelWidth/Height are missing in the Delphi RTL and declared inside this unit.Gorilla.Context.Backend first in the uses clause of the .dpr and apply GorillaGraphicsBackend / ForceToUseNVIDIAorAMDGPU before Application.Initialize.GORILLA_FORCE_HIGHPERFORMANCE_GPU instead of calling ForceToUseNVIDIAorAMDGPU manually when you cannot guarantee the call site runs early enough.CheckHybridGraphicsState) and log GetGpuDiagnosticsReport().Detected = False as "no hybrid system" — it means the constellation could not be determined on this platform.GetGpuAdapters, GetHybridGraphicsState and GetGpuDiagnosticsReport can also be called later at runtime, for example behind a diagnostics menu item.The Gorilla.Controller unit provides the foundation for render pass management in Gorilla3D. It defines the TGorillaRenderPassController class and supporting infrastructure for implementing custom multi-pass rendering techniques, including reflections, refractions, shadows, and post-processing effects.
The controller system uses a hierarchical structure:
TGorillaController (Base)
├─ TGorillaComponentController
└─ TGorillaRenderPassController
├─ Own Renderer
├─ Frame Buffer Object (FBO)
├─ Shader Material (optional)
└─ Control Collections (allowed/ignored)
Base controller class for all Gorilla3D controllers.
Inheritance: TFmxObject → TGorillaController
Platforms: All Gorilla3D supported platforms
| Property | Type | Default | Description |
|---|---|---|---|
| Enabled | Boolean | True | Enable/disable controller. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Standard component lifecycle management.
Controller with target component link.
Inheritance: TGorillaController → TGorillaComponentController
Platforms: All Gorilla3D supported platforms
| Property | Type | Description |
|---|---|---|
| Target | TControl3D | Target 3D control for controller operations. |
Base class for render pass shader materials.
Inheritance: TMaterialSource → TGorillaRenderPassMaterialSource
Platforms: All Gorilla3D supported platforms
| Property | Type | Description |
|---|---|---|
| OwnerPass | TGorillaRenderPassController | Render pass that owns this material source. |
| InputPass | TGorillaRenderPassController | Input render pass (for chaining). |
| HasMaterial | Boolean | Whether material instance exists. |
constructor Create(AOwnerPass: TGorillaRenderPassController); reintroduce; virtual;
Creates material source owned by a render pass controller.
Parameters:
AOwnerPass - The render pass controller that owns this materialprocedure PassesChanged(Sender: TObject);
Notification that render pass configuration changed.
Internal material class for render pass shaders.
Inheritance: TCustomMaterial → TGorillaRenderPassMaterial
| Property | Type | Description |
|---|---|---|
| Source | TGorillaRenderPassMaterialSource | Parent material source. |
| ShaderUpdateCounter | NativeUInt | Shader rebuild counter. |
constructor Create(ASource: TGorillaRenderPassMaterialSource); reintroduce; virtual;
Creates material instance from material source.
function GetPreviousRenderTexture(AContext: TContext3D): TTexture; virtual;
Returns the output texture of the previous renderer in the render pipeline.
Parameters:
AContext - Rendering contextReturns: Previous pass output texture, or current context texture if none
Collection item representing a managed (allowed/ignored) control.
Inheritance: TCollectionItem → TGorillaManagedControl
| Property | Type | Description |
|---|---|---|
| DisplayName | String | Display name in collection editor. |
| Control | TControl3D | Reference to managed 3D control. |
procedure Notification(AComponent: TComponent; Operation: TOperation);
Handles component notifications for lifetime management.
Collection of managed controls for allow/ignore filtering.
Inheritance: TOwnedCollection → TGorillaManagedControls
function GetManagedControl(ACtrl: TControl3D): TGorillaManagedControl;
Finds collection item for a specific control.
Parameters:
ACtrl - Control to findReturns: Collection item if found, nil otherwise
function IndexOf(ACtrl: TControl3D): Integer;
Returns index of control in collection, or -1 if not found.
function Contains(ACtrl: TControl3D): Boolean;
Checks if control exists in collection.
procedure Remove(ACtrl: TControl3D);
Removes control from collection.
procedure Notification(AComponent: TComponent; Operation: TOperation);
Handles component notifications for all collection items.
Primary render pass controller class. Abstract base - must be inherited for specific pass types.
Inheritance: TGorillaController → TGorillaRenderPassController
Platforms: All Gorilla3D supported platforms
Abstract: Cannot instantiate directly - use specialized subclasses like TGorillaRenderPassReflection
| Property | Type | Description |
|---|---|---|
| Id | String | Unique render pass identifier. Duplicate IDs overwrite existing passes. |
| _Type | TRenderPassType | Execution timing: Pre, Post, or Intermediate. |
| Method | TRenderPassMethod | Render method: RenderListToFBO or RectToFBO. |
| RenderProc | TRenderPassRenderingProc | Rendering procedure: DefaultRendering or ListRendering. |
| Viewport | TGorillaViewport | Parent viewport for rendering. |
| Iterations | Integer | Number of times to execute pass per frame (for ping-pong effects). Default: 1. |
| Property | Type | Range | Description |
|---|---|---|---|
| ViewportWidth | Integer | > 0 | Custom viewport width (if OverwriteViewportSize). |
| ViewportHeight | Integer | > 0 | Custom viewport height (if OverwriteViewportSize). |
| OverwriteViewportSize | Boolean | - | Use custom viewport size instead of main viewport. |
| ScaleViewportSize | Boolean | - | Multiply the individual ViewportSize by ViewportScale. Only effective with OverwriteViewportSize; otherwise the pass renders in the viewport's render target size (incl. RenderScale / HighRes). |
| ViewportScale | Single | > 0 | Scaling factor for viewport dimensions. |
| Property | Type | Description |
|---|---|---|
| OverwriteColor | Boolean | Use custom background color instead of viewport color. |
| BackgroundColor | TAlphaColor | Custom background color (if OverwriteColor is True). |
| Property | Type | Description |
|---|---|---|
| AllowedControls | TGorillaManagedControls | Collection of explicitly allowed controls. Empty = allow all. |
| IgnoredControls | TGorillaManagedControls | Collection of controls to exclude from rendering. |
| Property | Type | Description |
|---|---|---|
| OnBeginSetup | TRenderPassEvent | Called once per frame before pass setup. |
| OnEndSetup | TRenderPassEvent | Called once per frame after pass setup. |
| OnBeginRender | TRenderPassEvent | Called before each iteration renders. |
| OnEndRender | TRenderPassEvent | Called after each iteration completes. |
| Property | Type | Description |
|---|---|---|
| Shader | TGorillaRenderPassMaterialSource | Shader material source for RectToFBO rendering. |
| RendererType | TRendererType | Renderer type: ForwardRenderer or LegacyRenderer. |
| Renderer | TRenderer | Internal renderer instance used by this pass. |
| PreviousRenderer | TRenderer | Renderer that was active before this pass. |
| RendererFlags | TRendererFlags | Renderer creation flags. |
| FBO | TFrameBufferObject | Frame buffer object for render-to-texture. |
| FBOTexture | TGorillaTextureBitmap | Output texture bitmap. |
| OutputTexture | TTexture | Final output texture (read-only). |
| ViewportSize | TPoint | Actual rendering dimensions. |
| ProjMatrix | TMatrix3D | Computed projection matrix (read-only). |
| ViewMatrix | TMatrix3D | Computed view matrix (read-only). |
| PrevViewMatrix | TMatrix3D | View matrix before pass execution (read-only). |
| PrevProjMatrix | TMatrix3D | Projection matrix before pass execution (read-only). |
| RenderingSkipped | Boolean | Whether rendering was skipped this frame (read-only). |
constructor Create(AOwner: TComponent; const AId: String); reintroduce; virtual;
Creates render pass controller with unique identifier.
Parameters:
AOwner - Component ownerAId - Unique pass identifierExample:
var Pass := TMyRenderPass.Create(Self, 'CustomPass');
destructor Destroy(); override;
Destroys render pass and releases GPU resources.
procedure AfterConstruction(); override;
Called after construction completes. Override for initialization.
procedure Refresh();
Recreates renderer (useful after major configuration changes).
procedure BindRenderer(); virtual;
Activates this pass's renderer and FBO.
procedure UnbindRenderer(); virtual;
Deactivates this pass's renderer and FBO.
procedure BeginRenderPassRendering(AContext: TContext3D; AFill: TAlphaColor;
ADepth: Single = 1; AStencil: Cardinal = 0); virtual;
Begins render pass rendering cycle.
Parameters:
AContext - Rendering contextAFill - Clear colorADepth - Depth clear value (default: 1.0)AStencil - Stencil clear value (default: 0)procedure EndRenderPassRendering(AContext: TContext3D); virtual;
Ends render pass rendering cycle.
procedure AllowControl(ACtrl: TControl3D); virtual;
Adds control to allowed list. Automatically includes sub-meshes and child components.
Parameters:
ACtrl - Control to allowExample:
ReflectionPass.AllowControl(Skybox);
ReflectionPass.AllowControl(Mountains);
procedure IgnoreControl(ACtrl: TControl3D); virtual;
Adds control to ignored list. Automatically includes sub-meshes and child components.
Parameters:
ACtrl - Control to ignoreExample:
ReflectionPass.IgnoreControl(WaterPlane);
function IsControlIgnored(ACtrl: TControl3D): Boolean; virtual;
Checks if control is ignored by this pass.
Parameters:
ACtrl - Control to checkReturns: True if control will not be rendered
Logic:
AllowedControls is not empty and control is not in list: IgnoredIgnoredControls: IgnoredExample:
if not ReflectionPass.IsControlIgnored(TreeModel) then
ShowMessage('Tree will be rendered in reflection');
procedure UpdateOnResize(); virtual;
Called when viewport resizes. Updates internal viewport size and recreates textures.
procedure UpdateRenderPass(); virtual;
Updates render pass registration in context. Called automatically when configuration changes.
function CreateRenderPassInstance(const AContext: TContext3D): TRenderPass; virtual;
Creates temporary render pass instance (for internal rendering).
Parameters:
AContext - Rendering contextReturns: New TRenderPass instance
class function IsInternalRenderPass(): Boolean; virtual;
Returns True if pass is internal (not registered with context).
Returns: False by default. Override to return True for internal passes.
function IsPrimitivesKindSupported(AKind: TPrimitivesKind): Boolean; virtual;
Checks if primitive type is supported by this pass.
Parameters:
AKind - Primitive typeReturns: True by default. Override to restrict primitive types.
procedure SetInputPass(const APass: TGorillaRenderPassController); virtual;
Sets input pass for chaining passes together.
Parameters:
APass - Pass whose output becomes this pass's inputExample:
BlurVertical.SetInputPass(BlurHorizontal);
function GetInputPass(): TGorillaRenderPassController; virtual;
Returns currently set input pass.
Returns: Input pass controller, or nil if none
function GetOutputTexture(): TTexture; virtual;
Returns final output texture of this render pass.
Returns: FBO output texture
Note: Override for custom texture handling.
function GetTextureMatrix(AContext: TContext3D;
const AUseBias: Boolean = false): TMatrix3D; virtual;
Returns texture matrix for this pass.
Parameters:
AContext - Rendering contextAUseBias - Apply bias matrix (for shadow mapping)Returns: Texture coordinate transformation matrix
Note: Override for custom matrix computation (e.g., shadow map projection).
function GetCurrentModelViewProjectionMatrix(): TMatrix3D; virtual;
Returns combined model-view-projection matrix.
Returns: MVP matrix for current pass
function GetViewMatrix(): TMatrix3D; overload; virtual;
function GetViewMatrix(const AContext: TContext3D): TMatrix3D; overload; virtual;
Returns view (camera) matrix for this pass.
Returns: View matrix (from camera or identity)
Note: Override for custom view matrices (e.g., mirrored for reflections).
function GetProjectionMatrix(): TMatrix3D; overload; virtual;
function GetProjectionMatrix(const AContext: TContext3D): TMatrix3D; overload; virtual;
Returns projection matrix for this pass.
Returns: Projection matrix (computed from viewport size and camera FOV)
Note: Override for custom projections (e.g., orthographic for shadow maps).
procedure RenderToContext(const AContext: TContext3D; const ATexture: TTexture;
const ARect: TRect; const ADstPos: TPoint);
Renders pass output to context using a fullscreen quad.
Parameters:
AContext - Rendering contextATexture - Input textureARect - Destination rectangleADstPos - Destination positionUse Case: Compositing passes, post-processing
function ComputeRenderingSize(const AContext: TContext3D;
const AWidth: Integer = 0; const AHeight: Integer = 0): TPoint;
Computes actual rendering size based on pass configuration.
Parameters:
AContext - Rendering contextAWidth - Optional width overrideAHeight - Optional height overrideReturns: Final rendering dimensions (considering OverwriteViewportSize and ScaleViewportSize)
procedure SetViewportSizeAndScaleWithoutResize(AViewport: TComponent;
ASize: TPoint; AScale: Single);
Sets viewport size and scale without triggering renderer resize.
Parameters:
AViewport - Viewport componentASize - New sizeAScale - New scaleUse Case: Batch configuration updates
procedure IncFrameCount();
Increments frame counter. Called automatically by render pass instance.
procedure SkipRendering(); virtual;
Skips rendering for current frame.
Example:
// Only update reflection every 3rd frame
if (FrameCount mod 3) <> 0 then
ReflectionPass.SkipRendering();
procedure ResetSkippedRendering();
Resets skip flag (called automatically after skipped frame).
Defines when the render pass executes relative to the main rendering loop.
TRenderPassType = (
Pre, // Execute before main rendering loop
Post, // Execute after main rendering loop
Intermediate // Execute during main rendering loop
);
Usage:
ReflectionPass._Type := TRenderPassType.Pre; // Before main scene
BlurPass._Type := TRenderPassType.Post; // After main scene
Defines how the render pass produces output.
TRenderPassMethod = (
RenderListToFBO, // Renders all elements in the renderlist with the render pass material or the original material
RectToFBO // Renders with a render pass material a specific shader effect onto a rect
);
Usage:
ReflectionPass.Method := TRenderPassMethod.RenderListToFBO; // Scene rendering
BlurPass.Method := TRenderPassMethod.RectToFBO; // Post-process
| Render Pass Method | Description |
|---|---|
| RenderListToFBO | Will render all objects in renderlist with the provided render pass material. The output will be written to the FBO of your renderpass. Use this method in case you need to re-render all elements with their original material or all elements with the same render pass material |
| RectToFBO | Will render on basis of the latest context FBO or on a attached renderpass output. The output will be written to the FBO of your renderpass. Use this method if you want to produce a pre/post effect. |
Defines rendering procedure for scene objects.
TRenderPassRenderingProc = (
DefaultRendering, // WBOIT with separate opaque/translucent passes
ListRendering // Forward rendering without transparency separation
);
Usage:
ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering; // Accurate transparency
DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering; // Fast depth-only
Event callback signature for render pass events.
TRenderPassEvent = procedure(ASender: TObject; const AContext: TContext3D;
const ACount: Integer; const APass: TRenderPass) of object;
Parameters:
ASender - Render pass controllerAContext - Rendering contextACount - Current iteration index (0-based)APass - Render pass instanceExample:
procedure TForm1.OnPassBegin(ASender: TObject; const AContext: TContext3D;
const ACount: Integer; const APass: TRenderPass);
begin
// Custom setup logic
end;
ReflectionPass.OnBeginRender := OnPassBegin;
Class reference type for render pass controllers.
TGorillaRenderPassControllerClass = class of TGorillaRenderPassController;
var
DepthPass: TGorillaRenderPassCustomDepth;
begin
DepthPass := TGorillaRenderPassCustomDepth.Create(Self, 'DepthPass');
DepthPass.Viewport := GorillaViewport1;
DepthPass._Type := TRenderPassType.Pre;
DepthPass.Method := TRenderPassMethod.RenderListToFBO;
DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering;
// Custom shadow map resolution
DepthPass.OverwriteViewportSize := True;
DepthPass.ViewportWidth := 2048;
DepthPass.ViewportHeight := 2048;
end;
// Exclude water from reflection
ReflectionPass.IgnoreControl(WaterPlane);
ReflectionPass.IgnoreControl(UnderwaterRocks);
// Allow only sky and terrain
BackfacePass.AllowControl(SkyDome);
BackfacePass.AllowControl(Terrain);
// Fixed size
BlurPass.OverwriteViewportSize := True;
BlurPass.ViewportWidth := 512;
BlurPass.ViewportHeight := 512;
// Scaled fixed size - ScaleViewportSize needs OverwriteViewportSize
BlurPass.ScaleViewportSize := True;
BlurPass.ViewportScale := 0.5; // Results in 256x256
// Without OverwriteViewportSize the pass follows the viewport resolution,
// so lower it there for the main pass and all such passes together
Viewport.RenderScale := 0.5;
// Blur pipeline: Horizontal → Vertical → Output
BlurHorizontal.SetInputPass(SourcePass);
BlurVertical.SetInputPass(BlurHorizontal);
OutputPass.SetInputPass(BlurVertical);
| Event | Type | Description |
|---|---|---|
| OnBeginSetup | TRenderPassEvent | Callback event when setting up render pass on each cycle was started. |
| OnEndSetup | TRenderPassEvent | Callback event when setting up render pass on each cycle was done. |
| OnBeginRender | TRenderPassEvent | Callback event when rendering is about to begin for each iteration. |
| OnEndRender | TRenderPassEvent | Callback event when rendering is finished for each iteration. |
To create a custom render pass, inherit from TGorillaRenderPassController and override required methods:
type
TMyCustomRenderPass = class(TGorillaRenderPassController)
protected
// Create material source for RectToFBO method
function CreateMaterialSource(): TGorillaRenderPassMaterialSource; override;
// Optionally override matrix computation
function GetViewMatrix(const AContext: TContext3D): TMatrix3D; override;
function GetProjectionMatrix(const AContext: TContext3D): TMatrix3D; override;
// Custom configuration
procedure DoConfigure(); override;
public
constructor Create(AOwner: TComponent; const AId: String); override;
end;
implementation
constructor TMyCustomRenderPass.Create(AOwner: TComponent; const AId: String);
begin
inherited;
// Custom initialization
end;
procedure TMyCustomRenderPass.DoConfigure();
begin
inherited;
FType := TRenderPassType.Pre;
FMethod := TRenderPassMethod.RenderListToFBO;
FRenderProc := TRenderPassRenderingProc.DefaultRendering;
end;
function TMyCustomRenderPass.CreateMaterialSource(): TGorillaRenderPassMaterialSource;
begin
Result := TMyCustomMaterialSource.Create(Self);
end;
function TMyCustomRenderPass.GetViewMatrix(const AContext: TContext3D): TMatrix3D;
begin
// Custom view matrix computation
Result := ComputeCustomViewMatrix();
end;
Unique IDs Required: Each render pass must have a unique Id. Duplicate IDs overwrite existing passes.
Viewport Assignment: Pass must have Viewport assigned before use. Renderer is created automatically on assignment.
Control Filtering Order: If AllowedControls is not empty, it acts as a whitelist. Only controls in AllowedControls render, then IgnoredControls is checked.
Automatic Children: Calling IgnoreControl() or AllowControl() automatically includes sub-meshes and child components.
Matrix Caching: View and projection matrices are cached and recalculated only when needed. Set FRecalcViewMatrix/FRecalcProjMatrix when custom changes require recomputation.
Abstract Class: TGorillaRenderPassController is abstract. Use specialized subclasses like TGorillaRenderPassReflection or create your own.
Renderer Ownership: Pass owns its renderer (FOwnsRenderer). Don't manually free renderer.
FBO Auto-Creation: FBO and textures are created automatically based on ViewportSize.
Event Timing: OnBeginSetup/OnEndSetup called once per frame. OnBeginRender/OnEndRender called per iteration.
Skip Persistence: SkipRendering() affects only the current frame. Call each frame to continuously skip.
The Gorilla.Controller.Input.Character unit provides the abstract base class TGorillaCharacterController for all character controllers in Gorilla3D. It manages character states (idle, moving, jumping, crouching, crawling, boosting), default hotkey registration, trigger point integration, and audio manager linking. This class is not used directly — use TGorillaFirstPersonController or TGorillaThirdPersonController instead.
Record for hotkey registration.
TGorillaCharacterControllerHotKeyCode = record
Name: String;
Code: Integer;
Device: TGorillaInputDeviceType;
end;
TOnCharacterControllerHotKeyTriggered = procedure(ASender: TObject;
const AKind: TGorillaCharacterControllerHotKey;
const AHotKey: TGorillaHotKeyItem;
const AStates: TGorillaCharacterControllerStates;
const AMode: TGorillaInputMode) of object;
TOnCharacterControllerMoveEvent = procedure(ASender: TObject;
AKind: TGorillaCharacterControllerHotKey;
ADir: TPoint3D;
ACurrentSpeed: Single) of object;
TOnCharacterControllerRotateEvent = procedure(ASender: TObject;
ACurrentRotation: TQuaternion3D;
ANewRotation: TQuaternion3D;
ADelta: TPointF) of object;
TOnCharacterControllerEvent = procedure(ASender: TObject;
AState: TGorillaCharacterControllerState;
AMode: TGorillaInputMode) of object;
TOnCharacterControllerTriggerPoint = procedure(ASender: TObject;
AManager: TGorillaTriggerPointManager;
APt: TGorillaTriggerPoint;
ADist: Single) of object;
Abstract base class for character controllers. Inherits from TDummy.
Inheritance: TDummy → TGorillaCharacterController
| Property | Type | Access | Description |
|---|---|---|---|
| States | TGorillaCharacterControllerStates | Read/Write | Current set of character states (idle, moving, crouching, etc.) |
| HotKey[Index] | TGorillaHotKeyItem | Read | Access registered hotkey by enum index |
| JumpingStartPos | TPoint3D | Read | Starting position for jump animation |
| CrouchingStartPos | TPoint3D | Read | Starting position for crouch animation |
| CrawlingStartPos | TPoint3D | Read | Starting position for crawl animation |
| JumpingEndPos | TPoint3D | Read | Destination position for jump animation |
| CrouchingEndPos | TPoint3D | Read | Destination position for crouch animation |
| CrawlingEndPos | TPoint3D | Read | Destination position for crawl animation |
| CurrentJumpingTime | Single | Read | Current time in jump animation |
| CurrentCrouchingTime | Single | Read | Current time in crouch animation |
| CurrentCrawlingTime | Single | Read | Current time in crawl animation |
| AdjustJumpingPosition | Boolean | Read/Write | Auto-adjust position during jumping |
| AdjustCrouchingPosition | Boolean | Read/Write | Auto-adjust position during crouching |
| AdjustCrawlingPosition | Boolean | Read/Write | Auto-adjust position during crawling |
| Property | Type | Description |
|---|---|---|
| Camera | TCamera | Linked camera for perspective control |
| InputController | TGorillaInputController | Linked input controller for keyboard/mouse/gamepad events |
| TriggerPoints | TGorillaTriggerPointManager | Linked trigger point manager |
| AudioManagerController | TGorillaAudioManagerController | Linked audio manager for automatic sound playback |
| LockXAxis | Boolean | Lock movement on X axis |
| LockYAxis | Boolean | Lock movement on Y axis |
| LockZAxis | Boolean | Lock movement on Z axis |
| MoveSideways | Boolean | If true, left/right keys strafe; if false, they rotate |
| RotateOnSideways | Boolean | Rotate controller on sideway movement |
| CameraYAngleLimit | TPointF | Min/max horizontal rotation in degrees. Default: (-180, 180) |
| CameraXAngleLimit | TPointF | Min/max vertical rotation in degrees. Default: (-45, 45) |
| Speed | Single | Base movement speed. Default: 0.25 |
| SidewayRotationSpeed | Single | Rotation speed on sideway keys. Default: 1.0 |
| CrouchingSpeedReduction | Single | Speed factor when crouching (0.0–1.0). Default: 0.75 |
| CrawlingSpeedReduction | Single | Speed factor when crawling (0.0–1.0). Default: 0.9 |
| RunningSpeedBoost | Single | Speed factor when boosting (1–1000). Default: 2.0 |
| CharacterHeight | Single | Character height on Y axis |
| CurrentCharacterHeight | Single | Current height during crouch/crawl transitions |
| JumpingHeight | Single | Jump height. Default: 2.0 |
| CrouchingHeight | Single | Crouch depth. Default: 0.5 |
| CrawlingHeight | Single | Crawl depth. Default: 0.25 |
| JumpingAnimationTime | Single | Jump animation duration in seconds |
| CrouchingAnimationTime | Single | Crouch transition duration in seconds |
| CrawlingAnimationTime | Single | Crawl transition duration in seconds |
| Event | Type | Description |
|---|---|---|
| OnIdle | TOnCharacterControllerEvent | Fired on idle state |
| OnMove | TOnCharacterControllerMoveEvent | Fired on movement (direction + speed) |
| OnRotate | TOnCharacterControllerRotateEvent | Fired on rotation |
| OnBoost | TOnCharacterControllerEvent | Fired on boost toggle |
| OnCrouch | TOnCharacterControllerEvent | Fired on crouch toggle |
| OnCrawl | TOnCharacterControllerEvent | Fired on crawl toggle |
| OnJump | TOnCharacterControllerEvent | Fired on jump |
| OnAim | TOnCharacterControllerEvent | Fired on aim toggle |
| OnPush | TOnCharacterControllerEvent | Fired on push action |
| OnPull | TOnCharacterControllerEvent | Fired on pull action |
| OnCustomAction | TOnCharacterControllerHotKeyTriggered | Fired by custom hotkeys |
| OnClick | TOnCharacterControllerHotKeyTriggered | Fired by mouse clicks |
| OnStart | TOnCharacterControllerEvent | Fired on start button |
| OnMode | TOnCharacterControllerEvent | Fired on mode button |
| OnBack | TOnCharacterControllerEvent | Fired on back button |
| OnNavigate | TOnCharacterControllerHotKeyTriggered | Fired on menu navigation |
| OnHotKey | TOnCharacterControllerHotKeyTriggered | General hotkey trigger |
| OnTriggerPoint | TOnCharacterControllerTriggerPoint | Fired when trigger point detected |
| OnChangeSize | TNotifyEvent | Fired when character height changes |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
function GetCurrentSpeed(): Single; virtual; abstract;
Returns the current effective movement speed (accounting for crouch/boost modifiers).
function GetHotKeyType(AItem: TGorillaHotKeyItem): TGorillaCharacterControllerHotKey; virtual;
Returns the hotkey enum value for a given hotkey item.
class function GetStatesString(AStates: TGorillaCharacterControllerStates): String;
Converts a states set to a string representation like "[fpIdle,fpCrouching]".
class function GetStatesValue(AValue: String): TGorillaCharacterControllerStates;
Parses a states string back to a set value.
procedure AddState(AState: TGorillaCharacterControllerState); virtual;
Adds a state and resolves conflicting states (e.g., idle vs moving).
procedure RemoveState(AState: TGorillaCharacterControllerState); virtual;
Removes a state and resolves conflicts.
procedure Push(AEnabled: Boolean); virtual;
Manually activate or deactivate pushing state.
procedure Pull(AEnabled: Boolean); virtual;
Manually activate or deactivate pulling state.
procedure AbortJumping(); virtual; abstract;
Cancel the current jump animation.
The Gorilla.Controller.Input.FirstPerson unit provides TGorillaFirstPersonController, a concrete implementation of the character controller for ego-perspective (first-person) 3D navigation. It handles mouse look, keyboard movement (WASD), gamepad input, jump/crouch/crawl animations, and drag-mode interactions.
First-person camera and character controller with mouse look, keyboard movement, and gamepad support.
Inheritance: TDummy → TGorillaCharacterController → TGorillaFirstPersonController
Platforms: All Gorilla3D supported platforms
All properties from TGorillaCharacterController are published (Camera, InputController, TriggerPoints, AudioManagerController, Speed, LockXAxis/Y/Z, MoveSideways, CameraXAngleLimit, CameraYAngleLimit, CrouchingSpeedReduction, CrawlingSpeedReduction, RunningSpeedBoost, JumpingHeight, CrouchingHeight, CrawlingHeight, JumpingAnimationTime, CrouchingAnimationTime, CrawlingAnimationTime, and all events).
| Property | Type | Default | Description |
|---|---|---|---|
| MouseControllerSpeed | Single | 0.075 | Mouse look sensitivity. Lower values = slower rotation. |
| GamePadThumbstickSpeed | Single | 0.5 | Gamepad right thumbstick sensitivity for rotation. |
| ShowCursor | Boolean | True | Show or hide the mouse cursor during controller operation. |
| RotationDragMode | Boolean | False | If true, camera rotation only applies while a mouse button is held. |
| RotationDragModeButton | TGorillaMouseState | — | Which mouse button activates rotation drag mode (LButtonDown, MButtonDown, RButtonDown). |
| UseCameraDirection | Boolean | True | If true, movement direction follows the camera; if false, follows the controller orientation. |
| MovementDragMode | Boolean | False | If true, movement by mouse only applies while a mouse button is held. |
| MovementDragModeButton | TGorillaMouseState | — | Which mouse button activates movement drag mode. |
| InvertMovementDragModeXAxis | Boolean | False | Invert horizontal axis when in movement drag mode. |
| InvertMovementDragModeYAxis | Boolean | False | Invert vertical axis when in movement drag mode. |
| RotateAroundCenter | Boolean | False | Rotate the controller component itself instead of free camera rotation. |
| UseDefaultBehaviour | Boolean | True | Enable or disable built-in hotkey behavior. |
| UseDefaultMovement | Boolean | True | Enable or disable built-in WASD/gamepad movement. Camera rotation is unaffected. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
function GetCurrentSpeed(): Single; override;
Returns the current effective speed accounting for crouch, crawl, and boost modifiers.
procedure AbortJumping(); override;
Cancels the current jump animation immediately.
The Gorilla.Controller.Input.ThirdPerson unit provides TGorillaThirdPersonController, which extends the first-person controller to implement an orbital (third-person) camera. The camera is placed at a configurable distance from the character and orbits around it using mouse movement. The scroll wheel adjusts camera distance.
Third-person orbital camera controller. The camera is positioned behind the character and rotates around it.
Inheritance: TDummy → TGorillaCharacterController → TGorillaFirstPersonController → TGorillaThirdPersonController
Platforms: All Gorilla3D supported platforms
When created, the third-person controller changes these defaults from the first-person controller:
| Property | FirstPerson Default | ThirdPerson Default |
|---|---|---|
UseCameraDirection |
True | False |
RotateOnSideways |
False | True |
MoveSideways |
True | False |
CameraYAngleLimit |
(-180, 180) | (-180, 180) |
CameraXAngleLimit |
(-45, 45) | (-45, 45) |
The camera is automatically parented to the controller and positioned at (0, -Height*4, -10).
| Property | Type | Default | Description |
|---|---|---|---|
| MouseWheelSpeed | Single | 1.0 | Speed of mouse wheel zoom. Range: 0–10. |
| CameraZLimit | TPointF | (-1, -25) | Camera distance limits. X = closest distance, Y = farthest distance (as negative Z values). |
All properties from TGorillaFirstPersonController and TGorillaCharacterController are also available.
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
Orbit Mode (UseCameraDirection = False, default):
Camera.Target := Self)CameraZLimitCamera Direction Mode (UseCameraDirection = True):
CameraZLimitThe Gorilla.DefTypes unit provides fundamental definition types used throughout Gorilla3D for storing and managing 3D model data. It defines the internal structure for models, meshes, materials, textures, animations, and all related components. These definition classes serve as data containers that can be serialized to/from JSON or binary formats.
The definition types implement a hierarchical structure for 3D model data:
TModelDef (Root)
├─ Children (Meshes, VertexGroups, Lights, Cameras, Segments, Groups)
├─ Materials (TMaterialDef)
├─ Lights (TLightDef)
├─ Cameras (TCameraDef)
├─ Armatures (TArmatureDef)
│ └─ Joints (TJointDef hierarchy)
├─ Controllers (TControllerDef)
│ └─ Skin (TSkinDef with joint references)
└─ Animations (TAnimationDef)
└─ Stages (TAnimationStageDef)
└─ Interpolators (TInterpolatorDef)
GORILLA_POLYGON_MAXSIZE = 16; // Maximum vertices per polygon
GORILLA_ARRAY_TEXTURE_MAX = 32; // Maximum texture layers
GORILLA_ARRAY_COLOR_MAX = 4; // Maximum color sets
GORILLA_MAX_JOINTS_PER_VERTEX = 24; // Maximum joint influences per vertex
GORILLA_CACHE_CAPACITY = High(UInt16); // Cache capacity (65535)
// Animation cache frame rates
GORILLA_ANIMATION_CACHE_FRAMERATE_24 = 24;
GORILLA_ANIMATION_CACHE_FRAMERATE_30 = 30;
GORILLA_ANIMATION_CACHE_FRAMERATE_60 = 60;
// Platform-specific defaults
{$IFDEF MSWINDOWS}
GORILLA_ANIMATION_CACHE_FRAMERATE = 60;
GORILLA_INDEX_FORMAT = TIndexFormat.UInt32;
{$ENDIF}
{$IFDEF ANDROID}
GORILLA_ANIMATION_CACHE_FRAMERATE = 24;
GORILLA_INDEX_FORMAT = TIndexFormat.UInt16;
{$ENDIF}
// ... other platforms
GORILLA_SEGMENT_ID_FORMAT = '%s_Seg'; // Segment ID format string
Base class for all definition types.
| Property | Type | Description |
|---|---|---|
| Id | String | Unique identifier for this definition. |
constructor Create(); virtual;
destructor Destroy(); override;
function Clone(AOwner: TModelDef): TCustomDef; virtual;
function GetSize(): Int64; virtual;
Returns memory size in bytes.
function GetAssetsPackage(): TObject; virtual;
Returns associated assets package.
function ToJSON(): TJSONObject; virtual;
procedure FromJSON(const AModel: TModelDef; const AValue: TJSONObject); virtual;
function LateResolveFromJSON(const AModel: TModelDef;
const AValue: TJSONObject): Boolean; virtual;
JSON serialization methods.
Root definition for complete 3D models. Contains all sub-components including meshes, materials, animations, lights, cameras, and armatures.
Inheritance: TCustomDef → TTransformDef → TModelDef
| Property | Type | Description |
|---|---|---|
| Children | TObjectList | List of child definitions (meshes, groups, etc.). |
| Materials | TObjectList<TMaterialDef> | List of material definitions. |
| Lights | TObjectList<TLightDef> | List of light definitions. |
| Cameras | TObjectList<TCameraDef> | List of camera definitions. |
| Armatures | TObjectList<TArmatureDef> | List of armature definitions. |
| Controllers | TObjectList<TControllerDef> | List of controller definitions for skinning. |
| Animations | TObjectList<TAnimationDef> | List of animation definitions. |
| MetaData | TModelMetaDef | Model metadata (title, author, license, etc.). |
| Package | TObject | Reference to assets package if stored in one. |
Mesh geometry definition containing vertices, indices, and material references.
Inheritance: TCustomDef → TTransformDef → TCustomMeshDef → TMeshDef
| Property | Type | Description |
|---|---|---|
| Vertices | TArray<TVertexData> | Array of vertex data. |
| Indices | TArray<TIndexType> | Array of triangle indices. |
| Material | TMaterialDef | Reference to material definition. |
| IsStatic | Boolean | Indicates if mesh is static (prebuffered to GPU). |
| BoundingBox | TBoundingBox | Mesh bounding box. |
| Children | TObjectList | List of child meshes. |
One animation clip of a model: its stages (one per animated joint or property), its timing and its baked frames.
Inheritance: TCustomDef → TAnimationDef
| Property | Type | Description |
|---|---|---|
| Model | TModelDef | Owning model definition (read-only). |
| Stages | TAnimationStageDefList | Animated joints / properties of this clip (read-only). |
| FrameRate | Integer | Frames per second used for baking. |
| FrameCount | Integer | Number of baked frames (read-only). |
| Duration | Double | Clip length in seconds (read-only). |
| IsCached | Boolean | True while the clip has baked frames, i.e. BufferingState is not None (read-only). |
| IsCacheable | Boolean | True if caching flags were set for this clip (read-only). |
| CachingFlags | TAnimationCachingFlags | Flags the clip was baked with (read-only). |
| BufferingState | TAnimationBufferingState | None, Started, Caching, Cached or Ready (read-only). |
| InPlace | Boolean | Removes the horizontal root motion from the clip. Assigning it discards the baked frames without rebuilding them - see SetInPlace below. |
| RootMotionJoint | String | Name of the joint carrying the root motion. Empty means auto-detect: the animated joint whose horizontal translation actually varies. |
| HasRootMotion | Boolean | True if the clip carries a measurable horizontal root motion (read-only). |
procedure SetInPlace(const AValue: Boolean; const ARebuildCache: Boolean;
const AModel: TComponent = nil); overload;
Sets InPlace and, with ARebuildCache, bakes the clip again right away, so a clip that
was cached keeps being drawn animated instead of falling back to its bind pose.
Parameters:
AValue - Take the horizontal root motion out (True) or put it back (False)ARebuildCache - Bake the clip again afterwards. Not the default, because it costs what the initial caching cost. Has no effect when the clip is not cacheable (CachingFlags = []).AModel - TGorillaModel the frames are baked from. Leave it nil and a temporary instance is built from the definition; the frames are stored per mesh definition either way. TGorillaAnimation.SetInPlace passes its own model and saves that instance.function RootMotionAt(const ANormTime: Single): TPointF;
function RootMotionTotal(): TPointF;
function RootMotionPeak(): Single;
The motion InPlace took out - at a normalised position 0..1, in total from first to
last key, and as the largest distance reached anywhere. Values are relative to the first
frame and in model units; X is the world X component, Y the world Z one.
procedure Cache(const ACache: TObject {TAnimationCaching});
Bakes this clip. Normally driven by TModelDef.CacheAnimations, which the model loaders
call when caching flags are passed.
Material definition with textures and properties.
Inheritance: TCustomDef → TMaterialDef
| Property | Type | Description |
|---|---|---|
| Textures | TObjectList<TTextureDef> | List of texture definitions. |
| Diffuse | TAlphaColorF | Diffuse color. |
| Ambient | TAlphaColorF | Ambient color. |
| Emissive | TAlphaColorF | Emissive color. |
| Specular | TAlphaColorF | Specular color. |
| Shininess | Single | Shininess factor. |
| Extensions | TExtensionDefList | List of extensions (PBR, etc.). |
Configuration structure for loading models with fine-grained control.
| Field | Type | Description |
|---|---|---|
| FileInfo | TGorillaFileInfo | File information (path, extension, URL, etc.). |
| Package | TObject of type TGorillaAssetsPackage |
Optional assets package of type. |
| Asset | TObject of type TGorillaModelAsset |
Optional model asset reference of type. |
| DisjointModel | Boolean | Load model with disjointed hierarchy. |
| ImportLights | Boolean | Import embedded lights. |
| ImportCameras | Boolean | Import embedded cameras. |
| ImportAnimations | Boolean | Import animations. |
| AdditionalAnimations | TArray<String> | Absolute paths to additional animation files. |
| Caching | TAnimationCachingFlags | Animation caching configuration. |
| VertexDataFlags | TVertexDataFlags | Vertex data processing flags. |
| OnStatus | TGorillaLoadingStatus = procedure(ALoader : TObject) of object; |
Status callback procedure. |
| ExtractDirectory | String | Directory for extracting downloads. |
| BitmapCache | TGorillaBitmapCache | Bitmap cache for textures. |
| TextureLimits | TPoint | Combined texture size limits. TPoint.Zero (the default) means no limit. Reduces the RESOLUTION of imported textures - for reducing their memory without losing resolution see GPU block compression. |
| Storage | TArray<TGorillaLoadStorage> | Storage for embedded file formats. |
constructor Create(APathOrUID: String; APackage: TObject = nil;
AAsset: TObject = nil); overload;
constructor Create(APathOrUID: String; AExt: String;
APackage: TObject = nil; AAsset: TObject = nil); overload;
constructor Create(APathOrUID: String; ACaching: TAnimationCachingFlags;
APackage: TObject = nil; AAsset: TObject = nil); overload;
function GetExtension(): String;
procedure SetExtension(const AValue: String);
procedure SetPathOrUID(const AValue: String);
function AddAnimation(const AFilename: String): Integer;
function AddStorage(const AName: String; const AStream: TStream): Integer;
function GetStorage(const AName: String): TStream;
procedure CopyTo(var ADest: TGorillaLoadOptions);
procedure Clear();
var
Options: TGorillaLoadOptions;
begin
Options := TGorillaLoadOptions.Create('model.fbx', [], nil, nil);
// Configure loading
Options.ImportLights := True;
Options.ImportCameras := True;
Options.ImportAnimations := True;
Options.Caching := [TAnimationCachingFlag.VertexPosition];
Options.TextureLimits := TPoint.Create(2048, 2048);
// Add additional animations
Options.AddAnimation('walk.fbx');
Options.AddAnimation('run.fbx');
// Load model
MyModel.LoadFromFile(Options);
end;
File information record for model loading.
| Field | Type | Description |
|---|---|---|
| PathOrUID | String | File path or unique identifier. |
| StrictFilename | Boolean | Require exact filename match in packages. |
| Ext | String | File extension for format detection. |
| OpenFormat | TGorillaFileOpenFormat | Local file or download mode. |
| OAuthMode | TGorillaOAuthMode | OAuth authentication mode (Sketchfab). |
| URL | String | Download URL. |
| Username | String | Login username for third-party systems. |
| Password | String | Login password. |
| ClientId | String | OAuth client ID. |
| ClientSecret | String | OAuth client secret. |
| AuthorizationEndpoint | String | Custom authorization endpoint URL. |
| AccessTokenEndpoint | String | Custom access token endpoint URL. |
| RedirectionEndpoint | String | Custom redirection endpoint URL. |
procedure CopyTo(var ADest: TGorillaFileInfo);
procedure Clear();
Vertex data record containing all vertex attributes.
| Field | Type | Description |
|---|---|---|
| Position | TPoint3D | Vertex position (XYZ coordinates). |
| Normal | TPoint3D | Normal vector. |
| Binormal | TPoint3D | Binormal vector (for normal mapping). |
| Tangent | TPoint3D | Tangent vector (for normal mapping). |
| TexCoords | TPointFDynArray | Texture coordinates (multiple layers). |
| Colors | TColorDynArray | Vertex colors (multiple sets). |
| SmoothGroup | Integer | Smooth group ID. |
| Flags | TVertexDataFlags | Processing flags. |
class function Create(): TVertexData; static;
procedure Clear();
function ToJSON(): TJSONObject;
procedure FromJSON(const AValue: TJSONObject);
function GetHash(): UInt64;
function Equals(const V: TVertexData): Boolean;
Ray casting intersection result.
| Field | Type | Description |
|---|---|---|
| T | Single | Distance along ray to intersection. |
| Normal | TPoint3D | Surface normal at intersection. |
| Hit | Boolean | True if intersection occurred. |
| Intersection | TPoint3D | Intersection point in 3D space. |
| Instance | TObject | Intersected object reference. |
| Triangle | Array[0..2] of TPoint3D | Triangle vertex positions. |
Animation caching configuration flags.
| Flag | Description |
|---|---|
| AllAttributes | Cache all vertex attributes (high memory, maximum speed). |
| Compressed | Compress cached data (lower memory, slower). |
| VertexPosition | Cache vertex positions only (recommended: balanced). |
Usage:
// Recommended: vertex positions only
[TAnimationCachingFlag.VertexPosition]
// Maximum performance
[TAnimationCachingFlag.AllAttributes]
// Compressed for large animations
[TAnimationCachingFlag.VertexPosition, TAnimationCachingFlag.Compressed]
Vertex data processing flags.
| Flag | Description |
|---|---|
| CalcNormals | Calculate normals. |
| CalcTangents | Calculate tangents and binormals. |
| CalcTexCoords | Calculate texture coordinates. |
| CalcSmoothNormals | Calculate smooth normals (averaged across faces). |
Texture channel types for materials.
| Channel | Description |
|---|---|
| Diffuse | Diffuse/albedo map. |
| Ambient | Ambient occlusion map. |
| Emissive | Emissive/glow map. |
| Specular | Specular map. |
| Normal | Normal map (bump mapping). |
| Opacity | Opacity/transparency map. |
| Reflection | Reflection map. |
| Refraction | Refraction map. |
| Environment | Environment map. |
| Lightmap | Lightmap. |
| Displacement | Displacement map. |
| Metalness | Metalness map (PBR). |
| Roughness | Roughness map (PBR). |
| AO | Ambient occlusion (PBR). |
| HeightMap | Height map. |
| POM | Parallax occlusion map. |
| Depth | Depth map. |
| UserSpecific | Custom user channel. |
File opening mode.
| Value | Description |
|---|---|
| fofLocal | Load from local filesystem (default). |
| fofDownload | Download format (Sketchfab, etc.). |
Vertex winding order for triangles.
| Value | Description |
|---|---|
| CW | Clockwise vertex order [0, 2, 1]. |
| CCW | Counter-clockwise vertex order [1, 2, 0]. |
Face culling mode.
| Value | Description |
|---|---|
| FrontFace | Render front faces only. |
| BackFace | Render back faces only. |
| TwoFace | Render both sides (no culling). |
Collection for caching texture bitmaps at design-time.
Inheritance: TOwnedCollection → TGorillaBitmapCache
function FindBitmap(AFilename: String): TGorillaBitmapCacheEntry;
Finds cached bitmap by filename.
Individual cached bitmap entry.
Inheritance: TCollectionItem → TGorillaBitmapCacheEntry
| Property | Type | Description |
|---|---|---|
| Filename | String | Original filename of bitmap. |
| Bitmap | TBitmap | Bitmap data (embedded or referenced). |
Memory-efficient list for caching with fixed-size growth steps.
| Property | Type | Description |
|---|---|---|
| Count | Integer | Number of items. |
| Steps | Integer | Growth step size. |
| Items[Index] | T | Access items by index. |
| List | TArray<T> | Internal array. |
function Add(AValue: T): Integer;
procedure AddRange(AArray: TArray<T>);
procedure Clear();
function ToArray(): TArray<T>;
function GetMemorySize(): Int64;
Dictionary for storing extended properties.
Inheritance: TDictionary<String, TValue> → TProperties
function GetSize(): Int64;
procedure ToJSON(AJSON: TJSONObject);
procedure FromJSON(const AValue: TJSONObject);
// Dynamic arrays
TFloatDynArray = TArray<Single>;
TPoint3DDynArray = TArray<TPoint3D>;
TVector3DDynArray = TArray<TVector3D>;
TQuaternion3DDynArray = TArray<TQuaternion3D>;
TPointFDynArray = TArray<TPointF>;
TColorDynArray = TArray<TAlphaColorF>;
TMatrix3DDynArray = TArray<TMatrix3D>;
// Lists
TVertexDataList = class(TList<TVertexData>);
TIndexDataList = class(TList<TIndexType>);
TFaceIndexList = class(TList<TFaceIndex>);
// Maps
TVertexDataMap = TDictionary<TIndexType, TVertexData>;
var
Options: TGorillaLoadOptions;
begin
// Basic options
Options := TGorillaLoadOptions.Create('character.dae', nil, nil);
// With caching
Options := TGorillaLoadOptions.Create('character.dae',
[TAnimationCachingFlag.VertexPosition], nil, nil);
// Advanced configuration
Options := TGorillaLoadOptions.Create('scene.fbx', [], MyPackage, nil);
Options.ImportLights := True;
Options.ImportCameras := True;
Options.TextureLimits := TPoint.Create(512, 512);
Options.AddAnimation('walk.fbx');
Options.AddAnimation('run.fbx');
end;
var
Vertex: TVertexData;
begin
Vertex := TVertexData.Create();
Vertex.Position := Point3D(1, 2, 3);
Vertex.Normal := Point3D(0, 1, 0);
// Add texture coordinates
SetLength(Vertex.TexCoords, 1);
Vertex.TexCoords[0] := PointF(0.5, 0.5);
// Add vertex color
SetLength(Vertex.Colors, 1);
Vertex.Colors[0] := TAlphaColorF.Create(1, 1, 1, 1);
end;
var
Cache: TGorillaBitmapCache;
Entry: TGorillaBitmapCacheEntry;
begin
Cache := TGorillaBitmapCache.Create(Self, TGorillaBitmapCacheEntry);
// Find cached bitmap
Entry := Cache.FindBitmap('texture.png');
if Assigned(Entry) then
ShowMessage('Found: ' + Entry.Filename);
end;
Memory Management: Definition objects are typically owned by TGorillaAssetsManager when using packages. Standalone models own their definitions. So if a TModelDef/TMeshDef is destroyed all of its sub-meshes gets destroyed too.
Serialization: All definition types support JSON serialization via ToJSON/FromJSON methods. Binary serialization uses BSON format (G3D files).
A TSkinDef that drives several meshes stores its additional targets (TargetMeshes), and each TJointRefDef stores its vertex indices and weights per mesh (MeshWeights, keyed by mesh id). TSkinDef.PrepareForMesh() selects the set of a mesh after loading. Format-specific skins (e.g. glTF) compute the sets from their source data and complete them in PrepareAllMeshWeights() before serializing. Note that PrepareForMesh() also switches Target (= Controller.Target), so callers have to restore it.
Caching: Animation caching significantly improves playback performance. Use VertexPosition flag for best balance.
Index Format: Platform-dependent (UInt32 on desktop, UInt16 on Android) for memory optimization.
Texture Limits: Essential for mobile platforms to prevent memory exhaustion from high-resolution textures.
Extensions: Material extensions (PBR, custom properties) stored in TExtensionDefList for format compatibility.
Gorilla.Loader Unit — model loading infrastructure (no reference page yet)The Gorilla.Light unit provides an extended light source component for Gorilla3D. TGorillaLight enhances FireMonkey's TLight with additional properties used by Gorilla3D shaders, including ambient and specular colors, attenuation control, intensity, and light scattering parameters for global illumination.
Extended light source component with additional properties for Gorilla3D shaders.
Inheritance: TLight → TGorillaLight
Platforms: All Gorilla3D supported platforms
| Property | Type | Access | Description |
|---|---|---|---|
| Def | TLightDef | Read | Access to the light definition object containing light parameters. |
| LightDescriptionEx | TGorillaShaderLight | Read | Extended light description for shader use, including all Gorilla3D-specific parameters. |
| Property | Type | Default | Description |
|---|---|---|---|
| Color | TAlphaColor | - | Diffuse color of the light (inherited from TLight). |
| Ambient | TAlphaColorF | (0,0,0,1) | Ambient component of light color. Affects overall scene brightness. |
| Specular | TAlphaColorF | (1,1,1,1) | Specular component of light color. Affects shiny highlights on surfaces. |
| Property | Type | Range | Default | Description |
|---|---|---|---|---|
| Intensity | Single | 0.0-10.0 | 1.0 | Light intensity controlling the range and strength of light application. Clamped to 0-10. |
Attenuation controls how light intensity decreases with distance using the formula:
Attenuation = 1 / (Constant + Linear * Distance + Quadratic * Distance²)
| Property | Type | Default | Description |
|---|---|---|---|
| ConstantAttenuation | Single | 1.0 | Constant factor in attenuation calculation. Always applied regardless of distance. |
| LinearAttenuation | Single | 0.0 | Linear factor in attenuation. Causes proportional falloff with distance. |
| QuadraticAttenuation | Single | 0.0 | Quadratic factor in attenuation. Causes rapid falloff at distance. |
Light scattering parameters for volumetric lighting effects in global illumination rendering. Each light source can have individual scattering settings.
| Property | Type | Range | Default | Description |
|---|---|---|---|---|
| ScatteringIntensity | Single | 0.0-10.0 | 0.1 | How intensely light scattering is mixed into the final image. |
| ScatteringExposure | Single | 0.0-1.0 | 0.0034 | Ray exposure parameter controlling visibility of light rays. |
| ScatteringDecay | Single | 0.0-2.0 | 1.0 | How quickly light rays decay along their path. |
| ScatteringDensity | Single | 0.0-10.0 | 0.84 | Density of the scattering medium. Higher = more visible rays. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
Standard lifecycle methods.
procedure LoadFromDefinition(const ADef: TLightDef); virtual;
Load light settings from a light definition object, including:
From FireMonkey's TLight, accessible via the LightType property:
Common attenuation configurations for different light ranges:
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.0;
Light.QuadraticAttenuation := 0.0;
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.7;
Light.QuadraticAttenuation := 1.8;
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.35;
Light.QuadraticAttenuation := 0.44;
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.22;
Light.QuadraticAttenuation := 0.20;
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.07;
Light.QuadraticAttenuation := 0.017;
Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.045;
Light.QuadraticAttenuation := 0.0075;
Ambient vs Diffuse:
Color) - Direct light on surfacesAmbient) - Indirect/environmental lightSpecular) - Shiny highlightsIntensity: Use intensity to control light strength without changing color. More intuitive than adjusting color brightness.
Attenuation:
Light Scattering:
Performance: Each additional light increases rendering cost. Use the minimum number of lights necessary and disable lights when not visible.
Gorilla3D Materials Required: Advanced light properties only affect Gorilla3D default materials, not standard FMX materials.
The Gorilla.Material.Default unit provides the core material system for Gorilla3D, including the TGorillaDefaultMaterialSource component and related shader infrastructure. This unit implements a node-based shader generation system that automatically creates GLSL shaders based on enabled features and properties.
The material system uses a hierarchical node structure to compose shaders:
TGorillaDefaultMaterialSource
└─ TGorillaDefaultMaterial
├─ TGorillaGLSLVertexShader (Node Builder)
│ └─ Shader Nodes
└─ TGorillaGLSLFragmentShader (Node Builder)
└─ Shader Nodes
Primary material source component providing comprehensive rendering features.
Inheritance: TCustomMaterialSource → TGorillaDefaultMaterialSource
Platforms: All Gorilla3D supported platforms
| Property | Type | Default | Description |
|---|---|---|---|
| Diffuse | TAlphaColorF | - | Base diffuse color (RGB + alpha). |
| Ambient | TAlphaColorF | - | Ambient color contribution. |
| Specular | TAlphaColorF | - | Specular highlight color. |
| Emissive | TAlphaColorF | - | Self-illumination color. |
| Shininess | Single | 32.0 | Specular shininess exponent (higher = sharper highlights). |
| Property | Type | Default | Description |
|---|---|---|---|
| ShadingModel | TGorillaShadingModel | smLambert | Shading algorithm: smLambert, smPhong, smBlinnPhong, smPBR. |
| ShadingIntensity | Single | 1.0 | Intensity of shading applied to diffuse and specular. |
| Brightness | Single | 1.0 | Overall brightness multiplier. |
| UseLighting | Boolean | True | Enable/disable lighting calculations. |
| UseSpecular | Boolean | True | Enable/disable specular highlights. |
| Property | Type | Description |
|---|---|---|
| Texture | TBitmap | Diffuse/albedo texture (texture unit 0). |
| NormalMap | TBitmap | Normal map texture. |
| SpecularMap | TBitmap | Specular map texture. |
| EmissiveMap | TBitmap | Emissive/glow map texture. |
| DisplacementMap | TBitmap | Displacement/height map texture. |
| OpacityMap | TBitmap | Opacity/alpha map texture. |
| EnvironmentMap | TBitmap | Environment cube map texture. |
| Property | Type | Default | Description |
|---|---|---|---|
| UseVertexColor | Boolean | False | Use mesh vertex colors. |
| UseTexturing | Boolean | False | Enable texture mapping. |
| UseTexture0 | Boolean | False | Enable diffuse texture. |
| UseNormalMapping | Boolean | False | Enable normal mapping. |
| UseBumpMapping | Boolean | False | Enable bump mapping (grayscale). |
| UseSpecularMapping | Boolean | False | Enable specular mapping. |
| UseEmissiveColoring | Boolean | False | Enable emissive color. |
| UseEmissiveMapping | Boolean | False | Enable emissive texture. |
| UseDisplacementMapping | Boolean | False | Enable displacement mapping. |
| UseDisplacementTexture | Boolean | False | Enable displacement texture. |
| UseOpacityMapping | Boolean | False | Enable opacity texture. |
| UseParallaxOcclusionMapping | Boolean | False | Enable POM (requires displacement texture). |
| UseDepthMap | Boolean | False | Enable depth mapping. |
| Property | Type | Description |
|---|---|---|
| Texture | TBitmap | PBR albedo/base color texture. |
| PBRMetallicTexture | TBitmap | PBR metallic map (0=dielectric, 1=metal). |
| PBRRoughnessTexture | TBitmap | PBR roughness map (0=smooth, 1=rough). |
| PBRAOTexture | TBitmap | PBR ambient occlusion map. |
| EmissiveTexture / EmissiveMap | TBitmap | PBR emissive map. |
| PBRSpecularTexture | TBitmap | PBR specular map. |
| Property | Type | Default | Description |
|---|---|---|---|
| UsePBRAlbedoTexture | Boolean | False | Enable PBR albedo texture. |
| UsePBRMetallicTexture | Boolean | False | Enable PBR metallic texture. |
| UsePBRRoughnessTexture | Boolean | False | Enable PBR roughness texture. |
| UsePBRAOTexture | Boolean | False | Enable PBR AO texture. |
| UsePBREmissiveTexture | Boolean | False | Enable PBR emissive texture. |
| UsePBRSpecularTexture | Boolean | False | Enable PBR specular texture. |
| Property | Type | Range | Description |
|---|---|---|---|
| MetallicBias | Single | 0.0-1.0 | Metalness value (0=dielectric, 1=metal). |
| RoughnessBias | Single | 0.0-1.0 | Surface roughness (0=smooth, 1=rough). |
| AOBias | Single | 0.0-1.0 | Ambient occlusion intensity. |
| Property | Type | Default | Description |
|---|---|---|---|
| NormalIntensity | Single | 1.0 | Normal/bump intensity multiplier. The value differs between usage for regular normal mapping and parallax occlusion mapping (POM). When using POM the recommended value is 0.1. |
| InverseNormalMapping | Boolean | False | Invert green channel (OpenGL vs DirectX convention). |
| ParallaxLevels | Integer | 64 | POM raytracing steps (4-256, higher = better quality). |
| Property | Type | Default | Description |
|---|---|---|---|
| Shadows | Boolean | False | Enable shadow reception. |
| ShadowMethod | TGorillaShadowMethod | smShadowMapping | Shadow algorithm: smShadowMapping or smVSM. |
| Reflections | Boolean | False | Enable reflection mapping. |
| ReflectionPower | Single | 0.5 | Reflection intensity (0-1). |
| ReflectionPass | TGorillaRenderPassController | - | Link an existing reflection render pass controller. |
| Refractions | Boolean | False | Enable refraction mapping. |
| RefractionPower | Single | 0.8 | Refraction intensity (0-1). |
| RefractionPass | TGorillaRenderPassController | - | Link an existing refraction render pass controller. |
| UseRefractionDepth | Boolean | False | The refraction render pass is able to provide depth information. To use this data instead of a separated DepthPass. |
| DepthMapping | Boolean | False | Enable depth mapping. |
| DepthPass | TGorillaRenderPassController | - | Link an existing depth render pass controller. |
| Environment | Boolean | False | Enable environment mapping. To control reflection and refraction use ReflectionPower and RefractionPower properties. |
| EnvironmentPass | TGorillaRenderPassController | - | Link an existing environment render pass controller. |
| Property | Type | Default | Description |
|---|---|---|---|
| UseAlphaCutoff | Boolean | False | Enable alpha testing (discard fragments). |
| AlphaCutoff | Single | 0.5 | Alpha threshold (0-1). |
| UseFragmentDepthTransparency | Boolean | False | Enable fragment depth rendering for transparency. |
| UseColorClipping | Boolean | False | Enable color-based clipping. |
| ClippingColor | TAlphaColorF | - | Color to discard in fragment shader. |
| Property | Type | Default | Description |
|---|---|---|---|
| Tonemapping | TGorillaTonemapping | tmNone | Tonemapping operator: tmNone, tmReinhard, tmACESFilmic, etc. |
| TonemappingExposure | Single | 1.0 | Exposure adjustment for tonemapping. |
| Property | Type | Description |
|---|---|---|
| Behaviours | TGorillaMaterialBehaviourCollection | Collection of attached material behaviours. |
| Property | Type | Description |
|---|---|---|
| MeasureTime | Boolean | Enable time measurement for animated shaders. |
| StartTime | Double | Initial time value. |
| RenderTime | Double | Current render time. |
| LastTime | Double | Previous frame time. |
| DeltaTime | Double | Time delta between frames (read-only). |
| Property | Type | Description |
|---|---|---|
| ShadowMapPass[Index] | TGorillaRenderPassController | Shadow map render pass (0-7). |
| Inputs | TGorillaInputRenderPassMap | Render pass inputs map. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure BeginChange();
procedure EndChange();
Batch multiple property changes to prevent shader rebuilds.
Example:
Material.BeginChange();
try
Material.Diffuse := NewDiffuse;
Material.Specular := NewSpecular;
Material.Shininess := NewShininess;
finally
Material.EndChange();
end;
function MaterialBehaviourAttached(ABehaviour: TGorillaMaterialBehaviour): Boolean;
Returns True if a specific behaviour is attached to this material source.
Parameters:
ABehaviour - The behaviour component to checkReturns: True if behaviour is attached, False otherwise
Example:
if Material.MaterialBehaviourAttached(WindBehaviour) then
ShowMessage('Wind behaviour is active');
function IndexOfMaterialBehaviour(ABehaviour: TGorillaMaterialBehaviour): Integer;
Returns the numeric index of a behaviour in the collection, or -1 if not found.
Parameters:
ABehaviour - The behaviour component to findReturns: Index (0-based) or -1 if not attached
Example:
var Index := Material.IndexOfMaterialBehaviour(WindBehaviour);
if Index >= 0 then
ShowMessage('Found at index: ' + IntToStr(Index));
procedure AttachMaterialBehaviour(ABehaviour: TGorillaMaterialBehaviour);
Attaches a material behaviour to this material source. If the behaviour is already attached, it will be ignored.
Parameters:
ABehaviour - The behaviour component to attachExample:
WindBehaviour := TGorillaMaterialWindBehaviour.Create(Self);
WindBehaviour.WindPower := 1.5;
Material.AttachMaterialBehaviour(WindBehaviour);
procedure DetachMaterialBehaviour(ABehaviour: TGorillaMaterialBehaviour);
Detaches a material behaviour from this material source. If the behaviour is not found, the method will ignore it.
Parameters:
ABehaviour - The behaviour component to detachExample:
Material.DetachMaterialBehaviour(WindBehaviour);
procedure ClearMaterialsBehaviours();
Detaches all attached material behaviours from this material source.
Example:
Material.ClearMaterialsBehaviours();
Internal material class that performs actual rendering.
Inheritance: TCustomMaterial → TGorillaDefaultMaterial
| Property | Type | Description |
|---|---|---|
| Source | TGorillaDefaultMaterialSource | Parent material source component. |
| ShaderData | TGorillaShaderData | Uniform buffer data structure. |
| Textures | TGorillaTexturePool | Texture management pool. |
| Behaviours | TGorillaMaterialBehaviourCollection | Material behaviours collection. |
procedure DoApply(const Context: TContext3D); override;
Applies material to rendering context. Called automatically during rendering.
procedure DoInitialize(); override;
procedure DoUninitialize(); override;
Initialize/uninitialize material resources.
Packed record containing all uniform data for shaders. Transferred to GPU via uniform buffer objects for maximum performance.
Memory Layout: Carefully aligned for std140 layout (GLSL uniform buffer standard).
| Field | Type | Description |
|---|---|---|
| ModelViewProjectionMatrix | TMatrix3D | Combined MVP matrix. |
| ViewMatrix | TMatrix3D | View/camera matrix. |
| ProjectionMatrix | TMatrix3D | Projection matrix. |
| TimeInfo | TVector3D | X=start time, Y=current time, Z=previous time, W=delta. |
| EyePos | TVector3D | Absolute camera position. |
| ViewDir | TPoint3D | Camera view direction. |
| ShadingModel | FixedInt | Active shading model. |
| Material | TGorillaShaderMaterial | Material properties (colors, etc.). |
| Lights | Array | Light sources (size platform-dependent). |
| LightsCount | FixedInt | Number of active lights. |
| Options | FixedInt | Shader options bitmask. |
| ShadingIntensity | Single | Shading intensity multiplier. |
| Brightness | Single | Brightness multiplier. |
| FogMode | FixedInt | Fog settings bitmask. |
| FogDensity | Single | Fog density. |
| FogStart | Single | Fog start distance. |
| FogEnd | Single | Fog end distance. |
| FogColor | TAlphaColorF | Fog color. |
| FrustumMin/Max | TVector3D | Camera frustum bounds. |
| SceneMin/Max | TVector3D | Scene bounds. |
| BoundaryMin/Max | TVector3D | Boundary bounds. |
| ViewSize | TVector3D | X/Y=viewport size, Z/W=near/far planes. |
| ClippingPlane | TVector3D | Clipping plane equation. |
| PassData | TGorillaShaderPassData | Render pass specific data. |
Data specific to render passes (shadows, reflections, refractions).
| Field | Type | Description |
|---|---|---|
| ShadowMapMatrix | Array[0..7] of TMatrix3D | Shadow projection matrices. |
| ReflectTextureMatrix | TMatrix3D | Reflection texture matrix. |
| RefractTextureMatrix | TMatrix3D | Refraction texture matrix. |
| ReflectionPower | Single | Reflection intensity. |
| RefractionPower | Single | Refraction intensity. |
| TranslucentDistance | Single | Translucent depth distance. |
| NormalIntensity | Single | Normal mapping intensity. |
| ParallaxLevels | FixedInt | POM raytracing levels. |
| PBRMetallic | Single | PBR metallic value. |
| PBRRoughness | Single | PBR roughness value. |
| PBRAO | Single | PBR ambient occlusion value. |
Shading model selection.
| Value | Description |
|---|---|
| smLambert | Lambert diffuse shading (no specular). |
| smPhong | Phong shading with specular highlights. |
| smBlinnPhong | Blinn-Phong shading (optimized Phong). |
| smPBR | Physically-Based Rendering. |
Tonemapping operators for HDR to LDR conversion.
| Value | Description |
|---|---|
| tmNone | No tonemapping. |
| tmExposure | Simple exposure adjustment. |
| tmNarkowicz | ACES Narkowicz approximation. |
| tmHill | ACES Hill operator. |
| tmHillBoost | ACES Hill with exposure boost. |
| tmReinhard | Reinhard operator. |
| tmLumaBasedReinhard | Luminance-based Reinhard. |
| tmWhitePreservingLumaBasedReinhard | White-preserving Reinhard. |
| tmRomBinDaHouse | RomBinDaHouse operator. |
| tmFilmic | Filmic operator. |
| tmUncharted2 | Uncharted 2 operator. |
Shadow mapping techniques.
| Value | Description |
|---|---|
| smShadowMapping | Standard shadow mapping. |
| smVSM | Variance Shadow Mapping. |
GORILLA_MATERIAL_DEFAULT_LIGHTS = Platform-dependent
// Windows/Linux (OpenGL 4.3): 32 lights
// Linux (OpenGL 4.3): 32 lights
// macOS (Metal): 32 lights
// Android (GLES 3.0): 8 lights
// Android (GLES 2.0): 2 lights
// iOS (Metal): 8 lights
var
Material: TGorillaDefaultMaterialSource;
begin
Material := TGorillaDefaultMaterialSource.Create(Self);
Material.ShadingModel := TGorillaShadingModel.smBlinnPhong;
Material.Diffuse := TAlphaColorF.Create(0.7, 0.5, 0.3, 1.0);
Material.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
Material.Shininess := 32.0;
Material.UseTexture0 := False;
Mesh.MaterialSource := Material;
end;
Material.UseTexturing := True;
Material.UseTexture0 := True;
Material.Texture.LoadFromFile('diffuse.png');
Material.UseNormalMapping := True;
Material.NormalMap.LoadFromFile('normal.png');
Material.NormalIntensity := 1.0;
Material := TGorillaPBRMaterialSource.Create(Self);
// Texture-based PBR
Material.UsePBRAlbedoTexture := True;
Material.Texture.LoadFromFile('albedo.png');
Material.UsePBRMetallicTexture := True;
Material.MetallicTexture.LoadFromFile('metallic.png');
Material.UsePBRRoughnessTexture := True;
Material.RoughnessTexture.LoadFromFile('roughness.png');
Material.UsePBRAOTexture := True;
Material.AmbientOcclusionTexture.LoadFromFile('ao.png');
// Or use bias values
Material.MetallicBias := 0.8;
Material.RoughnessBias := 0.3;
Material.AOBias := 1.0;
var
WindBehaviour: TGorillaWindBehaviour;
Item: TGorillaMaterialBehaviourItem;
begin
WindBehaviour := TGorillaWindBehaviour.Create(Self);
WindBehaviour.Viewport := Viewport;
Material.AttachMaterialBehaviour(WindBehaviour);
end;
Material.BeginChange();
try
Material.Diffuse := NewColor;
Material.UseTexturing := True;
Material.UseTexture0 := True;
Material.Texture := NewTexture;
Material.UseNormalMapping := True;
Material.NormalMap := NewNormal;
finally
Material.EndChange();
end;
Shader Rebuilding: Changing material properties may trigger shader recompilation. Use BeginChange/EndChange to batch updates.
Platform Light Limits: Number of supported lights varies by platform and graphics API version.
Texture Units: Each texture type uses a specific texture unit. Ensure hardware supports required number of units.
PBR Requirements: PBR shading requires modern graphics hardware. Fallback to Blinn-Phong on older devices.
Uniform Buffer Alignment: TGorillaShaderData uses std140 layout. Manual modifications require understanding of GPU memory alignment.
Material Behaviours: Behaviours are v1.1+ feature. Provide modular shader functionality without subclassing.
Fog Integration: Fog properties are controlled by viewport, not material. Material must support fog rendering.
Gorilla.Material.Types Unit — shared material type definitions (no reference page yet)The Gorilla.Mesh unit provides the core mesh component for Gorilla3D rendering. It contains the TGorillaMesh class, which represents individual 3D meshes with geometry data, materials, and rendering capabilities. Each mesh within a TGorillaModel is an instance of TGorillaMesh.
Default Gorilla3D mesh control. Can be used as standalone component or child of TGorillaModel. Each mesh inside a model is a TGorillaMesh instance.
Inheritance: TGorillaTransform → TGorillaMesh
Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)
| Property | Type | Description |
|---|---|---|
| Model | TGorillaControl | Get or set parent model component holding reference to mesh instance. |
| ReferencedName | String | Reference name for identifying mesh explicitly. |
| MeshData | TMeshData | Returns internal mesh data object with vertex and indices buffers. May be empty if mesh is STATIC for memory savings. |
| VertexJoints | TVertexJointsList | Returns used vertex joints list for skeletal animation. |
| Meshes | TGorillaMeshList | Returns list of sub-meshes. |
| Coordinates | TPoint3DDynArray | Get or set vertex coordinates array. |
| Vertices | TVertexDataMap | Get or set vertex data map containing all vertex attributes. |
| IsStatic | Boolean | Get or set static mesh flag. Static meshes prebuffer vertex data to GPU, clearing CPU memory. |
| WrapMode | TMeshWrapMode | Get or set mesh wrap mode for texture coordinates. |
| FlatShading | Boolean | Enable or disable flat shading. Recalculates normals per-face instead of per-vertex. |
| Property | Type | Default | Description |
|---|---|---|---|
| MaterialSource | TMaterialSource | nil | Get or set material source for mesh rendering. |
| Shadows | Boolean | False | Whether this mesh receives cascaded shadows. Setting True flips the linked default material(s) to ShadowMethod = CascadedShadowMapping and propagates to all sub-meshes. |
| CastShadows | Boolean | True | Whether this mesh is rendered into the cascaded-shadow depth atlas as a caster. Set False to keep an object from throwing a shadow — e.g. a water surface or transparent wall that sits between the light and the scene and would otherwise shadow everything beneath it. Independent of Shadows. |
| Wireframe | Boolean | False | Enable wireframe rendering (performance intensive, debugging only). |
| WireframeMaterial | TMaterialSource | nil | Material source for wireframe rendering in post-processing. |
| ShowNormals | Boolean | False | Enable normal visualization (performance intensive). |
| NormalsColor | TAlphaColor | - | Color for rendered normals if ShowNormals is active. |
| ShowBoundingBox | Boolean | False | Inherited from TGorillaControl. Renders the box of GetAnimatedBoundingBox() around the mesh and its sub-meshes (main render pass only). Works for static meshes too. |
| BoundingBoxColor | TAlphaColor | Orange | Inherited from TGorillaControl. Line color of the box drawn by ShowBoundingBox. |
| Instances | TGorillaMeshInstances | - | Collection managing mesh instances for GPU instancing. |
| Materials | TGorillaMeshMaterialCollection | - | Read-only design-time collection showing linked material sources. |
| Behaviours | TGorillaMeshBehaviourCollection | - | Collection of material behaviours attached to mesh. |
| MeshCollection | TGorillaMeshCollection | - | Read-only design-time collection showing submeshes. |
Standard properties: Width, Height, Depth, Position, Scale, RotationAngle, Visible, Opacity, etc.
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function GetBoundingBox(): TBoundingBox; override;
Returns absolute bounding box with applied mesh and local matrices.
function GetAnimatedBoundingBox(): TBoundingBox; override;
Returns the bounding box of the current vertices in local space of this mesh (relative to AbsoluteMatrix), as union with all sub-meshes. This is the box drawn by ShowBoundingBox.
Per (sub-)mesh the source is: the box stored with the current cached animation frame of the model, otherwise the live (CPU animated or dynamic) vertex buffer, otherwise the static vertex data of the mesh definition, which is where static meshes (IsStatic = True) keep their data. The mesh matrix (WrapMode) and the transformations of the sub-meshes are applied. Returns TBoundingBox.Empty if no mesh has vertices.
TGorillaSingletonMesh (and with it TGorillaCube, TGorillaSphere, ...) returns its body box (GetBodySize()) instead, the same box IsMarked draws. The base implementation in TGorillaControl returns the size box (Width, Height, Depth) of the control.
var
LWorld: TBoundingBox;
begin
LWorld := GorillaMesh1.GetAnimatedBoundingBox().Transform(GorillaMesh1.AbsoluteMatrix);
end;
See Models - Instancing for a complete guide.
function AddInstanceItem(AName: String): TGorillaMeshInstance; overload;
function AddInstanceItem(AName: String; ATransform: TMatrix3D): Integer; overload;
Adds a TGorillaMeshInstance item to the Instances collection. The first overload returns the item (identity transform), the second one applies the matrix and returns the index of the item in Instances. Items are passed on to all sub-meshes.
Example:
var LInst := GorillaModel1.AddInstanceItem('Tree_1');
LInst.BeginUpdate();
try
LInst.Position.Point := Point3D(10, 0, 5);
LInst.RotationAngle.Point := Point3D(0, 45, 0);
LInst.Scale.Point := Point3D(2, 2, 2);
finally
LInst.EndUpdate();
end;
procedure BeginInstancesEditing();
procedure EndInstancesEditing();
Locks the instance collection, all instance items and all sub-meshes for mass manipulation. EndInstancesEditing() rebuilds all instance matrices and the instance buffers once. Always pair both calls in a try..finally block.
Example:
GorillaModel1.BeginInstancesEditing();
try
for var I := 0 to 999 do
begin
var LInst := GorillaModel1.AddInstanceItem(Format('Rock_%d', [I]));
LInst.Position.Point := Point3D(Random(100) - 50, 0, Random(100) - 50);
LInst.RotationAngle.Y := Random(360);
end;
finally
GorillaModel1.EndInstancesEditing();
end;
function AddInstance(ATransform: TMatrix3D): Integer;
Adds a plain matrix to the instance cache without creating a collection item (fastest, runtime only). Returns the cache index (starting at 1). Not passed on to sub-meshes and dropped as soon as the instance items of the mesh change.
function GetInstance(AIndex: Integer): TMatrix3D;
procedure SetInstance(AIndex: Integer; const AValue: TMatrix3D);
Get or set a transformation matrix in the instance cache by its cache index. Index 0 is the mesh itself and is overwritten every frame. Additional instances start at index 1 (item Instances.Items[I] is cache index I + 1). For instance items, prefer changing Position, RotationAngle and Scale of the item - SetInstance() is overwritten when the cache is rebuilt from the items.
Example:
// move a matrix-only instance
var LIdx := Mesh.AddInstance(TMatrix3D.CreateTranslation(Point3D(10, 0, 0)));
Mesh.SetInstance(LIdx, TMatrix3D.CreateTranslation(Point3D(10, 2, 0)));
function DeleteInstance(AIndex: Integer): Boolean;
procedure ClearInstances();
DeleteInstance() removes the instance item at the given collection index. ClearInstances() removes all instance items and all matrix-only instances.
function RayCastIntersect(const ARayPos, ARayDir: TPoint3D;
var AIntersection, ANormal: TPoint3D): Boolean; reintroduce;
Performs ray cast intersection test on this mesh using absolute ray position and direction. Returns TRUE if ray intersects any triangle, with intersection point and normal vector at that position. Searches entire mesh hierarchy including all submeshes.
Important: Requires absolute world-space ray position and direction vectors.
Example:
var
RayPos, RayDir: TPoint3D;
Intersection, Normal: TPoint3D;
begin
// Absolute world-space ray
RayPos := Point3D(0, 10, 0);
RayDir := Point3D(0, -1, 0); // Downward
if Mesh.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
begin
ShowMessage('Hit at: ' + Intersection.ToString);
ShowMessage('Normal: ' + Normal.ToString);
end;
end;
function PickTriangle(const X, Y: Single;
var AIntersection, ANormal: TPoint3D; out A, B, C: TPoint3D): Boolean; overload;
Detects intersected triangle using screen coordinates (X, Y in pixels). Converts screen coordinates to 3D ray and performs intersection test. Returns TRUE if triangle hit, providing intersection point, normal, and absolute triangle corner coordinates (A, B, C).
Parameters:
X, Y - Screen coordinates in pixelsAIntersection - Output: 3D intersection point (world space)ANormal - Output: Surface normal at intersectionA, B, C - Output: Triangle corner positions (world space)Example:
var
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Mouse click at screen position
if Mesh.PickTriangle(MouseX, MouseY, Intersection, Normal, A, B, C) then
begin
ShowMessage('Triangle hit at: ' + Intersection.ToString);
ShowMessage(Format('Triangle corners: [%s, %s, %s]',
[A.ToString, B.ToString, C.ToString]));
end;
end;
function PickTriangle(const X, Y: Single;
var AResult: TTriangleRayCastResult): Boolean; overload;
Detects intersected triangle using screen coordinates and returns comprehensive result structure. Provides intersection point, normal, triangle corners, distance, and reference to intersected object.
Parameters:
X, Y - Screen coordinates in pixelsAResult - Output: Complete ray cast result structureExample:
var
Result: TTriangleRayCastResult;
begin
if Mesh.PickTriangle(MouseX, MouseY, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f', [Result.T]));
ShowMessage('Point: ' + Result.Intersection.ToString);
ShowMessage('Normal: ' + Result.Normal.ToString);
// Access triangle corners
ShowMessage(Format('Triangle: [%s, %s, %s]',
[Result.Triangle[0].ToString,
Result.Triangle[1].ToString,
Result.Triangle[2].ToString]));
// Check intersected object
if Assigned(Result.Instance) then
ShowMessage('Hit object: ' + TComponent(Result.Instance).Name);
end;
end;
function PickTriangle(const ARayPos, ARayDir: TVector3D;
var AIntersection, ANormal: TPoint3D; out A, B, C: TPoint3D): Boolean; overload;
Detects intersected triangle using absolute ray position and direction. Returns intersection point, normal, and triangle corner coordinates.
Important: Requires absolute world-space ray vectors.
Parameters:
ARayPos - Absolute ray start position (world space)ARayDir - Absolute ray direction vector (world space)AIntersection - Output: 3D intersection pointANormal - Output: Surface normal at intersectionA, B, C - Output: Triangle corner positionsExample:
var
RayPos, RayDir: TVector3D;
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Setup ray from camera position
RayPos := Vector3D(Camera.Position.X, Camera.Position.Y, Camera.Position.Z);
RayDir := Vector3D(0, 0, 1); // Forward
if Mesh.PickTriangle(RayPos, RayDir, Intersection, Normal, A, B, C) then
begin
// Process triangle intersection
ShowMessage('Triangle hit!');
end;
end;
function PickTriangle(const ARayPos, ARayDir: TVector3D;
var AResult: TTriangleRayCastResult): Boolean; overload;
Detects intersected triangle using absolute ray position and direction and returns comprehensive result structure.
Important: Requires absolute world-space ray vectors.
Parameters:
ARayPos - Absolute ray start position (world space)ARayDir - Absolute ray direction vector (world space)AResult - Output: Complete ray cast result structureExample:
var
Result: TTriangleRayCastResult;
RayPos, RayDir: TVector3D;
begin
RayPos := Vector3D(0, 100, 0);
RayDir := Vector3D(0, -1, 0); // Downward ray
if Mesh.PickTriangle(RayPos, RayDir, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f units', [Result.T]));
ShowMessage('Intersection: ' + Result.Intersection.ToString);
ShowMessage('Normal: ' + Result.Normal.ToString);
// Calculate impact details
var ImpactForce := 100.0 / Result.T; // Force based on distance
end;
end;
procedure ApplyMaterialSource(AValue: TMaterialSource);
Applies material source to mesh and all submeshes recursively.
procedure ComputeTangentsAndBinormals();
Computes tangent and binormal vectors for normal mapping. Called automatically when needed.
procedure BuildTriangleMesh();
Debugging routine creating simple triangle in mesh data. Deletes existing data.
Collection item describing one GPU instance of a mesh. Returned by TGorillaMesh.AddInstanceItem().
Inheritance: TCollectionItem → TGorillaMeshInstance
| Property | Type | Description |
|---|---|---|
| Position | TPosition3D | Absolute translation of the instance (not relative to the mesh). |
| RotationAngle | TPosition3D | Rotation in degrees around X, Y, Z. |
| Scale | TPosition3D | Scaling, default (1, 1, 1). |
| RotationCenter | TPosition3D | Pivot of the rotation, default (0, 0, 0). |
| DisplayName | String | Name of the instance. |
| Transform | TMatrix3D | Read-only resulting matrix (Scale → Rotation → Translation). |
| OwnerMesh | TGorillaMesh | Mesh owning this instance. |
procedure BeginUpdate();
procedure EndUpdate();
Defers the matrix rebuild and the rebuild of the instance buffer until the outermost EndUpdate(). Use it when changing several properties of one instance. For many instances use TGorillaMesh.BeginInstancesEditing().
procedure SetTransform(const ATransform: TMatrix3D);
Sets the instance by a matrix and extracts Position, Scale and RotationAngle from it.
procedure ResetRotationAngle();
procedure UpdateTransform();
ResetRotationAngle() resets the rotation to zero. UpdateTransform() recomputes Transform from the properties (does nothing while updating).
Collection managing mesh instances for GPU instancing.
Inheritance: TOwnedCollection → TGorillaMeshInstances
| Property | Type | Description |
|---|---|---|
| OwnerMesh | TGorillaMesh | Returns owning mesh component. |
| CacheUpdated | Boolean | Indicates if instance cache was updated. |
| CachedInstancesPtr | PMatrix3D | Pointer to cached instances array. |
| CachedInstancesCount | Integer | Number of cached instances. |
function AddInstance(const ATransform: TMatrix3D; const ACreateItem: Boolean;
AName: String = ''): Integer;
Add new instance to collection. For runtime, reduce memory by setting ACreateItem to false.
Example:
// Add instances without creating collection items (memory efficient)
for var x := 0 to 9 do
for var z := 0 to 9 do
begin
var Transform := TMatrix3D.CreateTranslation(Point3D(x * 2, 0, z * 2));
Mesh.Instances.AddInstance(Transform, False);
end;
function GetInstance(AIndex: Integer): TMatrix3D;
procedure SetInstance(AIndex: Integer; const AValue: TMatrix3D);
Get or update specific instance transformation by index.
function DeleteInstance(AIndex: Integer): Boolean;
Delete specific instance by index. Adjusts cache accordingly. Returns success.
procedure ClearInstances();
Clears all items and cached instances.
procedure UpdateInstanceCache(); overload;
procedure UpdateInstanceCache(const ABaseTransform: TMatrix3D;
const AInstances: TArray<TMatrix3D>); overload;
Updates internal instance cache for GPU rendering.
function ToArray(): TArray<TMatrix3D>;
Returns instances as array of transformation matrices.
Individual mesh instance with transform properties.
Inheritance: TCollectionItem → TGorillaMeshInstance
| Property | Type | Description |
|---|---|---|
| DisplayName | String | Instance display name. |
| Position | TPosition3D | Instance position. |
| Scale | TPosition3D | Instance scale. |
| RotationAngle | TPosition3D | Instance rotation angles. |
| RotationCenter | TPosition3D | Instance rotation center. |
| Property | Type | Description |
|---|---|---|
| Transform | TMatrix3D | Computed transformation matrix. |
| OwnerMesh | TGorillaMesh | Returns owning mesh. |
procedure UpdateTransform();
procedure SetTransform(const ATransform: TMatrix3D);
procedure ResetRotationAngle();
Read-only design-time collection showing linked material sources.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshMaterialCollection
class procedure Update(ACollection: TGorillaMeshMaterialCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current mesh materials.
function MaterialExists(AMaterial: TMaterialSource): Boolean;
Checks if material exists in collection.
Read-only design-time collection showing submeshes.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshCollection
class procedure Update(ACollection: TGorillaMeshCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current submeshes.
function MeshExists(AMesh: TGorillaMesh): Boolean;
Checks if mesh exists in collection.
Collection managing material behaviours attached to mesh.
Inheritance: TGorillaReadOnlyCollection → TGorillaMeshBehaviourCollection
class procedure Update(ACollection: TGorillaMeshBehaviourCollection;
AMesh: TGorillaMesh); reintroduce;
Updates collection to reflect current behaviours.
function BehaviourExists(ABehaviour: TGorillaMaterialBehaviour): Boolean;
Checks if behaviour exists in collection.
List of TGorillaMesh instances.
TGorillaMeshList = TObjectList<TGorillaMesh>;
List managing vertex joint information for skeletal animation.
var
Mesh: TGorillaMesh;
begin
Mesh := TGorillaMesh.Create(Self);
Mesh.Parent := Viewport;
Mesh.MaterialSource := MyMaterial;
end;
var
Mesh: TGorillaMesh;
Transform: TMatrix3D;
begin
Mesh := TGorillaMesh.Create(Self);
Mesh.Parent := Viewport;
// Add 100 instances
for var i := 0 to 99 do
begin
Transform := TMatrix3D.CreateTranslation(
Point3D(Random(100) - 50, 0, Random(100) - 50)
);
Mesh.Instances.AddInstance(Transform, False); // No collection item = memory efficient
end;
end;
// Iterate through all submeshes
for var i := 0 to Mesh.Meshes.Count - 1 do
begin
var SubMesh := Mesh.Meshes[i];
ShowMessage('SubMesh: ' + SubMesh.Name);
// Apply material to submesh
SubMesh.MaterialSource := BodyMaterial;
end;
// Mark mesh as static for better performance
Mesh.IsStatic := True;
// Static meshes prebuffer to GPU and clear CPU memory
// Use for meshes that never change geometry
// Enable flat shading for hard-edge look
Mesh.FlatShading := True;
// Normals recalculated per-face instead of per-vertex
Mesh.Wireframe := True;
Mesh.WireframeMaterial := WireframeMaterialSource;
// Warning: Performance intensive, use for debugging only
Mesh.ShowNormals := True;
Mesh.NormalsColor := TAlphaColors.Green;
// Shows normal directions for debugging
var
RayPos, RayDir: TPoint3D;
Intersection, Normal: TPoint3D;
begin
// Absolute world-space ray
RayPos := Point3D(0, 10, 0);
RayDir := Point3D(0, -1, 0); // Downward
if Mesh.RayCastIntersect(RayPos, RayDir, Intersection, Normal) then
begin
ShowMessage('Hit at: ' + Intersection.ToString);
ShowMessage('Surface normal: ' + Normal.ToString);
end;
end;
procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
Intersection, Normal: TPoint3D;
A, B, C: TPoint3D;
begin
// Pick triangle at mouse position
if Mesh.PickTriangle(X, Y, Intersection, Normal, A, B, C) then
begin
ShowMessage('Clicked on mesh at: ' + Intersection.ToString);
ShowMessage(Format('Triangle corners: [%s, %s, %s]',
[A.ToString, B.ToString, C.ToString]));
// Visualize hit point
Sphere.Position.Point := Intersection;
end;
end;
procedure TForm1.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
Result: TTriangleRayCastResult;
begin
if Mesh.PickTriangle(X, Y, Result) then
begin
ShowMessage(Format('Hit at distance: %.2f units', [Result.T]));
ShowMessage('Intersection: ' + Result.Intersection.ToString);
ShowMessage('Normal: ' + Result.Normal.ToString);
// Access all triangle corners
for var i := 0 to 2 do
ShowMessage(Format('Corner %d: %s', [i, Result.Triangle[i].ToString]));
// Check which object was hit
if Assigned(Result.Instance) then
begin
if Result.Instance is TGorillaMesh then
ShowMessage('Hit mesh: ' + TGorillaMesh(Result.Instance).Name);
end;
end;
end;
var
Result: TTriangleRayCastResult;
RayPos, RayDir: TVector3D;
begin
// Cast ray from above downward
RayPos := Vector3D(Character.Position.X, 100, Character.Position.Z);
RayDir := Vector3D(0, -1, 0);
if Mesh.PickTriangle(RayPos, RayDir, Result) then
begin
// Found ground height
var GroundHeight := Result.Intersection.Y;
Character.Position.Y := GroundHeight + 1.0; // Place character on ground
ShowMessage(Format('Ground found at height: %.2f', [GroundHeight]));
end;
end;
// Animate instances
for var i := 0 to Mesh.Instances.CachedInstancesCount - 1 do
begin
var Transform := Mesh.Instances.GetInstance(i);
// Rotate instance
Transform := Transform * TMatrix3D.CreateRotationY(0.01);
Mesh.Instances.SetInstance(i, Transform);
end;
// Update cache after modifications
Mesh.Instances.UpdateInstanceCache();
// Get vertex positions
var Coords := Mesh.Coordinates;
for var i := Low(Coords) to High(Coords) do
ShowMessage(Coords[i].ToString);
// Warning: Static meshes may have empty vertex data on CPU
if not Mesh.IsStatic then
begin
// Modify vertices
var Vertices := Mesh.Vertices;
// ... modify vertex data ...
Mesh.Vertices := Vertices;
end;
// Apply material to mesh and all submeshes
Mesh.ApplyMaterialSource(MyMaterial);
// Apply to specific mesh only
Mesh.MaterialSource := MyMaterial;
GORILLA_POLYGON_MAXSIZE = 16; // Maximum polygon size
Static Meshes: Set IsStatic = True for meshes with unchanging geometry to improve performance and reduce memory.
GPU Instancing: Use AddInstance with ACreateItem = False for memory-efficient instancing at runtime.
Wireframe/Normals: Both features are performance intensive. Use for debugging only.
Flat Shading: Recalculates normals per-face. Use for hard-edge modeling style.
Sub-Meshes: Complex models contain mesh hierarchies. Iterate through Meshes collection to access all parts.
Vertex Data Access: Static meshes may have empty CPU vertex data. Check IsStatic before accessing.
Ray Casting and Triangle Picking:
RayCastIntersect for absolute world-space ray testsPickTriangle with screen coordinates (X, Y) for mouse interactionPickTriangle with absolute ray for custom ray testsTTriangleRayCastResult provides complete intersection details including distance, normal, triangle corners, and intersected object referenceGorilla.Transform Unit — transformation helpers (no reference page yet)The Gorilla.Model unit provides the core model component for loading and managing 3D models in Gorilla3D. It contains the TGorillaModel class, which automatically manages sub-meshes, materials, animations, lights, cameras, and armatures.
Default model control for managing multi-mesh 3D models. The Gorilla3D model component differs significantly from the FMX equivalent, supporting multiple file formats and advanced features like vertex, skeleton, and skin animation.
Inheritance: TGorillaMesh → TGorillaModel
Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)
| Property | Type | Description |
|---|---|---|
| Wireframe | Boolean | Get or set property to draw wireframe onto model. Warning: Performance intensive, use for debugging only. |
| WireframeMaterial | TMaterialSource | Material source used for rendering wireframe in post-processing. |
| ShowNormals | Boolean | Get or set property to draw normals in post-processing. Warning: Performance intensive. |
| NormalsColor | TAlphaColor | Normal color drawn if ShowNormals is active. |
| ShowJoints | Boolean | Render visual controllers for all joints. Only works if an armature exists. |
| JointsColor | TAlphaColor | Get or set joints color for rendering visual controllers. Applied only if ShowJoints is TRUE. |
| Interpolators | TGorillaInterpolatorList | Returns list of internally used interpolators for animation. Each interpolator defines animation step for a specific mesh. |
| Package | TGorillaAssetsPackage | Returns linked package. If no package linked, getter tries to find package by PackageName and AssetsManager. |
| AnimationManager | TGorillaAnimationManager | Integrated animation manager for holding animation instances and managing interactions (playing, switching, stopping). |
| MetaData | TModelMetaDef | Tries to receive metadata from embedded TModelDef. |
| DefStoredInPackage | Boolean | Indicates if Definition is stored in a package (needed because package might be destroyed before model). |
| Property | Type | Description |
|---|---|---|
| AssetsManager | TGorillaAssetsManager | Link to existing assets manager component. Use PackageName to define the used/requested assets package. |
| PackageName | String | Get or set assets package name to load/store model and texture data. |
| Source | TFileName | Get or set source filename for model file. If assets package linked, component tries to load from package, otherwise from file. |
| ShowBoundingBox | Boolean | Inherited from TGorillaControl. Renders a box around the current pose of the model (main render pass only). Unlike the designer selection box (IsMarked) it follows skin, vertex and sub-mesh animations. See GetAnimatedBoundingBox(). Default: False. |
| BoundingBoxColor | TAlphaColor | Inherited from TGorillaControl. Line color of the box drawn by ShowBoundingBox. Default: TAlphaColorRec.Orange. |
Shadows:
TGorillaModelinheritsShadows(receives cascaded shadows) andCastShadows(defaultTrue; whether it is written into the shadow atlas) from TGorillaMesh. Because a model's sub-meshes and materials only exist after the file is loaded, the model re-appliesShadowsonce loading completes — so settingShadows := Truein the form designer (where it is streamed beforeSource) correctly switches every loaded material toCascadedShadowMapping. To stop a model from throwing a shadow, setCastShadows := False.
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Standard component lifecycle methods.
procedure LoadFromFile(const APackage: TGorillaAssetsPackage;
const AFilename: String; const ACaching: TAnimationCachingFlags); overload;
procedure LoadFromFile(const AOptions: TGorillaLoadOptions); overload;
Loads model data with sub-meshes, materials, animations to existing instance.
Parameters:
APackage - Optional. If nil, loads from file. If assigned, looks up in assets package first.AFilename - Path to model fileACaching - Animation caching flagsAOptions - Advanced loading options structureExample:
// Simple loading
GorillaModel1.LoadFromFile(nil, 'character.dae', []);
// With asset package
GorillaModel1.LoadFromFile(MyPackage, 'character.g3d',
[TAnimationCachingFlag.VertexPosition]);
// Advanced loading
var Options := TGorillaLoadOptions.Create('model.fbx', [], nil, nil);
Options.ImportLights := True;
GorillaModel1.LoadFromFile(Options);
procedure LoadFromStream(const APackage: TGorillaAssetsPackage;
const AStream: TStream; const APath: String;
const ACaching: TAnimationCachingFlags); overload;
procedure LoadFromStream(const AStream: TStream;
const AOptions: TGorillaLoadOptions); overload;
Loads model data from stream to existing instance.
Parameters:
APackage - Optional assets packageAStream - Stream containing model dataAPath - Path/filename for format detectionACaching - Animation caching flagsAOptions - Advanced loading optionsclass function LoadNewModelFromFile(const AOwner: TComponent;
const APackage: TGorillaAssetsPackage; const AFilename: String;
const ACaching: TAnimationCachingFlags): TGorillaModel; overload;
class function LoadNewModelFromFile(const AOwner: TComponent;
const AOptions: TGorillaLoadOptions): TGorillaModel; overload;
Loads model data from file and creates new instance.
Returns: New TGorillaModel instance
Example:
var MyModel := TGorillaModel.LoadNewModelFromFile(
Viewport,
nil,
'models\character.dae',
[]
);
MyModel.Parent := Viewport;
class function LoadNewModelFromOptions(const AOwner: TComponent;
const AOptions: TGorillaLoadOptions): TGorillaModel;
Alternative method for scripting compatibility where RTTI cannot detect correct overloaded method.
class function LoadNewModelFromStream(const AOwner: TComponent;
const APackage: TGorillaAssetsPackage; const AStream: TStream;
const APath: String; const ACaching: TAnimationCachingFlags): TGorillaModel; overload;
class function LoadNewModelFromStream(const AOwner: TComponent;
const AStream: TStream; const AOptions: TGorillaLoadOptions): TGorillaModel; overload;
Loads model data from stream and creates new instance.
class function LoadNewModelFromDef(const AOwner: TComponent;
const ADef: TModelDef; const ACaching: TAnimationCachingFlags): TGorillaModel; overload;
class function LoadNewModelFromDef(const AOwner: TComponent;
const ADef: TModelDef; const AOptions: TGorillaLoadOptions): TGorillaModel; overload;
Creates new instance and applies existing model definition with sub-meshes, materials, animations. Use for instancing predefined models without assets manager.
procedure LoadFromDefinition(const ADef: TModelDef); reintroduce;
Applies given ModelDefinition to model instance. Automatically instantiates meshes, materials, animations. Internal use - called when loading from stream or file.
procedure StoreToDefinition(const ADef: TCustomDef); override;
Stores all data from visual component back to definition object.
function AddAnimationFromFile(const AFilename: String;
const ACaching: TAnimationCachingFlags = []): TGorillaAnimation;
Loads animation data from file to existing model and returns created animation instance.
Requirements: Model data (meshes, materials, textures) must be loaded before adding animation.
Important: You can only add animations on an existing model, if the meta data from original model import is still available. Because after reloading a model, it's not loaded from the original file format again. So the meta data from a FBX or DAE is lost and animation data cannot be applied again.
Example:
var Anim := GorillaModel1.AddAnimationFromFile(
'character_run.dae',
[TAnimationCachingFlag.VertexPosition]
);
function AddAnimationFromStream(const AStream: TStream;
const AFileName: String;
const ACaching: TAnimationCachingFlags = []): TGorillaAnimation;
Loads animation data from stream to existing model and returns created animation instance.
procedure RecacheAnimations(const ACaching: TAnimationCachingFlags = []); virtual;
procedure RecacheAnimationsByName(const AIds: Array of String;
const ACaching: TAnimationCachingFlags = []); virtual;
Throws the cached frames of all animations (or of the animations whose id is in AIds,
case-insensitive, unknown ids are ignored) away and bakes them again.
ACaching = [] keeps the flags each animation was cached with before - animations that
were never cached stay uncached. Pass flags (f.e. GORILLA_ANIMATION_CACHING_DEFAULT) to
cache all of them. Animations that were playing are restarted afterwards.
Takes as long as the initial caching did - for a character with many clips that is seconds.
Example:
GorillaModel1.RecacheAnimations(GORILLA_ANIMATION_CACHING_DEFAULT);
GorillaModel1.RecacheAnimationsByName(['walk', 'run']);
procedure DiscardAnimationCache(); virtual;
procedure DiscardAnimationCacheByName(const AIds: Array of String); virtual;
Throws the cached frames of all animations (or of the animations whose id is in AIds)
away. They play skinned on the CPU afterwards, like animations added without caching - a
playing animation keeps playing.
The animations are not cacheable any more afterwards, so RecacheAnimations() without
flags leaves them uncached - pass the flags to bake them again:
GorillaModel1.DiscardAnimationCache();
GorillaModel1.RecacheAnimations(GORILLA_ANIMATION_CACHING_DEFAULT);
Important: The frames belong to the model definition: other model instances sharing it (f.e. loaded from the same assets package) lose them too.
procedure ResetToBindPose();
Stops all animations and returns the model to its unanimated pose, for cached and CPU
skinned animations alike. Shortcut for AnimationManager.ResetToBindPose.
function HasCurrentAnimation(): Boolean;
True if the model has an animation manager with a current animation - short for
Assigned(AnimationManager) and Assigned(AnimationManager.Current). The current animation
does not need to be playing, see IsAnimationPlaying.
function TryGetCurrentAnimation(out AAnim: TGorillaAnimation): Boolean;
Returns the current animation in AAnim, or nil and False if there is none.
Example:
if GorillaModel1.TryGetCurrentAnimation(LAnim) then
Label1.Text := LAnim.Id;
function IsAnimationPlaying(): Boolean; overload;
function IsAnimationPlaying(const AId: String): Boolean; overload;
True if the current animation (or the animation with id AId) is playing at the moment.
With AId it does not matter whether it is the current animation or not (f.e. while
blending). The id is looked up like AnimationManager.GetAnimation does; unknown ids give
False.
Example:
if GorillaModel1.IsAnimationPlaying('walk') then
GorillaModel1.ResetToBindPose();
Interpolators are controls that animate single parts of a model. For example they are used to animate joints inside of a skeleton mesh. It's helpful to request interpolators to modify behaviour of specific parts. For example to manually move a joint.
procedure AddInterpolator(const AName: String;
AInterpolator: TPropertyKeyAnimation);
Adds property key animation interpolator to model. Used while loading animated model from file.
function FindInterpolator(const AName: String): TPropertyKeyAnimation;
Tries to find specific property key animation interpolator by name. Returns nil if not found.
function FindInterpolatorByDef(const ADef: TCustomDef): TPropertyKeyAnimation;
Tries to find specific property key animation interpolator by its definition. Returns nil if not found.
function FindControlByDeepSearch(const AName: String): TComponent; override;
Searches for interpolator or sub-mesh inside model hierarchy by name. Searches all levels. Returns nil if not found.
function FindControlByDefDeepSearch(const ADef: TCustomDef): TComponent; override;
Searches for interpolator or sub-mesh inside model hierarchy by definition. Returns nil if not found.
procedure FindControlsByDeepSearch(const AName: String;
const AResult: TReferencedControlList); override;
Searches for all interpolators or sub-meshes with submitted name. Results added to AResult list. List stays empty if nothing found.
procedure Clear();
Destroys all sub-meshes and animations.
procedure ResolvingSegment(AId: String; AObj: TGorillaTransform);
Used by sub-components to resolve segment instances. Segments created as dummies might be replaced by real instance later.
procedure UpdateBinaryData();
Clears internal binary data storage and stores model definition data to binary format. Called at design time to save model into DFM/FMX file.
function GetFirstArmature(): TComponent;
Tries to find armature instance and returns first one found.
procedure DebugOut(ACompHierarchy: Boolean = false);
Outputs model hierarchy into log. Useful to check hierarchy built after importing. Check event log for printed content.
Parameters:
ACompHierarchy - False = FMX hierarchy, True = Component hierarchyfunction GetBoundingBox(): TBoundingBox; override;
function GetAbsoluteBoundingBox(): TBoundingBox; override;
Returns ABSOLUTE bounding box with applied mesh and local matrices. Union of all submeshes.
function GetAnimatedBoundingBox(): TBoundingBox; override;
Declared in TGorillaControl, implemented by TGorillaMesh (see Gorilla.Mesh). Returns the bounding box of the CURRENT (animated) pose in local model space, i.e. relative to AbsoluteMatrix. Unlike GetBoundingBox(), which is built from the static vertex data, it follows skin, vertex and node animations.
For each sub-mesh the source is: the box stored with the current cached animation frame, otherwise the live CPU-animated vertex buffer, otherwise the static vertex data of the definition. Without animation caching all vertices are iterated, so avoid calling it needlessly every frame on large models. Returns TBoundingBox.Empty if no mesh has vertices.
var
LWorld: TBoundingBox;
begin
LWorld := GorillaModel1.GetAnimatedBoundingBox().Transform(GorillaModel1.AbsoluteMatrix);
end;
Dictionary mapping interpolator names to TPropertyKeyAnimation instances.
TGorillaInterpolatorList = TDictionary<String, TPropertyKeyAnimation>;
var
Model: TGorillaModel;
begin
Model := TGorillaModel.LoadNewModelFromFile(
Viewport,
nil,
'models\spaceship.dae',
[TAnimationCachingFlag.VertexPosition]
);
Model.Parent := Viewport;
Model.Position.Point := Point3D(0, 0, 0);
end;
var
Model: TGorillaModel;
begin
Model := TGorillaModel.LoadNewModelFromFile(
Viewport,
AssetsPackage1,
'character.g3d',
[TAnimationCachingFlag.VertexPosition]
);
Model.Parent := Viewport;
end;
// Load base model
GorillaModel1.LoadFromFile(nil, 'character.dae', []);
// Add additional animations
var WalkAnim := GorillaModel1.AddAnimationFromFile(
'character_walk.dae',
[TAnimationCachingFlag.VertexPosition]
);
var RunAnim := GorillaModel1.AddAnimationFromFile(
'character_run.dae',
[TAnimationCachingFlag.VertexPosition]
);
// Play animation
GorillaModel1.AnimationManager.PlayAnimation('Walk');
var
Options: TGorillaLoadOptions;
Model: TGorillaModel;
begin
Options := TGorillaLoadOptions.Create('scene.fbx', [], nil, nil);
// Configure import settings
Options.ImportLights := True;
Options.ImportCameras := True;
Options.ImportAnimations := True;
// Configure caching
Options.Caching := [TAnimationCachingFlag.VertexPosition];
// Limit texture sizes
Options.TextureLimits := TPoint.Create(2048, 2048);
// Load model
Model := TGorillaModel.LoadNewModelFromFile(Viewport, Options);
Model.Parent := Viewport;
end;
// Find specific mesh
var HeadMesh := GorillaModel1.FindControlByDeepSearch('Head') as TGorillaMesh;
if Assigned(HeadMesh) then
HeadMesh.MaterialSource := HeadMaterial;
// Find armature
var Armature := GorillaModel1.GetFirstArmature() as TGorillaArmature;
if Assigned(Armature) then
begin
Armature.ShowJoints := True;
Armature.JointsRenderColor := TAlphaColors.Yellow;
end;
// Find all meshes with specific name
var List := TReferencedControlList.Create;
try
GorillaModel1.FindControlsByDeepSearch('Wheel', List);
for var i := 0 to List.Count - 1 do
ShowMessage('Found: ' + TGorillaMesh(List[i]).Name);
finally
List.Free;
end;
// Output FMX hierarchy
GorillaModel1.DebugOut(False);
// Output component hierarchy
GorillaModel1.DebugOut(True);
GORILLA_ANIMATION_CACHING_DEFAULT = [];
Default animation caching configuration (no caching).
Loading Order: Model data must be loaded before adding animations for proper vertex-animation linking.
Asset Packages: Using asset packages improves IDE performance and enables model reuse across instances.
Memory Management: Models stored in packages are managed by TGorillaAssetsManager. Standalone models own their definitions.
Animation Caching: VertexPosition flag recommended for balanced performance/memory. AllAttributes uses more memory but provides maximum speed.
Binary Data: Design-time models stored as compressed G3D format in FMX files for efficient storage. Skins that drive several meshes (glTF meshes with several primitives, skins shared by several mesh nodes) keep the joint weights of every mesh. Models embedded with an older version, where only one part animated at runtime, have to be loaded again at design time.
Deep Search: FindControlByDeepSearch methods search entire hierarchy including interpolators, useful for accessing specific parts.
The Gorilla.Prefab unit provides the prefab system for Gorilla3D. Prefabs act as reusable templates — you store component hierarchies as DFM data and instantiate them at runtime. The system consists of TGorillaPrefab (a single prefab entry) and TGorillaPrefabSystem (the manager component).
TCollectionItem
└── TGorillaPrefab
TComponent
└── TGorillaPrefabSystem
A single prefab entry in the prefab collection. Stores DFM data and can load/save component hierarchies.
| Property | Type | Description |
|---|---|---|
DisplayName |
String |
Prefab display name |
FileName |
String |
File path to prefab file. Setting does not auto-load |
OwnerComponent |
TComponent |
Root node of the prefab component tree |
DFM |
TStrings |
Inline DFM content. If set, loading skips file access |
Stored |
Boolean |
Whether loaded components are stored in owner DFM |
WriteFormMethods |
Boolean |
Write event properties linked to form methods |
IgnoreUnresolvedEvents |
Boolean |
Silently ignore missing event methods (default shows dialog) |
| Event | Type | Description |
|---|---|---|
OnLoaded |
TOnPrefabLoadedEvent |
Fired after prefab components are loaded |
OnStored |
TNotifyEvent |
Fired after prefab is saved |
| Property | Type | Description |
|---|---|---|
OnCreateComponent |
TOnCreateComponentEvent |
Custom component creation callback |
| Method | Returns | Description |
|---|---|---|
Load() |
TList<TComponent> |
Load prefab from DFM or file |
LoadFromFile(AFileName) |
TList<TComponent> |
Load prefab from a specific file |
LoadFromStream(AStream, AIsPrefabZ) |
TList<TComponent> |
Load from stream (supports compressed .prefabz) |
Save(AUpdateFilename, AUseForm) |
— | Save prefab to current file |
SaveToFile(AFileName, AUpdateFilename, AUseForm) |
— | Save prefab to a specific file |
SaveToStream(AStream, AUseForm) |
— | Save prefab to stream |
TOnCreateComponentEvent = function(AComponentClass: TComponentClass;
AParent: TComponent; ALeft, ATop, AWidth, AHeight: Integer): TComponent of object;
TOnPrefabLoadedEvent = procedure(ASender: TObject;
AComponents: TList<TComponent>) of object;
The manager component that holds a collection of prefabs. Drop onto a form or data module.
| Property | Type | Description |
|---|---|---|
Prefabs |
TGorillaPrefabCollection |
Collection of TGorillaPrefab items |
| Method | Description |
|---|---|
AddPrefab(AName, AOwner, AFileName) |
Add a new prefab entry |
RemovePrefab(AName) |
Remove prefab by name |
IndexOfPrefab(AName) |
Find prefab index by name |
FindPrefab(AName) |
Find prefab by name (returns TGorillaPrefab or nil) |
LoadAllPrefabs(AList) |
Load all prefabs into a component list |
SaveAllPrefabs() |
Save all prefabs to their files |
The Gorilla.Renderer unit provides the rendering pipeline infrastructure for Gorilla3D. It includes base renderer classes and specialized renderers for different rendering techniques including forward rendering with WBOIT (Weighted Blended Order Independent Transparency) and legacy rendering.
Base renderer class for all renderer types.
Inheritance: TObject → TRenderer
| Property | Type | Access | Description |
|---|---|---|---|
| Id | String | Read | Unique identifier for the renderer instance. |
| Flags | TRendererFlags | Read | Renderer flags controlling pipeline behavior. |
| Multisample | TMSAASamples | Read/Write | Get or set MSAA (multi-sample anti-aliasing) level. |
| SharedContext | TContext3D | Read | Shared 3D rendering context. |
| CompositeTexture | TGorillaTextureBitmap | Read | Final composite output texture. |
| CompositeTextureMSAA | TGorillaTexture | Read | Multi-sampled version of composite texture. |
| RenderTargets | TRenderTargets | Read/Write | Active render targets for this renderer. |
| Owner | TComponent | Read/Write | Owner component (TGorillaViewport or TGorillaRenderPassController). |
| Size | TPoint | Read/Write | Renderer output size in pixels. Set by the owner: for the viewport TGorillaViewport.GetRenderTargetSize() (incl. RenderWidth / RenderHeight / RenderScale / HighRes), for a render pass TGorillaRenderPassController.GetRenderTargetSize(). Do not set it yourself - the next resize overwrites it. |
| Scale | Single | Read/Write | Texture scale handed to the render context (the owner's ViewportScale). Not a resolution factor - to render in a different resolution use TGorillaViewport.RenderScale or SetRenderSize. |
| Color | TAlphaColorF | Read/Write | Clear color for the renderer. |
| AttachedRenderer | TRenderer | Read/Write | Reference to attached sub-renderer. |
| DefaultFrameBuf | TFrameBufferObject | Read | Default framebuffer object for rendering. |
| TranslucentBuf | TFrameBufferObject | Read | Framebuffer for translucent rendering (WBOIT). |
| OnCreateCompositeTexture | TOnRendererCreateCompositeTexture | Read/Write | Event for custom composite texture creation. |
constructor Create(AId: String; AOwner: TComponent;
const AMultisamples: TMSAASamples = TMSAASamples.None;
AFlags: TRendererFlags = [];
ACompositeTextureEvent: TOnRendererCreateCompositeTexture = nil); virtual;
destructor Destroy(); override;
Create and destroy the renderer.
procedure Resize(const ASize: TPoint; const AScale: Single);
Resize the renderer output. ASize is in pixels. Called by the viewport or render pass controller on every resize and on a change of the render resolution - normally not called by application code.
procedure Apply(); virtual;
procedure Reset(); virtual;
Apply or reset renderer settings.
procedure BeginMainRenderPass(ACamera: TMatrix3D; AAngleOfView: Single); virtual;
procedure EndMainRenderPass(); virtual;
Begin and end the main rendering pass.
function BeginOpaqueRendering(): Boolean; virtual;
procedure EndOpaqueRendering(); virtual;
Begin and end opaque object rendering phase.
function BeginTranslucentRendering(): Boolean; virtual;
procedure EndTranslucentRendering(); virtual;
Begin and end translucent object rendering phase.
Simple renderer with single framebuffer for basic rendering needs.
Inheritance: TRenderer → TLegacyRenderer
This renderer provides a straightforward single-pass rendering pipeline without advanced features. Use when:
Base class for forward and deferred renderers with WBOIT 3-phase rendering.
Inheritance: TRenderer → TCompositeRenderer
| Property | Type | Description |
|---|---|---|
| AlbedoTexture | TTexture | Albedo color output (opaque objects only). |
| TranslucentAlbedoTexture | TTexture | Albedo color output (translucent objects only). |
| AlphaTexture | TTexture | Alpha channel output. |
| PositionTexture | TTexture | Fragment position output (world space vec3). |
| NormalsTexture | TTexture | Fragment normal vectors output (world space vec3). |
| EmissiveTexture | TTexture | Emissive color output. |
| Property | Type | Description |
|---|---|---|
| EmissiveBlurCtrl | TObject | Emissive blur render pass controller. |
| GlobalIllumCtrl | TObject | Global illumination render pass controller. |
| ScreenSpaceShadowsCtrl | TObject | Screen space shadows render pass controller. |
| SSAOCtrl | TObject | Screen space ambient occlusion controller. |
| DeferredCompositeCtrl | TObject | Deferred composite render pass controller. |
| Property | Type | Range | Description |
|---|---|---|---|
| TranslucentDistance | Single | - | Distance value for transparency weighting. Affects how translucent objects blend based on depth. |
| Saturation | TPoint3D | - | Saturation values: X=Opaque, Y=Translucent, Z=Composite. Zero disables saturation for that stage. |
| EmissiveBlur | Integer | 0-∞ | Emissive blur intensity. 0=disabled. Higher values = stronger glow but lower performance. |
| OutputLayer | TRendererOutputLayer | - | Which render layer to output for debugging (all layers, albedo only, normals only, etc.). |
| Property | Type | Range | Description |
|---|---|---|---|
| GlobalIllumDetail | Integer | 0-7 | Global illumination detail level. 0=off, 1-7=increasing quality. |
| GlobalIllumSoftness | Single | 0.0-5.0 | Softness of GI shadows and reflections. |
| ShadowStrength | Single | 0.0-10.0 | Darkness of GI shadows. |
| ReflectionStrength | Single | 0.0-10.0 | Intensity of GI reflections. |
| FXAA | Integer | 0-8 | Fast approximate anti-aliasing steps. 0=off, 8=maximum quality. |
| Property | Type | Description |
|---|---|---|
| SSS_Enabled | Boolean | Enable screen space shadows. |
| SSS_NumSamples | Integer | Number of samples for SSS (affects performance heavily). |
| SSS_SampleStep | Single | Step size for SSS sampling. |
| SSS_ShadowStrength | Single | Darkness of screen space shadows. |
| SSAO_Enabled | Boolean | Enable screen space ambient occlusion. |
| SSAO_Radius | Single | Sampling radius for SSAO. |
| SSAO_Bias | Single | Bias to prevent self-shadowing artifacts. |
| SSAO_NoiseScale | TPointF | Noise texture scale for SSAO. |
constructor Create(AId: String; AOwner: TComponent;
const AMultisamples: TMSAASamples = TMSAASamples.None;
AFlags: TRendererFlags = [];
ACompositeTextureEvent: TOnRendererCreateCompositeTexture = nil); override;
destructor Destroy(); override;
Create and destroy the composite renderer.
function BeginOpaqueRendering(): Boolean; override;
Begin opaque rendering phase.
procedure FragDepthRendering(const ARenderContext: PRenderContext); virtual;
Render fragment depth pre-pass for improved transparency.
function GetFragDepthRendering(): TTexture; virtual;
Get the fragment depth texture for use in shaders.
procedure Composite(const ARenderContext: PRenderContext); virtual;
Perform final compositing of all render layers.
Forward renderer with WBOIT for order-independent transparency.
Inheritance: TRenderer → TCompositeRenderer → TForwardRenderer
The recommended renderer providing:
Deferred renderer with multiple color channels and final composite pass.
Inheritance: TRenderer → TCompositeRenderer → TDeferredRenderer
| Property | Type | Description |
|---|---|---|
| ComponentsTexture | TTexture | Material component properties output. |
| AmbientTexture | TTexture | Ambient lighting output. |
| SpecularTexture | TTexture | Specular lighting output. |
procedure Composite(const ARenderContext: PRenderContext); override;
Deferred compositing combining all G-buffer layers.
Enumeration of renderer types.
Values:
ForwardRenderer - Forward renderer with WBOIT (recommended)LegacyRenderer - Simple single-pass rendererFlags controlling renderer behavior.
Values:
IgnoreRenderTargets - Don't create render targetsIgnoreCompositeCtrl - Don't create composite render passIgnoreEmissiveBlur - Don't create emissive blur passIgnoreGlobalIllum - Don't create global illumination passIgnoreSSS - Don't create screen space shadows passIgnoreSSAO - Don't create SSAO passIgnoreSSR - Don't create screen space reflections passSet of TRendererFlag values.
Enumeration of output layers for debugging.
Values:
OutputAll - All layers combined (normal rendering)OutputAlbedo - Albedo/color onlyOutputTranslucentAlbedo - Translucent albedo onlyOutputAlpha - Alpha channel onlyOutputDepth - Depth bufferOutputPosition - World space positionsOutputNormal - World space normalsOutputEmissive - Emissive channel onlyOutputComps - Material componentsOutputAmbient - Ambient lighting onlyOutputSpecular - Specular lighting onlyOutputSSS - Screen space shadowsOutputSSAO - Ambient occlusionEvent type for custom composite texture creation.
TOnRendererCreateCompositeTexture = procedure(
ASender: TObject;
const ASize: TPoint;
const AScale: Single;
out ATexture: TGorillaTextureBitmap
) of object;
| Level | Voxel Size | Target GPU | Min Texture3D Size |
|---|---|---|---|
| 0 | - | - | 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-end GPUs | 4096 |
| 7 | 512 | High-end GPUs | 4096 |
Renderer Selection: Use TForwardRenderer for most cases. Only use TLegacyRenderer when you need maximum FMX compatibility or are doing extensive native OpenGL rendering.
MSAA: Set multisample level in constructor or via the Multisample property. Not all platforms support all MSAA levels.
Render Targets: The composite renderer creates multiple render targets for different rendering stages. Access these via properties like AlbedoTexture, NormalsTexture, etc.
Performance: Higher EmissiveBlur and FXAA values significantly impact performance. Start with low values and increase as needed.
Debugging: Use OutputLayer to visualize individual render passes during development.
Global Illumination: Only available in GAME_PACKAGE edition. Requires significant GPU resources at higher detail levels.
Render Resolution: The resolution is controlled by the viewport (RenderScale, RenderWidth / RenderHeight, SetRenderSize). Size shows the result in pixels. See Render Resolution and Scaling.
The Gorilla.Viewport unit provides the core viewport component for Gorilla3D rendering. It contains the TGorillaViewport class, which is the primary container for 3D scenes and replaces FireMonkey's standard TViewport3D component.
Main viewport class for rendering 3D scenes using Gorilla3D.
Inheritance: TControl → TGorillaViewport
Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)
| Property | Type | Description |
|---|---|---|
| Context | TContext3D | Get or set the current 3D context. Do not change unless you know what you are doing. |
| CurrentCamera | TCamera | Returns the currently applied camera component (user or design camera). |
| Gizmo | TControl3D | Returns the embedded gizmo component (TGorillaGizmo) for design-time Control3D editing. |
| FPS | Double | Legacy frame rate: with UseFixedFrameRate the rate of the frame rate timer, otherwise an estimate from the scene rendering time. For the real output use FramesPerSecond. |
| FramesPerSecond | Single | Frames that really reach the screen per second of wall clock (= Diagnostics.RealFramesPerSecond). Includes frame limits (FixedFrameRate, VSync). Updated every 30 frames, 0 while DiagnosticsMeasuring is off. |
| DeltaTime | Double | Seconds between the start of the previous and the current rendered frame - the value to scale per-frame movement with. 0 on the first frame. Not clamped after pauses. Always measured. |
| CurrentFrameTime | Double | Start of the current rendered frame in seconds, counted from the first rendered frame of this viewport. |
| PreviousFrameTime | Double | Start of the previous rendered frame in seconds. DeltaTime = CurrentFrameTime - PreviousFrameTime. |
| ViewportScale | Single | Texture scale handed to the render context: the display scale (HighRes), or 1 as soon as a render resolution or HighRes on a scaled display is in use - then ViewToRenderPoint / RenderToViewPoint do the mapping. Not the render resolution factor, see RenderScale. |
| RenderSize | TPoint | RenderWidth x RenderHeight as one value. Writing it calls SetRenderSize (one rebuild for both values). Point(0, 0) = native resolution. Not published, because TPoint cannot be streamed. |
| Smooth | Boolean | Activate or deactivate smooth rendering. |
| SceneBounds | TBoundingBox | Returns the lately computed scenery boundary. |
| CurrentFrustum | TGorillaFrustum | Returns the lately computed camera frustum. |
| Saturation | TPoint3D | Get or set saturation values applied while color merging. Contains 3 parts: X=Opaque, Y=Translucent, Z=Composite saturation. |
| LockRendering | Boolean | Lock or unlock the rendering process. |
| EditMode | Boolean | Activate/deactivate edit mode at design-time (also available at runtime). |
| FogMode | TGorillaFogMode | Get or set fog computation mode (linear, exp, exp2). |
| FragmentDepthRendering | Boolean | Enable/disable pre-render pass for fragment depth rendering. Improves translucent rendering but affects performance. |
| CurrentRenderer | TRenderer | Get or set the current active renderer. |
| MainPassRenderer | TRenderer | Returns the main pass renderer. |
| Diagnostics | TRenderingDiagnostics | Frame statistics, measured while DiagnosticsMeasuring (or DiagnosticsActive) is set. |
| RenderingList | TList<TControl3D> | Access the list of objects to be rendered. |
| Property | Type | Default | Description |
|---|---|---|---|
| RendererType | TRendererType | ForwardRenderer | Define which renderer to use: ForwardRenderer (WBOIT, recommended) or LegacyRenderer (single framebuffer). |
| ManualRendering | Boolean | False | Enable manual rendering mode where viewport only renders when RenderManual() is called. Only effective with UseFixedFrameRate = False. |
| UseFixedFrameRate | Boolean | True (False on iOS) | Enable fixed framerate rendering: the viewport renders continuously from its own frame rate tick. Available on Windows, macOS, Linux and Android - on Linux and Android (since v1.5.4) the tick paces the rendering and the frame is rendered inside the FMX paint cycle. Not available on iOS (always False). |
| FixedFrameRate | Integer | 60 | Fixed frame rate value (only affects rendering if UseFixedFrameRate is enabled). |
| FrustumCulling | Boolean | True | Enable or disable frustum culling for performance optimization. |
| HighRes | Boolean | False | Render in the physical display resolution on high-DPI displays (Android, Windows with a display scaling above 100 %). RenderScale multiplies on top. |
| VSync | Boolean | False | Limit frame rate between FixedFrameRate and monitor refresh rate. |
| NearPlane | Single | 0.1 | Near plane rendering clipping distance. |
| FarPlane | Single | 10000.0 | Far plane rendering clipping distance. |
| Property | Type | Default | Description |
|---|---|---|---|
| RenderWidth | Integer | 0 | Fixed render resolution width in pixels. Only effective if RenderWidth AND RenderHeight are greater than 0, then RenderScale is ignored. 0 = native resolution. At runtime prefer SetRenderSize to change both at once. |
| RenderHeight | Integer | 0 | Fixed render resolution height in pixels. See RenderWidth. |
| RenderScale | Single | 1 | Factor on the native resolution (incl. the HighRes display scale), if no fixed resolution is set. 0.5 renders a quarter of the pixels, values above 1 render supersampled. Uniform, so the aspect ratio stays the one of the viewport. Clamped to 0.1 .. 4. |
| RenderFit | TGorillaRenderFit | rfLetterbox | Placement of a fixed resolution with a different aspect ratio than the viewport: letterbox (centered, black borders) or stretch (distorted, fills the viewport). No effect with RenderScale. |
| RenderFilter | TGorillaRenderFilter | rflLinear | Interpolation when the image is scaled onto the viewport: linear or nearest (blocky). Only relevant if the render resolution differs from the viewport. Nearest only works on canvases that honor the HighSpeed flag of TCanvas.DrawBitmap (Direct2D, Skia); the FMX GPU canvas always scales linear. |
Changing RenderWidth, RenderHeight, RenderScale or RenderFit rebuilds the render targets of the viewport and of all render passes without an individual size, like a resize. RenderFilter only repaints. See Render Resolution and Scaling.
| Property | Type | Default | Description |
|---|---|---|---|
| Fog | Boolean | False | Enable or disable fog computation. |
| FogKind | TGorillaFogKind | fkLinear | Fog computation mode: fkLinear, fkExp, or fkExp2. |
| FogDensity | Single | - | Density of computed fog. |
| FogStart | Single | - | Lower limit of fog by distance. |
| FogEnd | Single | - | Upper limit of fog by distance. |
| FogColor | TAlphaColor | - | Fog color (TAlphaColor format). |
| FogColorF | TAlphaColorF | - | Fog color (TAlphaColorF format). |
| Property | Type | Default | Description |
|---|---|---|---|
| OpaqueSaturation | Single | 0.0 | Saturation of opaque object rendering (ForwardRenderer/DeferredRenderer only). |
| TranslucentSaturation | Single | 1.5 | Saturation of translucent object rendering (ForwardRenderer/DeferredRenderer only). |
| CompositeSaturation | Single | 0.0 | Saturation of final composition (ForwardRenderer/DeferredRenderer only). |
| EmissiveBlur | Integer | 0 | Emissive rendering blurring intensity. 0 deactivates. Higher values affect performance. |
| FXAA | Integer | 0 | Number of FXAA anti-aliasing steps (0-8). Higher values = softer edges but lower performance. |
| Property | Type | Range | Description |
|---|---|---|---|
| GlobalIllumDetail | Integer | 0-7 | Detail level of global illumination. 0=off, 1-7=increasing voxel sizes (32-512). |
| GlobalIllumSoftness | Single | 0.0-5.0 | Softness of global illumination including shadows and reflections. |
| ShadowStrength | Single | 0.0-10.0 | Strength/darkness of shadows in global illumination. |
| ReflectionStrength | Single | 0.0-10.0 | Strength/intensity of reflections in global illumination. |
| Property | Type | Description |
|---|---|---|
| DesignPosition | TPosition3D | Design camera target position (for design-time usage). |
| DesignRotationAngle | TPosition3D | Design camera target rotation angle (for design-time usage). |
| UsingDesignCamera | Boolean | Use the built-in design camera or custom camera. |
| Property | Type | Default | Description |
|---|---|---|---|
| DiagnosticsActive | Boolean | False | Shows the diagnostics overlay. Only the display - the values are measured by DiagnosticsMeasuring. While the overlay is shown, the values are measured in any case. |
| DiagnosticsMeasuring | Boolean | True | Collects the frame statistics (Diagnostics, FramesPerSecond, FPS). Switch off to save the measuring work per frame; the frame rates then read 0. Does not affect DeltaTime, CurrentFrameTime, PreviousFrameTime, OnBeforeRender and OnAfterRender. |
| RendererOutputLayer | TRendererOutputLayer | - | Control which renderer output layers to display. |
Standard FireMonkey properties: Align, Anchors, Camera, ClipChildren, ClipParent, Color, Cursor, DragMode, EnableDragHighlight, Enabled, Height, HitTest, Locked, Padding, MSAA, Margins, Opacity, PopupMenu, Position, RotationAngle, RotationCenter, Scale, Size, Visible, Width.
| Event | Type | Description |
|---|---|---|
| OnBeforeRender | TGorillaFrameEvent | Called once per rendered frame, BEFORE the scene is rendered - the place for per-frame logic, changes show in this frame. Runs on the main thread inside the render lock: moving, adding or removing objects is fine; freeing the viewport, calling ProcessMessages or RenderManual is not. |
| OnAfterRender | TGorillaFrameEvent | Called once per rendered frame, AFTER the frame is complete and the render lock is released. Changes show from the next frame on. Suited for reading Diagnostics or capturing the image. |
Both events fire only for frames that are really rendered (never for a paint that only shows the previous image), with and without UseFixedFrameRate, and not at design time. Unlike OnPaint, which follows FMX painting, they match the rendered frames 1:1. See Frame Timing and Per-Frame Logic.
Standard FireMonkey events: OnDragDrop, OnDragEnd, OnDragEnter, OnDragLeave, OnDragOver, OnKeyDown, OnKeyUp, OnClick, OnDblClick, OnCanFocus, OnEnter, OnExit, OnMouseDown, OnMouseMove, OnMouseUp, OnMouseWheel, OnMouseEnter, OnMouseLeave, OnPainting, OnPaint, OnResize, OnResized.
procedure BeginUpdate(); override;
procedure EndUpdate(); override;
procedure EndUpdateWithoutInvalidate(); virtual;
Batch property changes into single render instruction to optimize performance.
procedure Lock(); virtual;
procedure Unlock(); virtual;
Lock/unlock the viewport for thread-safe operations.
procedure Invalidate(); virtual;
Mark the viewport for redraw.
procedure RenderManual(); virtual;
Manually trigger rendering when ManualRendering is enabled.
procedure ForceUpdateEffects(); virtual;
Force update of all rendering effects.
procedure RebuildRenderingList(); virtual;
procedure RenderRenderList(const ARenderContext: PRenderContext);
procedure RenderRenderListByMode(AOpaque: Boolean);
Manage and render the list of 3D objects.
procedure AddRenderPass(const AController: TComponent); virtual;
procedure RemoveRenderPass(const AController: TComponent); virtual;
procedure UpdateRenderPasses(); virtual;
procedure UpdateRenderPassesOnResize(); virtual;
procedure CleanupRenderPasses(const AController: TComponent); virtual;
Manage custom render passes in the pipeline.
function ScreenToWorld(const APoint2D: TPointF): TPoint3D; virtual;
function WorldToScreen(const APoint3D: TPoint3D): TPointF; virtual;
Convert between screen and world coordinates. The 2D point is in local viewport coordinates, also with a changed render resolution: scale, letterbox offset and stretch are mapped internally.
procedure SetRenderSize(const AWidth, AHeight: Integer); overload;
procedure SetRenderSize(const ASize: TPoint); overload;
Set RenderWidth and RenderHeight at once with a single rebuild of the render targets. Setting both properties one after the other rebuilds twice, and the first rebuild runs with a mixed, unwanted resolution. Negative values are treated as 0. SetRenderSize(0, 0) switches back to the native resolution.
function IsRenderScaled(): Boolean;
function HasFixedRenderResolution(): Boolean;
IsRenderScaled is True if the scene is not rendered in the native resolution, because a fixed resolution or a RenderScale other than 1 is set. HasFixedRenderResolution is True if RenderWidth and RenderHeight are both greater than 0.
function GetRenderTargetSize(): TPoint;
Size in pixels of the main render target - the resolution the scene is really rendered in. Either the fixed RenderWidth x RenderHeight, or the viewport size multiplied by the display scale (HighRes) and RenderScale (at least 1 x 1 for a visible viewport). Render passes without an individual size use the same.
function GetRenderDisplayRect(): TRectF;
Rectangle in local viewport coordinates the rendered image is shown in. LocalRect, except for a fixed resolution with rfLetterbox.
function GetRenderAspectRatio(): Single;
Aspect ratio (width / height) of the rendered image - the one the camera projection is built with.
function ViewToRenderPoint(const APoint: TPointF): TPointF;
function RenderToViewPoint(const APoint: TPointF): TPointF;
Convert a point in local viewport coordinates (e.g. a mouse position) into the coordinate space the render context expects for picking (TContext3D.Pick, TGorillaContext.ScreenToWorld), and back. Identity, as long as neither a render resolution nor HighRes on a scaled display is in use. Only needed if you call the context yourself - the viewport methods above already convert.
function ObjectAtPoint(P: TPointF): IControl; override;
function RayCastIntersect(const P: TPointF): TControl3D; virtual;
Find objects at specific screen positions using raycasting.
function GetDesignCamera(): TCamera; virtual;
function GetDesignCameraController(): TGorillaSmoothCameraController; virtual;
Access the built-in design camera and controller.
function MakeScreenshot(): FMX.Graphics.TBitmap;
Capture the current viewport rendering as a bitmap. The bitmap has the size of the viewport (multiplied by the display scale), not the render resolution; an image of a different resolution is scaled in as shown on screen, letterbox borders stay transparent.
procedure ShowGizmo(); overload;
procedure ShowGizmo(const ACtrl: TControl3D); overload;
procedure ChangeGizmoMode(const AMode: Byte);
procedure HideGizmo();
function IsGizmoActive(): Boolean;
function GetGizmoActivatedControl(): TControl3D;
Control the design-time gizmo for object manipulation.
procedure StartDesignMode();
procedure EndDesignMode();
Enter and exit design mode programmatically.
procedure UpdateDisplayRefreshRate(); virtual;
Update the cached display refresh rate.
Helper class for rendering operations.
class function Renderable(const ACtrl: TControl3D; const AFrustum: TGorillaFrustum;
const AComponentState: TComponentState; var ASceneBounds: TBoundingBox;
const AFrustumCulling: Boolean; const ACheckVisibility: Boolean): Boolean;
Determine if a control should be rendered based on frustum culling and visibility.
class procedure UpdateSceneBounds(const ACtrl: TControl3D;
const AComponentState: TComponentState; var ASceneBounds: TBoundingBox);
Update scene bounds based on a control's bounding box.
Enumeration for fog modes (wrapper for TGorillaFogMode).
Values:
fkLinear - Linear fog calculationfkExp - Exponential fog calculationfkExp2 - Exponential squared fog calculationPlacement of the image of a fixed render resolution whose aspect ratio differs from the viewport. Scoped enum - write TGorillaRenderFit.rfLetterbox.
Values:
rfLetterbox - Keep the aspect ratio of the render resolution, center the image and fill the borders black (default)rfStretch - Stretch the image onto the whole viewport (distorted, like a low resolution in fullscreen mode)Interpolation of the rendered image when it is scaled onto the viewport. Scoped enum - write TGorillaRenderFilter.rflLinear.
Values:
rflLinear - Smooth (bilinear) scaling (default)rflNearest - Blocky scaling, e.g. for a pixel-art lookTGorillaFrameEvent = procedure(ASender: TObject; const ADeltaTime: Double) of object;
Event type of OnBeforeRender and OnAfterRender. ADeltaTime is TGorillaViewport.DeltaTime in seconds.
Record containing rendering performance diagnostics. Measured while TGorillaViewport.DiagnosticsMeasuring or DiagnosticsActive is set; the averages and frame rates are updated once per measure window of AverageFrameTimeClip (30) frames.
Fields:
Enabled - Overlay shown (= DiagnosticsActive). Not the measuring switchTotalFrames - Total number of frames rendered while measuringAverageFrameTime - Average work per frame in milliseconds, without the idle time between two framesAverageFramesPerSecond - Headroom: 1000 / AverageFrameTime, the rate the renderer could sustainRealFramesPerSecond - Output: frames per second of wall clock, including frame limits (= TGorillaViewport.FramesPerSecond)DrawCalls - Number of draw callsDrawInstances - Number of draw instancesTotalVertexCount - Total vertices processedTotalIndexCount - Total indices processedRenderPasses - Number of render passesRenderListSize - Size of rendering listRenderedObjects - Number of objects renderedDisplayRefreshRate - Monitor refresh rateGORILLA_FRAMERATE_FIXED_DEFAULT = 60; // All platforms
Compatibility: TGorillaViewport replaces FireMonkey's TViewport3D and TForm3D. They are not compatible.
Fog Requirements: Fog effect requires TGorillaDefaultMaterialSource materials and is incompatible with standard FMX materials.
Performance: Use BeginUpdate/EndUpdate to batch property changes. Enable ManualRendering for better control over rendering cycles. Set DiagnosticsMeasuring to False if no frame statistics are needed.
Per-frame logic: Use OnBeforeRender and DeltaTime instead of OnPaint or a timer. DeltaTime is not clamped - limit it after pauses (debugger, hidden window).
Frustum Culling: Improves performance but may affect render passes using different view matrices.
Global Illumination: Only available in GAME_PACKAGE edition.
Render Resolution: RenderScale or a fixed resolution (SetRenderSize) changes only the internal render targets, not the monitor resolution. Do not change them every frame - each change rebuilds all render targets.
The Gorilla.Volumetric.Mesh unit provides TGorillaVolumetricMesh, a mesh that renders a 3D scalar field (a volume) with GPU ray marching. It reads its data from a 3D texture and composites the samples along each ray. It is used for medical/scientific volume visualization and is the base class of TGorillaVolumetricNoise.
The mesh embeds a TGorillaVolumetricMeshMaterialSource that exposes most of the rendering parameters; the mesh forwards them, so you normally only touch the mesh.
TGorillaSingletonMesh
└── TGorillaVolumetricMesh
└── TGorillaVolumetricNoise (see separate reference)
TGorillaVolumetricMeshSize = (vms4x4x4, vms8x8x8, vms16x16x16, vms32x32x32,
vms64x64x64, vms128x128x128, vms256x256x256, vms512x512x512, vms768x768x768,
vms1024x1024x1024, vmsCustom);
TGorillaVolumetricMeshDataType = (vmdtUInt8, vmdtUInt16, vmdtHalfFloat, vmdtFloat,
vmdtRGBUInt8, vmdtRGBAUInt8, vmdtRGBFloat, vmdtRGBAFloat);
TGorillaVolumetricMeshShape = (vmsCube, vmsSphere, vmsCylinder);
TGorillaVolumetricMeshByteOrder = (vmboLittleEndian, vmboBigEndian);
TGorillaVolumetricGamutMode = (GamutNone, GamutByValue, GamutByValueMultiply,
GamutBySum, GamutBySumMultiply);
TRayCastDistanceMethod = (rcdNone, rcdTexture, rcdFocused, rcdLinear, rcdInvLinear,
rcdQuadratic, rcdInvQuadratic, rcdLogN, rcdInvLogN, rcdGaussian);
| Property | Type | Description |
|---|---|---|
Sizes |
TGorillaVolumetricMeshSize |
Fixed cubic volume resolution, or vmsCustom |
CustomWidth / CustomHeight / CustomDepth |
Integer |
Per-axis slice counts when Sizes = vmsCustom (adjusted to multiples of 2) |
DataType |
TGorillaVolumetricMeshDataType |
Format of a single voxel |
Spacings |
TPoint3D |
Spacing between voxels/slices (for compressed scans) |
Shape |
TGorillaVolumetricMeshShape |
Surrounding projection shape (cube/sphere/cylinder) |
| Property | Type | Description |
|---|---|---|
Details |
Single |
Ray-march step density (steps ≈ Slices × Details). Higher = finer/slower |
RayStop |
Single |
Alpha value at which a ray terminates early (default 0.95) |
RayLimits |
TPoint |
Ray front offset (X) and back reduction (Y) |
Dithering |
Boolean |
Per-pixel ray-start jitter to remove step banding (default True) |
LinearFiltering |
Boolean |
Trilinear filtering of the 3D texture |
MipMaps |
Boolean |
Mip-map minification filtering |
TextureInterpolation |
TTextureInterpolation |
Sampling of the front/back-face position textures |
RenderInside |
Boolean |
Two-sided rendering so the camera can fly inside the volume |
| Property | Type | Description |
|---|---|---|
UseLighting |
Boolean |
Enable iso-surface lighting |
IsoSurfaceLimit |
Single |
Threshold that defines the lit surface |
ShadingModel |
TGorillaShadingModel |
Shading model when lighting is on |
ShadingIntensity |
Single |
Shading strength |
Brightness |
Single |
Final color brightness |
| Property | Type | Description |
|---|---|---|
Gamut |
TBitmap |
Transfer-function (color) texture |
GamutMode |
TGorillaVolumetricGamutMode |
How the gamut is applied |
GamutFactor |
Single |
Value factor before mapping onto the gamut |
GamutIntensity |
Single |
RGB contribution of the gamut |
GamutAlphaIntensity |
Single |
Alpha contribution of the gamut |
| Property | Type | Description |
|---|---|---|
Overlay |
TBitmap |
Overlay texture projected onto the volume |
UseOverlay |
Boolean |
Enable overlay rendering |
OverlayIntensity |
Single |
Overlay strength |
ClippingPlane |
TPlaneF |
Clipping plane for slice selection |
IntensityMode / AlphaIntensityMode |
TRayCastDistanceMethod |
Distance-based value / alpha modulation |
IntensityFocus / IntensityExp |
Single |
Focus band parameters for rcdFocused |
AlphaIntensityFocus / AlphaIntensityExp |
Single |
Alpha focus band parameters for rcdFocused |
RayIntensityTexture / RayAlphaIntensityTexture |
TBitmap |
1D textures used when the mode is rcdTexture |
BeforeRaytracingFunc |
TStrings |
Custom GLSL run before ray marching (advanced) |
BlendFunc |
TStrings |
Custom GLSL compositing function (advanced) |
| Property | Type | Description |
|---|---|---|
FrontFaceRenderPass |
TGorillaRenderPassController |
Pass providing ray entry positions (required) |
BackFaceRenderPass |
TGorillaRenderPassController |
Pass providing ray exit positions (required) |
OnUpdateTexture3D |
TOnUpdateTexture3D |
Fired when the internal 3D texture is (re)built |
| Property | Type | Description |
|---|---|---|
CustomSize |
TSize3D |
Non-adjusted custom volume size (not stored in DFM) |
| Method | Description |
|---|---|
SetEmissionAbsorptionBlend(AAbsorptionScale = 1.0) |
Switch to the physically based emission-absorption (Beer-Lambert) blend for translucent media (fog/clouds/smoke). The scale is resolution-independent (1.0 = neutral). |
SetLinearBlend() |
Restore the default linear front-to-back compositing (solid / lit objects). |
| Method | Description |
|---|---|
SetRawData(AData, ASize, ADoCopyData = True) |
Upload a raw voxel buffer directly |
ClearRawData() |
Release the cached raw data |
PushRawData() |
Re-upload the cached raw data to the 3D texture |
LoadFromRawFile(AFileName, AWidth, AHeight, ADepth, ASrcDataType, AByteOrder, AOffset) |
Load a RAW volume file |
LoadFromRawStream(AStream, AWidth, AHeight, ADepth, ASrcDataType, AByteOrder, AOffset) |
Load a RAW volume from a stream |
LoadFromNRRDFile(AFileName, AByteOrder) |
Load an NRRD volume file (size/type from header) |
LoadFromNRRDStream(AStream, AByteOrder) |
Load an NRRD volume from a stream |
LoadFromImageSlices(APath, AFileNamePattern, AFromIdx, AToIdx, APadLeftLen, APadChar, ATexWidth, ATexHeight, ATexDepth) |
Assemble a volume from numbered 2D image slices |
| Method | Returns | Description |
|---|---|---|
GetSizeAsVector() |
TPoint3D |
Current volume resolution as width/height/depth |
BeginUpdate() / EndUpdate() |
— | Batch Sizes / DataType changes to rebuild the texture once |
TOnUpdateTexture3D = procedure(ASender: TObject;
ATexture: TGorillaTextureBitmap) of object;
TGorillaRenderPassFace, unit Gorilla.Controller.Passes.Face) to obtain ray entry/exit positions.UseLighting); SetEmissionAbsorptionBlend produces translucent media. Lit iso-surface hits are refined to sub-sample precision for smooth shading.IsoSurfaceLimit), so it never affects fog/clouds.The Gorilla.Volumetric.Noise unit provides TGorillaVolumetricNoise, a ready-to-use procedural cloud / smoke / fog body. It subclasses TGorillaVolumetricMesh, fills its own 3D texture with fractal (FBM) Perlin noise, and renders it as a physically based emission-absorption medium you can fly through.
The constructor applies cloud-friendly defaults: Sizes = vms64x64x64, DataType = vmdtUInt8, RenderInside = True, UseLighting = False, LinearFiltering = True, and the emission-absorption blend (with Density driving the absorption). All properties inherited from TGorillaVolumetricMesh remain available.
TGorillaSingletonMesh
└── TGorillaVolumetricMesh
└── TGorillaVolumetricNoise
TGorillaVolumetricNoisePreset = (vnpClouds, vnpSmoke, vnpFog);
| Value | Look |
|---|---|
vnpClouds |
Puffy cumulus clouds (billowy, rounded, medium coverage). Default. |
vnpSmoke |
Denser, more filled smoke body. |
vnpFog |
Thin, evenly distributed haze. |
| Property | Type | Default | Description |
|---|---|---|---|
Seed |
LongWord |
1500 |
Random seed of the Perlin generator |
Frequency |
Single |
3.0 |
Base noise scale (cycles across the volume) |
Octaves |
Integer |
5 |
Number of FBM octaves summed for detail |
Persistence |
Single |
0.5 |
Amplitude falloff per octave (0–1) |
Lacunarity |
Single |
2.0 |
Frequency growth per octave |
Coverage |
Single |
0.9 |
Cloud coverage 0–1 (lower = fewer/smaller puffs) |
Density |
Single |
1.5 |
Overall opacity (render-time absorption scale) |
EdgeFalloff |
Single |
0.5 |
Border fade 0–1 (rounded blob vs. filled cube) |
Billowy |
Boolean |
True |
Use abs() noise for the puffy cumulus / smoke look |
Changing any shaping property (except Density) re-samples the volume automatically. Density only rebuilds the render-time blend, so it is cheap to change.
| Property | Type | Description |
|---|---|---|
Offset |
TPoint3D |
Sampling offset added to every voxel. Animate it (and call Regenerate) to make the body drift like moving smoke. |
| Method | Description |
|---|---|
ApplyPreset(APreset) |
Load a complete set of shaping parameters (vnpClouds / vnpSmoke / vnpFog) and rebuild the volume |
Regenerate() |
Re-sample the noise volume from the current parameters and upload it. Call after changing Offset for animation. |
From TGorillaVolumetricMesh:
| Member | Note for noise bodies |
|---|---|
Sizes |
Volume resolution — drop to vms32x32x32 for animated bodies |
Details |
Ray-march quality/performance dial |
RenderInside |
True by default so you can fly through |
RayStop |
Ray termination alpha |
SetEmissionAbsorptionBlend / SetLinearBlend |
The noise uses emission-absorption; Density feeds its absorption scale |
FrontFaceRenderPass / BackFaceRenderPass |
Required face passes (as for any volumetric mesh) |
Density is applied as a render-time Beer-Lambert absorption scale, not baked into the voxel data. This keeps dense bodies smooth (no saturation "shells") and makes Density cheap and safe to animate.Regenerate re-samples the whole volume on the CPU — the costly part of animation. Use a modest Sizes and a timer rather than a per-frame update.This unit implements Screen-Space Ambient Occlusion (SSAO) for the Gorilla3D deferred rendering pipeline. It computes per-pixel ambient occlusion by sampling a hemisphere kernel in screen space, using position and normal G-buffer data.
The unit defines two classes:
TGorillaRenderPassSSAO -- The standalone SSAO pass.TGorillaRenderPassEmbeddedSSAO -- A variant used internally by the deferred composite system.SSAO uses a 128-sample hemisphere kernel and a 4x4 noise texture for randomized sample rotation. The kernel and noise data are transferred to the GPU via a Uniform Buffer Object (UBO) named SSAOShaderData, providing efficient bulk data transfer.
The pass is a post-pass using RectToFBO rendering. It is marked as an internal render pass (IsInternalRenderPass = True), meaning it is typically managed by the deferred composite rather than used standalone.
Inherits from: TGorillaRenderPassController
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TGorillaRenderPassController |
nil | Input render pass providing the position G-buffer texture. |
Normals |
TGorillaRenderPassController |
nil | Input render pass providing the normals G-buffer texture. |
Radius |
Single |
1.0 | Radius of the sampling hemisphere in world units. Larger values detect occlusion over a wider area. |
Bias |
Single |
0.5 | Depth comparison bias to prevent self-occlusion artifacts. |
NoiseScale |
TPointF |
(1, 1) | Scale factor for the noise texture tiling. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Inherits from: TGorillaRenderPassSSAO
An embedded variant designed for use within the deferred composite pipeline. Functionally identical to TGorillaRenderPassSSAO but integrated into the deferred rendering workflow.
uses
Gorilla.Controller.Passes.SSAO;
var
LSSAOPass: TGorillaRenderPassSSAO;
begin
LSSAOPass := TGorillaRenderPassSSAO.Create(nil);
LSSAOPass.Viewport := GorillaViewport1;
LSSAOPass.Position := MyPositionPass;
LSSAOPass.Normals := MyNormalsPass;
LSSAOPass.Radius := 1.5;
LSSAOPass.Bias := 0.25;
LSSAOPass.NoiseScale := PointF(1, 1);
LSSAOPass.Enabled := True;
end;
SSAOShaderDataRadius.This unit implements Fast Approximate Anti-Aliasing (FXAA) for the Gorilla3D rendering pipeline. FXAA is a post-processing technique that smooths jagged edges by detecting and blending high-contrast boundaries using luminance analysis.
FXAA operates as a post-pass using RectToFBO rendering with blending disabled. It runs in a single iteration and is marked as an internal render pass (IsInternalRenderPass = True), meaning it is typically managed automatically by the deferred composite system.
Inherits from: TGorillaRenderPassController
| Method | Signature | Description |
|---|---|---|
Create |
constructor Create(AOwner: TComponent) |
Creates the FXAA pass and compiles the FXAA shader. |
Destroy |
destructor Destroy() |
Cleans up resources. |
SetCompositeInputTexture |
Method | Assigns the input texture from the composite pass to be anti-aliased. |
GetFinalOutputTexture |
Function | Returns the resulting anti-aliased texture for use by subsequent passes or final display. |
uses
Gorilla.Controller.Passes.FXAA;
var
LFXAAPass: TGorillaRenderPassFXAA;
begin
LFXAAPass := TGorillaRenderPassFXAA.Create(nil);
LFXAAPass.Viewport := GorillaViewport1;
LFXAAPass.Enabled := True;
end;
TRenderPassType.Post)This unit implements planar reflections for the Gorilla3D rendering pipeline. It renders a mirrored view of the scene from a virtual camera positioned on the opposite side of a reflective plane, producing a reflection texture that can be applied to flat reflective surfaces such as floors, water, or mirrors.
The reflection pass is a pre-pass using RenderListToFBO -- it re-renders scene objects into an off-screen FBO using a mirrored camera. The mirror matrix is computed internally using ray-plane intersection, and a clip plane prevents rendering of geometry behind the mirror surface.
Inherits from: TGorillaRenderPassController
| Property | Type | Default | Description |
|---|---|---|---|
Camera |
TCamera |
nil | The scene camera. The reflection pass creates a mirrored version of this camera for rendering. |
Target |
TControl3D |
nil | The reflective surface object. This object is excluded from the reflection render to prevent self-reflection artifacts. |
MirrorPosition |
TPoint3D |
(0, 0, 0) | World-space position of the mirror plane. |
MirrorNormal |
TPoint3D |
(0, -1, 0) | Normal vector of the mirror plane, pointing away from the reflective side. |
MirrorSize |
Single |
10 | Size of the mirror surface, used for clipping calculations. |
| Method | Description |
|---|---|
CalcMirrorMatrix |
Computes the mirror transformation matrix using ray-plane intersection. Called internally before each render. |
uses
Gorilla.Controller.Passes.Reflection;
var
LReflection: TGorillaRenderPassReflection;
begin
LReflection := TGorillaRenderPassReflection.Create(nil);
LReflection.Viewport := GorillaViewport1;
LReflection.Camera := Camera1;
LReflection.Target := FloorPlane;
LReflection.MirrorPosition := Point3D(0, 0, 0);
LReflection.MirrorNormal := Point3D(0, -1, 0);
LReflection.MirrorSize := 20;
LReflection.Enabled := True;
end;
After enabling the reflection pass, assign its output texture to the reflective material's reflection texture slot to display the reflection on the surface.
TRenderPassType.Pre)MirrorNormal default of (0, -1, 0) is oriented for a horizontal floor reflection. For vertical mirrors, adjust the normal accordingly (e.g., (0, 0, 1) for a wall mirror facing the Z direction).Target property is important for preventing the mirror surface itself from appearing in the reflection, which would cause visual artifacts.This unit implements a depth-of-field (DoF) post-processing effect with bokeh simulation for the Gorilla3D rendering pipeline. It produces realistic camera focus blur with configurable focal parameters, pentagon-shaped bokeh, chromatic aberration, and vignetting.
The bokeh pass is a post-pass using RectToFBO rendering. It requires a depth pass as input (set via SetInputPass) to read per-pixel depth values. The shader samples surrounding pixels in concentric rings to simulate the blur circle of confusion, with the blur intensity determined by the distance from the focal plane.
TGorillaBokehType = (btDefault, btGlow);
| Value | Description |
|---|---|
btDefault |
Standard depth-of-field blur |
btGlow |
Bokeh with enhanced glow effect |
Inherits from: TGorillaRenderPassController
| Property | Type | Default | Description |
|---|---|---|---|
FocalDepth |
Single |
10 | Distance from the camera to the focal plane (in-focus region). |
FocalLength |
Single |
75 | Simulated lens focal length in mm. Affects the size of the blur circle. |
Vignette |
Single |
16 | Vignette darkening intensity at screen edges. |
VignetteFade |
Single |
24 | Distance over which the vignette fades from edge to center. |
FrustumNearFar |
TPointF |
(1, 100) | Camera frustum near (X) and far (Y) plane distances. Must match the camera settings. |
BlurSamples |
Integer |
4 | Number of blur samples per ring. Clamped to range 1..16. Higher values produce smoother blur at higher cost. |
BlurRings |
Integer |
4 | Number of concentric blur rings. Clamped to range 1..16. More rings increase the maximum blur radius. |
ShowFocus |
Boolean |
False | When True, renders a visual indicator of the focus plane for debugging. |
AutoFocus |
Boolean |
True | When True, automatically focuses on the object at screen center using the depth buffer. |
BokehType |
TGorillaBokehType |
btDefault |
Bokeh rendering style. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure SetInputPass(AValue: TGorillaRenderPassController);
Unit: Gorilla.Bokeh
TGorillaBokeh is a design-time convenience component that wraps a TGorillaRenderPassCustomDepth and a TGorillaRenderPassBokeh into a single droppable component. It exposes the same published properties as the bokeh pass.
| Property | Type | Description |
|---|---|---|
Viewport |
TGorillaViewport |
Target viewport |
Enabled |
Boolean |
Enable/disable the effect |
FocalDepth |
Single |
Focal plane distance |
FocalLength |
Single |
Lens focal length |
Vignette |
Single |
Vignette intensity |
VignetteFade |
Single |
Vignette fade |
FrustumNearFar |
TPointF |
Near/far planes |
BlurSamples |
Integer |
Samples per ring |
BlurRings |
Integer |
Concentric rings |
ShowFocus |
Boolean |
Focus plane debug view |
AutoFocus |
Boolean |
Auto-focus on center |
| Property | Type | Description |
|---|---|---|
DepthPass |
TGorillaRenderPassCustomDepth |
The internal depth pass |
MainPass |
TGorillaRenderPassBokeh |
The internal bokeh pass |
uses
Gorilla.Bokeh;
var
LBokeh: TGorillaBokeh;
begin
LBokeh := TGorillaBokeh.Create(GorillaViewport1);
LBokeh.Viewport := GorillaViewport1;
LBokeh.FocalDepth := 15;
LBokeh.FocalLength := 50;
LBokeh.BlurSamples := 6;
LBokeh.BlurRings := 6;
LBokeh.AutoFocus := True;
LBokeh.Enabled := True;
end;
uses
Gorilla.Controller.Passes.CustomDepth,
Gorilla.Controller.Passes.Bokeh;
var
LDepth: TGorillaRenderPassCustomDepth;
LBokeh: TGorillaRenderPassBokeh;
begin
LDepth := TGorillaRenderPassCustomDepth.Create(nil);
LDepth.Viewport := GorillaViewport1;
LDepth.Enabled := True;
LBokeh := TGorillaRenderPassBokeh.Create(nil);
LBokeh.Viewport := GorillaViewport1;
LBokeh.SetInputPass(LDepth);
LBokeh.FocalDepth := 15;
LBokeh.FocalLength := 50;
LBokeh.Enabled := True;
end;
TRenderPassType.Post)FocalLength.BlurSamples * BlurRings determines the total number of texture lookups per pixel. Values of 4x4 (16 total samples) provide a good quality/performance balance.This unit implements global illumination (GI) using voxel cone tracing for the Gorilla3D deferred rendering pipeline. It computes indirect lighting, soft shadows, and reflections by tracing cones through a voxelized representation of the scene.
The unit defines two classes:
TGorillaRenderPassGlobalIllum -- The standalone global illumination pass.TGorillaRenderPassEmbeddedGlobalIllum -- A variant used internally by the deferred composite system.The GI pass is a post-pass using RectToFBO rendering. It is marked as an internal render pass (IsInternalRenderPass = True). It reads position and normal G-buffers and samples a 3D voxel texture (produced by TGorillaRenderPassVoxelize) to compute:
Light data (up to 8 lights) is transferred to the GPU via a Uniform Buffer Object (UBO).
Inherits from: TGorillaRenderPassController
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TGorillaRenderPassController |
nil | Input render pass providing the position G-buffer texture. |
Normals |
TGorillaRenderPassController |
nil | Input render pass providing the normals G-buffer texture. |
VoxelGeometry |
TGorillaRenderPassController |
nil | The voxelization pass (TGorillaRenderPassVoxelize) providing the 3D voxel texture. |
ShadowStrength |
Single |
0.4 | Strength of indirect shadows. Higher values produce darker indirect shadows. |
ReflectionStrength |
Single |
0.0 | Strength of indirect reflections. Set to 0 by default (reflections disabled). Increase to add voxel-based reflections. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
Inherits from: TGorillaRenderPassGlobalIllum
An embedded variant designed for use within the deferred composite pipeline. Functionally identical to TGorillaRenderPassGlobalIllum but integrated into the deferred rendering workflow.
The voxelization pass (TGorillaRenderPassVoxelize) must be set up first to provide the 3D voxel texture:
| Property | Type | Default | Description |
|---|---|---|---|
VoxelSize |
Integer |
-- | Voxel grid resolution (32..512, multiples of 32) |
FocalLength |
Single |
-- | Focal length for voxel projection |
Public properties include VoxelCenter (TPoint3D), BiasMatrix (TMatrix3D), and GetTexture3D (returns the 3D texture).
Constants: VOXEL_LOD = 8 (LOD levels used internally), VOXEL_MAX_LIGHTS = 8.
TGorillaRenderPassGlobalIllumBlur extends TGorillaRenderPassBlur to smooth the GI output:
| Property | Type | Description |
|---|---|---|
GlobalIllumPass |
TGorillaRenderPassGlobalIllum |
The GI pass whose output to blur |
UpdateTexture |
Method | Updates the input texture reference |
Default blur amount is 1. Marked as internal render pass.
uses
Gorilla.Controller.Passes.Voxelize,
Gorilla.Controller.Passes.GlobalIllumination;
var
LVoxel: TGorillaRenderPassVoxelize;
LGI: TGorillaRenderPassGlobalIllum;
begin
// 1) Create voxelization pass
LVoxel := TGorillaRenderPassVoxelize.Create(nil);
LVoxel.Viewport := GorillaViewport1;
LVoxel.Enabled := True;
// 2) Create global illumination pass
LGI := TGorillaRenderPassGlobalIllum.Create(nil);
LGI.Viewport := GorillaViewport1;
LGI.Position := MyPositionPass;
LGI.Normals := MyNormalsPass;
LGI.VoxelGeometry := LVoxel;
LGI.ShadowStrength := 0.5;
LGI.ReflectionStrength := 0.2;
LGI.Enabled := True;
end;
TRenderPassType.Post)ShadowStrength and ReflectionStrength properties control the intensity of these contributions in the final composite.This unit implements a customizable post-processing render pass for the Gorilla3D rendering pipeline. It allows users to supply their own GLSL fragment shader code to create custom visual effects, with access to the deferred rendering G-buffer textures and time information.
The PostFX pass is a post-pass using RectToFBO rendering. It compiles a user-provided GLSL surface shader function and executes it as a full-screen post-processing effect. A Uniform Buffer Object (UBO) provides time data for animated effects.
Inherits from: TGorillaRenderPassController
| Property | Type | Default | Description |
|---|---|---|---|
SurfaceShader |
TStrings |
nil | The custom GLSL shader code. Must contain a function with the signature vec3 SurfaceShader(inout TLocals DATA). |
MaskTexture |
TBitmap |
nil | An optional mask texture accessible in the shader as _MaskTexture. |
| Method | Signature | Description |
|---|---|---|
Create |
constructor Create(AOwner: TComponent) |
Creates the PostFX pass. |
Destroy |
destructor Destroy() |
Cleans up resources. |
ResetTime |
Procedure | Restarts the internal stopwatch and sets all _TimeInfo components to zero. Useful for restarting time-based animations. |
UpdateShader |
Procedure | Recompiles the shader program after modifying SurfaceShader. Must be called after changing the shader text at runtime. |
Your custom GLSL code must implement the following function:
vec3 SurfaceShader(inout TLocals DATA)
The DATA structure provides access to the current fragment's color and other per-pixel information. The function returns the final RGB color for the fragment.
The following sampler uniforms are available in the shader:
| Uniform | Type | Description |
|---|---|---|
_RenderedTexture |
sampler2D |
The main rendered scene texture (color buffer). |
_MaskTexture |
sampler2D |
The user-supplied mask texture (from the MaskTexture property). |
_AlphaTexture |
sampler2D |
Alpha channel from the G-buffer. |
_PositionTexture |
sampler2D |
World-space position from the G-buffer. |
_NormalsTexture |
sampler2D |
World-space normals from the G-buffer. |
_EmissiveTexture |
sampler2D |
Emissive channel from the G-buffer. |
A vec4 uniform _TimeInfo is provided via a Uniform Buffer Object:
| Component | Description |
|---|---|
_TimeInfo.x |
Start time - always 0, all values are relative to the start |
_TimeInfo.y |
Current time in seconds since the pass was created or ResetTime was called |
_TimeInfo.z |
Previous frame time |
_TimeInfo.w |
Delta time (time elapsed since previous frame) |
Note: Since v1.5.3.3984 the time values are relative to the start. Before they held the absolute system timestamp in single precision, which resolved only 1/128..1/16 s on a machine running for a while - time-based effects stuttered.
_TimeInfo.y - _TimeInfo.xgives the same result as before.
uses
Gorilla.Controller.Passes.PostFX;
var
LPostFX: TGorillaRenderPassPostFX;
begin
LPostFX := TGorillaRenderPassPostFX.Create(nil);
LPostFX.Viewport := GorillaViewport1;
LPostFX.SurfaceShader.Text :=
'vec3 SurfaceShader(inout TLocals DATA) {' + sLineBreak +
' vec3 col = DATA.Color.rgb;' + sLineBreak +
' float gray = dot(col, vec3(0.299, 0.587, 0.114));' + sLineBreak +
' return vec3(gray);' + sLineBreak +
'}';
LPostFX.UpdateShader;
LPostFX.Enabled := True;
end;
LPostFX.SurfaceShader.Text :=
'vec3 SurfaceShader(inout TLocals DATA) {' + sLineBreak +
' float t = _TimeInfo.y - _TimeInfo.x;' + sLineBreak +
' vec2 uv = DATA.TexCoord;' + sLineBreak +
' uv.x += sin(uv.y * 10.0 + t) * 0.01;' + sLineBreak +
' return texture(_RenderedTexture, uv).rgb;' + sLineBreak +
'}';
LPostFX.UpdateShader;
When modifying the SurfaceShader text at runtime, always call UpdateShader afterward to recompile:
LPostFX.SurfaceShader.Clear;
LPostFX.SurfaceShader.Add('vec3 SurfaceShader(inout TLocals DATA) {');
LPostFX.SurfaceShader.Add(' return vec3(1.0, 0.0, 0.0);');
LPostFX.SurfaceShader.Add('}');
LPostFX.UpdateShader;
TRenderPassType.Post)UpdateShader is called. Shader compilation errors will be reported through the standard Gorilla3D error handling.ResetTime method restarts the stopwatch and sets all _TimeInfo components to zero, effectively restarting time-based animations from zero._PositionTexture, _NormalsTexture, etc.) are only available when the deferred rendering pipeline is active.This unit implements planar refraction for the Gorilla3D rendering pipeline. It re-renders the scene from the normal camera view into an off-screen FBO while clipping geometry against a refraction surface plane, producing a refraction texture that can be applied to transparent surfaces such as water or glass.
The refraction pass is a pre-pass using RenderListToFBO — it renders the scene from the regular camera, but a clip plane (defined by SurfacePosition / SurfaceNormal) removes geometry on the wrong side of the refractive surface. In addition to the color output the pass exposes a position/depth texture (OutputDepthTexture), which materials like TGorillaWaterMaterialSource use for depth-based edge blending.
Inherits from: TGorillaRenderPassController
Default pass id: 'Refraction'
| Property | Type | Default | Description |
|---|---|---|---|
SurfacePosition |
TPosition3D |
(0, 0, 0) | World-space position of the refraction clipping surface plane. |
SurfaceNormal |
TPosition3D |
(0, 1, 0) | Normal vector of the clipping surface, pointing to the side that is kept. |
SurfaceCutOff |
Single |
0 | Additional offset that shifts the clipping plane along its normal. |
ClippingEnabled |
Boolean |
True | Enables/disables the refraction clipping surface. |
| Property | Type | Description |
|---|---|---|
OutputDepthTexture |
TTexture |
Read-only. The position/depth texture produced by the refraction renderer. |
function GetOutputTexture() : TTexture; override;
function GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = false) : TMatrix3D; override;
procedure SetupMatrices(const AContext : TContext3D);
CreateMaterialSource() returns nil — the refraction pass renders objects with their original materials.
uses
Gorilla.Controller.Passes.Refraction;
var
LRefraction: TGorillaRenderPassRefraction;
begin
LRefraction := TGorillaRenderPassRefraction.Create(nil);
LRefraction.Viewport := GorillaViewport1;
// Configure the water surface (Y = 0 plane, normal pointing up)
LRefraction.SurfacePosition := Point3D(0, 0, 0);
LRefraction.SurfaceNormal := Point3D(0, 1, 0);
LRefraction.ClippingEnabled := True;
// Exclude the water plane itself from the refraction render
LRefraction.IgnoreControl(WaterPlane);
LRefraction.Enabled := True;
end;
Assign the pass via the material's RefractionPass property (see Materials → Reflections and Refractions).
TRenderPassType.Pre)RenderListToFBO (re-renders scene objects)SurfacePosition, SurfaceNormal and SurfaceCutOff. Set ClippingEnabled := False to capture the full scene without clipping.OutputDepthTexture exposes the position buffer so refractive materials can blend by water depth and soften surface edges.This unit renders scene depth into a single-channel floating-point texture. The resulting depth map is used for shadow mapping, depth-based post effects, soft particles, and any technique that needs per-pixel scene depth.
The custom depth pass is a pre-pass using RenderListToFBO with ListRendering (transparency sorting is skipped because it is irrelevant for depth). It renders all objects with a dedicated depth material that writes the selected Z-value into an R16F red-channel texture.
Inherits from: TGorillaRenderPassController
Default pass id: 'CustomDepth'
| Property | Type | Default | Description |
|---|---|---|---|
DepthMethod |
TDepthMethod |
dmDefault |
Selects which Z-value is stored: dmDefault (window-space gl_FragCoord.z), dmMVPPosZ (clip-space Z), dmModelViewPosZ (eye-space Z). |
| Property | Type | Default | Description |
|---|---|---|---|
MapSize |
TPoint |
viewport size | Resolution of the depth map texture. |
BiasMatrix |
TMatrix3D |
— | Read-only bias matrix for sampling the depth texture in [0..1] space. |
DefaultDepth |
Single |
1 | Depth clear value. |
DefaultColor |
TAlphaColor |
Black | Color clear value. |
function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
procedure SetupMatrices(const AContext : TContext3D);
function GetOutputTexture() : TTexture; override;
function GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = true) : TMatrix3D; override;
TDepthMethod = (dmDefault, dmMVPPosZ, dmModelViewPosZ);
uses
Gorilla.Controller.Passes.CustomDepth;
var
LDepth: TGorillaRenderPassCustomDepth;
begin
LDepth := TGorillaRenderPassCustomDepth.Create(nil);
LDepth.Viewport := GorillaViewport1;
LDepth.DepthMethod := dmDefault;
// Custom resolution (e.g. a 2048² shadow/depth map)
LDepth.OverwriteViewportSize := True;
LDepth.ViewportWidth := 2048;
LDepth.ViewportHeight := 2048;
LDepth.Enabled := True;
end;
TRenderPassType.Pre)RenderListToFBOListRendering (no transparency separation — faster)R16F, data type dtHalfFloat, Linear filtering, WrapS/WrapT = ClampToBorder with a white border color (1, 1, 1, 1) so out-of-range samples read as "far".This unit provides a configurable blur post-process. It supports several blur algorithms and is typically chained in a horizontal/vertical ping-pong arrangement to blur the output of another render pass — for bloom, depth-of-field, soft shadows, or general screen-space smoothing.
The blur pass uses RectToFBO rendering: it draws a fullscreen quad with a blur material that samples an input texture. Separable blur is achieved by running the pass twice — once Horizontal, once Vertical — feeding the first result into the second via SetInputPass().
Inherits from: TGorillaRenderPassController
Default pass id: 'Blur'
| Property | Type | Default | Description |
|---|---|---|---|
BlurType |
TPassBlurType |
— | Blur algorithm: RadialBlur, FastBlur, GaussianBlur. |
BlurMode |
TPassBlurMode |
— | Pass direction: Horizontal or Vertical. |
BlurAmount |
Single |
— | Strength / radius of the blur. |
PingPongMode |
Boolean |
False | Enables ping-pong texture swapping for iterative blurring. |
Exposure |
Single |
— | Exposure adjustment applied during tonemapping. |
function GetOutputTexture() : TTexture; override;
function GetFinalOutputTexture() : TTexture;
TPassBlurType = (RadialBlur, FastBlur, GaussianBlur);
TPassBlurMode = (Horizontal, Vertical);
Note:
FastBlurcan produce artefacts on some NVIDIA GPUs. PreferGaussianBlur(kernel size 35) when quality matters.
Internal material classes (TGorillaRenderPassMaterial / TGorillaRenderPassMaterialSource) that hold the actual blur shaders and expose BlurType, BlurMode, BlurAmount, InputTexture and Exposure. You normally configure the pass, not these classes directly.
uses
Gorilla.Controller.Passes.CustomBlur;
var
LBlurH, LBlurV: TGorillaRenderPassBlur;
begin
// Horizontal blur reads from a source pass
LBlurH := TGorillaRenderPassBlur.Create(nil);
LBlurH.Viewport := GorillaViewport1;
LBlurH.Method := TRenderPassMethod.RectToFBO;
LBlurH.BlurType := GaussianBlur;
LBlurH.BlurMode := Horizontal;
LBlurH.BlurAmount := 4.0;
LBlurH.SetInputPass(SourcePass);
LBlurH.Enabled := True;
// Vertical blur reads the horizontal result
LBlurV := TGorillaRenderPassBlur.Create(nil);
LBlurV.Viewport := GorillaViewport1;
LBlurV.Method := TRenderPassMethod.RectToFBO;
LBlurV.BlurType := GaussianBlur;
LBlurV.BlurMode := Vertical;
LBlurV.BlurAmount := 4.0;
LBlurV.SetInputPass(LBlurH);
LBlurV.Enabled := True;
end;
RectToFBO (fullscreen quad)RadialBlur, FastBlur (separable, horizontal/vertical), GaussianBlur (separable, kernel size 35)GetFinalOutputTexture() to obtain the result after all blur iterations have run.Horizontal and a Vertical pass; a single direction alone looks streaked.This unit renders the scene into a cube map from a chosen point in space. The resulting environment texture is used for dynamic reflections, image-based lighting and environment mapping on materials — instead of a static skybox image, the cube map is generated from the live scene.
The environment pass is a pre-pass using RenderListToFBO with 6 iterations, one per cube map face. An internal camera (90° field of view, 1:1 aspect) is reoriented for each face, and the six faces are rendered into a TGorillaCubeMapTextureBitmap render target with mip-maps. An optional embedded point light can illuminate the capture.
Inherits from: TGorillaRenderPassController
Default pass id: 'Environment'
| Property | Type | Default | Description |
|---|---|---|---|
Position |
TPosition3D |
(0, 0, 0) | World-space point from which the environment is captured. |
IsDynamic |
Boolean |
False | True re-renders the cube map every cycle; False renders once (static). |
Target |
TControl3D |
nil | Optional object the environment capture is linked to. |
UseEmbeddedLight |
Boolean |
True | Enables the built-in point light used during capture. |
CenterOffsetFront |
Single |
0 | Render-point offset for the +Z (front) face. |
CenterOffsetBack |
Single |
0 | Render-point offset for the −Z (back) face. |
CenterOffsetLeft |
Single |
0 | Render-point offset for the −X (left) face. |
CenterOffsetRight |
Single |
0 | Render-point offset for the +X (right) face. |
CenterOffsetTop |
Single |
0 | Render-point offset for the +Y (top) face. |
CenterOffsetBottom |
Single |
0 | Render-point offset for the −Y (bottom) face. |
| Property | Type | Default | Description |
|---|---|---|---|
Camera |
TCamera |
— | Internal cube map camera (angle of view forced to 90°). |
EmbeddedLight |
TLight |
— | Built-in point light used to support the capture. |
MapSize |
Integer |
128 | Quadratic cube map face size. Use powers of two (16, 32, 64, 128, 256, 512, 1024). |
CubeMap |
TTextureBitmap |
— | The underlying TGorillaCubeMapTextureBitmap. |
BiasMatrix |
TMatrix3D |
— | Read-only texture bias matrix. |
function GetOutputTexture() : TTexture; override;
function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
procedure SetupMatrices(const AContext : TContext3D);
function GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = true) : TMatrix3D; override;
procedure InvalidateEnvironment();
procedure SetCenterOffsets(AFront, ABack, ALeft, ARight, ATop, ABottom : Single); overload;
procedure SetCenterOffsets(AOffset : Single); overload;
InvalidateEnvironment() forces a refresh of a static capture; it is called automatically when Position changes.
CreateMaterialSource() returns nil — objects are rendered with their original materials.
uses
Gorilla.Controller.Passes.Environment;
var
LEnv: TGorillaRenderPassEnvironment;
begin
LEnv := TGorillaRenderPassEnvironment.Create(nil);
LEnv.Viewport := GorillaViewport1;
LEnv.Position := Point3D(0, 2, 0); // capture point
LEnv.MapSize := 256;
LEnv.IsDynamic := True; // refresh every frame
// Don't capture the reflective object itself
LEnv.IgnoreControl(ReflectiveSphere);
LEnv.Enabled := True;
end;
Assign the pass to a material's EnvironmentPass property (see Materials → Environment Mapping).
TRenderPassType.Pre)RenderListToFBO, 6 iterations (one per cube map face)DefaultRenderingTGorillaTextureKind.CubeMap, style [RenderTarget, MipMaps], 9 mip-map levels, Linear filtering. Mip-maps are generated at the end of the capture.IsDynamic := False for static environments (e.g. fixed rooms) to capture only once and save performance; use InvalidateEnvironment() when the scene changes.CenterOffset* values let you bias the capture point per direction to reduce parallax errors for non-spherical reflectors.This unit renders mesh vertex positions (front or back faces) into a floating-point texture. It is primarily used as the entry/exit geometry for ray-cast volumetric rendering: by capturing front-face and back-face positions, a ray's start and end points through a volume can be reconstructed in screen space.
The face pass is a pre-pass using RenderListToFBO with ListRendering. A dedicated face material outputs the vertex position in a selectable coordinate space (TFaceOutput). Front- or back-face selection is controlled via FaceKind. The output texture format adapts to the selected output mode and platform (see Technical Details).
Inherits from: TGorillaRenderPassController
Default pass id: 'Face'
| Property | Type | Default | Description |
|---|---|---|---|
FaceKind |
TFaceKind |
— | Which side to render: FrontFace or BackFace. |
FaceOutput |
TFaceOutput |
— | Coordinate space written to the texture: Default, ModelSpace, ViewSpace, ViewProjSpace, FragDepth. |
| Property | Type | Description |
|---|---|---|
VertexUserFunc |
TStrings |
User-defined GLSL vertex code that can modify the position before output. |
BiasMatrix |
TMatrix3D |
Read-only texture bias matrix. |
function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
procedure SetupMatrices(const AContext : TContext3D);
function GetTextureMatrix(AContext : TContext3D;
const AUseBias : Boolean = true) : TMatrix3D; override;
TFaceKind = (FrontFace, BackFace);
TFaceOutput = (Default, ModelSpace, ViewSpace, ViewProjSpace, FragDepth);
Inherits from: TGorillaRenderPassFace
An internal variant (IsInternalRenderPass returns True) managed by higher-level systems rather than used standalone.
Internal material classes holding the per-space vertex shaders. They expose FaceKind, FaceOutput and VertexUserFunc; configure the pass rather than these directly.
uses
Gorilla.Controller.Passes.Face;
var
LFront, LBack: TGorillaRenderPassFace;
begin
// Front-face entry positions
LFront := TGorillaRenderPassFace.Create(nil);
LFront.Viewport := GorillaViewport1;
LFront.FaceKind := FrontFace;
LFront.FaceOutput := ModelSpace;
LFront.Enabled := True;
// Back-face exit positions
LBack := TGorillaRenderPassFace.Create(nil);
LBack.Viewport := GorillaViewport1;
LBack.FaceKind := BackFace;
LBack.FaceOutput := ModelSpace;
LBack.Enabled := True;
end;
TRenderPassType.Pre)RenderListToFBOListRenderingFaceOutput and platform:FragDepth: R16F (Android) / R32F (desktop), single channel.RGB16F (Android) / RGB32F (desktop), three channels for the position.Linear filtering, WrapS/WrapT = ClampToBorder.VertexUserFunc allows custom displacement/animation so the captured positions match a deformed mesh.This unit implements a full-screen underwater post-processing effect. When the camera dips below a defined water surface, it applies animated refraction distortion, depth-based color absorption (fog), caustics shimmer, a fisheye/barrel warp and a diving-mask vignette — fading smoothly in and out around the surface.
The underwater pass is a post-pass using RectToFBO. It draws a fullscreen quad with a screen-space shader that reads the rendered scene color (Color_0) and the transformed-position buffer (Color_2) from the main renderer. All effect parameters are packed into a TUnderwaterShaderData UBO and updated per frame. The effect strength is driven by the camera position relative to SurfaceHeight, smoothed over TransitionBand.
Inherits from: TGorillaRenderPassController
Default pass id: 'Underwater'
| Property | Type | Default | Description |
|---|---|---|---|
SurfaceHeight |
Single |
0 | World-space Y of the water surface; the effect activates below it. |
TransitionBand |
Single |
0.35 | Fade width (world units) around the surface for a smooth in/out blend. |
Intensity |
Single |
1.0 | Master effect strength (0..1). |
TintColor |
TAlphaColor |
$FF14506E |
Underwater tint / fog color (deep teal-blue). |
Distortion |
Single |
1.0 | Amount of animated wavy refraction. |
Fisheye |
Single |
0.15 | Radial barrel-distortion amount. |
Density |
Single |
0.06 | Depth-fog density. |
Caustics |
Single |
0.15 | Animated caustics shimmer amount. |
Vignette |
Single |
0.6 | Edge darkening (diving-mask) amount. |
WaveScale |
Single |
12.0 | Spatial frequency of the wavy distortion. |
WaveSpeed |
Single |
1.2 | Animation speed of distortion and caustics. |
procedure Loaded(); override;
procedure UpdateShader();
function ComputeUnderwaterAmount() : Single;
procedure ApplyEffectParams();
ComputeUnderwaterAmount() returns the current fade factor (0..1) from the camera position versus SurfaceHeight, smoothstepped across TransitionBand. ApplyEffectParams() pushes the parameters into the shader each frame.
Internal material classes holding the post-process shader and the TUnderwaterShaderData record. TUnderwaterMaterialSource exposes a TransfPosition texture input.
| Field | Type | Contents |
|---|---|---|
TimeInfo |
TVector3D |
start / current / previous / delta time - seconds relative to the start (ResetTime), start is always 0 |
Params |
TVector3D |
underwater amount × intensity, distortion, fisheye, density |
Tint |
TVector3D |
tint color RGB + caustics shimmer |
Extra |
TVector3D |
vignette, wave scale, wave speed |
CameraPos |
TVector3D |
camera world position (for depth fog) |
uses
Gorilla.Controller.Passes.Underwater;
var
LUnderwater: TGorillaRenderPassUnderwater;
begin
LUnderwater := TGorillaRenderPassUnderwater.Create(nil);
LUnderwater.Viewport := GorillaViewport1;
LUnderwater.SurfaceHeight := 0.0; // water plane at Y = 0
LUnderwater.TransitionBand := 0.5;
LUnderwater.TintColor := $FF14506E;
LUnderwater.Density := 0.08;
LUnderwater.Caustics := 0.2;
LUnderwater.Enabled := True;
end;
TRenderPassType.Post)RectToFBO (fullscreen quad)Color_0) and transformed position (Color_2) MRT outputs from the main renderer.SurfaceHeight, so the pass can stay enabled permanently.This unit implements Gorilla3D's modern shadow system: Cascaded Shadow Maps (CSM) with support for directional, spot and point lights. Every shadow-casting light on a viewport is captured into a shared depth atlas before the main scene renders; the default material then samples that atlas (plus a per-light uniform buffer) to filter the shadow contribution of each fragment.
Unlike the other render passes you create manually, the cascaded shadow pass is an internal pass driven by the viewport. You enable and tune it through TGorillaViewport.Shadows — you do not normally construct TGorillaRenderPassCascadedShadows yourself.
This is the recommended shadow path. It supersedes the older
smShadowMapping/smVSMmaterial flags noted as incomplete in Materials → Shadow Mapping.
// Turn the CSM system on and configure it
GorillaViewport1.Shadows.Enabled := True;
GorillaViewport1.Shadows.CascadeCount := 4;
GorillaViewport1.Shadows.MapResolution := 2048;
GorillaViewport1.Shadows.MaxDirLights := 1;
GorillaViewport1.Shadows.Filter := TGorillaShadowFilter.PCF3;
// Mark the lights that should cast shadows
MyDirLight.CastShadow := True;
Viewport.Shadows is a published TGorillaShadowSystemSettings instance owned by the viewport. The embedded pass automatically gathers every TGorillaLight with CastShadow := True, honouring the per-kind budgets.
The depth pass renders the whole scene into the shadow atlas, so by default every mesh casts a shadow. To stop a specific object from casting — typically a surface that sits between the light and the rest of the scene, such as a water plane or a transparent wall, which would otherwise shadow everything beneath it — set its CastShadows property to False:
WaterSurface.CastShadows := False; // still visible & still receives shadows, but throws none
CastShadows (default True) is independent of Shadows (which controls whether the object receives shadows). The cascaded-shadow pass skips any TGorillaMesh with CastShadows = False via its IsControlIgnored override.
The user-facing configuration object (Gorilla.Context.ShadowSettings).
| Property | Type | Default | Description |
|---|---|---|---|
Enabled |
Boolean |
False | Activates the embedded shadow pass on the viewport. |
CascadeCount |
Integer |
4 | Cascade slices per directional light. Clamped to [1..GORILLA_SHADOW_MAX_CASCADES]. |
MapResolution |
Integer |
2048 | Shadow map side length in texels (per atlas layer). |
Strength |
Single |
1.0 | Global shadow darkness multiplier [0..1], applied on top of every caster's per-light ShadowStrength. 1.0 = full, 0.0 = shadows off. This is the discoverable single knob for shadow darkness — see the note below. |
CascadeSplitLambda |
Single |
0.75 | Blend between uniform (0) and logarithmic (1) cascade splits. Higher = more detail near the camera. |
StabilizeCascades |
Boolean |
True | Snap cascades to texel boundaries to suppress shimmering when the camera moves. |
AutoFitCascades |
Boolean |
True | Fit the directional cascade range to the scene's shadow-casting geometry instead of spreading it over the whole camera frustum. Keeps shadow-texel density high for small casters without a manual ShadowNearFar. Never widens past the camera frustum — see Cascade Fitting. |
Filter |
TGorillaShadowFilter |
PCF3 |
Shadow softening kernel evaluated by the default material. |
PointLightMethod |
TGorillaPointShadowMethod |
CubeMap |
Algorithm for omnidirectional point-light shadows. |
MaxDirLights |
Integer |
1 | Directional lights allowed to cast shadows per frame. |
MaxSpotLights |
Integer |
0 | Spot lights allowed to cast shadows per frame. |
MaxPointLights |
Integer |
0 | Point lights allowed to cast shadows per frame. |
Bias |
Single |
0.0005 | Global constant depth bias (fallback when a light has no override). |
SlopeBias |
Single |
0.001 | Global slope-scaled depth bias (fallback). |
NormalOffset |
Single |
0.02 | Global normal-offset bias in world units (fallback). |
FrontFaceCulling |
Boolean |
True | Render back-faces only into the atlas. Removes acne on rounded geometry but can cause Peter-Panning on thin meshes. |
DebugAtlasLayer |
Integer |
-1 | Diagnostic: -1 = normal; a non-negative atlas-layer index makes the material sample that layer's raw depth for visualisation. |
function ComputeAtlasLayerCount() : Integer;
Returns the total atlas-layer budget: MaxDirLights × CascadeCount (directional) + MaxSpotLights × 1 (spot) + MaxPointLights × 6 (point cube faces).
TGorillaShadowFilter = (None, PCF3, PCF5, Poisson, PCSS);
| Value | Description |
|---|---|
None |
Hard shadows — a single hardware-compared depth tap. |
PCF3 |
3×3 percentage-closer filter (default). |
PCF5 |
5×5 percentage-closer filter. |
Poisson |
12-tap Poisson-disk with rotation noise. |
PCSS |
Percentage-Closer Soft Shadows (most expensive). |
TGorillaPointShadowMethod = (CubeMap, DualParaboloid);
CubeMap (default) records six perspective faces; DualParaboloid uses two hemispheres as a fallback for restricted GPUs.
TGorillaShadowResolution = (Res512 = 512, Res1024 = 1024, Res2048 = 2048, Res4096 = 4096);
Use Viewport.Shadows.Strength to control how dark cascaded shadows are:
GorillaViewport1.Shadows.Strength := 0.5; // half-strength shadows
It is a [0..1] multiplier applied on top of each caster's per-light ShadowStrength, so the two compose (final darkness = light.ShadowStrength × Shadows.Strength). Per-light values let one caster be lighter than another; the global value is the single scene-wide dial.
Do not confuse this with
Viewport.ShadowStrength(noShadows.prefix). That legacy property only affects the Global Illumination pass and has no effect on cascaded shadow maps.
Note that the shadow only attenuates direct lighting — it does not darken the ambient / image-based-lighting term. In a bright skybox/IBL environment shadows therefore cannot get darker than the ambient floor allows, regardless of Strength.
By default a directional light spreads its cascades across the whole camera frustum (camera near .. camera far). When the far plane sits well beyond the actual geometry — e.g. a small model (< 1 unit) in a scene with a large far plane — even the tightest cascade covers many world units, so a single shadow texel is larger than the caster and the shadow looks coarse or disappears.
Two mechanisms tighten the cascade depth band so the Practical Split Scheme concentrates texels where the geometry actually is. In increasing priority:
Shadows.AutoFitCascades, default True) — the eight corners of the viewport's SceneBounds are projected onto the camera view axis; the cascade band is clamped to that span (intersected with the camera frustum). It can only ever narrow the range, so it never reduces quality. Because SceneBounds is the union of all renderable geometry, large ground planes pull the far end out — for a tightly-cropped result on one small caster, prefer the manual override below.TGorillaLight.ShadowNearFar) — set an explicit (near, far) to clamp the band yourself; each component > 0 wins over auto-fit. Ideal for a small caster the camera sits close to:MyDirLight.ShadowNearFar := PointF(0.1, 8); // crisp shadows in a tight depth band
Bias values default to the same numbers as the global settings, but each light may override them.
| Property | Type | Default | Description |
|---|---|---|---|
CastShadow |
Boolean |
False | Enables shadow casting; the pass picks the light up automatically when Viewport.Shadows.Enabled. |
ShadowBias |
Single |
0.0005 | Constant depth bias during the shadow comparison. |
ShadowSlopeBias |
Single |
0.001 | Slope-scaled bias, multiplied by (1 - dot(N, L)) to fight acne on grazing surfaces. |
ShadowNormalOffset |
Single |
0.02 | Shifts the sample position along the surface normal (world units) to reduce self-shadowing. |
ShadowStrength |
Single |
1.0 | Per-light shadow opacity [0..1]; 1.0 = fully opaque, 0.0 = no shadow. Multiplied by the global Shadows.Strength. |
ShadowNearFar |
TPointF |
(0, 0) | Shadow projection near/far override (X = near, Y = far); only components > 0 apply. Spot/point: (0, 0) auto-derives from attenuation. Directional: an explicit range clamps the cascade band (overrides auto-fit per component); (0, 0) keeps auto-fit / camera-frustum behaviour. |
Inherits from: TGorillaRenderPassCustomDepth
Default pass id: 'CascadedShadows'. IsInternalRenderPass() returns True — the pass is driven manually by the composite renderer (DoRenderShadowMaps), not by the automatic Pre-pass loop.
| Member | Type | Description |
|---|---|---|
CurrentInstance |
class var |
The most recently constructed pass; lit materials locate the shadow pass through it without coupling to viewport ownership. |
Settings |
TGorillaShadowSystemSettings |
Read-only — the bound settings instance. |
Lights |
TGorillaShadowLightEntryList |
Read-only — per-light bookkeeping gathered this frame. |
ActiveEntryIdx |
Integer |
Light entry currently selected for rendering. |
ActiveCascade |
Integer |
Slice within the active entry (cascade, cube face, or 0). |
procedure SetSettings(const ASettings : TGorillaShadowSystemSettings);
procedure PrepareFrame();
procedure SetActiveLightSlice(const AEntryIdx, ASliceIdx : Integer);
function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
function GetShaderData() : PGorillaCSMShaderData;
function GetShaderDataSize() : Integer;
PrepareFrame() performs the per-frame snapshot (gather casters → allocate/resize atlas → rebuild the GPU UBO). The host renderer calls it once per frame; then it iterates each gathered light entry, walking 0..Entry.LayerCount-1 via SetActiveLightSlice and dispatching a depth render per slice.
| Type | Purpose |
|---|---|
TGorillaShadowLightKind |
slkDirectional, slkSpot, slkPoint. |
TGorillaShadowLightEntry |
Per-light frame data: kind, atlas layer, per-slice LightSpace/View/Proj matrices, split depths, cube-face matrices. |
TGorillaCSMLightGPU |
std140 mirror of the GLSL CSMLight struct. |
TGorillaCSMShaderData |
std140 mirror of the GLSL uShadowBlock UBO, bound by the default material on every shader-program swap. |
TGorillaCascadeFrustumCorners |
The eight world-space corners of a cascade sub-frustum. |
TRenderPassType.Pre), internal — RenderListToFBO + ListRendering (inherited from TGorillaRenderPassCustomDepth).R32F (dtFloat), Linear filtering, WrapS/WrapT = ClampToBorder with a white border (1,1,1,1) so off-cascade reads resolve to "no occluder". The atlas is a Texture2DArray sized by ComputeAtlasLayerCount(); the depth target is cleared to FAR (1.0) each slice.CascadeSplitLambda mix of logarithmic and uniform spacing. Directional cascades fit a stabilised bounding-sphere ortho per slice. The split range is the camera frustum, optionally narrowed by AutoFitCascades (scene-bounds fit) and/or a per-light ShadowNearFar override.SpotCutOff.Bias + SlopeBias + NormalOffset combine against acne; FrontFaceCulling trades acne for potential Peter-Panning.Gorilla.Context.ShadowSettings): GORILLA_SHADOW_MAX_CASCADES = 4, GORILLA_SHADOW_MAX_LIGHTS = 16, GORILLA_SHADOW_LIGHTSPACE_SLOTS = 6.The Gorilla.Utils.Dialogue.System unit implements the Gorilla3D dialogue system. It provides a hierarchical structure of dialogues, items (questions/answers), events, and characters. Dialogues are organized in collections with support for branching, timeouts, skipping, multi-language names, and XML serialization.
TComponent
└── TGorillaDialogueSystem
TCollectionItem
└── TGorillaDialogueCustomItem
└── TGorillaDialogueParameterizedItem
├── TGorillaDialogueItemEvent
└── TGorillaDialogueParentItem
├── TGorillaDialogueItem
├── TGorillaDialogueCharacter
└── TGorillaDialogue
TOnBeginDialogueItemEvent = procedure(const AEvent: TGorillaDialogueItemEvent;
const AScope: TObject; var AHandled: Boolean) of object;
TOnEndDialogueItemEvent = procedure(const AEvent: TGorillaDialogueItemEvent;
const AScope: TObject) of object;
TOnBeginDialogueItem = procedure(const AItem: TGorillaDialogueItem;
const AItems: TArray<TGorillaDialogueItem>) of object;
TOnEndDialogueItem = procedure(const AItem: TGorillaDialogueItem) of object;
TOnStartDialogue = procedure(const ADialogue: TGorillaDialogue;
const AItems: TArray<TGorillaDialogueItem>) of object;
TOnStopDialogue = procedure(const ADialogue: TGorillaDialogue) of object;
TOnPauseDialogue = procedure(const ADialogue: TGorillaDialogue) of object;
TOnSkippedDialogue = procedure(const ADialogue: TGorillaDialogue;
const ABeginItem, AEndItem: TGorillaDialogueItem) of object;
TOnSkipAvailability = procedure(const ADialogue: TGorillaDialogue;
const AItem: TGorillaDialogueItem; const AIsAvailable: Boolean) of object;
TOnBeginItemTimeout = procedure(const AItem: TGorillaDialogueItem;
const ATime: Integer) of object;
TOnEndItemTimeout = procedure(const AItem: TGorillaDialogueItem) of object;
Base class for all dialogue entities.
| Property | Type | Description |
|---|---|---|
Ident |
String |
Unique identifier |
Enabled |
Boolean |
Whether the item can be used/executed |
| Property | Type | Description |
|---|---|---|
DialogueSystem |
TGorillaDialogueSystem |
Parent dialogue system |
UIElement |
TObject |
Linked UI element (used by overlay components) |
Position |
TPointF |
Flow chart position (for editor layout) |
| Method | Description |
|---|---|
GetRandomId() |
Generate a random identifier |
Clone() |
Clone this item (abstract) |
Extends TGorillaDialogueCustomItem with a parameter list.
| Property | Type | Description |
|---|---|---|
Parameters |
TGorillaDialogueParameters |
Custom key-value parameters |
| Method | Description |
|---|---|
AddParameter(AName, AValue) |
Add or overwrite a parameter |
RemoveParameter(AName) |
Remove parameter by name |
GetParameter(AName) |
Get parameter value by name |
An event attached to a dialogue item.
| Property | Type | Description |
|---|---|---|
Kind |
TGorillaDialogueItemEventKind |
Event kind (Message, Sound, Animation, etc.) |
Trigger |
TGorillaDialogueItemEventTrigger |
When to fire (OnBegin, OnEnd, OnTimeout, etc.) |
Value |
String |
Event payload |
A single dialogue entry (question, answer, or text).
| Property | Type | Description |
|---|---|---|
Kind |
TGorillaDialogueItemKind |
Item kind: Question, Answer, Text, Group, Random |
Text |
TGorillaLanguageMap |
Multi-language dialogue text |
Timeout |
Integer |
Auto-advance timeout in ms (0 = disabled) |
Audio |
String |
Audio file path |
Character |
TGorillaDialogueCharacter |
Speaking character |
Items |
TGorillaDialogueItemCollection |
Child items (for branching) |
Events |
TGorillaDialogueItemEventCollection |
Attached events |
ImageIndex |
Integer |
Icon index in TImageList |
A named character participating in dialogues.
| Property | Type | Description |
|---|---|---|
Items |
TGorillaDialogueItemCollection |
Character's dialogue items |
ImageIndex |
Integer |
Character icon index |
A complete dialogue tree.
| Property | Type | Description |
|---|---|---|
Items |
TGorillaDialogueItemCollection |
Root dialogue items |
Characters |
TGorillaDialogueCharacterCollection |
Participating characters |
ImageIndex |
Integer |
Dialogue icon index |
Main component managing all dialogues.
| Property | Type | Description |
|---|---|---|
Dialogues |
TGorillaDialogueCollection |
Collection of dialogues |
Language |
String |
Current language for text display |
ImageList |
TImageList |
Linked image list for icons |
| Event | Type | Description |
|---|---|---|
OnStartDialogue |
TOnStartDialogue |
Dialogue started |
OnStopDialogue |
TOnStopDialogue |
Dialogue stopped |
OnPauseDialogue |
TOnPauseDialogue |
Dialogue paused |
OnBeginItem |
TOnBeginDialogueItem |
Item processing started |
OnEndItem |
TOnEndDialogueItem |
Item processing ended |
OnBeginItemEvent |
TOnBeginDialogueItemEvent |
Item event started |
OnEndItemEvent |
TOnEndDialogueItemEvent |
Item event ended |
OnSkipped |
TOnSkippedDialogue |
Dialogue skipped |
OnSkipAvailability |
TOnSkipAvailability |
Skip availability changed |
OnBeginTimeout |
TOnBeginItemTimeout |
Item timeout started |
OnEndTimeout |
TOnEndItemTimeout |
Item timeout ended |
Gorilla.Utils.Dialogue.Types — enumerations and type definitions (no reference page yet)The Gorilla.Utils.Inventory unit implements the Gorilla3D inventory system. It uses a template-instance pattern: groups organize item templates, templates define item blueprints, and collectables are runtime instances. The system supports crafting/manufacturing, upgrade/downgrade chains, dependencies, multi-language names, custom parameters, and XML serialization.
TComponent
└── TGorillaInventory
TCollectionItem
└── TGorillaInventoryCustomItem
└── TGorillaInventoryItem
├── TGorillaInventoryItemTemplate
└── TGorillaInventoryCollectable
└── TGorillaInventoryGroup
TObjectList<TGorillaInventoryIngredient>
└── TGorillaInventoryCustomIngredientList
├── TGorillaInventoryIngredientList
├── TGorillaInventoryDependencyList
└── TGorillaInventoryResultItemList
| Value | Description |
|---|---|
None |
No action |
Allowed |
Collection permitted |
Collected |
Successfully collected |
QuantityExceeded |
Max quantity reached |
Disabled |
Item template is disabled |
NotFound |
Template not found |
Missing |
Missing dependency |
| Value | Description |
|---|---|
Undefined |
Not started |
Processing |
Crafting in progress |
Completed |
Crafting finished |
Failed |
Crafting failed |
Base class for all inventory items.
| Property | Type | Description |
|---|---|---|
Id |
String |
Unique identifier |
Enabled |
Boolean |
Whether the item can be used |
Data |
TValue |
Runtime data (not serialized) |
Name |
TGorillaInventoryLanguageMap |
Multi-language display name |
ImageIndex |
Integer |
Icon index in TImageList |
| Property | Type | Description |
|---|---|---|
Inventory |
TGorillaInventory |
Parent inventory component |
Extends base item with custom parameters.
| Property | Type | Description |
|---|---|---|
Parameters |
TGorillaInventoryParameters |
Custom key-value parameters |
Blueprint/prototype for collectible items.
| Property | Type | Description |
|---|---|---|
Group |
TGorillaInventoryGroup |
Category group |
MaxQuantity |
Integer |
Maximum stack size |
Weight |
Single |
Item weight |
MaxWeight |
Single |
Maximum weight |
IsPooled |
Boolean |
Whether instances are pooled |
UpgradeItem |
TGorillaInventoryItemTemplate |
Next tier upgrade |
DowngradeItem |
TGorillaInventoryItemTemplate |
Previous tier downgrade |
Dependency |
TGorillaInventoryDependencyList |
Required items for collection |
| Method | Description |
|---|---|
Build() |
Create a TGorillaInventoryCollectable from this template |
AddDependency(AId, AQuantity) |
Add a collection dependency |
A runtime instance of a template in the player's inventory.
Inherits Id, Name, Parameters, Data from parent classes.
Category for organizing item templates.
| Property | Type | Description |
|---|---|---|
Templates |
TGorillaInventoryItemCollection |
Item templates in this group |
Crafting system for combining items.
| Class | Description |
|---|---|
TGorillaInventoryManufacturer |
Contains crafting processes |
TGorillaInventoryManufacturingProcess |
A single recipe with ingredients and results |
TGorillaInventoryIngredient |
An ingredient (template reference + quantity) |
Main inventory component.
| Property | Type | Description |
|---|---|---|
Groups |
TGorillaInventoryGroupCollection |
Item group categories |
Manufacturers |
TGorillaInventoryManufacturerCollection |
Crafting recipes |
Language |
String |
Current language for display names |
ImageList |
TImageList |
Linked image list for icons |
| Method | Description |
|---|---|
ToXml(AParent) |
Serialize to XML element |
FromXml(ANode, ACache) |
Deserialize from XML element |
Multi-language string map extending TGorillaLanguageMap with XML serialization.
Custom key-value parameter map extending TGorillaParametersMap with XML serialization.
Resolves circular references during XML loading (templates referencing other templates for upgrade/downgrade chains).
The Gorilla.Utils.Pathfinding unit provides the base pathfinding framework for Gorilla3D. It defines TGorillaPathfindingAlgorithm, an abstract base class that manages obstacles, an agent, and obstacle margins. The actual A* algorithm is implemented in Gorilla.Utils.Pathfinding.AStar.
TComponent
└── TControl3D
└── TGorillaControl
└── TGorillaPathfindingAlgorithm
└── TGorillaPathfindingAStar (in Gorilla.Utils.Pathfinding.AStar)
EPathFindingException = class(Exception); // General pathfinding error
EPathFindingAbort = class(EAbort); // Pathfinding abort (silent)
TOnPathfindingObstacleUpdate = procedure(const AControl: TControl3D;
out ABounds: TBoundingBox) of object;
Structure storing information about each obstacle.
| Field | Type | Description |
|---|---|---|
Control |
TControl3D |
The visual component acting as obstacle |
IsStatic |
Boolean |
If True, bounding box is computed once (better performance) |
Bounds |
TBoundingBox |
Current bounding box |
Computed |
Boolean |
Whether grid rect has been calculated |
GridRect |
TRectF |
Computed grid coordinates |
| Method | Description |
|---|---|
Create(AControl, AIsStatic) |
Constructor |
Reset() |
Reset computed state, forcing recalculation |
Abstract base class for pathfinding algorithms. Manages obstacles and the navigating agent.
| Property | Type | Description |
|---|---|---|
Agent |
TControl3D |
The character/NPC that navigates |
ObstacleMargin |
TPoint3D |
Buffer zone around obstacles (e.g., (0.5, 0, 0.5)) |
OnUpdate |
TOnPathfindingObstacleUpdate |
Custom bounding box callback for obstacles |
| Property | Type | Description |
|---|---|---|
AgentPosition |
TPoint3D |
Current agent position (returns (0,0,0) if no agent) |
| Method | Description |
|---|---|
AddObstacle(ACtrl, AIsStatic) |
Add obstacle with auto bounding box |
AddObstacle(ACtrl, ABounds, AIsStatic) |
Add obstacle with explicit bounding box |
RemoveObstacle(ACtrl) |
Remove a specific obstacle |
ClearObstacles() |
Remove all obstacles |
ResetObstacles() |
Reset computed grid rects (force recalculation) |
CountObstacles() |
Return number of registered obstacles |
A* pathfinding implementation (in Gorilla.Utils.Pathfinding.AStar). Extends TGorillaPathfindingAlgorithm with grid-based pathfinding that finds the shortest path from agent to target while avoiding obstacles.
uses Gorilla.Utils.Pathfinding, Gorilla.Utils.Pathfinding.AStar;
var Pathfinder := TGorillaPathfindingAStar.Create(Self);
Pathfinder.Parent := GorillaViewport1;
Pathfinder.Agent := CharacterModel;
// Add obstacles
Pathfinder.AddObstacle(WallMesh, True); // static
Pathfinder.AddObstacle(MovingPlatform, False); // dynamic
Pathfinder.ObstacleMargin := Point3D(0.5, 0, 0.5);
The Gorilla.Utils.SkillSystem unit implements a hierarchical skill tree framework for Gorilla3D games. Skills are organized in groups, support leveling with configurable interpolation, async leveling processes, multi-language names, and XML serialization.
TComponent
└── TGorillaSkillSystem
TCollectionItem
└── TGorillaCustomSkillEntity
└── TGorillaSkillGroup
└── TGorillaSkill (extends group, so skills can have sub-skills)
| Value | Description |
|---|---|
LinearInterpolation |
Value = BaseValue + Level * Factor |
LogarithmicInterpolation |
Logarithmic growth curve |
ExponentialInterpolation |
Exponential growth curve |
ExponentialMinus1Interpolation |
Exponential minus 1 curve |
Base class for skills and groups.
| Property | Type | Description |
|---|---|---|
Enabled |
Boolean |
Whether this entity is unlocked |
Icon |
Integer |
Icon index in TImageList |
Position |
TPointF |
Flow chart position (editor layout) |
| Property | Type | Description |
|---|---|---|
GUID |
TGUID |
Unique identifier (auto-generated) |
Name |
String |
Display name (current language) |
Names[Index] |
String |
Name by language index |
NameMap |
TGorillaLanguageMap |
Full language map |
SkillSystem |
TGorillaSkillSystem |
Parent skill system |
| Method | Description |
|---|---|
FromXml(ANode) |
Load from XML |
ToXml(AParent) |
Save to XML |
A category of skills.
| Property | Type | Description |
|---|---|---|
Skills |
TGorillaSkillCollection |
Contained skill entities |
| Method | Returns | Description |
|---|---|---|
AddSkill() |
TGorillaSkill |
Add a new empty skill |
FindSkillByName(ASkillName) |
TGorillaSkill |
Find skill by display name |
FindSkillByGUID(AGUID) |
TGorillaSkill |
Find skill by GUID |
GetActivatedSkills(AMap) |
— | Return all activated skills (flat list) |
A single skill with leveling support. Extends TGorillaSkillGroup, so skills can contain sub-skills forming a hierarchy.
| Property | Type | Default | Description |
|---|---|---|---|
Activated |
Boolean |
False | Whether the skill is currently active |
Value |
Single |
1.0 | Main skill value |
Factor |
Single |
1.0 | Interpolation factor |
Interpolation |
TGorillaSkillLevelInterpolation |
Linear | How value scales with level |
Level |
Integer |
0 | Current skill level |
MaxLevel |
Integer |
— | Maximum achievable level |
LevelingTime |
Integer |
— | Time required to level up (ms) |
| Property | Type | Description |
|---|---|---|
Data |
TValue |
Custom runtime data (not serialized) |
SkillGroup |
TGorillaSkillGroup |
Parent group |
| Method | Returns | Description |
|---|---|---|
StartLevelingUp() |
TGorillaSkillProcess |
Start async leveling (targets first sub-skill) |
StartLevelingUp(ADest) |
TGorillaSkillProcess |
Start async leveling toward specific sub-skill |
Manages an async leveling operation.
Main component managing all skill groups.
| Property | Type | Description |
|---|---|---|
Groups |
TGorillaSkillGroupCollection |
Collection of skill groups |
Language |
String |
Current language for display names |
ImageList |
TImageList |
Linked image list for icons |
| Method | Returns | Description |
|---|---|---|
AddGroup() |
TGorillaSkillGroup |
Add a new skill group |
FindGroupByName(AName) |
TGorillaSkillGroup |
Find group by name |
FindGroupByGUID(AGUID) |
TGorillaSkillGroup |
Find group by GUID |
FindSkillByName(AName) |
TGorillaSkill |
Find skill across all groups |
FindSkillByGUID(AGUID) |
TGorillaSkill |
Find skill by GUID across all groups |
| Method | Description |
|---|---|
ToXml(AParent) |
Serialize to XML element |
FromXml(ANode) |
Deserialize from XML element |
TGorillaSkillMap = TDictionary<String, TGorillaSkill>;
Animation state machine for automatic clip switching by transitions.
Unit: Gorilla.Animation.Controller
The Gorilla.Animation.Controller unit implements a transition-driven animation state
machine on top of the Gorilla.Animation system. Instead of starting clips manually,
you declare transitions between animations and dispatch the events that should trigger
them.
Structure:
TGorillaAnimationController
└─ TGorillaAnimationTransitionLayerCollection
└─ TGorillaAnimationTransitionLayer
├─ TGorillaAnimationRefList (animations referenced by this layer)
└─ TGorillaAnimationTransitionCollection
├─ TGorillaAnimationTransitionsMap (lookup map, key -> transition list)
└─ TGorillaAnimationTransition
Dependencies: Gorilla.Controller, Gorilla.Animation, Gorilla.Model,
Gorilla.AssetsManager, Gorilla.Controller.Input.Types,
Gorilla.Controller.Input.Character
TGorillaAnimationTransitionDetectionKind = (tkHotKeyAndStates, tkCustom);
Defines what kind of information triggers a transition.
| Value | Description |
|---|---|
tkHotKeyAndStates |
A pressed hotkey and the active character states are checked |
tkCustom |
A variable name and its value are submitted |
TGorillaAnimationTransitionMode = (tmImmediatly, tmSequentially, tmBlend);
Defines how switching between two animations is handled.
| Value | Description |
|---|---|
tmImmediatly |
The destination animation is switched immediately |
tmSequentially |
The controller switches to the destination animation at the end of the current animation |
tmBlend |
Blending between animations. Not supported yet - currently treated like tmSequentially |
TGorillaAnimationDispatcher = record
Kind : TGorillaAnimationTransitionDetectionKind;
HotKey : TGorillaCharacterControllerHotKey;
States : TGorillaCharacterControllerStates;
Variable : String;
Value : TValue;
end;
Stores dispatch information for recalling. The controller keeps the last dispatch in
DispatchState and replays it when a non-looping animation finishes.
TGorillaAnimationTransitionKey = record
class function GetKey(AAnimFrom: String;
AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates): String; overload; static;
class function GetKey(AAnimFrom: String;
AVariable: String; AValue: String): String; overload; static;
class function GetKey(AAnimFrom: String;
AVariable: String; AValue: TValue): String; overload; static;
end;
Builds the lookup key used by TGorillaAnimationTransitionsMap.
<AnimationFrom>:0;<Ord(HotKey)><AnimationFrom>:1;<Variable>;<Value>The states are deliberately not part of the hotkey key. All transitions sharing source animation and hotkey land in one bucket and are checked individually, so state sets can overlap.
TGorillaAnimationTransitionList = TList<TGorillaAnimationTransition>;
TGorillaAnimationTransitionsMap = class(TDictionary<String, TGorillaAnimationTransitionList>)
constructor Create(); reintroduce; virtual;
end;
Maps a transition key to all transitions sharing that key. Owns the sub-lists: removing a value frees the list.
Links an animation to the layer that uses it, plus editor metadata.
TGorillaAnimationRef = class
property Animation : TGorillaAnimation read FAnimation write FAnimation;
property UIPosition : TPointF read FUIPosition write FUIPosition;
property Visible : Boolean read FVisible write FVisible;
end;
| Member | Description |
|---|---|
Animation |
The referenced animation instance |
UIPosition |
Node position in the design-time transition editor; serialized per layer |
Visible |
Editor visibility flag |
TGorillaAnimationRefList = class(TObjectList<TGorillaAnimationRef>)
function Find(const AId: String): TGorillaAnimationRef; overload;
function Find(const AAnim: TGorillaAnimation): TGorillaAnimationRef; overload;
function AddByAnimation(const AAnim: TGorillaAnimation): TGorillaAnimationRef;
end;
| Method | Description |
|---|---|
Find(AId) |
Returns the reference whose animation has the given Def.Id, or nil |
Find(AAnim) |
Returns the reference for the given animation instance, or nil |
AddByAnimation |
Returns the existing reference, or creates and adds a new one |
Defines the switch between two animations.
Inheritance: TCollectionItem → TGorillaAnimationTransition
Created with Mode = tmSequentially and Loop = True.
property DisplayName;
The transition name, used by FindTransition and DeleteTransition and shown in the
collection editor.
property Key: String read GetKey;
Read-only lookup key built from DetectionKind, AnimationFrom and the detection
properties. Used to file the transition into the collection's lookup map.
property DetectionKind: TGorillaAnimationTransitionDetectionKind
read FDetectionKind write FDetectionKind;
Selects which properties are evaluated: HotKey / States for tkHotKeyAndStates,
Variable / Value for tkCustom. Set automatically by the matching
AddTransition() overload.
property Mode: TGorillaAnimationTransitionMode read FMode write FMode;
How the switch is carried out. See TGorillaAnimationTransitionMode.
property Loop: Boolean read FLoop write FLoop;
Whether the destination animation loops. With Loop = False and
Mode = tmImmediatly, the controller restores looping on the clip when it finishes and
replays the last dispatch, so a matching "way back" transition can take over.
property HotKey: TGorillaCharacterControllerHotKey read FHotKey write FHotKey;
Hotkey to match. Only evaluated for DetectionKind = tkHotKeyAndStates. Must be equal
to the dispatched hotkey.
property States: TGorillaCharacterControllerStates read FStates write FStates;
Character states to match. Only evaluated for DetectionKind = tkHotKeyAndStates.
Matching is a subset test: every state in States must be present in the dispatched
set, which may contain additional states. An empty set matches any state.
property Variable: String read FVariable write FVariable;
Variable name to match. Only evaluated for DetectionKind = tkCustom. Compared
case-sensitively for equality.
property Value: String read FValue write FValue;
Variable value to match, stored as a string. AddTransition() fills it with
AValue.ToString(), and dispatched values are compared the same way.
property AnimationFrom: String read GetAnimationFrom write SetAnimationFrom;
property AnimationTo: String read GetAnimationTo write SetAnimationTo;
Source and destination animation, referenced by ID. The instances are resolved lazily
through Controller.Model.AnimationManager and cached; assigning a new ID drops the
cached link. As long as a model is missing or the ID is unknown, the link stays nil
and the transition never triggers.
property OffsetAnimationFrom: Single read FOffsetAnimationFrom write FOffsetAnimationFrom;
property OffsetAnimationTo: Single read FOffsetAnimationTo write FOffsetAnimationTo;
property Duration: Single read FDuration write FDuration;
Blend window for tmBlend: the offsets mark where blending starts in the source and
destination animation, Duration defines the length of the blending section. Stored and
serialized, but without effect until blending is implemented.
function DispatchInput(ACurrent: TGorillaAnimation;
AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates): Boolean; overload; virtual;
function DispatchInput(ACurrent: TGorillaAnimation;
AVariable: String; AValue: TValue): Boolean; overload; virtual;
Checks whether this transition is triggered. Returns False when the detection kind
does not match the overload, when ACurrent is not the resolved source animation, or
when hotkey / states / variable / value do not match.
procedure Switch(ACurrent: TGorillaAnimation);
Performs the animation switch. Called automatically after DispatchInput returned
True. Does nothing if the destination animation is already current or cannot be
resolved.
| Mode | Effect |
|---|---|
tmImmediatly |
Clears OnFinish on the current clip, makes the destination current, applies Loop, hooks the finish handler when Loop = False, and starts it |
tmSequentially |
Sets the current clip to non-looping and hooks the finish handler; the destination starts when the current clip ends |
tmBlend |
Same as tmSequentially |
function ToJSON(): TJSONObject; virtual;
function ToJSONString(): String; virtual;
procedure FromJSON(AJSON: TJSONObject); virtual;
Serialize all transition settings. Keys: Name, DetectionKind, Mode, HotKey,
States, Variable, Value, AnimationFrom, AnimationTo, OffsetAnimationFrom,
OffsetAnimationTo, Duration. Enumerations are written by name; the state set is
written as a bracketed, comma-separated list (e.g. [fpIdle,fpMoving]).
FromJSONresets all fields first, usingtkHotKeyAndStatesandtmImmediatlyas defaults for missing entries.
procedure Assign(Source: TPersistent); override;
Copies all settings from another transition. The cached animation links are not copied, so the target relinks against its own controller.
Holds all transitions of one layer.
Inheritance: TOwnedCollection → TGorillaAnimationTransitionCollection
| Property | Type | Description |
|---|---|---|
Layer |
TGorillaAnimationTransitionLayer |
The owning layer |
Controller |
TGorillaAnimationController |
The controller of the owning layer |
HashMap |
TGorillaAnimationTransitionsMap |
Lookup map, built on demand |
procedure UpdateHashMap();
Rebuilds the lookup map so transitions can be found without iterating the collection.
The map is created lazily on the first TryGetTransition call and is not refreshed
automatically when transitions are added, changed or removed afterwards - call this
method after runtime modifications.
function TryGetTransition(ACurrent: TGorillaAnimation;
AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates;
out ATransition: TGorillaAnimationTransition): Boolean; overload;
function TryGetTransition(ACurrent: TGorillaAnimation;
AVariable: String; AValue: String;
out ATransition: TGorillaAnimationTransition): Boolean; overload;
Looks up the bucket for the given key and returns the first transition in it whose
DispatchInput returns True. Builds the map first if necessary.
function ToJSON(): TJSONArray; virtual;
procedure FromJSON(AJSON: TJSONArray); virtual;
Serializes the collection as an array of transition objects. FromJSON clears the
collection first.
Groups transitions so complex animation behaviour stays manageable.
Inheritance: TCollectionItem → TGorillaAnimationTransitionLayer
| Property | Type | Description |
|---|---|---|
DisplayName |
String |
The layer name, used by FindLayer / RemoveLayer |
Transitions |
TGorillaAnimationTransitionCollection |
Transitions of this layer |
Animations |
TGorillaAnimationRefList |
Animations referenced by the transitions of this layer |
Model |
TGorillaModel |
The controller's model |
Controller |
TGorillaAnimationController |
The owning controller |
function AddTransition(const AName: String; const AFrom: String; const ATo: String;
ADoLoop: Boolean; AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates;
AMode: TGorillaAnimationTransitionMode): TGorillaAnimationTransition; overload; virtual;
function AddTransition(const AName: String; const AFrom: String; const ATo: String;
ADoLoop: Boolean; AVariable: String; AValue: TValue;
AMode: TGorillaAnimationTransitionMode): TGorillaAnimationTransition; overload; virtual;
Creates a transition and sets DetectionKind to tkHotKeyAndStates or tkCustom
respectively. Animation references are refreshed afterwards.
Parameters:
| Parameter | Description |
|---|---|
AName |
Transition name (DisplayName) |
AFrom / ATo |
Source and destination animation ID |
ADoLoop |
Loop of the destination animation |
AHotKey / AStates |
Trigger condition for the hotkey variant |
AVariable / AValue |
Trigger condition for the custom variant; the value is stored as AValue.ToString() |
AMode |
Switch mode |
function FindTransition(const AName: String): TGorillaAnimationTransition; overload; virtual;
function FindTransition(const AFrom: String; const ATo: String): TGorillaAnimationTransition; overload; virtual;
By name, or by animation pair.
The by-name overload searches the collection's lookup map and returns
nilwhile the map has not been built yet. CallTransitions.UpdateHashMap()first, or use the by-pair overload, which always scans the collection.
procedure DeleteTransition(const AName: String); overload; virtual;
procedure DeleteTransition(const AFrom: String; const ATo: String); overload; virtual;
Removes the matching transition and refreshes the animation references. Silently does nothing if nothing matches.
procedure DispatchInput(ADispatcher: TGorillaAnimationDispatcher); overload; virtual;
procedure DispatchInput(AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates); overload; virtual;
procedure DispatchInput(AVariable: String; AValue: String); overload; virtual;
procedure DispatchInput(AVariable: String; AValue: TValue); overload; virtual;
Evaluates the transitions of this layer against the current animation and switches on the
first match. Returns without effect when no model, no transitions or no current animation
exist. Every call stores the dispatch in the controller's DispatchState.
The hotkey overload uses the lookup map; the variable overloads iterate the collection in order.
procedure RebuildAnimationReferences();
procedure RequestAnimationReferences();
procedure AddAllAnimationReferences();
| Method | Description |
|---|---|
RequestAnimationReferences |
Adds the source and destination animation of every transition to Animations if not present |
RebuildAnimationReferences |
Clears Animations first, then requests them again |
AddAllAnimationReferences |
Adds all animations of the linked model, whether used by a transition or not |
These references carry the editor node positions; they are not needed for triggering.
procedure Clear(); virtual;
procedure Assign(Source: TPersistent); override;
function ToJSON(): TJSONObject; virtual;
procedure FromJSON(AJSON: TJSONObject); virtual;
Clear empties transitions and animation references. JSON keys: Id, Animations
(each with Id and UIPosition), Transitions.
Holds all layers of a controller.
Inheritance: TOwnedCollection → TGorillaAnimationTransitionLayerCollection
| Member | Description |
|---|---|
Controller |
The owning TGorillaAnimationController |
FindLayer(AName) |
Returns the layer with that name, or nil |
DispatchInput(...) |
Forwards the dispatch to every layer, in collection order |
ToJSON / FromJSON |
Serializes the layers as a JSON array |
Because layers are processed in order and each one evaluates against the animation that is current at that moment, a later layer can see and override the switch of an earlier one.
The component that switches character animations depending on configured transitions.
Inheritance: TGorillaController → TGorillaAnimationController
Platforms: All Gorilla platforms
property Model: TGorillaModel read FModel write SetModel;
The model the transitions apply to. The controller uses this model's
AnimationManager. Without a model, transitions are never triggered.
A model that was auto-loaded by
FromJSON/LoadFromFileis owned by the controller and is freed whenModelis reassigned, whenClearis called, or on destruction. A model assigned by the user is only unlinked.
property DefaultAnimation: String read FDefaultAnimation write SetDefaultAnimation;
ID of the animation the controller starts with. Assigning it resolves the animation,
makes it current and starts it immediately - so assign Model first. Without a default
animation there is no current animation and no transition can match.
property Layers: TGorillaAnimationTransitionLayerCollection read FLayers write SetLayers;
The layer collection. Each layer manages its own set of transitions.
property DispatchState: TGorillaAnimationDispatcher read FLastDispatch;
The last dispatched state. Useful to query the current intent, but not necessarily the currently active state, because animation switches can be delayed.
function GetAnimationManager(): TGorillaAnimationManager; virtual;
Returns the animation manager of the linked model, or nil if no model is linked.
function GetCurrentAnimation(): TGorillaAnimation; virtual;
Returns the currently playing animation, or nil if no model is linked.
procedure DispatchInput(ADispatcher: TGorillaAnimationDispatcher); overload; virtual;
procedure DispatchInput(AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates); overload; virtual;
procedure DispatchInput(AVariable: String; AValue: String); overload; virtual;
procedure DispatchInput(AVariable: String; AValue: TValue); overload; virtual;
Forwards the dispatch to all layers.
// custom variable
GorillaAnimationController1.DispatchInput('anim', 1);
// hotkey and states
GorillaAnimationController1.DispatchInput(
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving]);
TGorillaPhysicsCharacterController calls the hotkey overload automatically when its
Model and AnimationController properties are assigned.
function AddLayer(const AName: String): TGorillaAnimationTransitionLayer; virtual;
procedure RemoveLayer(const AName: String); virtual;
function FindLayer(const AName: String): TGorillaAnimationTransitionLayer; virtual;
function LayerExists(const AName: String): Boolean; virtual;
AddLayer returns the existing layer when the name is already in use, so it is safe to
call repeatedly.
function AddTransition(const ALayer: String; const AName: String; const AFrom: String;
const ATo: String; ADoLoop: Boolean; AHotKey: TGorillaCharacterControllerHotKey;
AStates: TGorillaCharacterControllerStates;
AMode: TGorillaAnimationTransitionMode): TGorillaAnimationTransition; overload; virtual;
function AddTransition(const ALayer: String; const AName: String; const AFrom: String;
const ATo: String; ADoLoop: Boolean; AVariable: String; AValue: TValue;
AMode: TGorillaAnimationTransitionMode): TGorillaAnimationTransition; overload; virtual;
Convenience wrappers around the layer methods. Return nil if the named layer does not
exist - create it with AddLayer first.
function FindTransition(const ALayer: String; const AName: String): TGorillaAnimationTransition; overload; virtual;
function FindTransition(const ALayer: String; const AFrom: String; const ATo: String): TGorillaAnimationTransition; overload; virtual;
procedure DeleteTransition(const ALayer: String; const AName: String); overload; virtual;
procedure DeleteTransition(const ALayer: String; const AFrom: String; const ATo: String); overload; virtual;
Delegate to the named layer; return nil / do nothing if the layer is unknown.
procedure Clear();
Resets the default animation, clears all layers, unlinks (and frees, if standalone) the model, and resets the stored dispatch state.
procedure SaveToFile(const AFilename: String);
procedure SaveToStream(AStream: TStream);
procedure LoadFromFile(const AFilename: String;
const APackage: TGorillaAssetsPackage = nil);
procedure LoadFromStream(AStream: TStream;
const APackage: TGorillaAssetsPackage = nil);
Persist the complete setup as UTF-8 JSON. The optional assets package receives models and textures that have to be auto-loaded.
function ToJSON(): TJSONObject; virtual;
procedure FromJSON(AJSON: TJSONObject;
const APackage: TGorillaAssetsPackage = nil); virtual;
JSON layout:
{
"Model": {
"Id": "GorillaModel1",
"Filename": "assets\\c.dae",
"Animations": ["c-idle.dae", "c-run.dae"]
},
"DefaultAnimation": "c-idle.dae",
"Layers": [
{
"Id": "Layer0",
"Animations": [ { "Id": "c-idle.dae", "UIPosition": [120, 80] } ],
"Transitions": [
{
"Name": "idle > run",
"DetectionKind": "tkHotKeyAndStates",
"Mode": "tmImmediatly",
"HotKey": "KeyboardMoveForward",
"States": "[fpMoving]",
"Variable": "",
"Value": "",
"AnimationFrom": "c-idle.dae",
"AnimationTo": "c-run.dae",
"OffsetAnimationFrom": 0,
"OffsetAnimationTo": 0,
"Duration": 0
}
]
}
]
}
FromJSON resolves the model in this order:
Id, searched in the owner and its child objectsTGorillaModel whose Source matches the stored FilenameFilename as a standalone model owned by the
controller, followed by every animation file listed in AnimationsExceptions: raised when the model cannot be found or auto-loaded, and when an animation file listed in the JSON does not exist.
TGorillaAnimationControllerEditor = class(TComponentEditor)
Design-time component editor. Adds the verb Transition Editor, which opens the
flow-chart editor (TTransitionFlowChartForm) for the selected controller. Available
in the IDE design package only.
The unit registers TGorillaAnimationController,
TGorillaAnimationTransitionLayerCollection, TGorillaAnimationTransitionLayer,
TGorillaAnimationTransitionCollection and TGorillaAnimationTransition with
System.Classes.RegisterClasses on initialization, so the collections survive DFM/FMX
streaming, and unregisters them on finalization.
AddAnimationFromFile() that is the file name.Transitions.UpdateHashMap() on the
affected layer.1, '1' and TValue.From<Integer>(1) are
equivalent conditions.tmBlend currently behaves like tmSequentially; the offset and duration properties
have no visible effect yet.Enabled property is not evaluated by this unit: dispatching and
switching work independently of it.TGorillaCharacterControllerHotKey, TGorillaCharacterControllerStateThe Gorilla.Arena.Directory unit provides TGorillaArenaDirectory, the client
side of the Arena lobby directory. A host publishes the session it just opened;
everybody else reads a list and picks one, instead of typing an IP address.
It talks to the PHP endpoint in <gorilla>\source\lib\arena\server. Every call
is made on a background thread and answers on the main thread, so nothing here
blocks the user interface.
The address never surfaces. A listing does not carry one, TGorillaArenaLobby
has no field that could hold one, and the address JoinLobby receives goes
straight into the session's Target without passing through any published
property or event parameter.
TComponent
└── TGorillaArenaDirectory
TThread
└── TArenaDirectoryTicker (internal)
| Field | Type | Description |
|---|---|---|
Id |
String |
Opaque handle; the only thing JoinLobby needs |
Name |
String |
What the list shows |
Host |
String |
Name of whoever opened it |
Game |
String |
Which game, as the application names it |
Note |
String |
One short line |
Players |
Integer |
How many are in |
Max |
Integer |
How many fit, or 0 when unsaid |
Locked |
Boolean |
Needs a password to join |
Started |
Boolean |
The match is already running |
Age |
Integer |
Seconds since it was opened |
Seen |
Integer |
Seconds since it was last heard from |
TGorillaArenaLobbies = TArray<TGorillaArenaLobby>
| Type | Signature |
|---|---|
TGorillaArenaLobbiesEvent |
procedure(const ASender : TObject; const ALobbies : TGorillaArenaLobbies) of object |
TGorillaArenaPublishedEvent |
procedure(const ASender : TObject; const AId : String; const APublicAddress : String) of object |
TGorillaArenaJoinedEvent |
procedure(const ASender : TObject; const ALobbyId : String; const ALobbyName : String) of object |
TGorillaArenaDirectoryError |
procedure(const ASender : TObject; const ACode : String; const AMessage : String) of object |
APublicAddress in TGorillaArenaPublishedEvent is our own address, which
is the one thing worth showing — it is what somebody types in when the
directory cannot be reached. TGorillaArenaJoinedEvent deliberately has no
address parameter.
GUID {4B7A1E62-2D93-4F58-9C10-3A6E5D84B7F1}
Tells a background request whether the component that started it is still
alive. A request hands its result back through TThread.Queue, which can run
after the component has been destroyed; the thread holds a reference to this
token, so it outlives the component.
| Member | Description |
|---|---|
Alive : Boolean |
The owner is still there |
Terminate() |
Marks it gone. Called from the destructor |
| Property | Type | Default | Description |
|---|---|---|---|
Endpoint |
String |
URL of the directory endpoint (index.php) |
|
Session |
TGorillaArenaSession |
The session to publish and to join with | |
Timeout |
Integer |
8000 |
Milliseconds to wait for the endpoint |
BeatInterval |
Integer |
60 |
Seconds between heartbeats. Clamped to a minimum of 5 |
RefreshInterval |
Integer |
0 |
Seconds between automatic refreshes; 0 for none |
OnLobbies |
TGorillaArenaLobbiesEvent |
A list arrived | |
OnPublished |
TGorillaArenaPublishedEvent |
Our lobby is in the directory | |
OnJoined |
TGorillaArenaJoinedEvent |
We are on our way into somebody's lobby | |
OnError |
TGorillaArenaDirectoryError |
Something went wrong | |
OnNotice |
TGorillaArenaNoticeEvent |
Something worth telling the user |
Refresh works without a Session. Publish reads the member count off it,
and JoinLobby cannot work at all without one.
| Property | Type | Description |
|---|---|---|
IsPublished |
Boolean |
Our own lobby is in the directory |
Busy |
Boolean |
A request is in flight |
LobbyId |
String |
Our own lobby's id, or '' |
The owner token that proves the registration is ours is held privately and is never exposed.
| Method | Description |
|---|---|
Refresh() |
Fetches the open lobbies. Answers through OnLobbies |
Publish(const AName : String; const AGame : String = ''; const ANote : String = ''; const APassword : String = '') |
Puts our session into the directory and starts the heartbeat. Calling it while already published does an Update instead |
Update() |
Pushes the current player count and state. The heartbeat does this by itself |
Withdraw() |
Takes our lobby out. IsPublished is false immediately, whatever the endpoint answers |
JoinLobby(const ALobbyId : String; const ADisplayName : String; const APassword : String = '') |
Asks where the lobby is and hands that to Session.JoinSession |
Lobbies() : TGorillaArenaLobbies |
A snapshot of the last list fetched |
| Method | Description |
|---|---|
Request(const AAction : String; APayload : TJSONObject; out AResponse : TJSONObject; out ACode, AError : String) : Boolean |
One synchronous round trip. virtual — a test seam for the network. The caller owns AResponse |
RunAsync(const AWork : TProc) |
Runs work on a background thread with the lifetime token held |
Sync(const AWork : TProc) |
Queues work to the main thread, unless the component is gone |
EnsureTicker() |
Starts the ticker when there is something to tick, stops it otherwise |
Tick() |
One tick on the main thread: does whatever came due |
ParseLobbies(AResponse : TJSONObject) : TGorillaArenaLobbies |
Reads the lobby array of a list answer |
DoError, DoNotice, DoLobbies |
Raise the matching events |
Reported through OnError as ACode.
| Code | Description |
|---|---|
no_endpoint |
Endpoint was never set |
unreachable |
No network, no DNS, or the server is down |
bad_answer |
Something answered, but not this API |
not_found |
The lobby is no longer open |
forbidden |
Wrong owner token |
locked |
Wrong or missing password |
too_many |
This address already has as many lobbies as it may |
rate_limited |
Too many requests |
full |
The directory is at its limit |
no_session |
JoinLobby without a Session |
Without an OnError handler the message goes to OnNotice, so a failure is
never silent.
The heartbeat is a thread, not a timer. A TTimer needs a platform service
and a message loop that a console or service application does not have, and it
would make this component depend on FireMonkey. The ticker wakes four times a
second, and the work itself is still queued to the main thread.
The clock is monotonic. Due times are measured on a TStopwatch, not on the
wall clock — a clock that jumps backwards would otherwise stop the heartbeat
for as long as the jump was.
A lobby the directory has forgotten is dropped locally. An update that
comes back not_found clears LobbyId and the token and stops the heartbeat,
so a later Publish makes a fresh registration rather than refreshing a ghost.
Other update failures are treated as passing network trouble and left to the
next heartbeat.
The destructor does not withdraw. That is a network round trip, and a
destructor is no place to wait for one; the lobby goes stale by itself within a
few minutes. Call Withdraw() when the session closes.
<gorilla>\source\lib\arena\server\README.md — the endpoint's own API documentationThe Gorilla.Arena.Entity unit provides TGorillaArenaEntity, the base class
for every object exchanged by tethering between all connected profiles — users
and their items, weapons, collected things, skills.
An entity keeps its properties in a JSON document rather than in fields.
Give each property a getter and setter that call GetJSONProperty and
SetJSONProperty, and no field declaration is needed: the document is the
storage, and it is also what goes on the wire.
TInterfacedObject
└── TJSONWrapObject (Gorilla.Arena.JSONWrap)
└── TGorillaArenaEntity implements IGorillaArenaEntity
└── TGorillaArenaUser
TGorillaArenaItemList = TList<IGorillaArenaEntity>
Field names every entity carries.
| Constant | Value | Description |
|---|---|---|
ARENA_ITEM_FIELD_SOURCEPROFILE |
SourceProfile |
Identifier of the profile the entity came from |
ARENA_ITEM_FIELD_GUID |
GUID |
The entity's identity |
ARENA_ITEM_FIELD_QUALIFIEDNAME |
QualifiedName |
Qualified class name, so the other side can build the right class |
ARENA_ITEM_FIELD_ID |
Id |
Free identifier |
ARENA_ITEM_FIELD_GROUP |
Group |
Free grouping key |
GUID {6D9D6905-61EF-4CF6-BC9E-3DB2CACD757A}, descends IJSONWrapObject.
| Member | Type | Description |
|---|---|---|
SourceProfile |
String |
Where it came from |
QualifiedName |
String |
Qualified class name (read only in effect) |
GUID |
TGUID |
Identity |
GUIDStr |
String |
The same as a string |
Id |
String |
Free identifier |
Group |
String |
Free grouping key |
SendLocalResource(AProfile) |
Broadcasts the complete entity | |
SendLocalResource(AProfile, AProperty, AValue) |
Broadcasts one changed property | |
BeginUpdate, EndUpdate, Submit, Changed |
See below |
constructor Create(const AProfile : TObject); reintroduce; virtual;
AProfile is whatever the entity reports its changes to — a component that
implements IGorillaArenaEntityHost (a session, a match, a manager), or, as
in code written for tethering, the manager's Profile: the manager installs
TGorillaArenaEntity.HostResolver, which leads from its app profile to itself.
The constructor generates a GUID and fills in GUID, QualifiedName and
SourceProfile — the host's EntityOwnerId, which makes the entity ours.
| Method | Called when |
|---|---|
EntityOwnerId() : String |
An entity is created here — its SourceProfile |
EntityChanged(const AEntity) |
A property changed (once per BeginUpdate/EndUpdate bracket) |
EntitySubmit(const AEntity) |
Submit or SendLocalResource — the entity is to reach everybody in full |
EntityPropertySubmit(const AEntity; const AProperty; const AValue) |
One property is to reach everybody |
The entity is handed over as an object, not as an interface: passing Self as
an interface from a reference counted object nobody holds yet would free it.
The tethering manager writes the shared resource and sends Item/Update
streams, as entities always did; a session on atDirect sends an owned,
listed entity in full to everybody.
| Method | Description |
|---|---|
RegisterEntityClass(const AClass) |
Makes a class findable by its qualified name when another participant shares an entity of it — and keeps the linker from dropping it |
FindEntityClass(const AQualifiedName) |
Registered classes first, then RTTI; nil when neither knows it |
HostResolver |
See above |
| Property | Type | Description |
|---|---|---|
QualifiedName |
String |
Setting it does nothing — the class name is not yours to change |
GUID |
TGUID |
Identity |
GUIDStr |
String |
Identity as a string |
Id |
String |
Free identifier |
Group |
String |
Free grouping key |
| Property | Type | Description |
|---|---|---|
Profile |
TObject |
What the entity was created with |
Host |
IGorillaArenaEntityHost |
Where changes go; nil once the host is gone |
SourceProfile |
String |
The owner — the tethering profile identifier, or the session member id on atDirect |
Bitmap |
TBitmap |
An image belonging to the entity. Needs streaming separately — it is not part of the JSON document |
| Method | Description |
|---|---|
BeginUpdate() |
Hold back updates while several properties change |
EndUpdate() |
End that |
Submit() |
Push the whole entity to everybody — EntitySubmit on the host |
Changed() |
Report the entity as changed — EntityChanged on the host |
SetJSONProperty(const AName : String; const AValue : TValue) |
Sets a property and reports the change; inside BeginUpdate/EndUpdate it is reported once, when the outermost EndUpdate is reached |
DetachHost() |
Lets go of the host; called by a host that is being destroyed |
GetEntity() : TGorillaArenaEntity |
The object behind the interface (also on IGorillaArenaEntity) |
ApplyFromJSON(const AData : TJSONObject) |
Replaces the document with the supplied one, then submits. Does not check that the data belongs to this class |
| Method | Description |
|---|---|
SendLocalResource(AProfile : TObject) |
EntitySubmit on the host. AProfile is kept for compatibility and ignored |
SendLocalResource(AProfile : TObject; const AProperty : String; const AValue : TValue) |
EntityPropertySubmit on the host |
UpdateLocalResource() |
EntityChanged on the host |
All three return immediately while an update is in progress.
Changing a property updates the local resource, which the other side mirrors. Changing several in a row therefore produces one update each — which is a lot of network traffic for no reason:
LItem.BeginUpdate();
try
LItem.Property1 := 'abc';
LItem.Property2 := 123;
LItem.Property3 := 1.25;
finally
LItem.EndUpdate();
LItem.Submit();
end;
type
TCard = class(TGorillaArenaEntity)
protected
function GetSuit() : String;
procedure SetSuit(const AValue : String);
published
property Suit : String read GetSuit write SetSuit;
end;
function TCard.GetSuit() : String;
begin
Result := GetJSONProperty('Suit').AsString().DeQuotedString('"');
end;
procedure TCard.SetSuit(const AValue : String);
begin
SetJSONProperty('Suit', AValue);
end;
Simple types are stored directly as JSON. For values that are not — a colour,
a 3D point — convert on the way in and out; see
Gorilla.Arena.Utils and the implementation of
TGorillaArenaUser.
The Gorilla.Arena.JSONWrap unit provides TJSONWrapObject, the JSON backed
object entities are built on. Instead of fields, an
instance holds a TJSONObject and reads and writes its properties through it,
using RTTI to convert between TValue and JSON.
That is what makes an entity serialisable without any per-class code: the document is already the wire format.
The interfaces are declared separately in Gorilla.Arena.Intf.JSONWrap, so a
unit can depend on the contract without depending on the implementation.
TInterfacedObject
└── TJSONWrapObject implements IJSONWrapObject
├── TJSONWrapError implements IJSONWrapError
└── TGorillaArenaEntity
TJSONWrapObjectClass = class of TJSONWrapObject
TJSONWrapErrorClass = class of TJSONWrapError
| Type | Description |
|---|---|
TJSONWrapObjectList |
TList<IJSONWrapObject> |
TJSONWrapArray |
TArray<TValue> |
GFloatFormat |
Global TFormatSettings, fixed to en-US so numbers travel between locales |
GUID {E51FDEE9-E41C-4498-B66D-B33B33F975F6}
| Method | Description |
|---|---|
GetRefCount() : Integer |
Current reference count |
ToString() : String |
The document, serialised |
ToJSON() : TJSONValue |
The document. The caller owns the result |
ApplyFromJSON(const AData : TJSONObject) |
Replaces the document |
GetPropertyType(const pName : String) : TClass |
The class behind a property, when it has one |
GetJSONProperty(const pName : String) : TValue |
Reads one property |
SetJSONProperty(const pName : String; const pValue : TValue) |
Writes one property |
GetListProperty(const pName : String; const pClass : TClass; const AMultipleTypes : Boolean = false) : TJSONWrapObjectList |
Reads an array of objects |
GetIntfProperty(const pName : String; const pClass : TClass) : IJSONWrapObject |
Reads a nested object |
GetArrayProperty(const pName : String) : TJSONWrapArray |
Reads an array of plain values |
IJSONWrapError (GUID {30EC6018-0B1F-4801-A7B7-2A674D519D6E}) descends it
and marks an object that carries an error rather than data.
| Property | Type | Description |
|---|---|---|
Origin |
Boolean |
True when this instance owns its document and frees it. False for a view onto somebody else's |
| Member | Description |
|---|---|
class var error_class : TJSONWrapErrorClass |
Which class to build for an error object |
class function ValueToJSON(const AValue : TValue) : TJSONValue |
Converts a TValue to JSON |
class function FromJSON(const AData : TJSONObject) : IJSONWrapObject |
Builds an instance from a document |
class function FromJSON(const AData : String) : IJSONWrapObject |
The same from text |
GetRttiValue reads JSON back into a TValue:
| JSON | Delphi |
|---|---|
true / false |
Boolean |
| number with a decimal point | Double |
| number without one | Integer |
| array | TJSONWrapArray |
| object | nested wrap object |
| anything else | String |
A number is therefore typed by how it was written: 1 comes back as
Integer, 1.0 as Double. Where that matters, write the value with a
decimal point, or convert explicitly on the way out.
| Method | Description |
|---|---|
class IsErrorObject(const AJSON : TJSONValue) : Boolean |
Whether a document is an error rather than data |
class GetErrorMessage(const ACode : Integer) : String |
Text for an error code |
Both are virtual — a descendant defines what an error looks like for its own
protocol.
The Gorilla.Arena.Manager unit provides TGorillaArenaManager, the component
every Arena application rests on. It wraps a TTetheringManager and a
TTetheringAppProfile, pairs the devices, connects their profiles, keeps the
list of participants, and mirrors entities between them.
Users, Items, Myself, the user and item events and the logging come from
its base class TGorillaArenaCustomManager (Gorilla.Arena.Base), which has
no tethering in it. The manager is the App Tethering part and does not exist on
Linux; there TGorillaArenaSession derives from the base class directly.
The tethering manager and the app profile are created in the constructor and
left disabled until Join(), so dropping the component on a form starts
nothing.
TComponent
└── TGorillaArenaCustomManager (Gorilla.Arena.Base)
└── TGorillaArenaManager (not on Linux)
└── TGorillaArenaSession
| Type | Signature |
|---|---|
TOnArenaStatusChanged |
procedure(const ASender : TObject; const AState : TArenaUserState) of object |
TOnArenaUserEvent |
procedure(const ASender : TObject; AUser : IGorillaArenaUser; const AAction : TArenaUserAction) of object |
TOnArenaMessage |
procedure(const ASender : TObject; const AMessage : String) of object |
TOnArenaError |
procedure(const ASender : TObject; const AMessage : String) of object |
TOnArenaItemEvent |
procedure(const ASender : TObject; AItem : IGorillaArenaEntity; const AAction : TArenaUserAction) of object |
The TOnArena* types are declared in Gorilla.Arena.Base and repeated here as
aliases, so code that only uses this unit keeps compiling.
| Type | Signature |
|---|---|
TRemoteResourceRequestProc |
reference to procedure(const AManager : TGorillaArenaManager; const AProfile : TTetheringProfileInfo; const ARes : TRemoteResource) |
TArenaUserState and TArenaUserAction are declared in
Gorilla.Arena.User.
GUID {2F3C8E51-6A44-4C0B-9E2D-7B15A0C4D8E9}
Tells a background task whether the manager that started it is still alive. The
asynchronous resource requests hand their result back through TThread.Queue,
which can run after the manager has been destroyed; the task holds a reference
to this token, so it outlives the manager and can be asked whether calling back
is still safe.
| Member | Description |
|---|---|
Alive : Boolean |
The owner is still there |
Terminate() |
Marks the owner as gone. Called from the destructor |
| Property | Type | Description |
|---|---|---|
Id |
String |
Stable identity in the group. Defaults to a fresh GUID; set it before Join(). Not what a user reads |
DisplayName |
String |
The name other participants see. Free text |
Target |
String |
The group to join. Changing it while joined disconnects and reconnects |
AllowedAdapters |
String |
Which tethering adapters may be used, comma separated. Defaults to Network_V4 |
BindToAddress |
String |
The local IPv4 address to advertise. Empty lets Join() choose |
OnStatusChanged |
TOnArenaStatusChanged |
None, Pending or Joined |
OnUserEvent |
TOnArenaUserEvent |
Somebody was added, removed or updated |
OnMessage |
TOnArenaMessage |
Log output |
OnError |
TOnArenaError |
Problems in plain text; also goes to OnMessage |
| Property | Type | Description |
|---|---|---|
Myself |
IGorillaArenaUser |
Our own user. Only assigned between Join and Leave |
Tethering |
TTetheringManager |
The internal tethering manager |
Profile |
TTetheringAppProfile |
The internal app profile |
Joined |
Boolean |
Join() brought the manager up — with or without anybody else |
Active |
Boolean |
The same, under the name that says what it means |
HasPeers |
Boolean |
At least one remote manager is paired |
Users |
TGorillaArenaUserList |
The participants, keyed by GUID |
Items |
TGorillaArenaItemList |
The known entities |
| Method | Description |
|---|---|
Join() |
Connects to the configured group, creates our user, reports Pending then Joined |
Leave() |
Leaves the group and reports None |
Broadcast(const AResource, AData : String) |
Sends AData to the named resource on every connected profile |
Greeting(const AMessage : String) |
A broadcast to the Greeting resource |
UpdateUsers() |
Asks every remote profile for its user list and raises OnUserEvent with Update for each |
CleanupUsers() |
Drops users whose profile is gone, raising OnUserEvent with Remove |
SetUserClass(AUserClass : TGorillaArenaUserClass) |
Use a user class of your own. Call before joining |
Log(const AMessage : String) |
Produces a log line through DoOutputMessage |
| Method | Description |
|---|---|
SetupDefaultProfile() |
Declare resources of your own. Called on the first Join(), never from the constructor |
EnsureDefaultProfile() |
Runs SetupDefaultProfile once |
ConnectRemoteProfiles() |
Connects our profile to every remote profile of our group |
PickBindAddress(const ASubnets : TArray<TIPv4Subnet>) : String |
Picks the address to advertise on a multi-homed machine |
EnsureBindAddress() |
Sets BindToAddress when the machine has two or more IPv4 subnets |
LocalIPv4Subnets() : TArray<TIPv4Subnet> |
This machine's IPv4 addresses |
DoOutputMessage(const AMessage : String) |
Where log output goes |
DoErrorMessage(const AMessage : String) |
Reports an error as a log line and through OnError |
DoStatusChanged, DoUserEvent |
Raise the matching events; both return at once while FDestroying |
CreateMyself() : IGorillaArenaUser |
Builds our own user |
AddRemoteUser(const AGUID : TGUID; const AProfile) : IGorillaArenaUser |
Builds an empty remote user |
RequestRemoteResources(const AResource : String; ACallback) |
Blocking round trip to every connected profile |
RequestRemoteResourcesAsync(const AResource : String; ACallback) |
The same in a background task; the callback runs on the main thread |
| Field | Type | Description |
|---|---|---|
FTetheringManager |
TTetheringManager |
|
FAppProfile |
TTetheringAppProfile |
|
FUsers |
TGorillaArenaUserList |
|
FItems |
TGorillaArenaItemList |
|
FProfileReady |
Boolean |
SetupDefaultProfile has run |
FDestroying |
Boolean |
Set while the destructor runs; suppresses all outgoing events |
FLifetime |
IArenaLifetime |
Handed to background tasks |
| Resource | Description |
|---|---|
UserList |
The participant list, requested from remote profiles |
Greeting |
Plain string messages, see Greeting() |
Item |
A complete entity |
Update |
A single changed property of an entity |
DispatchToResource works around the way the RTL delivers SendString and
SendStream: both wrap what arrived in a temporary resource with a freshly
generated name and put the sender's name in its Hint, raising only the
profile-wide OnResourceReceived. Without that dispatch, every per-resource
handler would be dead code for anything sent rather than mirrored.
On a machine with two or more IPv4 subnets — and only then — the RTL multicast
adapter puts the literal placeholder MULTIHOMED into its connection string
instead of an address. The UDP adapter substitutes a real address per interface
before a datagram leaves; the multicast adapter's BroadcastCommand does not,
so the placeholder goes out on the wire. Every manager that answers then opens
a TCP connection to the host MULTIHOMED, which resolves nowhere, and gives up
with "no connections available". Nobody discovers anybody and no error is
visible from the outside.
EnsureBindAddress sets BindToAddress, which makes the adapter leave its
subnet table empty and put its real address on the wire. A machine with a
single subnet never had the problem and is left alone.
Note that TGorillaArenaSession overrides PickBindAddress to return an empty
string — for a broadcast based session that is the better answer. See
Gorilla.Arena.Session.
The manager is not synchronized. It relies on the tethering manager delivering
its events on the main thread, which is what TTetheringManager.SynchronizeEvents
does and defaults to. With that switched off, every handler runs on a worker
thread and guarding the user and item lists is the caller's job. The only work
the manager does off the main thread by itself is
RequestRemoteResourcesAsync.
The Gorilla.Arena.Match unit provides TGorillaArenaMatch, a
TGorillaArenaSession in which everybody takes turns. It adds seating, turn
order, host authority and state synchronisation, and drives an
IGorillaArenaRules implementation supplied by the application.
The host owns the only authoritative rules instance. Every other device keeps one purely to render the state the host ships it.
TComponent
└── TGorillaArenaManager
└── TGorillaArenaSession
└── TGorillaArenaMatch
Payload field names used by the match messages.
| Constant | Value |
|---|---|
ARENA_DATA_IDS |
ids |
ARENA_DATA_NAMES |
names |
ARENA_DATA_HOST |
host |
ARENA_DATA_RULES |
rules |
ARENA_DATA_STARTED |
started |
ARENA_DATA_STATE |
state |
ARENA_DATA_HEADLINE |
headline |
ARENA_DATA_MEMBER |
member |
ARENA_DATA_TURN |
turn |
ARENA_DATA_BY |
by |
ARENA_DATA_MOVE |
move |
ARENA_DATA_NAME |
name |
The message types themselves are in Gorilla.Arena.Message.
| Type | Signature |
|---|---|
TGorillaArenaMoveEvent |
procedure(const ASender : TObject; const AName : String; const AMove : TJSONObject) of object |
TGorillaArenaCreateRulesEvent |
procedure(const ASender : TObject; const AId : String; out ARules : IGorillaArenaRules) of object |
AMove is borrowed and may be nil. Leave ARules nil for an id this build
cannot produce.
| Property | Type | Description |
|---|---|---|
RulesComponent |
TGorillaArenaRules |
A rules component on the same form, used when nothing else builds the rules |
OnMatchChanged |
TNotifyEvent |
The state, the turn or the outcome changed |
OnRemoteMove |
TGorillaArenaMoveEvent |
Somebody else moved |
OnCreateRules |
TGorillaArenaCreateRulesEvent |
Build the rules behind an id |
| Property | Type | Description |
|---|---|---|
Rules |
IGorillaArenaRules |
The rules in play. Settable for one fixed set |
RulesId |
String |
Id of the rules in play (read only) |
HostId |
String |
Id of whoever is hosting (read only) |
InMatch |
Boolean |
True while a match is running |
| Method | Description |
|---|---|
StartMatch(const ARulesId : String = '') |
Host only. Builds the rules, checks MinMembers, fixes the seating and announces the start |
SubmitMove(AMove : TJSONObject) |
Reports what we did on our turn. Takes ownership; AMove may be nil. Does nothing unless it was our turn |
CloseSession() |
Overridden: clears the match state, then leaves the session |
IsMyTurn() : Boolean |
Our turn, and we have not moved yet |
TurnSeat() : Integer |
Seat of whoever is on turn, or -1 |
TurnMemberName() : String |
Their name, or '' |
SeatOf(const AId : String) : Integer |
Seat of an id, or -1 |
Participants() : TGorillaArenaMembers |
Everybody, in the order they should be listed |
Scoreboard() : TGorillaArenaScoreboard |
The rules' scoreboard, or empty |
Headline() : String |
The rules' headline, or '' |
| Method | Description |
|---|---|
CreateRules(const AId : String) : IGorillaArenaRules |
Asks OnCreateRules, then falls back to RulesComponent. Override to use a registry |
DoDecorateStart(AMsg) |
Host: add application data to the start message |
DoApplyStart(AMsg) |
Client: read it back |
DoDecorateTurn(AMsg) |
Host: add application data to a turn message |
DoApplyTurn(AMsg) |
Client: read it back |
DoRemoteMove(const AName : String; const AMove : TJSONObject) |
Somebody else moved. The base raises OnRemoteMove |
MatchChanged() |
Raises OnMatchChanged |
| Field | Type | Description |
|---|---|---|
FRules |
IGorillaArenaRules |
The rules in play |
FRulesId |
String |
Their id |
FHostId |
String |
Id of the host |
FSeating |
TList<TGorillaArenaMember> |
Seating order; the truth on the host, a copy elsewhere |
FRoster |
TList<TGorillaArenaMember> |
Client side: who the host says is in |
FStarted |
Boolean |
A match is running |
FTurnId |
String |
Who is on turn |
FTurnNo |
Integer |
Which turn — distinguishes a new instruction from a repeat |
FReported |
Boolean |
Client side: we have already moved for FTurnNo |
Seating is fixed at the start. A member who leaves keeps their seat and
score and is marked Here := False; the rules are told through MemberLeft.
Turn numbers stop double moves. The host re-sends the current turn whenever somebody greets, and the session layer greets more than once per join. A turn message repeating the number this device already answered is ignored.
Participants() answers differently by situation — the seating during a
match, the host's roster on a client before one, and the session's member list
otherwise. A roster the client is not itself in is ignored.
Two hosts meeting settle by id: the lower id keeps the session, the other
switches to asrClient.
A newcomer mid match gets the lobby, the current state, and the running turn marked as a repeat.
The Gorilla.Arena.Message unit defines the wire format the Arena session and
match components speak: one JSON envelope carrying an envelope version, an
application version, a type, its sender, a sequence number and a free form
payload. It also provides the gate that keeps late and duplicated messages out.
Nothing in the unit knows what an application does with any of it.
TObject
├── TGorillaArenaMessage
└── TGorillaArenaSequenceGate
| Constant | Value | Description |
|---|---|---|
ARENA_MESSAGE_VERSION |
1 |
Version of the envelope itself, owned by the framework |
ARENA_FIELD_VERSION |
v |
Envelope version |
ARENA_FIELD_APPVERSION |
app |
Application version |
ARENA_FIELD_TYPE |
type |
Message type |
ARENA_FIELD_FROM |
from |
Sender id |
ARENA_FIELD_SEQ |
seq |
Sequence number |
ARENA_FIELD_DATA |
data |
Payload object |
| Constant | Value | Direction |
|---|---|---|
ARENA_MSG_HELLO |
hello |
client → host |
ARENA_MSG_LOBBY |
lobby |
host → all |
ARENA_MSG_START |
start |
host → all |
ARENA_MSG_TURN |
turn |
host → all |
ARENA_MSG_STATE |
state |
host → all |
ARENA_MSG_OVER |
over |
host → all |
ARENA_MSG_MOVE |
move |
client → host |
An application is free to use any other type name for messages of its own;
they arrive at TGorillaArenaSession.OnAppMessage.
One message on the wire. It owns its payload object: build one, fill in Data
through the helpers, hand it to the session — the session frees it once it is
on its way.
constructor Create(const AType : String; const AFrom : String = '';
const AAppVersion : Integer = 0);
Prefer TGorillaArenaSession.NewMessage, which fills in the sender and the
version for you.
| Property | Type | Access | Description |
|---|---|---|---|
MsgType |
String |
read | What the message is for |
From |
String |
read/write | Sender's member id |
Seq |
Int64 |
read/write | Sequence number, set by the session |
Version |
Integer |
read | Envelope version |
AppVersion |
Integer |
read/write | Application version |
Data |
TJSONObject |
read | The payload |
| Method | Description |
|---|---|
ToJSON() : String |
Serialises the complete envelope |
class Parse(const AText : String; const AAppVersion : Integer; out AError : String) : TGorillaArenaMessage |
Reads a message off the wire. Returns nil and fills AError with something a user can be shown |
Parse refuses a foreign envelope version and, unless AAppVersion is 0, a
foreign application version. Pass 0 to accept whatever arrives.
All work on Data.
| Method | Description |
|---|---|
SetStr(const AName, AValue : String) |
|
GetStr(const AName : String; const ADefault : String = '') : String |
|
SetInt(const AName : String; const AValue : Integer) |
|
GetInt(const AName : String; const ADefault : Integer = 0) : Integer |
|
SetBool(const AName : String; const AValue : Boolean) |
|
GetBool(const AName : String; const ADefault : Boolean = false) : Boolean |
|
SetIntArray(const AName : String; const AValues : TArray<Integer>) |
|
GetIntArray(const AName : String) : TArray<Integer> |
|
SetStrArray(const AName : String; const AValues : TArray<String>) |
|
GetStrArray(const AName : String) : TArray<String> |
|
SetObject(const AName : String; AValue : TJSONObject) |
Takes ownership of AValue |
GetObject(const AName : String) : TJSONObject |
Borrowed — the message keeps owning it |
Keeps late and duplicate messages out. Tethering does not promise ordering across resources, and a resource can be delivered twice. Every sender numbers its own messages upwards, and anything not newer than what was already seen from that sender is dropped.
| Method | Description |
|---|---|
Accept(const AFrom : String; const ASeq : Int64) : Boolean |
True when the message is new; remembers it in that case |
Forget(const AFrom : String) |
Forgets one sender — call it when somebody leaves, so a returning participant starting over at 1 is not ignored for good |
Clear() |
Forgets everybody |
TGorillaArenaSession owns one and applies it to everything that arrives, so
an application normally never touches this class.
The unit deliberately avoids TJSONObject.GetValue<T>(AName, ADefault): that
overload is younger than some of the IDE versions the package is built for.
Private helpers do the same job.
The Gorilla.Arena.Rules unit describes what a match is played by: the
participants, the seating over them, the scoreboard, and the
IGorillaArenaRules interface a TGorillaArenaMatch drives.
Nothing in the unit knows about tethering or FireMonkey, so a set of rules can be exercised on its own — without a network and without a form.
TInterfacedObject
└── TGorillaArenaCustomRules implements IGorillaArenaRules
TComponent
└── TGorillaArenaRules implements IGorillaArenaRules
One participant, as the rules see them.
| Field | Type | Description |
|---|---|---|
Id |
String |
Stable identity, handed out by the session |
Name |
String |
What the others read |
Here |
Boolean |
False once somebody left mid match — their turns get skipped |
TGorillaArenaMembers = TArray<TGorillaArenaMember>
| Field | Type | Description |
|---|---|---|
Name |
String |
Whose row this is |
Score |
Integer |
The number that decides the ranking |
Detail |
String |
Free text next to it |
Current |
Boolean |
Marks the member whose turn it is |
Gone |
Boolean |
Marks a member who left |
TGorillaArenaScoreboard = TArray<TGorillaArenaScoreRow>
What a lobby needs to know without instantiating anything.
| Field | Type | Description |
|---|---|---|
Id |
String |
Stable key. Travels on the wire — never translate it |
Name |
String |
What the lobby shows |
Description |
String |
One line under the name |
MinMembers |
Integer |
Below this the match will not start |
MaxMembers |
Integer |
Above this nobody else is seated. 0 means no limit |
The seating of one match and the turn order over it. Held by both base classes so the way a table is walked round exists once.
| Member | Description |
|---|---|
Members : TGorillaArenaMembers |
The seating |
Reset(const AMembers) |
Takes a copy |
MemberLeft(const ASeat : Integer) |
Marks one seat as left behind |
NextPresentSeat(const AFrom : Integer) : Integer |
Next occupied seat after AFrom, or -1. One lap at most |
PresentCount() : Integer |
How many are still here |
Count() : Integer |
How many seats there are |
SeatOf(const AId : String) : Integer |
Seat of an id, or -1 |
GUID {6B1D2A54-9F73-4C86-A1E2-0D7F35C9B481}
| Method | Description |
|---|---|
GetRulesInfo() : TGorillaArenaRulesInfo |
Describes the rules |
Reset(const AMembers : TGorillaArenaMembers) |
Starts a fresh match in this seating order |
CurrentSeat() : Integer |
Seat of whoever is to move, or -1 when the match is over |
SubmitTurn(const ASeat : Integer; const AMove : TJSONObject) |
Feeds one move in and advances the turn. AMove is borrowed and may be nil |
MemberLeft(const ASeat : Integer) |
A member is gone; their turns are skipped |
Finished() : Boolean |
The match is over |
StateToJSON() : TJSONObject |
Everything a client needs to render. The caller owns the result |
StateFromJSON(const AState : TJSONObject) |
Applies what the host sent. Does not take ownership |
Headline() : String |
One line above the scoreboard |
Scoreboard() : TGorillaArenaScoreboard |
The rows to show |
Only the host ever sees SubmitTurn, CurrentSeat and Finished acted upon;
on a client the instance is a renderer fed by StateFromJSON.
Reference counted base for rules built on demand — a registry of several games, for instance.
GetRulesInfo, CurrentSeat, SubmitTurn, Finished, StateToJSON,
StateFromJSON, Headline and Scoreboard are virtual; abstract — a
descendant must supply them. Reset and MemberLeft are virtual and already
maintain the seating; call inherited.
| Method | Description |
|---|---|
NextPresentSeat(const AFrom : Integer) : Integer |
Forwards to the seating |
PresentCount() : Integer |
Forwards to the seating |
| Property | Type | Description |
|---|---|---|
Members |
TGorillaArenaMembers |
The seating |
The same, as a component: drop a descendant on a form and point
TGorillaArenaMatch.RulesComponent at it. TComponent implements IInterface
without reference counting, so the match holding the interface does not change
who owns the component — the form does.
Same method and property set as TGorillaArenaCustomRules.
The Gorilla.Arena.Session unit provides TGorillaArenaSession, a component
that turns a group of devices into a session: a role, a chosen transport, a
member list and one message channel. It descends from TGorillaArenaManager
and adds what an application needs on top of raw tethering, including the
workarounds without which two devices on an ordinary network do not find each
other.
On Linux the class descends from TGorillaArenaCustomManager instead — App
Tethering has no Linux implementation there — and every session runs over the
Arena's own transport, atDirect (Gorilla.Arena.Net). Users, items and
entities work the same on every platform.
TComponent
└── TGorillaArenaCustomManager (Gorilla.Arena.Base - users, items, events)
├── TGorillaArenaManager (App Tethering, not on Linux)
│ └── TGorillaArenaSession
│ └── TGorillaArenaMatch
└── TGorillaArenaSession (Linux)
└── TGorillaArenaMatch
| Symbol | Meaning |
|---|---|
NOTETHER |
Defined by the unit itself when LINUX is defined. The tethered half is compiled out; sessions run over atDirect |
| Value | Description |
|---|---|
asrOffline |
Not in a session |
asrHost |
Opened the session; keeps the state and decides |
asrClient |
Joined somebody else's session |
| Value | Description |
|---|---|
atNetwork |
App Tethering, UDP broadcast over the local network |
atBluetooth |
App Tethering, RFCOMM to a device already paired at OS level |
atDirect |
The Arena's own transport: UDP discovery, TCP to the host. All platforms, the only one on Linux (default) |
Exactly one at a time — two allowed tethering adapters deadlock
TTetheringAppProfile.Connect. Tethering and atDirect do not see each other.
| Type | Signature |
|---|---|
TGorillaArenaNoticeEvent |
procedure(const ASender : TObject; const AText : String) of object |
TGorillaArenaMessageEvent |
procedure(const ASender : TObject; AMessage : TGorillaArenaMessage; var AHandled : Boolean) of object |
| Property | Type | Default | Description |
|---|---|---|---|
Transport |
TGorillaArenaTransport |
atDirect |
Which transport the next session uses |
MessageResource |
String |
ArenaMessage |
Name of the tethering resource all messages travel through |
AppVersion |
Integer |
1 |
Version of the application's payloads; a mismatch is refused |
EnvPrefix |
String |
ARENA |
Prefix of the environment variables read |
LogTag |
String |
Arena |
Prefix of platform log lines |
SearchInterval |
Integer |
4000 |
Milliseconds between two searches |
SearchWindow |
Integer |
3000 |
How long one search listens |
SearchMaxTries |
Integer |
15 |
Searches before giving up |
DirectPort |
Integer |
47810 |
atDirect: TCP port of the host; the next nine are tried when taken |
DiscoveryPort |
Integer |
47811 |
atDirect: UDP discovery port |
Id, DisplayName, Target, AllowedAdapters, BindToAddress |
String |
Inherited from TGorillaArenaManager; on Linux published by the session itself under the same names |
|
OnStatusChanged, OnUserEvent, OnItemEvent, OnMessage, OnError |
Inherited from TGorillaArenaCustomManager |
||
OnNotice |
TGorillaArenaNoticeEvent |
Something worth telling the user | |
OnMembersChanged |
TNotifyEvent |
Somebody arrived or left | |
OnAppMessage |
TGorillaArenaMessageEvent |
A message the framework does not know |
| Constant | Value | Payload |
|---|---|---|
ARENA_MSG_ENTITY |
arena.entity |
kind (user/item), entity (the entity's JSON). Accepted only from the owner named in SourceProfile |
ARENA_MSG_ENTITY_GONE |
arena.entity.gone |
guid of an item its owner removed |
Both are handled in DispatchMessage; they never reach OnAppMessage.
Everything TGorillaArenaManager publishes — Id, DisplayName, Target,
AllowedAdapters, BindToAddress, OnStatusChanged, OnUserEvent,
OnMessage, OnError — remains available and unused by this class.
| Property | Type | Description |
|---|---|---|
Role |
TGorillaArenaSessionRole |
Where this device stands |
IsHost |
Boolean |
Role = asrHost |
IsOffline |
Boolean |
Role = asrOffline |
MemberCount |
Integer |
How many members are known |
| Method | Description |
|---|---|
OpenSession(const ADisplayName : String) |
Opens a session and waits for others. On Android returns before the session is up — the Bluetooth permission is asked first |
JoinSession(const ADisplayName : String; const ATarget : String = '') |
Looks for a session and joins it. ATarget names a host directly |
CloseSession() |
Leaves the session. virtual |
SendMessage(AMsg : TGorillaArenaMessage) |
Sends to everybody. Takes ownership of AMsg |
NewMessage(const AType : String) : TGorillaArenaMessage |
Builds a message carrying this session's versions and sender |
Notice(const AText : String) |
Logs the text and raises OnNotice |
MyId() : String |
Our own member id; empty until opened or joined |
LocalAddress() : String |
The address others must be pointed at when discovery fails |
Members() : TGorillaArenaMembers |
Everybody known, ourselves included |
MemberName(const AId : String) : String |
The name behind an id, or '' |
LocalAddresses() : TArray<String> |
The IPv4 addresses of this machine, for choosing a network card |
ListenPort() : Integer |
atDirect host: the TCP port actually listened on; 0 otherwise |
UpdateUsers() |
atDirect: shares our entities again and reports every user with Update. Tethering: as the manager |
CleanupUsers() |
atDirect: drops the entities of everybody no longer in the session. Tethering: as the manager |
AddItem(const AItem) / RemoveItem(const AItem) |
Inherited from TGorillaArenaCustomManager: share one of our items, or take it back |
| Method | Description |
|---|---|
DoSessionStarting() |
A role was taken, before the network comes up |
DoSessionReady() |
The session is up |
DoMemberArrived(const AMember : TGorillaArenaMember) |
Somebody joined. The base raises a notice |
DoMemberGone(const AMember : TGorillaArenaMember) |
Somebody left |
DispatchMessage(AMsg) : Boolean |
Act on a message; False offers it to OnAppMessage |
Transmit(const AText : String) |
The only place the network is touched — a test seam |
RebuildMembers() |
Rebuild the member list from the arena user list — a test seam |
ApplyBindOverride() |
Applies <PREFIX>_BIND |
AdapterList() : String |
The adapters to allow, from Transport or <PREFIX>_ADAPTERS |
PickBindAddress(const ASubnets) : String |
Overridden to return '' — the RTL then binds every card |
ConnectRemoteProfiles() |
Overridden to accept a refused connection only when ConnectedProfiles confirms one, and to leave it to the search repeat otherwise |
DiscoverPairedProfiles() |
Asks a paired manager for its profiles again while none of ours is known from it — the passively paired side gets no discovery of its own |
EnvValue(const ASuffix : String) : String |
Reads <EnvPrefix>_<ASuffix> |
LogPrefix() : String |
LogTag, or Arena while the manager's constructor is still running |
UsesDirect() : Boolean |
Whether a session opened now goes over atDirect — always on Linux |
ApplyRoster(const APeers) |
atDirect: makes the member list the host's roster, raises DoMemberArrived/DoMemberGone, removes the entities of those who left and shares ours with those who came |
DirectCreateMyself() |
atDirect: our own user, owned by this session's member id |
SendEntity(const AEntity) / ResendOwnEntities() |
atDirect: shares one or all of our entities |
HandleEntity(AMsg) / HandleEntityGone(AMsg) |
atDirect: applies what an owner shared or removed |
EntityOwnerId, EntityChanged, EntitySubmit, EntityPropertySubmit |
IGorillaArenaEntityHost: on atDirect an owned, listed entity is sent in full; on tethering the manager's behaviour |
When overriding
DoStatusChangedorDoUserEvent, return immediately ifFDestroyingis set — the manager reports its own teardown through them.
| Field | Type | Description |
|---|---|---|
FRole |
TGorillaArenaSessionRole |
Current role |
FMembers |
TList<TGorillaArenaMember> |
The member list |
FMyId |
String |
Our own id |
FSeqOut |
Int64 |
Outgoing sequence counter |
FGate |
TGorillaArenaSequenceGate |
Drops late and duplicated messages |
All prefixed with EnvPrefix.
| Variable | Description |
|---|---|
<PREFIX>_LOG |
File to append the trace to |
<PREFIX>_BIND |
Network card to bind to; overrides everything |
<PREFIX>_ADAPTERS |
Adapters to allow. Separate with ; or \|, never with commas |
Destroy calls inherited before freeing its lists: tearing the manager
down runs Leave(), which comes back through DoStatusChanged and
DoUserEvent, and those read what would otherwise already be gone.
The Gorilla.Arena.User unit provides TGorillaArenaUser, the entity that
represents one participant, and TGorillaArenaUserList, the map the manager
keeps them in. A user is an entity with a colour, a
position and a list of items of its own.
TJSONWrapObject
└── TGorillaArenaEntity
└── TGorillaArenaUser implements IGorillaArenaUser
TDictionary<TGUID, IGorillaArenaUser>
└── TGorillaArenaUserList
TGorillaArenaUserClass = class of TGorillaArenaUser
| Constant | Value |
|---|---|
ARENA_USER_FIELD_COLOR |
Color |
ARENA_USER_FIELD_POSITION |
Position |
Reported by TGorillaArenaManager.OnStatusChanged.
| Value | Description |
|---|---|
None |
Not in a group |
Pending |
Joining |
Joined |
In |
Reported by TGorillaArenaManager.OnUserEvent.
| Value | Description |
|---|---|
Added |
A user appeared |
Remove |
A user is gone |
Update |
A user's data changed |
GUID {419101A0-C303-4E91-8568-2AFBEFF162B2}, descends IGorillaArenaEntity.
| Member | Type | Description |
|---|---|---|
Color |
TAlphaColorF |
The participant's colour |
Position |
TPoint3D |
Where they are |
Items |
TJSONWrapObjectList |
Whatever they carry |
Everything from IGorillaArenaEntity — Id, Group, GUID, GUIDStr,
SourceProfile, BeginUpdate, Submit — applies as well. The session layer
uses Id for the display name and GUIDStr as the member id.
constructor Create(const AProfile : TObject; const AId : String);
reintroduce; virtual;
Wrapped in BeginUpdate / EndUpdate, so creating a user produces no traffic
of its own. The colour starts at opaque red.
| Property | Type | Description |
|---|---|---|
Color |
TAlphaColorF |
Stored as a string; red and blue are swapped on Windows on the way in and out |
Position |
TPoint3D |
Stored as a string |
| Property | Type | Description |
|---|---|---|
Items |
TJSONWrapObjectList |
The user's items. Owned by the user |
A TDictionary<TGUID, IGorillaArenaUser> with one addition:
| Method | Description |
|---|---|
ToJSON() : String |
The whole map as a JSON object, keyed by GUID string |
That is what the manager serves as the UserList resource.
type
TMyUser = class(TGorillaArenaUser)
protected
function GetTeam() : Integer;
procedure SetTeam(const AValue : Integer);
published
property Team : Integer read GetTeam write SetTeam;
end;
FManager.SetUserClass(TMyUser); // before Join()
SetUserClass must be called before joining — otherwise the users have
already been created from the default class. Both CreateMyself and
AddRemoteUser honour it.
The Gorilla.Arena.Utils unit converts the two value types an
entity cannot store directly — a colour and a 3D
point — to and from the strings that go into its JSON document.
All four functions use an invariant (en-US) format, so a value written on a
machine with German locale reads back correctly on one with English locale.
That is the whole reason they exist: FloatToStr would produce 1,25 on one
device and fail to parse it on the other.
| Function | Description |
|---|---|
StringToAlphaColorF(const AValue : String) : TAlphaColorF |
Reads four floats. Accepts commas or spaces as separators. Missing alpha defaults to 1. Swaps red and blue |
AlphaColorFToString(const AValue : TAlphaColorF; const ADelimiter : Char = ' ') : String |
Writes R G B A with seven decimals |
StringToPoint3D(const AValue : String) : TPoint3D |
Reads three floats. Accepts commas or spaces |
Point3DToString(const AValue : TPoint3D; const ADelimiter : Char = ' ') : String |
Writes X Y Z with seven decimals |
StringToAlphaColorF exchanges the red and blue components as it reads. It is
the counterpart of the channel swap TGorillaArenaUser applies on Windows —
use the two together, as TGorillaArenaUser.GetColor and SetColor do, rather
than one on its own.
An unparsable component becomes 0 rather than raising, so a malformed value
arriving from another device cannot take the application down.
The Gorilla.Audio.Manager unit defines the backend independent audio API of
Gorilla3D. It contains the abstract TGorillaAudioManager implemented by the
FMOD and OpenAL drivers, the abstract TGorillaSoundItem, and the older
TGorillaLegacyAudioManager, a thread based wrapper around the FMX
TMediaPlayer.
TThread
└── TGorillaLegacyAudioManager
TFmxObject
└── TGorillaAudioManager (abstract)
├── TGorillaFMODAudioManager (Gorilla.Audio.FMOD)
└── TGorillaOpenALManager (Gorilla.Audio.OpenAL)
TCollectionItem
├── TGorillaSoundItem (abstract)
│ ├── TGorillaFMODSoundItem
│ └── TGorillaOpenALSoundItem
├── TGorillaChannelItem
└── TGorillaAudioEffectItem
EGorillaAudioException = Exception;
| Value | Description |
|---|---|
Cache |
Cache audio file to memory |
Play |
Start playback |
Stop |
Stop playback |
Pause |
Pause or resume playback |
| Value | Description |
|---|---|
Once |
Play audio once |
Loop |
Play audio in a loop |
| Field | Type | Description |
|---|---|---|
Id |
Integer |
Unique audio identifier |
Mode |
TGorillaAudioMode |
Playback mode |
Volume |
Single |
Volume level |
Player |
TMediaPlayer |
FMX media player instance |
| Field | Type | Description |
|---|---|---|
Id |
Integer |
Unique audio identifier |
Mode |
TGorillaAudioMode |
Playback mode |
Action |
TGorillaAudioAction |
Queue action |
AudioFile |
String |
File path |
Volume |
Single |
Volume (default 0.75) |
TGorillaAudioCache = TDictionary<Integer, TCacheAudioEntry>;
Abstract base class of the modern audio backends. Everything built on top of the audio stack — playlist, text-to-speech, speech-to-text — programs against this class, which is what makes the driver exchangeable.
| Property | Type | Description |
|---|---|---|
OnUpdate |
TNotifyEvent |
Fired when Update() was called; synchronized with the main thread when the auto-update thread triggered it |
OnListenerUpdated |
TNotifyEvent |
Fired when the listener settings changed |
| Method | Description |
|---|---|
ClearSounds() |
Removes all sound handles (abstract) |
LoadSoundFromFile(AFilename) |
Loads a sound handle from file (abstract) |
LoadSoundFromStream(AStream) |
Loads a sound handle from a stream, read completely into memory (abstract) |
LoadSoundFromStream(AMemStream) |
Loads from a memory stream, supports continuous streaming (abstract) |
LoadSoundItemFromFile(AFilename) |
Loads a file and returns the TGorillaSoundItem (abstract) |
LoadSoundItemFromStream(AStream) |
Loads from a stream and returns the item (abstract) |
LoadSoundItemFromStream(AMemStream) |
Loads from a memory stream and returns the item (abstract) |
CreateSoundItem(AName) |
Creates an empty item that does not hold audio data yet |
GetSoundItem(AHandle) |
Returns the item belonging to a backend handle (abstract) |
GetSoundItemByFilename(AFilename) |
Returns the item loaded from that file (abstract) |
CreateSoundItem() exists because some settings — 3D handling for example — are
evaluated while the audio data is created and cannot be changed afterwards. The
item is created first, configured, and filled through
TGorillaSoundItem.LoadFromStream(). It returns nil when the backend does not
support the two step creation, in which case callers have to fall back to
LoadSoundItemFromStream().
| Method | Description |
|---|---|
PlaySound(AIndex) |
Plays a sound by index (abstract) |
PlaySound(ASound) |
Plays a sound item (abstract) |
StopAllChannels() |
Stops every channel (abstract) |
ClearAllChannels() |
Stops and releases every channel (abstract) |
Update() |
Updates streaming buffers and pending changes; call periodically (abstract) |
Abstract collection item representing a single sound.
| Property | Type | Description |
|---|---|---|
FileName |
TFileName |
Sound file path |
PlaybackPosition |
UInt32 |
Current playback position in ms (read-only) |
PlaybackLength |
UInt32 |
Total length in ms (read-only) |
| Method | Description |
|---|---|
IsPlaying() |
True while the sound is audible |
Play() |
Starts playback |
Pause() |
Pauses playback |
Resume() |
Resumes playback |
Stop() |
Stops playback |
LoadFromStream(AStream) |
Loads the audio data into an item created by CreateSoundItem() |
These methods form the backend independent interface used by modules on top of the audio stack, such as text-to-speech. The base class implements them as no-ops, so a backend only overrides what it actually supports.
| Method | Description |
|---|---|
Supports3DAudio() |
True when the backend can play this sound at a position in 3D space |
Set3DAudio(AEnabled) |
Enables positional playback — has to be called before the audio data is loaded, because some backends decide about 3D handling while creating the sound |
SetWorldPosition(APosition) |
Moves the sound to a world space position |
Set3DDistance(AMin, AMax) |
Distance range the sound is attenuated in |
SetPlaybackVolume(AVolume) |
Playback gain, 0.0 silent, 1.0 unchanged |
SetPlaybackPitch(APitch) |
Playback pitch, 1.0 unchanged, 2.0 one octave up |
Empty TCollectionItem base classes. The drivers derive their concrete channel
and effect items from them — see TGorillaOpenALChannelItem,
TGorillaOpenALEffectItem and the FMOD channel groups.
Thread based audio manager using FMX TMediaPlayer, one player per audio file.
Simple, but not built for performance. A global instance named AudioManager is
created by the unit.
var
AudioManager : TGorillaLegacyAudioManager;
| Property | Type | Default | Description |
|---|---|---|---|
LoopCheckInterval |
Integer |
100 | Interval in ms at which finished loops are restarted; lower values cost performance |
QueueTimeout |
Integer |
250 | Time in ms the worker waits for a queue event |
Mute |
Boolean |
False | Mutes every loaded audio file |
| Method | Description |
|---|---|
BeginCaching() |
Starts batch caching — call before adding files |
EndCaching() |
Ends the batch |
AudioAlreadyCached(AId) |
True when that id is already cached |
Add(AId, AFilename, AVolume) |
Caches an audio file under a unique id |
Play(AId, AMode, AVolume) |
Plays a cached file |
Stop(AId) |
Stops playback |
Pause(AId) |
Pauses, or resumes a paused file |
PauseAll() |
Pauses everything currently playing |
StopAll() |
Stops everything currently playing |
TMediaPlayer has to be created in the main thread. The unit
therefore stores an empty.mp3 resource in
System.IOUtils.TPath.GetTempPath() during initialization; if that fails, no
playback is possible.The Gorilla.Audio.FMOD unit implements the Gorilla3D audio manager on top of
the FMOD Core API. It provides TGorillaFMODAudioManager, the sound and channel
group collections used at design-time, and the update thread that keeps the FMOD
system alive.
TGorillaAudioManager
└── TGorillaFMODAudioManager
TGorillaSoundItem
└── TGorillaFMODSoundItem
TCollectionItem
└── TGorillaFMODChannelGroupItem
TOwnedCollection
├── TGorillaFMODSoundCollection
├── TGorillaFMODChannelGroupCollection
└── TGorillaFMODEffectCollection
TThread
└── FMOD auto update thread
| Unit | Content |
|---|---|
Gorilla.Audio.FMOD.System |
FMOD system initialization, IGorillaFMODSystem |
Gorilla.Audio.FMOD.Sound |
IGorillaFMODSound handles |
Gorilla.Audio.FMOD.Channel |
IGorillaFMODChannel handles |
Gorilla.Audio.FMOD.ChannelGroup |
IGorillaFMODChannelGroup handles |
Gorilla.Audio.FMOD.SoundGroup |
Sound groups |
Gorilla.Audio.FMOD.DSP |
DSP effect units |
Gorilla.Audio.FMOD.Reverb3D |
3D reverb zones |
Gorilla.Audio.FMOD.Geometry |
Geometry based occlusion |
Gorilla.Audio.FMOD.Custom |
Hooks for custom extensions |
Android.JNI.FMOD |
JNI bridge used on Android |
| Value | Description |
|---|---|
Mode2D |
Non-positional sound |
Mode3D |
Positional sound — evaluated while the sound is created |
| Member | Description |
|---|---|
UseProductiveLibrary |
Switches between the fmodL (logging, default) and fmod (productive) library. Set it in the .dpr before the first manager is created |
| Property | Type | Description |
|---|---|---|
SystemObject |
IGorillaFMODSystem |
The raw FMOD system handle, for everything the component does not wrap |
SoundRefs[Index] |
IGorillaFMODSound |
Sound handle by index |
ChannelGroupRefs[Name] |
IGorillaFMODChannelGroup |
Channel group by name |
IsPlaying |
LongBool |
True while any channel is playing |
| Property | Type | Default | Description |
|---|---|---|---|
AutoUpdate |
Boolean |
True | Runs an internal thread calling Update() |
AutoUpdateInterval |
Integer |
33 | Interval of that thread in ms |
Sounds |
TGorillaFMODSoundCollection |
— | Design-time collection of sounds |
ChannelGroups |
TGorillaFMODChannelGroupCollection |
— | Design-time collection of channel groups |
ListenerPosition |
TPosition3D |
— | Listener position |
ListenerVelocity |
TPosition3D |
— | Listener velocity, drives the Doppler effect |
ListenerForward |
TPosition3D |
— | Listener forward direction |
ListenerUp |
TPosition3D |
— | Listener up direction |
ListenerTarget |
TControl3D |
— | Control the listener follows automatically |
ListenerUpdateInterval |
Integer |
— | Interval the target is polled with |
AutoUpdateListenerForward |
Boolean |
— | Whether the forward vector follows the target too |
| Method | Description |
|---|---|
Update() |
Updates the FMOD system — every frame, or leave AutoUpdate on |
Set3DListener(AAttr, ...) |
Sets the complete listener attribute set at once |
ClearSounds() |
Removes all sound handles |
LoadSoundFromFile(AFilename) |
Loads a sound handle from file |
LoadSoundIntfFromFile(AFilename) |
Same, returns the IGorillaFMODSound |
LoadSoundFromStream(AStream) |
Loads from a stream, completely into memory |
LoadSoundFromStream(AMemStream) |
Loads from a memory stream, supports streaming |
LoadSoundIntfFromStream(...) |
Stream variants returning the FMOD interface |
CreateSoundItem(AName) |
Creates an empty item for the two step creation |
LoadSoundItemFromFile(AFilename) |
Loads and returns a TGorillaFMODSoundItem |
LoadSoundItemFromStream(...) |
Stream variants |
GetSoundItem(AHandle) |
Item by backend handle or by IGorillaFMODSound |
GetSoundItemByFilename(AFilename) |
Item by file name |
PlaySound(AIndex) |
Plays by index, returns an FMOD channel handle |
PlaySound(ASound) |
Plays a specific sound handle |
StopAllChannels() |
Stops every channel |
ClearAllChannels() |
Stops and releases every channel |
Derives from TGorillaSoundItem and exposes the FMOD channel feature set.
| Property | Type | Description |
|---|---|---|
Reference |
IGorillaFMODSound |
The FMOD sound handle |
ChannelGroupRef |
IGorillaFMODChannelGroup |
The group this sound plays in |
Channel |
IGorillaFMODChannel |
The channel currently used |
AudioManager |
TGorillaFMODAudioManager |
Owning manager |
PlaybackPosition / PlaybackLength |
UInt32 |
Position and length in ms |
| Property | Type | Description |
|---|---|---|
FileName |
TFileName |
Audio file |
Mode |
TGorillaFMODSoundMode |
2D or 3D — read while the sound is created |
ChannelGroup |
String |
Name of the channel group |
Loop |
Boolean |
Looped playback |
LoopCount |
Int32 |
Number of loops, -1 = endless |
AutoStart |
Boolean |
Starts automatically once the manager is loaded |
Volume |
Single |
Channel volume |
Pitch |
Single |
Playback pitch |
Mute |
Boolean |
Mutes this sound |
Frequency |
Single |
Playback rate in Hz; negative values play non-streamed sounds backwards |
Priority |
Int32 |
0 (most important) … 256, default 128 |
PositionInMilliseconds |
UInt32 |
Seek position |
VolumeRamp |
Boolean |
Smooths abrupt volume changes |
LowPassGain |
Single |
Gain of the low pass applied by occlusion and reverb |
FadeIn / FadeOut |
Single |
Fade durations |
AntiFatigue |
Boolean |
Tiny random volume variation, so a repeated sample stops sounding identical |
AntiFatigueLevel |
Integer |
Strength of that variation, 0..100 |
FadeInMinVol, FadeInMaxVol, FadeOutMinVol, FadeOutMaxVol |
Single |
Range the anti-fatigue variation works in |
Delay |
TGorillaFMODDelay |
Scheduling |
DelayDSPClockStart, DelayDSPClockEnd |
UInt64 |
Sample accurate start and end |
DelayStopChannels |
Boolean |
Whether the delayed end stops the channel |
Position3D |
TPosition3D |
3D position |
Velocity3D |
TPosition3D |
3D velocity |
MinMax3DDistance |
TPosition |
Minimum and maximum attenuation distance |
Cone3DSettings |
TPosition3D |
Inner angle, outer angle, outer volume |
Effects |
TGorillaFMODEffectCollection |
DSP effects attached to this sound |
OnPlay, OnPause, OnStop |
TNotifyEvent |
Playback events |
| Method | Description |
|---|---|
IsAvailable() |
True when the FMOD handle exists |
IsPlaying(), Play(), Pause(), Resume(), Stop() |
Playback control |
LoadFromStream(AStream) |
Loads audio data into an item created by CreateSoundItem() |
AttachEffects() / DetachEffects() |
Switches the whole effect chain on and off |
Supports3DAudio() |
True |
Set3DAudio(AEnabled) |
Switches Mode — before the data is loaded |
Set3DDistance(AMin, AMax) |
Sets MinMax3DDistance |
| Member | Type | Description |
|---|---|---|
Reference |
IGorillaFMODChannelGroup |
The FMOD channel group handle |
DisplayName |
String |
Name the group is addressed by |
Channel groups are the FMOD buses: assign a sound to a group by name and control volume, muting and effects for everything in it at once.
The auto update thread keeps the FMOD system updated so 3D positions, streaming and virtual voices stay correct.
| Property | Default | Description |
|---|---|---|
AudioManager |
— | The manager to update |
Interval |
33 | Update interval in ms |
Enable it through TGorillaFMODAudioManager.AutoUpdate. Switch it off when your
render loop calls Update() itself.
The FMOD binaries ship under <installation>\lib\fmod\. The logging build
(fmodL / fmodL64) is the default and has to be copied into the IDE binary
folder for design-time support. Set UseProductiveLibrary := true for release
builds. FMOD is a commercial product of Firelight Technologies —
https://www.fmod.com/licensing.
The Gorilla.Audio.OpenAL unit implements the Gorilla3D audio manager on top of
OpenAL Soft. It provides TGorillaOpenALManager together with three collections:
sounds (OpenAL buffers), channels (OpenAL sources) and effects (EFX auxiliary
effect slots).
TGorillaAudioManager
└── TGorillaOpenALManager
TGorillaSoundItem
└── TGorillaOpenALSoundItem
TGorillaChannelItem
└── TGorillaOpenALChannelItem
TGorillaAudioEffectItem
└── TGorillaOpenALEffectItem
TOwnedCollection
├── TGorillaOpenALSounds
├── TGorillaOpenALChannels
└── TGorillaOpenALEffects
| Unit | Content |
|---|---|
Gorilla.Audio.OpenAL.Loader |
LoadWAVFile(), LoadOGGFile(), LoadMP3File(), LoadAudioFile(), TAudioData |
Gorilla.Audio.OpenAL.API |
OpenAL and EFX bindings (openal32.dll and platform equivalents) |
Gorilla.Audio.MP3.API |
libmpg123 bindings |
Gorilla.Audio.OGG.API |
libogg / libvorbis / libvorbisfile bindings |
| Value | Description |
|---|---|
dmInverse |
Inverse distance attenuation |
dmLinear |
Linear distance attenuation |
dmExponent |
Exponential distance attenuation |
| Value | Description |
|---|---|
etNone |
No effect |
etReverb |
Reverb |
etChorus |
Chorus |
etEcho |
Echo |
etDistortion |
Distortion |
etFlanger |
Flanger |
etCompressor |
Compressor |
| Value | Description |
|---|---|
psInitial |
Channel has never been played |
psPlaying |
Currently playing |
psPaused |
Paused, can be resumed |
psStopped |
Stopped |
Format information about loaded audio data.
| Member | Description |
|---|---|
IsMono() |
True for single channel data |
IsStereo() |
True for two channel data |
ToString() |
Human readable description |
Six-component vector for the listener orientation: the first three components are the "at" (forward) vector, the last three the up vector.
| Member | Description |
|---|---|
Create(AAtX, AAtY, AAtZ, AUpX, AUpY, AUpZ) |
Constructor |
Default |
The standard orientation |
| Property | Type | Description |
|---|---|---|
Initialized |
Boolean |
True once device and context exist |
| Property | Type | Description |
|---|---|---|
Sounds |
TGorillaOpenALSounds |
Collection of audio buffers |
Channels |
TGorillaOpenALChannels |
Collection of audio sources |
Effects |
TGorillaOpenALEffects |
Collection of EFX effects |
ListenerPosition |
TPoint3D |
Global listener position |
ListenerVelocity |
TPoint3D |
Listener velocity, for the Doppler effect |
ListenerOrientation |
TVector6D |
Forward and up vectors |
DopplerFactor |
Single |
Doppler magnitude multiplier, default 1.0 |
| Method | Description |
|---|---|
InitializeOpenAL() |
Initializes device and context, returns success |
ShutdownOpenAL() |
Releases all OpenAL resources |
LoadAllSounds() |
Loads every file configured in Sounds |
ClearSounds() |
Removes all buffers |
Update() |
Updates streaming buffers and retires finished sources |
| Method | Description |
|---|---|
CreateSoundItem(AName) |
Creates an empty item for the two step creation |
LoadSoundItemFromFile(AFilename) |
Loads and returns the item |
LoadSoundFromFile(AFilename) |
Loads without returning it |
LoadSoundItemFromStream(AStream) |
Stream variants |
LoadSoundItemFromStream(AMemStream) |
Memory stream variant |
LoadSoundFromStream(...) |
Same without a return value |
GetSoundItem(AHandle) |
Item by backend handle |
GetSoundItemByFilename(AFilename) |
Item by file name |
| Method | Description |
|---|---|
AddSoundToChannel(AChannelName, ASoundName) |
Adds a sound to a channel |
RemoveSoundFromChannel(AChannelName, ASoundName) |
Removes it again |
ClearChannelSounds(AChannelName) |
Empties a channel |
ChannelHasSound(AChannelName, ASoundName) |
Membership test |
GetChannelSoundCount(AChannelName) |
Number of sounds in a channel |
PlayChannel(AChannelName / AChannel) |
Plays every sound of the channel |
StopChannel(...), PauseChannel(...), ResumeChannel(...) |
Channel playback control |
GetChannelState(...) |
Returns the TPlaybackState of a channel |
StopAllChannels() |
Stops everything |
ClearAllChannels() |
Clears every channel |
PlaySound(ASoundName) |
Plays one sound, returns the channel it landed in |
PlaySound(AIndex) / PlaySound(ASound) |
Base class overloads |
PlaySoundItem(ASound) |
Plays an item, returns the channel |
SetListenerWorldPosition(APosition) |
Convenience listener update |
ApplyEffectToChannel(AChannelName, AEffectName) |
Routes a channel through an effect slot |
An OpenAL buffer plus the source settings applied when it is played.
| Member | Description |
|---|---|
BufferID |
The OpenAL buffer id |
LoadBuffer() |
Loads the audio file into the buffer |
LoadBufferFromStream(AStream) |
Loads from a stream |
UnloadBuffer() |
Releases the buffer |
IsPlaying(), Play(), Pause(), Resume(), Stop() |
Playback control |
LoadFromStream(AStream) |
Fills an item created by CreateSoundItem() |
Supports3DAudio(), Set3DAudio(), SetWorldPosition(), Set3DDistance(), SetPlaybackVolume(), SetPlaybackPitch() |
Backend independent 3D interface |
| Property | Type | Description |
|---|---|---|
DisplayName |
String |
Unique identifier, used to link channels |
FileName |
TFileName |
Audio file path |
Loaded |
Boolean |
True when the buffer holds data (read-only) |
Format |
TStreamFormat |
Mono/stereo, sample rate (read-only) |
PlaybackLength |
UInt32 |
Length in ms |
PlaybackPosition |
UInt32 |
Position in ms |
Streaming |
Boolean |
Streams from disk instead of loading completely |
Position |
TPoint3D |
3D position |
Velocity |
TPoint3D |
Velocity for the Doppler effect |
Volume |
Single |
Gain, 0.0 … 1.0+ |
Looping |
Boolean |
Loops continuously |
Pitch |
Single |
Playback speed / pitch, 1.0 normal |
DistanceModel |
TDistanceModel |
Attenuation model |
MaxDistance |
Single |
Distance the attenuation stops at |
ReferenceDistance |
Single |
Distance up to which nothing is attenuated |
RolloffFactor |
Single |
Strength of the distance attenuation |
ConeInnerAngle |
Single |
Inner angle of the sound cone in degrees |
ConeOuterAngle |
Single |
Outer angle in degrees |
ConeOuterGain |
Single |
Gain outside the outer cone |
A named group of sounds played, paused and positioned together — the OpenAL counterpart to an FMOD channel group.
| Member | Type | Description |
|---|---|---|
IsPlaying |
Boolean |
True while any sound of the channel plays |
SoundCount |
Integer |
Number of sounds in the channel |
Sounds[Index] |
TGorillaOpenALSoundItem |
Sounds of the channel |
Name |
String |
Channel name |
Paused |
Boolean |
Pause state |
PlaybackPosition |
Cardinal |
Position in ms |
Position, Velocity |
TPoint3D |
3D placement |
Volume, Looping, Pitch |
Playback settings | |
DistanceModel, MaxDistance, ReferenceDistance, RolloffFactor |
Attenuation | |
ConeInnerAngle, ConeOuterAngle, ConeOuterGain |
Single |
Sound cone |
| Property | Type | Description |
|---|---|---|
Name |
String |
Unique identifier of the effect |
EffectType |
TEffectType |
Kind of effect |
Enabled |
Boolean |
Toggles the effect |
Slot |
Integer |
Auxiliary effect slot used by OpenAL |
EffectID |
Cardinal |
OpenAL effect id (read-only) |
EFX requires an OpenAL implementation that supports the extension. OpenAL Soft does; some vendor drivers do not.
| Class | Notable members |
|---|---|
TGorillaOpenALSounds |
Add(), FindByName(), FindByFileName(), Items[] |
TGorillaOpenALChannels |
Add(), Items[] |
TGorillaOpenALEffects |
Add(), Items[] |
| Format | Decoder | Library |
|---|---|---|
| WAV (PCM) | Built in | — |
| OGG Vorbis | Gorilla.Audio.OGG.API |
ogg, vorbis, vorbisfile |
| MP3 | Gorilla.Audio.MP3.API |
libmpg123-0.dll / libmpg123.so / libmpg123.dylib |
LoadAudioFile() picks the decoder by file extension.
The Gorilla.Audio.Playlist unit provides TGorillaAudioPlaylist, a non-visual
component that manages a list of audio tracks with shuffle, loop and auto-play
support. It drives an FMOD or OpenAL manager and can be used headless,
programmatically or behind a custom UI.
TComponent
└── TGorillaAudioPlaylist
TOwnedCollection
└── TGorillaPlaylistCollection
TCollectionItem
└── TPlaylistItem
| Value | Description |
|---|---|
FMOD |
Playback through TGorillaFMODAudioManager |
OpenAL |
Playback through TGorillaOpenALManager |
One track of the playlist. Implemented as a TCollectionItem, so the list can be
edited at design-time through the standard collection editor.
| Property | Type | Description |
|---|---|---|
Name |
String |
Display name of the track |
FilePath |
String |
Path of the audio file; setting it updates Name |
Owned collection of TPlaylistItem. Provides a typed default indexer, so
Playlist[I] works, and notifies the owning playlist when items are added,
removed or changed — including through the design-time editor.
| Member | Description |
|---|---|
Add() |
Appends a new TPlaylistItem |
Items[Index] |
Typed default indexer |
| Property | Type | Default | Description |
|---|---|---|---|
Items |
TGorillaPlaylistCollection |
— | Design-time editable list of tracks |
Driver |
TAudioDriver |
FMOD |
Backend used for playback |
FMODManager |
TGorillaFMODAudioManager |
— | Existing FMOD manager to drive; empty creates one internally |
OpenALManager |
TGorillaOpenALManager |
— | Existing OpenAL manager to drive |
AutoUpdate |
Boolean |
True | Polls playback itself and advances on its own |
AutoPlayNext |
Boolean |
True | Continues with the next track when one ends |
ShuffleMode |
Boolean |
False | Random play order |
LoopMode |
Boolean |
False | Starts over after the last track |
Volume |
Single |
— | Playback volume |
| Event | Type | Fired when |
|---|---|---|
OnPlaylistChanged |
TNotifyEvent |
Tracks were added, removed, moved or edited |
OnTrackChanged |
TNotifyEvent |
A different track became current |
OnPlaybackFinished |
TNotifyEvent |
The current track ended |
OnStateChanged |
TNotifyEvent |
Playing / paused / stopped changed |
| Property | Type | Description |
|---|---|---|
Playlist |
TGorillaPlaylistCollection |
The track collection |
PlaylistCount |
Integer |
Number of tracks |
CurrentIndex |
Integer |
Index of the current track |
CurrentTrackName |
String |
Name of the current track |
FMOD |
TGorillaFMODAudioManager |
The FMOD manager in use (read-only) |
OpenAL |
TGorillaOpenALManager |
The OpenAL manager in use (read-only) |
| Method | Description |
|---|---|
CreateAudioHandler() |
Creates the internally owned manager for the active driver |
DestroyAudioHandler() |
Releases it again |
A manager linked through FMODManager / OpenALManager stays owned by the form;
one created by the playlist is released by it.
| Method | Description |
|---|---|
AddToPlaylist(AFilename) |
Appends a track, returns its index |
RemoveFromPlaylist(AIndex) |
Removes a track |
ClearPlaylist() |
Empties the list |
MovePlaylistItem(AFrom, ATo) |
Reorders a track |
GetPlaylistItem(AIndex) |
Returns a TPlaylistItem |
| Method | Description |
|---|---|
LoadAudio(AFilename) |
Loads a file directly, bypassing the list |
LoadAudio(AStream: TMemoryStream) |
Loads from a memory stream |
LoadAudio(AStream: TStream) |
Loads from a stream |
| Method | Description |
|---|---|
Play() |
Starts or resumes playback |
Pause() |
Pauses playback |
Stop() |
Stops playback |
PlayItem(AIndex) |
Plays a specific track |
PlayNext() |
Advances to the next track |
PlayPrevious() |
Goes back one track |
IsPlaying() |
True while playing |
IsPaused() |
True while paused |
| Method | Description |
|---|---|
GetPlaybackPosition() |
Current position in ms |
SetPlaybackPosition(AValue) |
Seeks to a position in ms |
GetPlaybackLength() |
Length of the current track in ms |
UpdatePlayback(out AFinished) |
Returns the position and reports whether the track ended |
UpdatePlayback() is called periodically — either by the internal timer while
AutoUpdate is on, or by your own timer when it is off. The component latches
the actual start of playback, so a track is never reported as finished during
the start-up window.
The Gorilla.Audio.TTS unit defines the backend independent core of the
text-to-speech subsystem: the synthesis request, the result carrying audio and
lipsync data, the abstract TGorillaTTSEngine, and the registry that makes
backends selectable by name.
TPersistent
└── TGorillaTTSResult
TFmxObject
└── TGorillaTTSEngine (abstract)
└── TGorillaPiperEngine (Gorilla.Audio.TTS.Piper)
TGorillaTTSEngineRegistry (class with class methods only)
TGorillaTTSAudioFormat = TGorillaWaveFormat; // from Gorilla.Audio.TTS.Utils
TGorillaTTSVoices = TArray<TGorillaTTSVoice>;
TGorillaTTSEngineClass = class of TGorillaTTSEngine;
Describes a voice an engine is able to speak with.
| Field | Type | Description |
|---|---|---|
Id |
String |
Engine specific identifier; Piper uses the path of the .onnx model |
Name |
String |
Human readable name, shown in editors and drop-downs |
Language |
String |
Language code, e.g. de_DE |
SpeakerId |
Integer |
Speaker index inside a multi-speaker model, -1 = default |
SampleRate |
Integer |
Native sample rate of the voice |
| Method | Description |
|---|---|
Create(AId, AName, ALanguage, ASpeakerId, ASampleRate) |
Constructor |
DisplayName() |
Name including the speaker id where relevant |
Everything an engine needs to synthesize a single utterance.
| Field | Type | Description |
|---|---|---|
Text |
String |
The text to speak |
VoiceId |
String |
Voice identifier; empty uses the engine's default voice |
SpeakerId |
Integer |
Speaker index in a multi-speaker model, -1 = default |
Language |
String |
Language of the text, used for phonemization |
Rate |
Single |
Speaking rate, 1.0 normal, above speaks faster |
Expressiveness |
Single |
Variation of the generated voice, 0..1; Piper maps it onto its noise scale parameters |
SentenceSilence |
Single |
Pause between two sentences in seconds |
| Method | Description |
|---|---|
Create(AText, AVoiceId) |
Constructor with defaults |
CacheKey(AEngineName) |
Stable key identifying the synthesis result; playback-only settings such as volume or pitch are not part of it |
The audio and lipsync data an engine produced for one utterance.
| Property | Type | Description |
|---|---|---|
Wave |
TMemoryStream |
Complete RIFF/WAVE data of the utterance |
Visemes |
TGorillaVisemeTimeline |
Viseme timeline used for lipsync, may be empty |
Format |
TGorillaTTSAudioFormat |
Sample format of the wave data |
Duration |
Single |
Playback duration in seconds |
Text |
String |
The spoken text |
EngineName |
String |
Engine that produced the result |
VoiceId |
String |
Voice the result was spoken with |
IsValid |
Boolean |
True when the result carries usable audio |
| Method | Description |
|---|---|
Clear() |
Drops audio and timeline |
SetWave(AStream) |
Takes ownership of a RIFF/WAVE stream and refreshes format and duration from its header |
SaveToFile(AFilename) |
Writes audio and timeline to disk |
LoadFromFile(AFilename) |
Reads them back |
Assign(ASource) |
Standard TPersistent assignment |
Abstract base class of all text-to-speech backends. Synthesize() is called
from a worker thread of TGorillaTextToSpeech; a backend that cannot work in
parallel overrides IsThreadSafe() and returns false, in which case the caller
serializes all requests.
| Method | Description |
|---|---|
GetEngineName() |
Unique name of the backend, used by the registry and by EngineName (abstract) |
IsSupported() |
False when the backend can never work on the current platform |
| Method | Description |
|---|---|
IsAvailable() |
True when the backend is completely configured and ready |
IsThreadSafe() |
False when the backend must not be called from several threads |
GetVoices() |
The voices this engine offers |
FindVoice(AIdOrName, ...) |
Resolves a voice by id or name |
Synthesize(ARequest) |
Synthesizes an utterance; the caller owns the result, nil on failure |
Synthesize(AText, AVoiceId) |
Convenience overload |
| Property | Description |
|---|---|
LastError |
Reason of the last failed operation |
| Property | Type | Default | Description |
|---|---|---|---|
DefaultVoice |
String |
— | Voice used when a request does not name one |
DefaultLanguage |
String |
— | Language used when a request does not name one |
Lipsync |
Boolean |
True | Builds the viseme timeline after the synthesis |
| Method | Description |
|---|---|
DoSynthesize(ARequest, AResult) |
Produces the audio; must fill AResult.Wave and AResult.Format (abstract) |
BuildLipsync(ARequest, AResult) |
Estimates the viseme timeline; skipped when the backend filled AResult.Visemes itself |
SetError(AMessage) |
Stores an error message and returns false |
Registry of all available synthesis backends. Backends register themselves in the initialization section of their unit, so adding the unit to a project makes the engine selectable by name at design-time and at runtime.
| Class Method | Description |
|---|---|
RegisterEngine(AClass) |
Registers a backend |
UnregisterEngine(AClass) |
Removes it again |
FindEngineClass(AName) |
Resolves a backend class by engine name |
CreateEngine(AName, AOwner) |
Creates an instance; an empty name picks the first supported backend |
EngineNames() |
Names of all registered backends |
DefaultEngineName() |
Name of the first backend supported on this platform |
| Constant | Value | Description |
|---|---|---|
GORILLA_TTS_NEUTRAL |
1.0 | Neutral value for rate and pitch |
GORILLA_TTS_SENTENCE_SILENCE |
0.2 | Default pause between sentences in seconds |
The Gorilla.Audio.TTS.Speaker unit contains the component applications work
with: TGorillaTextToSpeech, its collection of TGorillaTTSSpeaker characters,
the utterance objects travelling from text to audible speech, the speech cache
and the synthesis worker thread.
TFmxObject
└── TGorillaTextToSpeech
TOwnedCollection
└── TGorillaTTSSpeakers
TCollectionItem
└── TGorillaTTSSpeaker
TObject
├── TGorillaTTSUtterance
└── TGorillaTTSCache
Lifecycle of a single spoken sentence.
| Value | Description |
|---|---|
usPending |
Queued, waiting for the worker thread |
usSynthesizing |
The engine is generating the audio |
usReady |
Audio is available and waits for its turn |
usPlaying |
Currently audible |
usFinished |
Playback completed |
usFailed |
Synthesis or playback failed, see Error |
usCancelled |
Dropped before it became audible |
TGorillaSpeechEvent = procedure(ASender : TObject;
const ASpeaker : TGorillaTTSSpeaker;
const AUtterance : TGorillaTTSUtterance) of object;
TGorillaSpeechErrorEvent = procedure(ASender : TObject;
const ASpeaker : TGorillaTTSSpeaker;
const AUtterance : TGorillaTTSUtterance; const AError : String) of object;
TGorillaVisemeEvent = procedure(ASender : TObject;
const ASpeaker : TGorillaTTSSpeaker; const AViseme : TGorillaVisemeKind;
const AWeights : TGorillaVisemeWeights) of object;
TGorillaSpeechWordEvent = procedure(ASender : TObject;
const ASpeaker : TGorillaTTSSpeaker; const AWordIndex : Integer;
const AWord : String) of object;
One sentence on its way from text to audible speech. Instances are owned by
TGorillaTextToSpeech and released once they finished — never keep a
reference beyond the event they were reported in.
| Property | Type | Description |
|---|---|---|
Id |
Cardinal |
Unique number identifying this utterance |
Speaker |
TGorillaTTSSpeaker |
The character it belongs to |
Text |
String |
The spoken text |
State |
TGorillaTTSUtteranceState |
Current lifecycle state |
Error |
String |
Reason of a failure, empty otherwise |
Duration |
Single |
Length of the generated audio in seconds |
Visemes |
TGorillaVisemeTimeline |
Lipsync data, nil until the synthesis finished |
Result |
TGorillaTTSResult |
Audio and lipsync data |
Request |
TGorillaTTSRequest |
The request handed to the engine |
CacheKey |
String |
Key this utterance is cached under |
Tag |
NativeInt |
Free for application use |
A talking character: voice settings, the 3D object the voice is emitted from, and the queue of sentences still to speak.
| Method | Description |
|---|---|
Speak(AText) |
Queues a sentence, returns the utterance id or 0 when the speaker is disabled or the text is empty. Returns immediately, synthesis happens in the background |
Stop() |
Stops the current sentence and clears the queue |
Pause() |
Pauses the current sentence |
Resume() |
Continues a paused sentence |
| Property | Type | Description |
|---|---|---|
TTS |
TGorillaTextToSpeech |
The owning component |
Current |
TGorillaTTSUtterance |
The sentence currently played, nil when silent |
IsSpeaking |
Boolean |
True while a sentence is audible |
QueueLength |
Integer |
Sentences waiting to be spoken |
PlaybackTime |
Single |
Position inside the current sentence in seconds |
Viseme |
TGorillaVisemeKind |
Dominant viseme at the current position |
VisemeWeights |
TGorillaVisemeWeights |
Blended weight of every viseme, ready for morph targets |
VisemeWeight[AViseme] |
Single |
Weight of a single viseme, 0..1 |
WordIndex |
Integer |
Index of the word currently spoken, -1 between words |
SoundDebugPosition |
UInt32 |
Position reported by the audio backend, diagnostic |
SoundDebugPlaying |
Boolean |
Playback state of the audio backend, diagnostic |
Offset |
TPoint3D |
Mouth offset relative to the target's origin |
| Property | Type | Default | Description |
|---|---|---|---|
Name |
String |
— | The name the character is addressed by |
VoiceId |
String |
— | Piper model name or path; empty uses the engine default |
SpeakerId |
Integer |
-1 | Speaker index inside a multi-speaker model |
Language |
String |
— | Language of the spoken text, drives phonemization |
Rate |
Single |
1.0 | Speaking rate, 1.2 speaks 20 % faster |
Pitch |
Single |
1.0 | Playback pitch — useful to derive several characters from one voice model |
Volume |
Single |
— | Playback gain, 0..1 |
Expressiveness |
Single |
— | Variation in the generated voice, 0..1 |
SentenceSilence |
Single |
— | Pause between two sentences in seconds |
Enabled |
Boolean |
True | A disabled speaker silently drops every Speak() |
Spatial |
Boolean |
True | Plays the voice at the position of Target instead of centred |
Interrupt |
Boolean |
False | A new sentence cuts off the running one instead of queueing |
MinDistance |
Single |
— | Distance the voice starts to get quieter at |
MaxDistance |
Single |
— | Distance the voice is completely faded out at |
Target |
TControl3D |
— | The 3D object the voice is emitted from |
| Event | Fired when |
|---|---|
OnSpeechStart |
A sentence became audible |
OnSpeechFinished |
A sentence finished playing |
OnViseme |
The dominant mouth shape changed |
OnWord |
The spoken word changed, e.g. for subtitles |
OnError |
A sentence could not be spoken |
Owned collection of all characters a component speaks for.
| Member | Description |
|---|---|
Add() |
Creates a new speaker |
FindByName(AName) |
Speaker by name, nil when unknown |
Items[AIndex] |
Typed default indexer |
| Method | Description |
|---|---|
ActiveEngine() |
The engine actually used; creates one of type EngineName when no component was assigned |
ActiveAudioManager() |
The audio manager actually used; falls back to the first manager next to this component |
AddSpeaker(AName, AVoiceId) |
Creates a new character |
FindSpeaker(AName) |
Character by name, nil when unknown |
Speak(ASpeakerName, AText) |
Queues a sentence, returns the utterance id or 0 for an unknown character |
Speak(ASpeaker, AText) |
Same for an already resolved character |
StopAll() |
Stops every character and clears all queues |
Update() |
Advances playback and lipsync of all characters |
ClearCache() |
Empties the speech cache |
PurgeCache() |
Empties it including its files on disk |
GetVoices() |
Lists the voices the current engine offers |
| Property | Description |
|---|---|
Cache |
Direct access to the speech cache |
| Property | Type | Default | Description |
|---|---|---|---|
Engine |
TGorillaTTSEngine |
— | Engine component doing the synthesis |
EngineName |
String |
— | Engine created internally when Engine is empty; empty picks the first backend, e.g. Piper |
AudioManager |
TGorillaAudioManager |
— | Manager used for playback; empty uses the first manager owned by the same form |
Speakers |
TGorillaTTSSpeakers |
— | The characters this component speaks for |
Active |
Boolean |
True | Starts and stops the synthesis worker |
AutoUpdate |
Boolean |
True | Drives Update() from an internal timer |
UpdateInterval |
Integer |
16 | Interval of that timer in ms |
CacheEnabled |
Boolean |
True | Reuses the audio of sentences spoken before |
CacheDirectory |
String |
— | Folder the cache persists its wave files in; empty = memory only |
CacheCapacity |
Integer |
64 | Sentences kept in the memory cache |
DefaultLanguage |
String |
— | Language for speakers that do not define their own |
Same set as the speaker, but raised for every character:
OnSpeechStart, OnSpeechFinished, OnViseme, OnWord, OnError.
| Constant | Value | Description |
|---|---|---|
GORILLA_TTS_CACHE_CAPACITY |
64 | Sentences the memory cache keeps by default |
The Gorilla.Audio.TTS.Piper unit implements TGorillaPiperEngine, a local
neural text-to-speech backend driving Piper.
The engine registers itself in the initialization section of the unit, so adding
the unit to a project makes 'Piper' selectable through EngineName.
Including this unit also activates the espeak-ng library phonemizer, because the
Piper releases ship espeak-ng.dll — see
Gorilla.Audio.TTS.Visemes.
Piper and its voice models are not part of the Gorilla3D distribution. See Getting Piper.
TGorillaTTSEngine
└── TGorillaPiperEngine
| Value | Description |
|---|---|
pmProcess |
Spawns the Piper executable for every utterance |
pmHttp |
Sends the text to a running Piper HTTP server |
| Method | Description |
|---|---|
GetEngineName() |
Returns 'Piper' |
IsSupported() |
False where the mode cannot work, e.g. pmProcess on mobile |
| Method | Description |
|---|---|
IsAvailable() |
True when executable and model were resolved |
GetVoices() |
All voices found in ModelDirectory; multi-speaker models report each speaker as model.onnx#3 |
RefreshVoices() |
Rescans ModelDirectory |
ResolveExecutable() |
The executable that would actually be called, resolved against the system search path and the release layouts next to the application. Empty when Piper was not found |
| Property | Type | Default | Description |
|---|---|---|---|
Mode |
TGorillaPiperMode |
pmProcess |
How the engine reaches Piper |
ExecutablePath |
String |
— | Path of the Piper executable; a bare name like piper is searched on the system path |
ModelPath |
String |
— | Model used when neither the request nor DefaultVoice names one |
ModelDirectory |
String |
— | Folder scanned for *.onnx voice models |
EspeakDataPath |
String |
— | Folder holding the espeak-ng data files; only needed when Piper does not find them itself |
ServerUrl |
String |
http://127.0.0.1:5000 |
Base address of the HTTP server in pmHttp |
HttpPath |
String |
— | Resource path appended to ServerUrl |
CommandTemplate |
String |
see below | Command line used in pmProcess |
Timeout |
Integer |
30000 | Milliseconds a single synthesis may take |
NoiseW |
Single |
0.8 | Piper noise-w parameter, controls the variation of phoneme lengths |
CudaEnabled |
Boolean |
False | Adds --cuda to the command line |
Inherited from TGorillaTTSEngine: DefaultVoice, DefaultLanguage,
Lipsync.
| Method | Description |
|---|---|
ResolveModel(AVoiceId, out AModel, ...) |
Splits a voice identifier of the form model.onnx#speaker and resolves the model into an absolute path |
ReadModelConfig(AModelFile, ...) |
Reads the .onnx.json configuration next to a model file |
DoSynthesizeProcess(...) |
Synthesis by spawning the executable |
DoSynthesizeHttp(...) |
Synthesis against the HTTP server |
When ExecutablePath and ModelDirectory are empty, the engine searches next to
the application:
| Kind | Locations |
|---|---|
| Executable | piper\piper.exe, piper.exe, Piper\piper\piper.exe |
| Voices | piper\voices, voices, models |
Default command line of the Piper executable:
%EXE% --model %MODEL% --output_file %OUTPUT%
--length_scale %LENGTH_SCALE% --noise_scale %NOISE_SCALE%
--noise_w %NOISE_W% --sentence_silence %SENTENCE_SILENCE%
%SPEAKER%%ESPEAK_DATA%%CUDA%
Placeholders: %EXE%, %MODEL%, %OUTPUT%, %LENGTH_SCALE%,
%NOISE_SCALE%, %NOISE_W%, %SENTENCE_SILENCE%, %SPEAKER%,
%ESPEAK_DATA%, %CUDA%.
The template matches rhasspy/piper 1.2.0, the version the backend was tested
against. If your Piper version expects a different command line, only
CommandTemplate needs adjusting.
Default address of a local Piper HTTP server: http://127.0.0.1:5000.
There is no Piper library to link against: piper_phonemize.dll only exports
C++-mangled functions with std::vector / std::string parameters, and the
actual VITS inference lives inside piper.exe. The only usable parts of the
release archives are espeak-ng.dll and, in principle, onnxruntime.dll — whose
C API would require reimplementing the whole Piper inference.
Every voice consists of two files that belong together: <voice>.onnx and
<voice>.onnx.json. The .json carries the sample rate and the speaker list; a
model without it cannot be used.
The Gorilla.Audio.TTS.Visemes unit contains everything the lipsync of the
text-to-speech subsystem is built from: the viseme set, the timeline of viseme
keys and word markers, the phonemizer interface with its implementations, and
the estimator that distributes phonemes over the amplitude envelope of the
generated audio.
TPersistent
└── TGorillaVisemeTimeline
TInterfacedObject
├── TGorillaRuleBasedPhonemizer (IGorillaPhonemizer)
├── TGorillaEspeakPhonemizer (IGorillaPhonemizer)
└── TGorillaEspeakLibPhonemizer (IGorillaPhonemizer, in Gorilla.Audio.TTS.Espeak)
TGorillaVisemeEstimator (class with class methods only)
Viseme set as used by the Oculus/Meta LipSync and ARKit compatible character rigs. Most commercial and free character assets ship blend shapes with exactly these names.
| Value | Blend shape name | Mouth shape |
|---|---|---|
vkSilence |
sil |
Closed / neutral mouth, used for pauses |
vkPP |
PP |
p, b, m — closed lips |
vkFF |
FF |
f, v — lower lip at the upper teeth |
vkTH |
TH |
th — tongue between the teeth |
vkDD |
DD |
t, d — tongue at the alveolar ridge |
vkKK |
kk |
k, g — back of the tongue |
vkCH |
CH |
ch, sh, j — rounded and pushed forward |
vkSS |
SS |
s, z — narrow teeth gap |
vkNN |
nn |
n, l — tongue visible at the teeth |
vkRR |
RR |
r — slightly rounded |
vkAA |
aa |
a — wide open mouth |
vkE |
E |
e — half open, spread |
vkIH |
I |
i — narrow, spread |
vkOH |
O |
o — rounded, open |
vkOU |
U |
u — rounded, narrow |
Classic Preston Blair / Rhubarb mouth chart, useful for cartoon rigs and sprite
based mouth animation: msA, msB, msC, msD, msE, msF, msG, msH,
msX.
TGorillaVisemeWeights = array[TGorillaVisemeKind] of Single;
TGorillaPhonemeArray = TArray<TGorillaPhonemeItem>;
TGorillaVisemeWeights holds the weight of every viseme at a given point in
time. The weights of a sample always add up to 1.0 and can be applied directly
to morph targets.
A single phoneme of a phonemized word.
| Field | Description |
|---|---|
| Viseme | Mouth shape this phoneme is rendered with |
| Phoneme | Source symbol; IPA when a real phonemizer was used |
| Weight | Relative duration weight — vowels are longer than plosives |
A viseme and the time span it is active in.
| Member | Description |
|---|---|
| Start / End | Time in seconds, relative to the utterance |
| WordIndex | Index into the word list of the timeline, -1 for pauses |
Duration() |
Length of the key |
Contains(ATime) |
Whether a time falls into this key |
A spoken word and the time span it is audible in, with the same Duration() and
Contains() helpers.
Ordered list of viseme keys and word markers of a single utterance.
| Member | Description |
|---|---|
Clear() |
Drops all keys and words |
AddKey(AKey) |
Appends a viseme key |
AddKey(AStart, AEnd, AViseme, APhoneme, AWordIndex) |
Appends a key from its parts |
AddWord(AStart, AEnd, AText) |
Appends a word marker |
Sort() |
Sorts all keys by start time; called automatically by the estimator |
Keys[AIndex] |
Viseme keys |
KeyCount |
Number of keys |
Words[AIndex] |
Word markers |
WordCount |
Number of words |
Duration |
Length of the utterance in seconds |
BlendTime |
Cross fade between two visemes in seconds |
Neighbouring keys sharing the same viseme are merged, which keeps the timeline small and the animation calm.
Backend independent interface turning text into phonemes.
| Method | Description |
|---|---|
GetName() |
Human readable name |
IsAvailable() |
False when the implementation cannot work, e.g. a missing library |
PhonemizeWord(AWord, ALanguage) |
Phonemes of a single word |
PhonemizeText(AText, ALanguage) |
Phonemes per word of a whole text |
| Priority | Class | Unit | Note |
|---|---|---|---|
| 100 | TGorillaEspeakLibPhonemizer |
Gorilla.Audio.TTS.Espeak |
espeak-ng library directly, real IPA, no process start |
| 50 | TGorillaEspeakPhonemizer |
this unit | espeak-ng as a command line tool; Executable property, ResolveExecutable() |
| 0 | TGorillaRuleBasedPhonemizer |
this unit | Grapheme approximation for DE/EN, always available |
The first available implementation, by priority, wins. The library variant is architecture bound: the official espeak-ng binaries shipped with Piper are 64 bit, so a Win32 build falls back to the rule-based phonemizer.
| Class Method | Description |
|---|---|
Estimate(AText, ALanguage, AEnvelope, AEnvelopeRate, ADuration, APhonemizer) |
Estimates the viseme timeline of an utterance |
AEnvelope is the normalized amplitude envelope of the generated audio, as
returned by GorillaExtractEnvelope() in Gorilla.Audio.TTS.Utils. It may be
empty, in which case the phonemes are distributed evenly across the whole
duration. APhonemizer may be nil to use the global default.
The estimator exists because Piper reports no phoneme times: the text is phonemized, each phoneme gets a class-dependent base duration, the speech sections are read out of the envelope, and the phoneme sequence is distributed over them — using the pauses as anchors, which keeps the mouth in sync even for long sentences.
| Function | Description |
|---|---|
GorillaVisemeName(AViseme) |
Blend shape name of a viseme |
GorillaVisemeByName(AName, ADefault) |
Viseme by blend shape name |
GorillaVisemeToMouthShape(AViseme) |
Maps onto the Preston Blair chart |
GorillaIPAToViseme(ASymbol, ...) |
Maps an IPA symbol onto a viseme |
GorillaSplitWords(AText) |
Splits a text into words |
GorillaDefaultPhonemizer() |
The phonemizer currently in use |
GorillaRegisterPhonemizer(AValue, APriority) |
Registers an implementation |
GorillaSetDefaultPhonemizer(AValue) |
Forces one implementation |
| Variable | Description |
|---|---|
GorillaEspeakExecutable |
Path to the espeak-ng executable used by TGorillaEspeakPhonemizer |
| Constant | Value | Description |
|---|---|---|
GORILLA_VISEME_NAMES |
'sil' 'PP' 'FF' 'TH' 'DD' 'kk' 'CH' 'SS' 'nn' 'RR' 'aa' 'E' 'I' 'O' 'U' |
Blend shape name per viseme |
GORILLA_VISEME_BLENDTIME |
0.045 | Default cross fade between two visemes in seconds |
GORILLA_VISEME_WEIGHTS |
— | Relative duration weight per viseme |
The Gorilla.Audio.STT unit defines the backend independent core of the speech
recognition subsystem: the recognition request, the result with its word
timeline, the abstract TGorillaSTTEngine and the registry that makes backends
selectable by name.
TPersistent
└── TGorillaSTTResult
TFmxObject
└── TGorillaSTTEngine (abstract)
├── TGorillaWhisperEngine (Gorilla.Audio.STT.Whisper)
└── TGorillaVoskEngine (Gorilla.Audio.STT.Vosk)
TGorillaSTTEngineRegistry (class with class methods only)
EGorillaSTTException = class(Exception);
How the listener component decides when to record.
| Value | Description |
|---|---|
smPushToTalk |
Records between BeginListen() and EndListen(), the release triggers the recognition. The most reliable mode in a noisy room |
smContinuous |
Records permanently and lets the voice activity detector cut the stream into utterances |
smSingleShot |
Records until the detector found exactly one utterance, then stops |
Everything an engine needs to recognize one utterance.
| Field | Type | Description |
|---|---|---|
Samples |
TArray<Single> |
Mono float samples of the utterance, normally 16 kHz |
SampleRate |
Integer |
Sample rate of Samples |
Language |
String |
Language code such as de or en; empty means auto detection, which only whisper.cpp supports |
Prompt |
String |
Context hint, e.g. the proper names of the game world; whisper.cpp uses it as its initial prompt |
Translate |
Boolean |
whisper.cpp only: translate the result into English |
MaxAlternatives |
Integer |
Alternative readings to report; 0 and 1 both mean "only the best one" |
| Grammar phrases | TArray<String> |
Phrases the recognizer should restrict itself to; only honoured by engines whose SupportsGrammar() is true |
| Method | Description |
|---|---|
Create(ASamples, ...) |
Constructor |
Duration() |
Length of the audio in seconds |
IsValid() |
True when the request carries audio to recognize |
A single recognized word with its position in the audio.
| Field | Description |
|---|---|
Text |
The word as the recognizer spelled it |
StartTime |
Start inside the utterance, in seconds |
EndTime |
End inside the utterance, in seconds |
Confidence |
How sure the recognizer is, 0..1 |
Duration() |
Length of the word |
An alternative reading of the same audio — its text and confidence.
What an engine understood.
| Property | Type | Description |
|---|---|---|
Text |
String |
The recognized sentence |
Words |
TGorillaSTTWords |
Word timings, empty when the backend does not report them |
Alternatives |
TArray<TGorillaSTTAlternative> |
Alternative readings, empty when none were requested |
Language |
String |
Language the engine detected or was told to use |
Confidence |
Single |
Overall confidence, 0..1 |
IsPartial |
Boolean |
True for an intermediate result of a streaming backend; always followed by a final one |
EngineName |
String |
Backend that produced the result |
Duration |
Single |
Length of the recognized audio in seconds |
StartTime |
Single |
Position of the utterance in the microphone stream, in seconds |
WordCount |
Integer |
Number of words in the timeline |
IsEmpty |
Boolean |
True when nothing was understood |
| Method | Description |
|---|---|
Clear() |
Empties the result |
AddWord(AWord) / AddWord(AText, ...) |
Appends a word to the timeline |
AddAlternative(AText, AConfidence) |
Appends an alternative reading |
RebuildTextFromWords() |
Rebuilds Text out of the word timeline, for backends that only report words |
RebuildConfidenceFromWords() |
Averages the word confidences into Confidence |
OffsetWordTimes(AOffset) |
Shifts all word timings by seconds |
Assign(ASource) |
Standard TPersistent assignment |
Abstract base class of all speech recognition backends. Recognize() is called
from the worker thread of TGorillaSpeechToText; a backend that cannot work in
parallel overrides IsThreadSafe() and returns false, in which case the caller
serializes all requests.
The streaming entry points Feed() and Flush() work for every backend: the
default implementation collects the samples and runs DoRecognize() once
Flush() is called. Only a backend that really recognizes incrementally — Vosk
does — overrides DoFeed() and DoFlush().
| Method | Description |
|---|---|
GetEngineName() |
Unique name of the backend (abstract) |
IsSupported() |
False when the backend can never work on the current platform, e.g. because it needs to spawn a process |
| Method | Description |
|---|---|
IsAvailable() |
True when the backend is completely configured and ready to listen |
IsThreadSafe() |
False when the backend must not be called from several threads |
SupportsStreaming() |
True when the backend reports intermediate results while the user is still speaking |
SupportsGrammar() |
True when the backend can restrict itself to a list of phrases |
GetLanguages() |
Language codes the backend is able to recognize |
| Method | Description |
|---|---|
Recognize(ARequest) |
Recognizes a complete utterance; the caller owns the result, nil on failure (LastError holds the reason) |
Recognize(ASamples, ...) |
Convenience overload for a block of 16 kHz mono samples |
RecognizeFile(AFilename, ...) |
Convenience overload reading the audio from a wave file — handy to test a backend without a microphone |
Feed(ASamples) |
Pushes samples into a running recognition, returns a partial result or nil |
Flush() |
Ends a running recognition and returns the final result |
ResetStream() |
Drops everything a running recognition collected |
SetGrammar(APhrases) |
Restricts the recognizer to a phrase list; an empty array recognizes free text again |
GetGrammar() |
The phrase list set by SetGrammar() |
| Property | Description |
|---|---|
LastError |
Reason of the last failed operation |
| Property | Type | Default | Description |
|---|---|---|---|
DefaultLanguage |
String |
— | Language used when a request does not name one |
WordTimings |
Boolean |
True | Asks the backend for word level timings; costs a little time and is only needed for subtitles or lipsync |
| Method | Description |
|---|---|
DoRecognize(ARequest, AResult) |
Recognizes a complete utterance (abstract) |
DoFeed(ASamples, AResult) |
Pushes samples into a running recognition; the default only buffers |
DoFlush(AResult) |
Ends a running recognition; the default recognizes everything buffered |
DoResetStream() |
Drops the state of a running recognition |
DoGrammarChanged() |
Called after Grammar was changed |
FinalizeResult(ARequest, AResult) |
Fills in everything the backend left empty and normalizes the text |
SetError(AMessage) |
Stores an error message and returns false |
Backends register themselves in the initialization section of their unit, so adding the unit to a project makes the engine selectable by name at design-time and at runtime.
| Class Method | Description |
|---|---|
RegisterEngine(AClass) |
Registers a backend |
UnregisterEngine(AClass) |
Removes it again |
FindEngineClass(AName) |
Resolves a backend class by engine name |
CreateEngine(AName, AOwner) |
Creates an instance; raises EGorillaSTTException for an unknown name, an empty name picks the first supported backend |
EngineNames() |
Names of all registered backends |
DefaultEngineName() |
Name of the first backend supported on this platform |
| Constant | Value | Description |
|---|---|---|
GORILLA_STT_MAX_UTTERANCE |
30.0 | Longest utterance a non-streaming engine is handed at once, in seconds. whisper.cpp works on 30 second windows, anything above gets split |
GORILLA_STT_SAMPLERATE |
16000 | Sample rate the recognizers work on (in Gorilla.Audio.STT.Utils) |
The Gorilla.Audio.STT.Listener unit contains the component applications work
with: TGorillaSpeechToText, its voice command collection, and the two threads
that keep recording and recognition off the main thread.
TFmxObject
└── TGorillaSpeechToText
TOwnedCollection
└── TGorillaSTTCommands
TCollectionItem
└── TGorillaSTTCommand
TThread
├── TGorillaSTTCaptureThread
└── TGorillaSTTWorkerThread
TGorillaSTTResultEvent = procedure(ASender : TObject;
const AResult : TGorillaSTTResult) of object;
TGorillaSTTCommandEvent = procedure(ASender : TObject;
const ACommand : TGorillaSTTCommand; const AConfidence : Single;
const AResult : TGorillaSTTResult) of object;
TGorillaSTTErrorEvent = procedure(ASender : TObject;
const AError : String) of object;
TGorillaSTTSpeechEvent = procedure(ASender : TObject;
const ALevel : Single) of object;
What the recognition worker is supposed to do with a block of samples.
| Value | Description |
|---|---|
wkSegment |
A complete utterance, recognized in one go |
wkChunk |
Part of a running utterance, pushed into a streaming engine |
wkFlush |
End of a streaming utterance, asks for the final result |
Kind of an event waiting to be raised on the main thread: ekSpeechStart,
ekSpeechEnd, ekPartial, ekResult, ekError.
One entry of the queue between capture and recognition: Kind, Samples,
StartTime, Duration.
One event a worker produced, waiting for the main thread to raise it: Kind,
Data (owned by the queue), Text, Level. Events must never be raised from a
worker thread — an application handler will touch the scene — so they are queued
here and dispatched by Update().
One voice command with all the phrases that trigger it. For a game the raw text is rarely the goal: a command bundles the synonyms a player might use — "angriff", "attackieren", "greif an" — under a single name the application reacts to.
| Member | Type | Default | Description |
|---|---|---|---|
Name |
String |
— | The name reported by OnCommand |
Phrases |
TStrings |
— | The phrases that trigger this command, one per line |
Enabled |
Boolean |
True | A disabled command is never matched |
Threshold |
Single |
0 | Similarity this command needs to fire; 0 uses the component's CommandThreshold |
Tag |
NativeInt |
— | Free for application use |
Match(AText) |
Single |
— | Best similarity of any phrase to a text: 1.0 literal hit, 0.0 nothing in common |
Collection of all voice commands a component listens for.
| Member | Description |
|---|---|
Add() |
Creates an empty command |
Add(AName, APhrases) |
Creates a command together with its phrases |
FindByName(AName) |
Command by name |
AllPhrases() |
Every phrase of every enabled command, for use as a recognizer grammar |
Items[AIndex] |
Typed default indexer |
Speech input: microphone in, recognized text and voice commands out. Drop the
component next to a TGorillaAudioManager, assign an engine, define your
commands and switch Active on.
| Method | Description |
|---|---|
ActiveEngine() |
The engine actually used; creates one of type EngineName when no component was assigned |
ActiveAudioManager() |
The manager actually used; falls back to the first one next to this component |
ActiveCapture() |
The capture backend, nil while inactive |
ActiveVAD() |
The voice activity detector, nil while inactive |
GetDevices() |
Names of all recording devices available |
BeginListen() |
Starts collecting audio for push-to-talk |
EndListen() |
Ends the push-to-talk recording and starts the recognition |
Listen() |
Listens until one utterance was recognized, then stops — switches Mode to smSingleShot and Active on |
Stop() |
Stops recording and discards everything not recognized yet |
RecognizeFile(AFilename) |
Recognizes a wave file instead of the microphone; runs synchronously and does not touch the capture layer. The caller owns the result |
SaveLastSegment(AFilename) |
Writes everything recorded since the last call into a wave file — the diagnostic for the capture layer |
Update() |
Raises all queued events |
DispatchResult(AResult) |
Reports a result through OnResult and the voice command matching; main thread only, the caller keeps ownership |
MatchCommand(AResult, out ACommand, out AConfidence) |
Looks for a command inside a result |
MatchCommand(AText, out ACommand, out AConfidence) |
Same for a plain text |
In smPushToTalk everything between BeginListen() and EndListen() is one
utterance and the detector is bypassed. In the other modes BeginListen() only
switches recording on — the detector then decides where an utterance starts and
ends, so EndListen() has nothing to trigger.
| Property | Type | Description |
|---|---|---|
IsListening |
Boolean |
True between BeginListen() and EndListen() |
IsSpeaking |
Boolean |
True while the detector reports speech |
Level |
Single |
Current input level, 0..1, ready for a level meter |
DroppedSegments |
Int64 |
Utterances dropped because the recognizer could not keep up — anything above zero means the engine is too slow for the mode |
| Property | Type | Default | Description |
|---|---|---|---|
Engine |
TGorillaSTTEngine |
— | Engine component doing the recognition |
EngineName |
String |
— | Engine created internally when Engine is empty; empty picks the first registered backend, e.g. Whisper |
AudioManager |
TGorillaAudioManager |
— | Manager whose backend is used for recording; empty uses the first manager of the same form |
VADName |
String |
— | Name of the voice activity detector; empty picks the highest priority one, which is Energy |
Active |
Boolean |
False | Starts and stops recording |
Mode |
TGorillaSTTMode |
smContinuous |
How the component decides when to record |
Device |
String |
— | Recording device out of GetDevices(); empty uses the system default |
SampleRate |
Integer |
16000 | Rate the device is opened with — leave it there unless the device refuses it |
Language |
String |
— | Language of the expected speech, e.g. de; empty asks the engine to detect it |
Prompt |
String |
— | Context hint handed to the engine; improves the spelling of unusual words noticeably |
Translate |
Boolean |
False | Lets the engine translate the result into English |
PartialResults |
Boolean |
False | Intermediate results while speaking; only with a streaming engine |
UseGrammar |
Boolean |
False | Hands the command phrases to the engine as a recognition grammar |
Commands |
TGorillaSTTCommands |
— | The voice commands this component listens for |
CommandThreshold |
Single |
0.75 | Similarity a phrase needs to fire its command; 1.0 accepts only literal hits |
AutoUpdate |
Boolean |
True | Drives Update() from an internal timer |
UpdateInterval |
Integer |
16 | Interval of that timer in ms |
PollInterval |
Integer |
20 | Interval the capture thread polls the device with, in ms |
MaxQueueLength |
Integer |
8 | Utterances that may wait for the recognizer; everything beyond is dropped and counted in DroppedSegments |
UseGrammar raises the hit rate for voice commands dramatically with a grammar
capable engine, at the price of no longer understanding anything else. Engines
without grammar support get the phrases as a context prompt instead.
| Event | Type | Fired when |
|---|---|---|
OnSpeechStart |
TGorillaSTTSpeechEvent |
The detector found the start of speech |
OnSpeechEnd |
TGorillaSTTSpeechEvent |
An utterance ended |
OnPartial |
TGorillaSTTResultEvent |
Intermediate result of a streaming engine |
OnResult |
TGorillaSTTResultEvent |
An utterance was recognized |
OnCommand |
TGorillaSTTCommandEvent |
A recognized text matched a command; fires after OnResult |
OnError |
TGorillaSTTErrorEvent |
Recording or recognition failed |
The result handed to OnPartial and OnResult is owned by the component and
invalid after the handler returned — copy what you need.
| Class | Description |
|---|---|
TGorillaSTTCaptureThread |
Reads the microphone, converts and segments its samples. Runs at a raised priority: a capture device that is not drained in time silently overwrites its own ring buffer, and the samples are gone |
TGorillaSTTWorkerThread |
Runs the recognition of queued utterances |
| Constant | Value | Description |
|---|---|---|
GORILLA_STT_COMMAND_THRESHOLD |
0.75 | Similarity a phrase needs to fire its command by default |
GORILLA_STT_QUEUE_LENGTH |
8 | Utterances that may wait for the recognizer |
GORILLA_STT_CHUNK_DURATION |
0.25 | Length of the sample block handed to a streaming engine, in seconds |
The Gorilla.Audio.STT.Whisper unit implements TGorillaWhisperEngine, a local
speech recognition backend driving
whisper.cpp. It can either load the
whisper.cpp shared library or call the whisper-cli executable and read the
JSON it produced. The engine registers itself in the initialization section of
the unit, so adding the unit makes 'Whisper' selectable through EngineName.
whisper.cpp and its models are not part of the Gorilla3D distribution. See Getting whisper.cpp.
TGorillaSTTEngine
└── TGorillaWhisperEngine
| Value | Description |
|---|---|
wmAuto |
Use the shared library when it can be loaded, otherwise fall back to the command line tool |
wmLibrary |
Only use the shared library, fail when it is missing |
wmProcess |
Only use the command line tool |
| Method | Description |
|---|---|
GetEngineName() |
Returns 'Whisper' |
IsSupported() |
False where the resolved mode cannot work, e.g. wmProcess on mobile |
| Method | Description |
|---|---|
IsAvailable() |
True when library or executable and a model were resolved |
IsThreadSafe() |
Reports whether parallel recognition is allowed |
GetLanguages() |
Language codes whisper.cpp is able to recognize |
ActiveMode() |
The mode the engine will actually work in, with wmAuto resolved |
LibraryAvailable() |
True when the shared library could be loaded and its parameter layout matches the one this unit was written against |
LibraryFile() |
Path of the shared library in use, empty when none |
ResolveExecutable() |
The executable the engine will call in wmProcess, resolved against the system search path and the release layouts next to the application. Empty when whisper-cli could not be found |
RefreshModels() |
Rescans ModelDirectory for ggml-*.bin files |
GetModels() |
Model files found in ModelDirectory |
Unload() |
Frees the loaded model; the next recognition loads it again |
| Property | Type | Default | Description |
|---|---|---|---|
Mode |
TGorillaWhisperMode |
wmAuto |
How the engine reaches whisper.cpp |
LibraryPath |
String |
— | Path of the shared library; empty searches next to the application and on the system library path |
ExecutablePath |
String |
— | Path of the whisper-cli executable; a bare name is searched on the system path |
ModelPath |
String |
— | Model used for recognition: absolute path, file name inside ModelDirectory, or a bare size name such as base or small.en |
ModelDirectory |
String |
— | Folder scanned for ggml-*.bin model files |
CommandTemplate |
String |
see below | Command line for wmProcess |
Threads |
Integer |
0 | Threads the inference may use; 0 picks half of the available cores, which leaves room for the render loop |
Timeout |
Integer |
60000 | Milliseconds a single recognition may take |
UseGPU |
Boolean |
False | Runs the inference on the GPU when the library was built with a GPU backend |
MaxSegmentLength |
Integer |
0 | Maximum characters per segment, 0 for no limit — useful for subtitles |
SplitOnWord |
Boolean |
True | Keeps words intact when MaxSegmentLength splits a segment |
Temperature |
Single |
— | Sampling temperature; 0 is deterministic and the right choice for voice commands |
NoSpeechThreshold |
Single |
— | Probability above which a segment is discarded as silence, 0..1 |
Inherited from TGorillaSTTEngine: DefaultLanguage, WordTimings.
UseGPU is off by default on purpose: a Vulkan build of whisper.cpp shares the
device with the Gorilla3D Vulkan renderer, and whether that is collision free is
unverified.
| Method | Description |
|---|---|
ResolveModel(AVoiceId, out AModel) |
Resolves a model identifier into an absolute file path; accepts an absolute path, a file name inside ModelDirectory, or a bare size name such as base, which is expanded into ggml-base.bin |
EnsureContext(AModel) |
Loads the model into the library, reusing an already loaded one |
ReleaseContext() |
Releases the loaded model |
DoRecognizeLibrary(...) |
Recognition through the shared library |
DoRecognizeProcess(...) |
Recognition through whisper-cli |
ParseJsonResult(AJson, AResult) |
Reads the JSON whisper-cli wrote into a result instance |
| Name | Description |
|---|---|
GorillaWhisperLibAvailable() |
True when the shared library could be loaded and initialized |
GorillaWhisperLibFile() |
Path of the shared library in use, empty when none was found |
GorillaWhisperLibraryPath |
Full path of the library all engine instances should use; leave empty to search next to the application and on the system library path. Has to be set before the first recognition |
| Platform | Library | Executable candidates |
|---|---|---|
| Windows | whisper.dll |
whisper-cli, main, whisper |
| macOS | libwhisper.dylib |
same |
| Linux | libwhisper.so, libwhisper.so.1 |
same |
Default command line of the whisper-cli executable:
%EXE% -m %MODEL% -f %INPUT% -of %OUTPUT% -oj%JSONFULL%
-t %THREADS% -np -l %LANGUAGE%%TRANSLATE%%PROMPT%
Placeholders: %EXE%, %MODEL%, %INPUT%, %OUTPUT%, %LANGUAGE%,
%THREADS%, %TRANSLATE%, %PROMPT%, %JSONFULL%.
| Constant | Value | Description |
|---|---|---|
GORILLA_WHISPER_MODEL_PREFIX |
ggml- |
File name prefix of the GGML models |
GORILLA_WHISPER_MODEL_EXT |
.bin |
File name extension of the GGML models |
GORILLA_WHISPER_TIME_UNIT |
0.01 | whisper.cpp reports segment and token timings in units of 10 ms |
whisper.cpp works on 30 second windows; longer utterances are split — see
GORILLA_STT_MAX_UTTERANCE in Gorilla.Audio.STT.
The backend does not support grammars. When UseGrammar is enabled on the
listener component, the command phrases are handed over as a context prompt
instead.
The Gorilla.Audio.STT.Vosk unit implements TGorillaVoskEngine, a local
streaming speech recognition backend driving
Vosk. Unlike whisper.cpp it reports
intermediate results while the user is still speaking, and it can be restricted
to a phrase list, which raises the hit rate for voice commands dramatically.
The engine registers itself in the initialization section of the unit, so adding
the unit makes 'Vosk' selectable through EngineName.
The Vosk library and its models are not part of the Gorilla3D distribution. See Getting Vosk.
TGorillaSTTEngine
└── TGorillaVoskEngine
| Method | Description |
|---|---|
GetEngineName() |
Returns 'Vosk' |
IsSupported() |
False when the platform cannot load the library |
| Method | Result |
|---|---|
IsAvailable() |
True when library and model were resolved |
IsThreadSafe() |
Reports whether parallel recognition is allowed |
SupportsStreaming() |
True — partial results while speaking |
SupportsGrammar() |
True — can be restricted to a phrase list |
| Method | Description |
|---|---|
LibraryAvailable() |
True when the Vosk shared library could be loaded |
LibraryFile() |
Path of the library in use, empty when none |
GetModels() |
Model directories found in ModelDirectory |
Unload() |
Frees model and recognizer; the next call reloads them |
| Property | Type | Default | Description |
|---|---|---|---|
LibraryPath |
String |
— | Path of the Vosk shared library; empty searches next to the application and on the system library path |
ModelPath |
String |
— | Model directory used for recognition: absolute path or a directory name inside ModelDirectory |
ModelDirectory |
String |
— | Folder scanned for vosk-model-* directories |
MaxAlternatives |
Integer |
0 | Alternative readings the recognizer reports; 0 asks for the best one only |
LogLevel |
Integer |
-1 | Verbosity of the Vosk internal logging; -1 silences it, 0 reports warnings and errors |
PartialWords |
Boolean |
False | Word timings in the intermediate results as well, at a little performance cost |
| Grammar fallback | String |
[unk] |
Token added to every grammar so the recognizer has a way to report something outside it |
Inherited from TGorillaSTTEngine: DefaultLanguage, WordTimings.
| Method | Description |
|---|---|
ResolveModel(AName, ...) |
Resolves a model identifier into an absolute directory path |
EnsureModel(AModel) |
Loads the model, reusing an already loaded one |
EnsureRecognizer(ASampleRate) |
Creates the recognizer, recreating it when the grammar changed |
ReleaseRecognizer() / ReleaseModel() |
Release the corresponding handles |
BuildGrammarJson(APhrases) |
Builds the JSON phrase list Vosk expects as a grammar |
ParseJsonResult(AJson, AResult) |
Reads a Vosk JSON result |
ParseJsonPartial(AJson, AResult) |
Reads a Vosk JSON partial result |
DoRecognize / DoFeed / DoFlush / DoResetStream / DoGrammarChanged |
The streaming implementation |
| Platform | Library |
|---|---|
| Windows | libvosk.dll |
| macOS | libvosk.dylib |
| Linux | libvosk.so |
| Constant | Value | Description |
|---|---|---|
GORILLA_VOSK_MODEL_PREFIX |
vosk-model |
Prefix of the model directory names |
GORILLA_VOSK_UNKNOWN |
[unk] |
Token representing anything outside the grammar |
A Vosk model is a directory, not a file — vosk-model-small-de-0.15 for
example. There is one model per language; Vosk cannot detect the language on its
own, which is the main difference to whisper.cpp in practice.
Enabling UseGrammar on the listener component restricts the recognizer to the
phrases of all enabled voice commands. That makes command recognition much more
reliable, but nothing outside the list is understood any more — the recognizer
then reports [unk].
The Gorilla.Audio.STT.VAD unit contains the voice activity detection of the
speech recognition subsystem: the backend independent IGorillaVAD interface,
the TGorillaVADBase state machine, the energy based detector registered by
default, and the registry that makes detectors selectable by name.
A detector is stateful and belongs to exactly one audio stream, so every
listener creates its own instance. Feed() is called from the capture thread,
everything else from the same thread.
TInterfacedObject
└── TGorillaVADBase (IGorillaVAD)
└── TGorillaEnergyVAD
TGorillaVADRegistry (class with class methods only)
| Value | Description |
|---|---|
| Silence | No speech, the noise floor is being tracked |
| Speech | Speech is running, samples are collected |
One complete utterance cut out of the microphone stream.
| Field | Description |
|---|---|
| Samples | 16 kHz mono float samples of the utterance |
| StartTime | Start of the utterance in the stream, in seconds |
| EndTime | End of the utterance in the stream, in seconds |
| PeakLevel | Loudest sample of the utterance, 0..1 |
| AverageLevel | Average level of the utterance, 0..1 |
| Truncated | True when the maximum length forced the cut |
Duration() |
Length of the utterance in seconds |
IsValid() |
True when the segment carries audio |
| Method | Description |
|---|---|
GetName() |
Human readable name of the detector |
IsAvailable() |
False when the detector cannot work, e.g. a missing library |
Configure(ASampleRate) |
Prepares the detector for a stream of that rate; resets all state, so it may be called again whenever the capture format changed |
Reset() |
Drops the collected audio and returns to silence |
Feed(ASamples, ACount) |
Pushes new samples in; returns the number of segments completed during this call |
Flush() |
Closes a running utterance immediately, e.g. when push-to-talk was released; returns the number of completed segments |
TakeSegment(out ASegment) |
Removes the oldest completed segment from the queue; false when none is waiting |
PendingSegments() |
Number of segments waiting |
GetState() |
Current TGorillaVADState |
GetLevel() |
Current input level, 0..1 |
GetNoiseFloor() |
Tracked noise floor |
GetStreamTime() |
Position in the stream, in seconds |
Implements the state machine shared by all detectors: threshold handling, pre-roll buffer, minimum durations and the segment queue. A concrete detector only implements the per-frame classification.
| Property | Type | Default | Description |
|---|---|---|---|
Threshold |
Single |
0.012 | Absolute level a frame has to exceed to count as speech. It acts as the lower bound of the adaptive threshold: the effective threshold is the larger of this value and NoiseFloor * NoiseMultiplier |
NoiseMultiplier |
Single |
2.5 | Factor the tracked noise floor is multiplied with |
MinSpeechDuration |
Single |
0.25 | Shortest utterance reported, in seconds; anything shorter is discarded as a click or a cough |
MinSilenceDuration |
Single |
0.6 | Pause that ends an utterance, in seconds. Too short cuts sentences apart at every breath, too long adds latency to every result |
PreRollDuration |
Single |
0.3 | Audio in front of the detected speech that is kept, in seconds; without it the plosive at the start of a word is cut off |
MaxSegmentDuration |
Single |
15.0 | Emergency brake: an utterance is cut after this many seconds even when the speaker does not pause |
Normalize |
Boolean |
— | Normalizes the collected audio before it is reported |
| Method | Description |
|---|---|
DoDetectFrame(ASamples, ...) |
Classifies one complete frame; true when it contains speech |
DoConfigure() |
Called after Configure() so a detector can size its state |
DoReset() |
Called by Reset() so a detector can drop its state |
GetVADName() |
Name the detector registers itself under |
The default detector: frame energy against an adaptive threshold, with a zero
crossing rate check to keep loud non-speech noise out. Registered under the name
Energy with priority 0.
| Property | Type | Default | Description |
|---|---|---|---|
MaxZeroCrossingRate |
Single |
0.42 | Crossing rate above which a loud frame is treated as noise, 0..1 |
NoiseAdaption |
Single |
0.05 | Speed the noise floor follows the input, 0..1; larger values adapt faster but are more easily fooled by slow speech |
| Class Method | Description |
|---|---|
RegisterVAD(AClass, APriority) |
Registers a detector with a priority |
UnregisterVAD(AClass) |
Removes it again |
FindVADClass(AName) |
Resolves a detector class by name |
CreateVAD(AName) |
Creates an instance; an empty name picks the highest priority detector |
VADNames() |
Names of all registered detectors |
DefaultVADName() |
Name of the highest priority detector |
| Constant | Value |
|---|---|
GORILLA_VAD_THRESHOLD |
0.012 |
GORILLA_VAD_NOISE_MULTIPLIER |
2.5 |
GORILLA_VAD_MIN_SPEECH |
0.25 |
GORILLA_VAD_MIN_SILENCE |
0.6 |
GORILLA_VAD_PREROLL |
0.3 |
GORILLA_VAD_MAX_SEGMENT |
15.0 |
GORILLA_VAD_MAX_ZCR |
0.42 |
GORILLA_VAD_NOISE_ADAPTION |
0.05 |
The Gorilla.Audio.STT.Capture unit provides backend independent access to a
recording device. It defines IGorillaAudioCapture, the shared base class
TGorillaAudioCaptureBase, and three implementations: OpenAL, FMOD and a null
device used when nothing else works.
The typical lifecycle is Open() — Start() — Read() in a loop — Stop() —
Close(). Read() never blocks; it returns whatever the device has ready.
TInterfacedObject
└── TGorillaAudioCaptureBase (IGorillaAudioCapture)
├── TGorillaOpenALCapture — name "OpenAL"
├── TGorillaFMODCapture — name "FMOD"
└── TGorillaNullCapture — name "None"
| Method | Description |
|---|---|
GetName() |
Human readable name of the backend |
GetDevices() |
Names of all recording devices the backend offers |
Open(ADevice, ASampleRate, AChannels) |
Opens a device without starting the recording. ADevice empty opens the system default |
Start() |
Begins filling the capture buffer |
Stop() |
Stops filling it, the device stays open |
Close() |
Stops the recording and releases the device |
The device may not be able to deliver the requested format. Query
GetSampleRate() and GetChannels() afterwards to learn what was actually
granted, and resample accordingly.
| Method | Description |
|---|---|
Read(var ABuffer) |
Reads everything the device has ready; returns the number of SmallInt entries written, which is the number of sample frames multiplied by GetChannels(). The buffer is grown as needed and may stay larger than the returned count |
GetAvailable() |
Number of sample frames waiting to be read |
| Method | Description |
|---|---|
IsCapturing() |
True between Start() and Stop() |
IsOpen() |
True while a device is open |
GetSampleRate() |
Rate the device was actually opened with |
GetChannels() |
Channel count the device was actually opened with |
GetDeviceName() |
Name of the device currently open |
GetLastError() |
Reason of the last failed operation |
| Method | Description |
|---|---|
GetCapturedFrames() |
Sample frames handed out since Start() |
GetThroughput() |
Share of real time the device delivers once it runs; 1.0 = healthy. Measured from the first sample actually received, not from Start() |
GetStartupLatency() |
Time the device needed to wake up |
A driver that silently drops samples is the most confusing failure of the whole subsystem: recording "works", the level meter moves, and the recognizer returns nonsense because it is fed audio with holes in it. Log the throughput during development.
Startup latency is reported separately on purpose — mixing the two would blame a slow-starting device for dropping samples it never lost.
| Class | Name | Notes |
|---|---|---|
TGorillaOpenALCapture |
OpenAL |
Uses the OpenAL capture extension |
TGorillaFMODCapture |
FMOD |
Uses the FMOD record API; constructed with the manager, GetNativeSampleRate() reports the driver rate, ResolveDriver() maps a device name onto an FMOD driver index |
TGorillaNullCapture |
None |
Placeholder whose Open() fails with an explanatory message |
Each implements IsSupported() as a class function.
DoOpen(), DoClose(), DoStart(), DoStop(), DoRead(),
DoGetAvailable() — the base class handles state tracking, error reporting and
the health statistics around them.
| Function | Description |
|---|---|
GorillaCreateAudioCapture(AManager) |
Creates the capture implementation matching an audio manager: an FMOD manager selects the FMOD backend, an OpenAL manager the OpenAL backend, nil picks the first backend available. Never returns nil — when no backend works, a TGorillaNullCapture is returned whose Open() fails with an explanatory message |
GorillaCaptureDevices(AManager) |
Lists the recording devices of the backend belonging to a manager |
GorillaCaptureSupported() |
True when any capture backend works on this platform |
| Name | Description |
|---|---|
TGorillaSampleBuffer |
Growable ring buffer of float samples |
GorillaInt16ToFloat() / GorillaFloatToInt16() |
Sample format conversion |
GorillaDownmixToMono() |
Stereo to mono |
GorillaResampleMono() |
Resampling to the recognition rate |
GorillaLowPassMono() |
Anti-alias filtering before downsampling |
GorillaPrepareForRecognition() |
Downmix, resample and convert in one call |
GorillaComputeRMS(), GorillaComputePeak(), GorillaComputeZeroCrossingRate() |
Level and noise metrics used by the detector |
GorillaRemoveDCOffset(), GorillaNormalizeSamples() |
Signal clean-up |
GorillaSamplesToWave(), GorillaSaveSamplesToWave(), GorillaWaveToSamples() |
Wave file helpers |
GorillaNormalizeSpokenText() |
Normalizes recognized text before command matching |
GORILLA_STT_SAMPLERATE |
16000 — the rate the recognizers work on |
Main input controller component for keyboard, mouse, and gamepad handling.
Unit: Gorilla.Controller.Input
High-performance, asynchronous input polling controller.
Inheritance: TGorillaController → TGorillaInputController
Platforms: All Gorilla platforms
TGorillaInputController provides a centralized, thread-safe input handling system. It continuously monitors input devices and triggers HotKeys and Sequences based on input combinations.
Architecture:
TGorillaInputController
├── Input Handlers (threads)
│ ├── Keyboard Handler
│ ├── Mouse Handler
│ └── GamePad Handler
├── Input Thread (HotKey/Sequence detection)
└── Main Thread (Event callbacks)
constructor Create(AOwner: TComponent); override;
Creates input controller with default settings:
destructor Destroy; override;
Stops all handler threads, clears collections, and frees resources.
property Enabled: Boolean read GetEnabled write SetEnabled;
Enables or disables input polling.
Default: False
Behavior:
property Supported: TGorillaInputDeviceTypes read FSupported write SetSupported;
Defines which input devices are monitored.
Type: Set of (Keyboard, Mouse, GamePad)
Default: [Keyboard, Mouse, GamePad]
Example:
// Desktop game - keyboard and mouse only
GorillaInputController1.Supported := [Keyboard, Mouse];
// Console game - gamepad only
GorillaInputController1.Supported := [GamePad];
// All devices
GorillaInputController1.Supported := [Keyboard, Mouse, GamePad];
property HighPerformanceHooks: Boolean read FHighPerformanceHooks
write SetHighPerformanceHooks default True;
Enables low-level hooks for keyboard and mouse (Windows only).
Default: True
Platform: Windows only (ignored on other platforms)
Trade-offs:
| Enabled (True) | Disabled (False) |
|---|---|
| Better input response | Slower input response |
| Global input capture | Window-focused only |
| Slower debugging | Normal debugging |
Recommendation: Disable during development, enable for release builds.
{$IFDEF DEBUG}
GorillaInputController1.HighPerformanceHooks := False;
{$ENDIF}
property HotKeys: TGorillaHotKeyCollection read FHotKeys write SetHotKeys;
Collection of input combination HotKeys.
property Sequences: TGorillaInputSequenceCollection read FSequences write SetSequences;
Collection of ordered HotKey Sequences.
See: TGorillaInputSequenceCollection
property Handlers: TGorillaInputHandlerList read FHandlers;
List of active input handlers (read-only).
Usage: Access individual handlers to configure sensitivity.
var
LHandler: TGorillaInputHandler;
begin
LHandler := GorillaInputController1.GetHandler(Keyboard);
if Assigned(LHandler) then
LHandler.Sensitivity := 5; // Poll every 5ms
end;
function AddHotKey(const AName: String): TGorillaHotKeyItem; virtual;
Creates and adds a new HotKey to the collection.
Parameters:
AName - Unique HotKey nameReturns: New TGorillaHotKeyItem instance
Example:
var
LHotKey: TGorillaHotKeyItem;
begin
LHotKey := GorillaInputController1.AddHotKey('Jump');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_SPACE);
LHotKey.TriggerOnActivate := True;
LHotKey.OnTriggered := OnJumpTriggered;
end;
function FindHotKey(const AName: String): TGorillaHotKeyItem; virtual;
Searches for a HotKey by name.
Parameters:
AName - HotKey name to findReturns: TGorillaHotKeyItem if found, nil otherwise
function GetOrAddHotKey(const AName: String): TGorillaHotKeyItem; virtual;
Gets existing HotKey or creates new one if it doesn't exist.
Parameters:
AName - HotKey nameReturns: Existing or new TGorillaHotKeyItem
Usage: Safely ensures HotKey exists without checking.
function IndexOfHotKey(const AName: String): Integer; overload; virtual;
function IndexOfHotKey(const AKey: TGorillaHotKeyItem): Integer; overload; virtual;
Returns collection index of HotKey.
Returns: Index (0-based) or -1 if not found
function HotKeyExists(const AName: String): Boolean; virtual;
Checks if HotKey with specified name exists.
procedure RemoveHotKey(const AName: String); overload; virtual;
procedure RemoveHotKey(const AKey: TGorillaHotKeyItem); overload; virtual;
Removes HotKey from collection by name or instance.
function AddSequence(const AName: String;
const AHotKeys: TArray<TGorillaHotKeyItem>): TGorillaInputSequenceItem; virtual;
Creates and adds a new Sequence to the collection.
Parameters:
AName - Unique Sequence nameAHotKeys - Array of HotKeys to chainReturns: New TGorillaInputSequenceItem or nil if AHotKeys is empty
Example:
var
LHK1, LHK2, LHK3: TGorillaHotKeyItem;
LSeq: TGorillaInputSequenceItem;
begin
LHK1 := GorillaInputController1.AddHotKey('Up');
LHK1.AddInput(Keyboard, GORILLA_INPUT_KEY_ARROW_UP);
LHK2 := GorillaInputController1.AddHotKey('Down');
LHK2.AddInput(Keyboard, GORILLA_INPUT_KEY_ARROW_DOWN);
LHK3 := GorillaInputController1.AddHotKey('A');
LHK3.AddInput(Keyboard, GORILLA_INPUT_KEY_A);
// Create Up-Down-A sequence
LSeq := GorillaInputController1.AddSequence('Combo1', [LHK1, LHK2, LHK3]);
LSeq.Sensitivity := 500;
LSeq.OnTriggered := OnCombo1Triggered;
end;
function GetHandler(const ADevice: TGorillaInputDeviceType): TGorillaInputHandler; virtual;
Retrieves handler for specified device type.
Parameters:
ADevice - Device type (Keyboard, Mouse, GamePad)Returns: Handler instance or nil if not found
Example:
var
LKbdHandler: TGorillaInputHandler;
begin
LKbdHandler := GorillaInputController1.GetHandler(Keyboard);
if Assigned(LKbdHandler) then
begin
LKbdHandler.Enabled := True;
LKbdHandler.Sensitivity := 10;
end;
end;
function GetPersistentMessage(const ADevice: TGorillaInputDeviceType;
const ACode: TGorillaInputCode; out AMessage: TGorillaInputMessage): Boolean; virtual;
Retrieves persistent message (mouse position, gamepad triggers/thumbsticks).
Parameters:
ADevice - Device typeACode - Input codeAMessage - Output message structureReturns: True if message available
Persistent Codes:
GORILLA_INPUT_MOUSE_POSITIONGORILLA_INPUT_GAMEPAD_TRIGGER_LEFTGORILLA_INPUT_GAMEPAD_TRIGGER_RIGHTGORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_LEFTGORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_RIGHTExample:
var
LMsg: TGorillaInputMessage;
LPos: TPoint;
begin
if GorillaInputController1.GetPersistentMessage(Mouse,
GORILLA_INPUT_MOUSE_POSITION, LMsg) then
begin
LPos := LMsg.Data.AsType<TPoint>;
// Use LPos.X, LPos.Y
end;
end;
function GetLastMousePosition(out APos: TPoint): Boolean;
Convenience method to get last mouse position.
Parameters:
APos - Output screen coordinatesReturns: True if position available
function GetLastGamePadTriggers(out APos: TPoint): Boolean;
Convenience method to get gamepad trigger values.
Parameters:
APos - Output (X=Left trigger, Y=Right trigger, 0-255 each)Returns: True if values available
function GetLastGamePadThumbstickPosLeft(out APos: TPointF): Boolean;
Convenience method to get left thumbstick position.
Parameters:
APos - Output normalized coordinates (-1.0 to +1.0)Returns: True if position available
function GetLastGamePadThumbstickPosRight(out APos: TPointF): Boolean;
Convenience method to get right thumbstick position.
Parameters:
APos - Output normalized coordinates (-1.0 to +1.0)Returns: True if position available
procedure SetCursorPos(APoint: TPoint);
Sets mouse cursor position asynchronously (thread-safe).
Parameters:
APoint - Screen coordinatesproperty OnMouseDown: TGorillaInputMouseEvent read FOnMouseDown write FOnMouseDown;
Fired when mouse button is pressed.
Signature:
TGorillaInputMouseEvent = procedure(ASender: TObject;
AStates: TGorillaMouseStates; APos: TPointF) of object;
Parameters:
AStates - Mouse button states (set)APos - Mouse positionproperty OnMouseUp: TGorillaInputMouseEvent read FOnMouseUp write FOnMouseUp;
Fired when mouse button is released.
property OnMouseDblClick: TGorillaInputMouseEvent read FOnMouseDblClick write FOnMouseDblClick;
Fired on mouse button double-click.
property OnMouseMove: TGorillaInputMouseMoveEvent read FOnMouseMove write FOnMouseMove;
Fired when mouse moves.
Signature:
TGorillaInputMouseMoveEvent = procedure(ASender: TObject;
AStates: TGorillaMouseStates; APos: TPointF) of object;
property OnMouseWheel: TGorillaInputMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;
Fired when mouse wheel scrolls.
Signature:
TGorillaInputMouseWheelEvent = procedure(ASender: TObject; APos: TPointF;
const AWheelDelta: Integer) of object;
property OnKeyDown: TGorillaInputKeyEvent read FOnKeyDown write FOnKeyDown;
Fired when keyboard key is pressed.
Signature:
TGorillaInputKeyEvent = procedure(ASender: TObject;
AKeyCode: Integer) of object;
property OnKeyUp: TGorillaInputKeyEvent read FOnKeyUp write FOnKeyUp;
Fired when keyboard key is released.
property OnGamePadConnect: TGorillaInputGamePadEvent read FOnGamePadConnect
write FOnGamePadConnect;
Fired when gamepad is connected.
Signature:
TGorillaInputGamePadEvent = procedure(ASender: TObject;
AState: TGorillaInputCode; AUser: Integer) of object;
Parameters:
AState - GORILLA_INPUT_GAMEPAD_CONNECTEDAUser - Gamepad user index (0-3)property OnGamePadDisconnect: TGorillaInputGamePadEvent read FOnGamePadDisconnect
write FOnGamePadDisconnect;
Fired when gamepad is disconnected.
property OnGamePadButtonDown: TGorillaInputGamePadButtonEvent
read FOnGamePadButtonDown write FOnGamePadButtonDown;
Fired when gamepad button is pressed.
Signature:
TGorillaInputGamePadButtonEvent = procedure(ASender: TObject;
AState: TGorillaInputCode; AButtons: TGorillaGamePadButtons) of object;
property OnGamePadButtonUp: TGorillaInputGamePadButtonEvent
read FOnGamePadButtonUp write FOnGamePadButtonUp;
Fired when gamepad button is released.
property OnGamePadTrigger: TGorillaInputGamePadTriggerEvent
read FOnGamePadTrigger write FOnGamePadTrigger;
Fired when gamepad trigger value changes.
Signature:
TGorillaInputGamePadTriggerEvent = procedure(ASender: TObject;
AState: TGorillaInputCode; const AButtons: TGorillaGamePadButtons;
AValue: Byte; AFlags: UInt64) of object;
Parameters:
AValue - Trigger pressure (0-255)property OnGamePadFeedback: TGorillaInputGamePadFeedbackEvent
read FOnGamePadFeedback write FOnGamePadFeedback;
Fired when gamepad thumbstick position changes.
Signature:
TGorillaInputGamePadFeedbackEvent = procedure(ASender: TObject;
AState: TGorillaInputCode; const AButtons: TGorillaGamePadButtons;
APos: TPointF; AFlags: UInt64) of object;
Parameters:
APos - Thumbstick position (normalized -1.0 to +1.0)Individual HotKey item representing an input combination.
property Name: String read FName write FName;
Unique HotKey identifier.
property Enabled: Boolean read FEnabled write SetEnabled default true;
Enables or disables HotKey detection.
Default: True
property TriggerOnActivate: Boolean read FTriggerOnActivate
write SetTriggerOnActivate;
Triggers event when all inputs are pressed.
Default: False
property TriggerOnDeactivate: Boolean read FTriggerOnDeactivate
write SetTriggerOnDeactivate;
Triggers event when all inputs are released.
Default: False
property Combinations: TGorillaHotKeyCombinations read FCombinations
write SetCombinations;
Collection of input codes forming the HotKey combination.
property LockTime: UInt32 read FLockTime write FLockTime;
Milliseconds before HotKey can trigger again after activation.
Default: 0 (no lock)
Use Cases:
property Action: TAction read FAction write FAction;
Optional FMX TAction to execute on trigger.
property OnTriggered: TGorillaOnHotKeyTriggered read FOnTriggered write FOnTriggered;
Event callback on HotKey trigger.
Signature:
TGorillaOnHotKeyTriggered = procedure(const AItem: TGorillaHotKeyItem;
const ACurrentInput: TGorillaHotKeyRaw; const AMode: TGorillaInputMode) of object;
Parameters:
AItem - The triggered HotKeyACurrentInput - Raw input stateAMode - Activated or Deactivatedproperty Tag: NativeInt read FTag write FTag;
Application-specific data storage.
function AddInput(const AKind: TGorillaInputDeviceType;
const ACode: TGorillaInputCode): TGorillaHotKeyInputItem;
Adds an input to the HotKey combination.
Parameters:
AKind - Device type (Keyboard, Mouse, GamePad)ACode - Input code constantReturns: New combination item
Example:
LHotKey := GorillaInputController1.AddHotKey('SpecialMove');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_CTRL_LEFT);
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_SPACE);
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
function GetOrAddInput(const AKind: TGorillaInputDeviceType;
const ACode: TGorillaInputCode): TGorillaHotKeyInputItem;
Gets existing input or adds new one if it doesn't exist.
function IndexOfInput(const AKind: TGorillaInputDeviceType;
const ACode: TGorillaInputCode): Integer;
Returns index of input in combinations.
Returns: Index or -1 if not found
procedure ClearInputs();
Removes all inputs from combination.
procedure Update();
Rebuilds internal raw key map after changing inputs.
Usage: Call after modifying combinations to ensure changes take effect.
procedure Trigger(const ACurrentInput: TGorillaHotKeyRaw;
const AMode: TGorillaInputMode); virtual;
Manually triggers HotKey (simulation/testing).
function TriggerSync(const ACurrentInput: TGorillaHotKeyRaw;
const AMode: TGorillaInputMode): Boolean; virtual;
Manually triggers HotKey synchronized with main thread.
Collection of HotKey items.
procedure SetUpdateRawMap();
Flags collection for raw map update on next detection cycle.
procedure UpdateRawMap();
Rebuilds internal hash map for HotKey detection. Called automatically by input thread.
Sequence item representing ordered HotKey chain.
property DisplayName: String read GetDisplayName write SetDisplayName;
Unique Sequence identifier.
property Enabled: Boolean read FEnabled write FEnabled default true;
Enables or disables Sequence detection.
Default: True
property Sensitivity: Integer read FSensitivity write FSensitivity;
Maximum milliseconds between HotKey activations.
Default: 500ms (GORILLA_INPUT_SEQUENCE_SENSITIVITY)
property HotKeys: TGorillaInputSequenceHotKeyCollection read FHotKeys write SetHotKeys;
Ordered collection of HotKey links (max 16).
property Action: TAction read FAction write FAction;
Optional FMX TAction to execute on trigger.
property OnTriggered: TOnGorillaInputSequenceTriggered read FOnTriggered write FOnTriggered;
Event callback on Sequence trigger.
Signature:
TOnGorillaInputSequenceTriggered = procedure(
const ASequence: TGorillaInputSequenceItem) of object;
function AddHotKeyItem(AHotKey: TGorillaHotKeyItem): TGorillaInputSequenceHotKeyItem;
Adds HotKey to sequence.
Parameters:
AHotKey - HotKey instance to addReturns: New sequence link item
function GetHotKeyItem(AHotKey: TGorillaHotKeyItem): TGorillaInputSequenceHotKeyItem;
Retrieves sequence link for HotKey.
function HotKeyItemExists(AHotKey: TGorillaHotKeyItem): Boolean;
Checks if HotKey exists in sequence.
function IndexOfHotKeyItem(AHotKey: TGorillaHotKeyItem): Integer;
Returns index of HotKey in sequence.
Returns: Index or -1 if not found
procedure RemoveHotKeyItem(AHotKey: TGorillaHotKeyItem);
Removes HotKey from sequence.
procedure Trigger(); virtual;
Manually triggers Sequence (simulation/testing).
procedure TriggerSync(); virtual;
Manually triggers Sequence synchronized with main thread.
Collection of Sequence items.
function GetSequence(const AIndex: Integer): TGorillaInputSequenceItem;
Gets Sequence by index.
Returns: Sequence item or nil if invalid index
function FindSequence(const AName: String): TGorillaInputSequenceItem;
Searches for Sequence by name.
Returns: First matching Sequence or nil
function SequenceExists(const AName: String): Boolean;
Checks if Sequence with name exists.
function IndexOfSequence(const AName: String): Integer;
Returns index of Sequence.
Returns: Index or -1 if not found
procedure RemoveSequence(const AName: String);
Removes Sequence by name.
// Maximum inputs per device in HotKey
GORILLA_HOTKEY_INPUTS_MAX = 4;
// Maximum HotKeys in Sequence
GORILLA_INPUT_SEQUENCE_HOTKEY_MAX = 16;
// Maximum simultaneous gamepads
GORILLA_GAMEPAD_USER_MAX = 4; // Windows (XInput)
GORILLA_GAMEPAD_USER_MAX = 1; // Android, iOS
// Handler polling interval (ms)
GORILLA_INPUT_HANDLER_SENSITIVITY = 10;
// Default sequence sensitivity (ms)
GORILLA_INPUT_SEQUENCE_SENSITIVITY = 500;
// GamePad availability check interval (ms)
GORILLA_GAMEPAD_AVAILIBILITY_CHECK = 3000;
Input code constants for keyboard, mouse, and gamepad.
Unit: Gorilla.Controller.Input.Consts
Predefined action codes for quick HotKey integration.
const
GORILLA_INPUT_ACTION_NONE = $00000000;
GORILLA_INPUT_ACTION_HOME = $00000001;
GORILLA_INPUT_ACTION_SETTINGS = $00000002;
const
GORILLA_INPUT_ACTION_BACK = $00000003;
GORILLA_INPUT_ACTION_CONTINUE = $00000004;
GORILLA_INPUT_ACTION_NEXT = $00000005;
GORILLA_INPUT_ACTION_PREV = $00000006;
const
GORILLA_INPUT_ACTION_MOVEFORWARD = $00000100;
GORILLA_INPUT_ACTION_MOVEBACKWARDS = $00000101;
GORILLA_INPUT_ACTION_STRIDELEFT = $00000102;
GORILLA_INPUT_ACTION_STRIDERIGHT = $00000103;
GORILLA_INPUT_ACTION_TURNLEFT = $00000104;
GORILLA_INPUT_ACTION_TURNRIGHT = $00000105;
GORILLA_INPUT_ACTION_LOOKUP = $00000106;
GORILLA_INPUT_ACTION_LOOKDOWN = $00000107;
GORILLA_INPUT_ACTION_RUNFORWARD = $00000108;
GORILLA_INPUT_ACTION_RUNBACKWARDS = $00000109;
const
// Jump variations
GORILLA_INPUT_ACTION_JUMP_0 = $00000200;
GORILLA_INPUT_ACTION_JUMP_1 = $00000201;
GORILLA_INPUT_ACTION_JUMP_2 = $00000202;
// Double jump variations
GORILLA_INPUT_ACTION_DOUBLEJUMP_0 = $00000203;
GORILLA_INPUT_ACTION_DOUBLEJUMP_1 = $00000204;
GORILLA_INPUT_ACTION_DOUBLEJUMP_2 = $00000205;
// Crouch variations
GORILLA_INPUT_ACTION_CROUCH_0 = $00000206;
GORILLA_INPUT_ACTION_CROUCH_1 = $00000207;
GORILLA_INPUT_ACTION_CROUCH_2 = $00000208;
// Stance changes
GORILLA_INPUT_ACTION_LAYDOWN = $00000209;
GORILLA_INPUT_ACTION_STANDUP = $0000020A;
GORILLA_INPUT_ACTION_HOLDDOWN = $0000020B;
GORILLA_INPUT_ACTION_HOLDUP = $0000020C;
GORILLA_INPUT_ACTION_KNEELDOWN = $0000020D;
GORILLA_INPUT_ACTION_KNEELUP = $0000020E;
// Hanging
GORILLA_INPUT_ACTION_HANG = $0000020F;
GORILLA_INPUT_ACTION_RELEASE = $00000210;
const
GORILLA_INPUT_ACTION_CLIMB_0 = $00000211;
GORILLA_INPUT_ACTION_CLIMB_1 = $00000212;
GORILLA_INPUT_ACTION_CLIMB_2 = $00000213;
GORILLA_INPUT_ACTION_CLIMB_3 = $00000214;
GORILLA_INPUT_ACTION_CLIMB_4 = $00000215;
GORILLA_INPUT_ACTION_CLIMB_5 = $00000216;
GORILLA_INPUT_ACTION_CLIMB_6 = $00000217;
GORILLA_INPUT_ACTION_CLIMB_7 = $00000218;
GORILLA_INPUT_ACTION_CLIMB_8 = $00000219;
GORILLA_INPUT_ACTION_CLIMB_9 = $0000021A;
const
GORILLA_INPUT_ACTION_COLLECT_LOW = $0000021B;
GORILLA_INPUT_ACTION_COLLECT_MID = $0000021C;
GORILLA_INPUT_ACTION_COLLECT_HIGH = $0000021D;
const
// Attack variations (0-9)
GORILLA_INPUT_ACTION_ATTACK_0 = $00010000;
GORILLA_INPUT_ACTION_ATTACK_1 = $00010001;
GORILLA_INPUT_ACTION_ATTACK_2 = $00010002;
GORILLA_INPUT_ACTION_ATTACK_3 = $00010003;
GORILLA_INPUT_ACTION_ATTACK_4 = $00010004;
GORILLA_INPUT_ACTION_ATTACK_5 = $00010005;
GORILLA_INPUT_ACTION_ATTACK_6 = $00010006;
GORILLA_INPUT_ACTION_ATTACK_7 = $00010007;
GORILLA_INPUT_ACTION_ATTACK_8 = $00010008;
GORILLA_INPUT_ACTION_ATTACK_9 = $00010009;
// Defend variations (0-9)
GORILLA_INPUT_ACTION_DEFEND_0 = $0001000A;
GORILLA_INPUT_ACTION_DEFEND_1 = $0001000B;
GORILLA_INPUT_ACTION_DEFEND_2 = $0001000C;
GORILLA_INPUT_ACTION_DEFEND_3 = $0001000D;
GORILLA_INPUT_ACTION_DEFEND_4 = $0001000E;
GORILLA_INPUT_ACTION_DEFEND_5 = $0001000F;
GORILLA_INPUT_ACTION_DEFEND_6 = $00010010;
GORILLA_INPUT_ACTION_DEFEND_7 = $00010011;
GORILLA_INPUT_ACTION_DEFEND_8 = $00010012;
GORILLA_INPUT_ACTION_DEFEND_9 = $00010013;
const
GORILLA_INPUT_KEY_A = Ord('A'); // 65
GORILLA_INPUT_KEY_B = Ord('B'); // 66
GORILLA_INPUT_KEY_C = Ord('C'); // 67
GORILLA_INPUT_KEY_D = Ord('D'); // 68
GORILLA_INPUT_KEY_E = Ord('E'); // 69
GORILLA_INPUT_KEY_F = Ord('F'); // 70
GORILLA_INPUT_KEY_G = Ord('G'); // 71
GORILLA_INPUT_KEY_H = Ord('H'); // 72
GORILLA_INPUT_KEY_I = Ord('I'); // 73
GORILLA_INPUT_KEY_J = Ord('J'); // 74
GORILLA_INPUT_KEY_K = Ord('K'); // 75
GORILLA_INPUT_KEY_L = Ord('L'); // 76
GORILLA_INPUT_KEY_M = Ord('M'); // 77
GORILLA_INPUT_KEY_N = Ord('N'); // 78
GORILLA_INPUT_KEY_O = Ord('O'); // 79
GORILLA_INPUT_KEY_P = Ord('P'); // 80
GORILLA_INPUT_KEY_Q = Ord('Q'); // 81
GORILLA_INPUT_KEY_R = Ord('R'); // 82
GORILLA_INPUT_KEY_S = Ord('S'); // 83
GORILLA_INPUT_KEY_T = Ord('T'); // 84
GORILLA_INPUT_KEY_U = Ord('U'); // 85
GORILLA_INPUT_KEY_V = Ord('V'); // 86
GORILLA_INPUT_KEY_W = Ord('W'); // 87
GORILLA_INPUT_KEY_X = Ord('X'); // 88
GORILLA_INPUT_KEY_Y = Ord('Y'); // 89
GORILLA_INPUT_KEY_Z = Ord('Z'); // 90
const
GORILLA_INPUT_KEY_0 = Ord('0'); // 48
GORILLA_INPUT_KEY_1 = Ord('1'); // 49
GORILLA_INPUT_KEY_2 = Ord('2'); // 50
GORILLA_INPUT_KEY_3 = Ord('3'); // 51
GORILLA_INPUT_KEY_4 = Ord('4'); // 52
GORILLA_INPUT_KEY_5 = Ord('5'); // 53
GORILLA_INPUT_KEY_6 = Ord('6'); // 54
GORILLA_INPUT_KEY_7 = Ord('7'); // 55
GORILLA_INPUT_KEY_8 = Ord('8'); // 56
GORILLA_INPUT_KEY_9 = Ord('9'); // 57
const
GORILLA_INPUT_KEY_ARROW_LEFT = Ord(#37); // 37
GORILLA_INPUT_KEY_ARROW_UP = Ord(#38); // 38
GORILLA_INPUT_KEY_ARROW_RIGHT = Ord(#39); // 39
GORILLA_INPUT_KEY_ARROW_DOWN = Ord(#40); // 40
const
GORILLA_INPUT_KEY_NONE = 0;
GORILLA_INPUT_KEY_SPACE = Ord(' '); // 32
GORILLA_INPUT_KEY_RETURN = Ord(Char(#$0D)); // 13
GORILLA_INPUT_KEY_ESCAPE = Ord(Char(#$1B)); // 27
GORILLA_INPUT_KEY_SHIFT_BACKSPACE = Ord(#8);
GORILLA_INPUT_KEY_SHIFT_TAB = Ord(#9);
GORILLA_INPUT_KEY_LINEFEED = Ord(Char(#$0A));
GORILLA_INPUT_KEY_DELETE = Ord(Char(#$7F));
GORILLA_INPUT_KEY_SHIFT_CAPS = Ord(#20);
GORILLA_INPUT_KEY_PAUSE = $13;
const
GORILLA_INPUT_KEY_SHIFT_LEFT = Ord(#160); // 160
GORILLA_INPUT_KEY_SHIFT_RIGHT = Ord(#161); // 161
GORILLA_INPUT_KEY_CTRL_LEFT = Ord(#162); // 162
GORILLA_INPUT_KEY_CTRL_RIGHT = Ord(#163); // 163
GORILLA_INPUT_KEY_ALT = Ord(#164); // 164
GORILLA_INPUT_KEY_ALTGR = Ord(#165); // 165
const
GORILLA_INPUT_KEY_PLUS = Ord('+');
GORILLA_INPUT_KEY_MINUS = Ord('-');
GORILLA_INPUT_KEY_DOT = Ord('.');
GORILLA_INPUT_KEY_COMMA = Ord(',');
GORILLA_INPUT_KEY_HASH = Ord('#');
GORILLA_INPUT_KEY_DIV = Ord('/');
GORILLA_INPUT_KEY_STAR = Ord('*');
GORILLA_INPUT_KEY_EXCL = Ord('!');
GORILLA_INPUT_KEY_QUOTE = Ord('"');
GORILLA_INPUT_KEY_PARA = Ord('§');
GORILLA_INPUT_KEY_DOLLAR = Ord('$');
GORILLA_INPUT_KEY_EURO = Ord('€');
GORILLA_INPUT_KEY_AT = Ord('@');
GORILLA_INPUT_KEY_PERCENT = Ord('%');
GORILLA_INPUT_KEY_AND = Ord('&');
GORILLA_INPUT_KEY_SLASH = Ord('/');
GORILLA_INPUT_KEY_BACKSLASH = Ord('\');
GORILLA_INPUT_KEY_BRACKETOPEN = Ord('(');
GORILLA_INPUT_KEY_BRACKETCLOSE = Ord(')');
GORILLA_INPUT_KEY_EQUAL = Ord('=');
GORILLA_INPUT_KEY_QUESTION = Ord('?');
GORILLA_INPUT_KEY_TILDE = Ord('~');
GORILLA_INPUT_KEY_UNDERSCORE = Ord('_');
GORILLA_INPUT_KEY_SEMICOLON = Ord(';');
GORILLA_INPUT_KEY_COLON = Ord(':');
GORILLA_INPUT_KEY_BAR = Ord('|');
GORILLA_INPUT_KEY_TAGOPEN = Ord('<');
GORILLA_INPUT_KEY_TAGCLOSE = Ord('>');
GORILLA_INPUT_APOSTROPHE = Ord('''');
Usage Example:
// WASD movement
LHotKey := GorillaInputController1.AddHotKey('MoveForward');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_W);
// Ctrl + S to save
LHotKey := GorillaInputController1.AddHotKey('Save');
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_CTRL_LEFT);
LHotKey.AddInput(Keyboard, GORILLA_INPUT_KEY_S);
const
GORILLA_INPUT_MOUSE_LBUTTON = $100002; // Left button
GORILLA_INPUT_MOUSE_LBUTTON_DBLCLK = $100003; // Left double-click
GORILLA_INPUT_MOUSE_RBUTTON = $100004; // Right button
GORILLA_INPUT_MOUSE_RBUTTON_DBLCLK = $100005; // Right double-click
GORILLA_INPUT_MOUSE_MBUTTON = $100006; // Middle button (wheel click)
GORILLA_INPUT_MOUSE_MBUTTON_DBLCLK = $100007; // Middle double-click
GORILLA_INPUT_MOUSE_X1BUTTON = $100008; // Extra button 1
GORILLA_INPUT_MOUSE_X1BUTTON_DBLCLK = $100009; // Extra 1 double-click
GORILLA_INPUT_MOUSE_X2BUTTON = $10000A; // Extra button 2
GORILLA_INPUT_MOUSE_X2BUTTON_DBLCLK = $10000B; // Extra 2 double-click
const
GORILLA_INPUT_MOUSE_POSITION = $100001; // Mouse position (persistent)
GORILLA_INPUT_MOUSE_WHEEL = $10000C; // Mouse wheel
Usage Example:
// Left click to shoot
LHotKey := GorillaInputController1.AddHotKey('Shoot');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_LBUTTON);
// Right click to aim
LHotKey := GorillaInputController1.AddHotKey('Aim');
LHotKey.AddInput(Mouse, GORILLA_INPUT_MOUSE_RBUTTON);
// Get persistent mouse position
var
LMsg: TGorillaInputMessage;
begin
if GorillaInputController1.GetPersistentMessage(Mouse,
GORILLA_INPUT_MOUSE_POSITION, LMsg) then
begin
// Use mouse position
end;
end;
const
GORILLA_INPUT_GAMEPAD_CONNECTED = $200001;
GORILLA_INPUT_GAMEPAD_DISCONNECTED = $200002;
const
GORILLA_INPUT_GAMEPAD_DPAD_UP = $200003;
GORILLA_INPUT_GAMEPAD_DPAD_DOWN = $200004;
GORILLA_INPUT_GAMEPAD_DPAD_LEFT = $200005;
GORILLA_INPUT_GAMEPAD_DPAD_RIGHT = $200006;
const
GORILLA_INPUT_GAMEPAD_STARTBUTTON = $200007; // Start/Menu
GORILLA_INPUT_GAMEPAD_MODEBUTTON = $200008; // Xbox/Guide/Home
GORILLA_INPUT_GAMEPAD_BACKBUTTON = $200009; // Back/View/Select
const
GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT = $20000A; // L3
GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT = $20000B; // R3
const
GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT = $20000C; // LB
GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT = $20000D; // RB
const
GORILLA_INPUT_GAMEPAD_BUTTON_A = $20000E; // A / Cross
GORILLA_INPUT_GAMEPAD_BUTTON_B = $20000F; // B / Circle
GORILLA_INPUT_GAMEPAD_BUTTON_X = $200011; // X / Square
GORILLA_INPUT_GAMEPAD_BUTTON_Y = $200012; // Y / Triangle
const
GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT = $200020; // LT (0-255)
GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT = $200021; // RT (0-255)
const
GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_LEFT = $200030; // Left stick position
GORILLA_INPUT_GAMEPAD_THUMBSTICK_POS_RIGHT = $200031; // Right stick position
Usage Example:
// Jump with A button
LHotKey := GorillaInputController1.AddHotKey('Jump');
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_BUTTON_A);
// Sprint with left thumbstick press
LHotKey := GorillaInputController1.AddHotKey('Sprint');
LHotKey.AddInput(GamePad, GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT);
// Get persistent left trigger value
var
LMsg: TGorillaInputMessage;
LValue: Byte;
begin
if GorillaInputController1.GetPersistentMessage(GamePad,
GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT, LMsg) then
begin
LValue := LMsg.WParam; // 0-255
end;
end;
const
{$IFDEF MSWINDOWS}
GORILLA_GAMEPAD_USER_MAX = 4; // XInput limitation
{$ENDIF}
{$IFDEF ANDROID}
GORILLA_GAMEPAD_USER_MAX = 1;
{$ENDIF}
{$IFDEF IOS}
GORILLA_GAMEPAD_USER_MAX = 1;
{$ENDIF}
{$IFDEF MACOS}
GORILLA_GAMEPAD_USER_MAX = 4;
{$ENDIF}
{$IFDEF LINUX}
GORILLA_GAMEPAD_USER_MAX = 4;
{$ENDIF}
Maximum number of simultaneously connected gamepads per platform.
const
// Maximum inputs per device in a HotKey
GORILLA_HOTKEY_INPUTS_MAX = 4;
// Maximum HotKeys in a Sequence
GORILLA_INPUT_SEQUENCE_HOTKEY_MAX = 16;
const
// Handler polling interval (milliseconds)
GORILLA_INPUT_HANDLER_SENSITIVITY = 10;
// Default sequence sensitivity (milliseconds)
GORILLA_INPUT_SEQUENCE_SENSITIVITY = 500;
// GamePad availability check interval (milliseconds)
GORILLA_GAMEPAD_AVAILIBILITY_CHECK = 3000;
// GamePad vibration check interval (milliseconds)
GORILLA_GAMEPAD_VIBRATION_CHECK = 100;
// GamePad battery check interval (milliseconds)
GORILLA_GAMEPAD_BATTERY_CHECK = 30000;
[Mode]
[LB] [RB]
[D-Pad] [Y]
[X] [B]
[A]
[L3] [R3]
LT RT
Mapping:
| Xbox | Code |
|---|---|
| D-Pad Up/Down/Left/Right | GORILLA_INPUT_GAMEPAD_DPAD_* |
| A | GORILLA_INPUT_GAMEPAD_BUTTON_A |
| B | GORILLA_INPUT_GAMEPAD_BUTTON_B |
| X | GORILLA_INPUT_GAMEPAD_BUTTON_X |
| Y | GORILLA_INPUT_GAMEPAD_BUTTON_Y |
| LB | GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT |
| RB | GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT |
| LT | GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT |
| RT | GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT |
| L3 | GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT |
| R3 | GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT |
| Start | GORILLA_INPUT_GAMEPAD_STARTBUTTON |
| Back | GORILLA_INPUT_GAMEPAD_BACKBUTTON |
| Mode | GORILLA_INPUT_GAMEPAD_MODEBUTTON |
[PS]
[L1] [R1]
[D-Pad] [△]
[□] [○]
[✕]
[L3] [R3]
L2 R2
Mapping:
| PlayStation | Xbox Equivalent | Code |
|---|---|---|
| D-Pad | D-Pad | GORILLA_INPUT_GAMEPAD_DPAD_* |
| ✕ (Cross) | A | GORILLA_INPUT_GAMEPAD_BUTTON_A |
| ○ (Circle) | B | GORILLA_INPUT_GAMEPAD_BUTTON_B |
| □ (Square) | X | GORILLA_INPUT_GAMEPAD_BUTTON_X |
| △ (Triangle) | Y | GORILLA_INPUT_GAMEPAD_BUTTON_Y |
| L1 | LB | GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT |
| R1 | RB | GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT |
| L2 | LT | GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT |
| R2 | RT | GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT |
| L3 | L3 | GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT |
| R3 | R3 | GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT |
| Options | Start | GORILLA_INPUT_GAMEPAD_STARTBUTTON |
| Share | Back | GORILLA_INPUT_GAMEPAD_BACKBUTTON |
| PS | Mode | GORILLA_INPUT_GAMEPAD_MODEBUTTON |
Type definitions for input handling system.
Unit: Gorilla.Controller.Input.Types
type
TGorillaInputDeviceType = (Keyboard, Mouse, GamePad);
Enumeration of supported input device types.
Values:
Keyboard - Physical keyboardMouse - Mouse or pointing deviceGamePad - Game controller (XInput, SDL2, etc.)type
TGorillaInputDeviceTypes = set of TGorillaInputDeviceType;
Set of input device types for enabling multiple devices.
Usage:
GorillaInputController1.Supported := [Keyboard, Mouse];
type
TGorillaInputMode = (Activated, Deactivated);
Input activation state.
Values:
Activated - Input pressed/activatedDeactivated - Input released/deactivatedtype
TGorillaMouseState = (
LButtonDown, LButtonUp,
RButtonDown, RButtonUp,
MButtonDown, MButtonUp,
X1ButtonDown, X1ButtonUp,
X2ButtonDown, X2ButtonUp,
LButtonDblClick, RButtonDblClick,
MButtonDblClick, X1ButtonDblClick, X2ButtonDblClick,
MouseMove, MouseWheel
);
Mouse event states.
Button States:
LButtonDown / LButtonUp - Left buttonRButtonDown / RButtonUp - Right buttonMButtonDown / MButtonUp - Middle button (wheel click)X1ButtonDown / X1ButtonUp - Extra button 1X2ButtonDown / X2ButtonUp - Extra button 2Double-Click States:
LButtonDblClick - Left button double-clickRButtonDblClick - Right button double-clickMButtonDblClick - Middle button double-clickX1ButtonDblClick - Extra button 1 double-clickX2ButtonDblClick - Extra button 2 double-clickMovement States:
MouseMove - Mouse position changedMouseWheel - Mouse wheel scrolledtype
TGorillaMouseStates = set of TGorillaMouseState;
Set of mouse states for event callbacks.
type
TGorillaInputCode = NativeInt;
Generic input code type for keyboard keys, mouse buttons, and gamepad buttons.
See: Gorilla.Controller.Input.Consts for available codes.
type
TGorillaCharacterControllerHotKey = (
UnknownHotKey,
// Keyboard Movement
KeyboardMoveForward, KeyboardMoveBackward,
KeyboardMoveLeft, KeyboardMoveRight,
// Keyboard Extended Movement
KeyboardJump, KeyboardCrouch, KeyboardCrawl,
KeyboardBoost, KeyboardAim,
// Keyboard Actions
KeyboardCustomAction1, KeyboardCustomAction2,
KeyboardCustomAction3, KeyboardCustomAction4,
// Keyboard Game Control
KeyboardStart, KeyboardMode, KeyboardBack,
// Keyboard Menu
KeyboardMenuUp, KeyboardMenuDown,
KeyboardMenuLeft, KeyboardMenuRight,
// Mouse Actions
MouseDragMove, MouseLeftButton,
MouseMiddleButton, MouseRightButton,
// GamePad Movement
GamePadMove, GamePadMoveForward,
GamePadMoveBackward, GamePadMoveLeft, GamePadMoveRight,
// GamePad Extended Movement
GamePadJump, GamePadCrouch, GamePadCrawl,
GamePadBoost, GamePadAim,
// GamePad Actions
GamePadButtonA, GamePadButtonB,
GamePadButtonX, GamePadButtonY,
// GamePad Game Control
GamePadStart, GamePadMode, GamePadBack,
// GamePad Menu
GamePadMenuUp, GamePadMenuDown,
GamePadMenuLeft, GamePadMenuRight
);
Predefined HotKey enumeration for character controllers.
Usage: Used internally by TGorillaCharacterController for standard FPS/TPS controls.
See: Character Controller documentation for usage examples.
type
TGorillaCharacterControllerState = (
fpIdle, fpMoving, fpRotating, fpRotateMoving,
fpBoost, fpCrouching, fpCrawling, fpJumping,
fpAiming, fpPushing, fpPulling,
fpCustomAction, fpClick,
fpStart, fpMode, fpBack,
fpNavigation
);
Character controller state enumeration.
Base States:
fpIdle - Character standing stillfpMoving - Character movingfpRotating - Character rotating in placefpRotateMoving - Character moving and rotatingAction States:
fpBoost - Sprinting/boostingfpCrouching - CrouchedfpCrawling - Crawling/pronefpJumping - JumpingfpAiming - Aiming weaponfpPushing - Pushing objectfpPulling - Pulling objectfpCustomAction - Custom action activefpClick - Mouse clickUI States:
fpStart - Start button pressedfpMode - Mode button pressedfpBack - Back button pressedfpNavigation - Menu navigationtype
TGorillaCharacterControllerStates = Set of TGorillaCharacterControllerState;
Set of character controller states. Multiple states can be active simultaneously.
Example:
if [fpMoving, fpBoost] <= Player.States then
// Player is sprinting
type
TGorillaGamePadDeviceType = (
Default,
Wheel,
ArcadeStick,
FlightStick,
DancePad
);
GamePad device classification.
Values:
Default - Standard gamepad (Xbox, PlayStation style)Wheel - Racing wheelArcadeStick - Arcade fight stickFlightStick - Flight joystickDancePad - Dance pad controllertype
TGorillaGamePadButton = (
None,
// D-Pad
DPadUp, DPadDown, DPadLeft, DPadRight,
// System
StartButton, ModeButton, BackButton,
// Thumbsticks (press)
LeftThumbStick, RightThumbStick,
// Shoulders
LeftShoulder, RightShoulder,
// Face Buttons
ButtonA, ButtonB, ButtonX, ButtonY
);
GamePad button enumeration.
D-Pad:
DPadUp / DPadDown / DPadLeft / DPadRight - Directional padSystem Buttons:
StartButton - Start/Menu buttonModeButton - Xbox/Guide/Home buttonBackButton - Back/View/Select buttonThumbsticks:
LeftThumbStick - L3 (left stick press)RightThumbStick - R3 (right stick press)Shoulders:
LeftShoulder - LB (left bumper)RightShoulder - RB (right bumper)Face Buttons:
ButtonA - A (Xbox) / Cross (PlayStation)ButtonB - B (Xbox) / Circle (PlayStation)ButtonX - X (Xbox) / Square (PlayStation)ButtonY - Y (Xbox) / Triangle (PlayStation)type
TGorillaGamePadButtons = set of TGorillaGamePadButton;
Set of gamepad buttons.
Usage:
if TGorillaGamePadButton.ButtonA in AButtons then
Player.Jump();
type
TGorillaGamePadButtonsArray = TArray<TGorillaGamePadButton>;
Dynamic array of gamepad buttons.
type
TGorillaGamePadButtonHelper = record
class function ToInputCode(const ABtn: TGorillaGamePadButton): TGorillaInputCode; static;
class function FromInputCode(const ACode: TGorillaInputCode): TGorillaGamePadButton; static;
end;
Helper for converting between gamepad buttons and input codes.
class function ToInputCode(const ABtn: TGorillaGamePadButton): TGorillaInputCode; static;
Converts gamepad button to input code.
Parameters:
ABtn - Gamepad buttonReturns: Input code constant or -1 if None
Example:
var
LCode: TGorillaInputCode;
begin
LCode := TGorillaGamePadButtonHelper.ToInputCode(TGorillaGamePadButton.ButtonA);
// LCode = GORILLA_INPUT_GAMEPAD_BUTTON_A
end;
class function FromInputCode(const ACode: TGorillaInputCode): TGorillaGamePadButton; static;
Converts input code to gamepad button.
Parameters:
ACode - Input codeReturns: Gamepad button or None if invalid
Example:
var
LButton: TGorillaGamePadButton;
begin
LButton := TGorillaGamePadButtonHelper.FromInputCode(GORILLA_INPUT_GAMEPAD_BUTTON_A);
// LButton = TGorillaGamePadButton.ButtonA
end;
type
TGorillaGamePadVector2 = record
X: NativeUInt;
Y: NativeUInt;
constructor Create(AX, AY: NativeUInt);
class function Zero(): TGorillaGamePadVector2; static;
class operator Subtract(V1, V2: TGorillaGamePadVector2): TGorillaGamePadVector2;
class operator Multiply(V: TGorillaGamePadVector2; F: Single): TGorillaGamePadVector2;
end;
2D vector for gamepad thumbstick positions.
constructor Create(AX, AY: NativeUInt);
Creates vector with specified coordinates.
class function Zero(): TGorillaGamePadVector2; static;
Returns zero vector (0, 0).
class operator Subtract(V1, V2: TGorillaGamePadVector2): TGorillaGamePadVector2;
Subtracts two vectors.
Example:
var
LDelta: TGorillaGamePadVector2;
begin
LDelta := LCurrentPos - LPreviousPos;
end;
class operator Multiply(V: TGorillaGamePadVector2; F: Single): TGorillaGamePadVector2;
Multiplies vector by scalar.
Example:
var
LScaled: TGorillaGamePadVector2;
begin
LScaled := LPos * 0.5; // Scale to 50%
end;
type
TGorillaInputMessage = record
Device: TGorillaInputDeviceType;
Mode: TGorillaInputMode;
Persistent: Boolean;
Time: NativeUInt;
Code: TGorillaInputCode;
Flags: NativeUInt;
WParam: NativeInt;
LParam: NativeInt;
Result: NativeInt;
Data: TValue;
constructor Create(const ADevice: TGorillaInputDeviceType;
const AMode: TGorillaInputMode);
end;
Raw input message structure.
Fields:
| Field | Type | Description |
|---|---|---|
| Device | TGorillaInputDeviceType | Source device (Keyboard, Mouse, GamePad) |
| Mode | TGorillaInputMode | Activated or Deactivated |
| Persistent | Boolean | True for continuous messages (position, triggers) |
| Time | NativeUInt | Timestamp (GetTickCount) |
| Code | TGorillaInputCode | Input code constant |
| Flags | NativeUInt | Platform-specific flags |
| WParam | NativeInt | Platform-specific parameter |
| LParam | NativeInt | Platform-specific parameter |
| Result | NativeInt | Platform-specific result |
| Data | TValue | Generic data container (TPoint, TPointF, etc.) |
Usage:
var
LMsg: TGorillaInputMessage;
LPos: TPoint;
begin
if GorillaInputController1.GetPersistentMessage(Mouse,
GORILLA_INPUT_MOUSE_POSITION, LMsg) then
begin
LPos := LMsg.Data.AsType<TPoint>;
ShowMessage(Format('Mouse at %d, %d', [LPos.X, LPos.Y]));
end;
end;
type
TGorillaHotKeyInputRaw = record
Count: Byte;
Codes: Array[0..GORILLA_HOTKEY_INPUTS_MAX - 1] of TGorillaInputCode;
procedure Sort();
function Contains(const AInput: TGorillaHotKeyInputRaw): Boolean;
function ToString(): String;
end;
Raw input combination for single device (internal use).
Fields:
Count - Number of active inputsCodes - Array of input codesMethods:
procedure Sort();
Sorts input codes from low to high value (for comparison).
function Contains(const AInput: TGorillaHotKeyInputRaw): Boolean;
Checks if this input contains all codes from AInput.
function ToString(): String;
Converts to string format for debugging.
type
TGorillaHotKeyRaw = record
Inputs: Array[TGorillaInputDeviceType] of TGorillaHotKeyInputRaw;
class function Create(): TGorillaHotKeyRaw; static;
procedure AddInput(const AInput: TGorillaHotKeyInputItem);
procedure Sort();
function GetWeight(): Integer;
function Contains(const AKey: TGorillaHotKeyRaw): Boolean;
function ToString(): String;
end;
Complete HotKey combination across all devices (internal use).
Methods:
class function Create(): TGorillaHotKeyRaw; static;
Creates empty raw HotKey.
procedure AddInput(const AInput: TGorillaHotKeyInputItem);
Adds input from collection item.
function GetWeight(): Integer;
Returns priority weight (more inputs = higher weight).
Usage: Resolves conflicts when multiple HotKeys match current input.
function Contains(const AKey: TGorillaHotKeyRaw): Boolean;
Checks if this HotKey contains all inputs from AKey.
Core particle structure for the particle system.
The particle record structure containing all properties of a single particle.
Unit: Gorilla.Particle
Type: Record
Id: Integer;
Unique identifier for each particle instance. Automatically assigned on creation.
Position: TPoint3D;
Current 3D world position of the particle.
Usage:
LParticle^.Position := Point3D(0, 10, 0);
Normal: TPoint3D;
Normal vector, used internally for camera facing direction. Typically set to view direction.
Velocity: TPoint3D;
Movement vector applied each frame. Defines particle direction and speed.
Usage:
// Move upward at 5 units/second
LParticle^.Velocity := Point3D(0, -5, 0);
Color: TAlphaColorF;
RGBA color of the particle in float format (0.0 - 1.0 range).
Usage:
LParticle^.Color := TAlphaColorF.Create(1.0, 0.5, 0.0, 1.0); // Orange
Size: Single;
Current size of the particle in pixels or world units.
Angle: Single;
Rotation angle in degrees.
Weight: Single;
Particle weight, affects gravity and other force influencers.
Age: Single;
Current age of the particle in seconds. Automatically updated each frame.
Read-only: Modified internally by emitter.
Life: Single;
Total lifetime of the particle in seconds. Particle is destroyed when Age >= Life.
Growth: Single;
Size change per frame. Positive values grow, negative values shrink.
Usage:
LParticle^.Growth := -0.5; // Shrink by 0.5 units per frame
Data: Pointer;
Custom user data pointer. Used internally by physics influencer to store physics body reference.
class function Create(): PGorillaParticle; static;
Creates and initializes a new particle instance.
Returns: Pointer to new particle
Usage:
var
LParticle: PGorillaParticle;
begin
LParticle := TGorillaParticle.Create();
try
LParticle^.Position := Point3D(0, 0, 0);
finally
Dispose(LParticle);
end;
end;
Note: Usually particles are managed by emitters. Manual creation is rarely needed.
function GetDeltaTime(): Single;
Returns normalized particle age (0.0 to 1.0).
Returns: Age / Life ratio
Usage:
var
LProgress: Single;
begin
LProgress := LParticle^.GetDeltaTime();
// 0.0 = just born, 0.5 = halfway, 1.0 = expired
end;
function GetEyeDistance(const APosition: TPoint3D): Single;
Calculates distance from particle to specified position (typically camera).
Parameters:
APosition - Reference position (usually camera position)Returns: Distance in world units
Usage:
var
LDist: Single;
begin
LDist := LParticle^.GetEyeDistance(Camera.Position.Point);
end;
class operator Equal(A, B: TGorillaParticle): Boolean;
Compares two particles by position.
class operator NotEqual(A, B: TGorillaParticle): Boolean;
Checks if two particles have different positions.
class operator GreaterThan(A, B: TGorillaParticle): Boolean;
Compares particles by Z-depth. Used for sorting.
class operator LessThan(A, B: TGorillaParticle): Boolean;
Compares particles by Z-depth. Used for sorting.
TGorillaParticleList = TList<PGorillaParticle>;
List type for managing particle collections.
var
LParticle: PGorillaParticle;
begin
LParticle := TGorillaParticle.Create();
try
LParticle^.Position := Point3D(0, 10, 0);
LParticle^.Velocity := Point3D(0, -2, 0);
LParticle^.Size := 32;
LParticle^.Color := TAlphaColorF.Create(1, 1, 1, 1);
LParticle^.Life := 5.0; // 5 seconds
LParticle^.Weight := 1.0;
// Use particle...
finally
Dispose(LParticle);
end;
end;
procedure UpdateParticleColor(const AParticle: PGorillaParticle);
var
LProgress: Single;
LStartColor, LEndColor: TAlphaColorF;
begin
LProgress := AParticle^.GetDeltaTime();
LStartColor := TAlphaColorF.Create(TAlphaColorRec.Blue);
LEndColor := TAlphaColorF.Create(TAlphaColorRec.Red);
// Interpolate color based on age
AParticle^.Color.R := LStartColor.R + (LEndColor.R - LStartColor.R) * LProgress;
AParticle^.Color.G := LStartColor.G + (LEndColor.G - LStartColor.G) * LProgress;
AParticle^.Color.B := LStartColor.B + (LEndColor.B - LStartColor.B) * LProgress;
end;
The particle system repurposes standard vertex attributes for extended functionality:
| Attribute | Purpose | Particle Field |
|---|---|---|
| a_Position | Position | Position |
| a_Normal | Velocity | Normal |
| a_Color0 | Current color | Color |
| a_TexCoord0 | Texture/atlas offset | - |
| a_Binormal | Size, angle, weight | Size, Angle, Weight |
| a_Tangent | Age, lifetime, delta | Age, Life |
Note: This attribute repurposing allows particle data to be efficiently passed to shaders using existing vertex formats.
All Gorilla platforms supported.
Particle emitter class and preset configuration for the particle system.
Randomization preset for single-value particle properties.
Inheritance: TPersistent → TParticlePreset
Unit: Gorilla.Particle.Emitter
constructor Create(const AMin, AMax: Integer; const ADivisor: Integer;
const ANegative: Boolean);
Creates a preset with specified range and options.
Parameters:
AMin - Minimum value (before division)AMax - Maximum value (before division)ADivisor - Divisor for converting to floatANegative - Allow negative values randomlyproperty Min: Integer;
Minimum value before division.
property Max: Integer;
Maximum value before division.
property Divisor: Integer;
Divisor for float conversion. Result = Value / Divisor.
property Negative: Boolean;
If True, randomly returns positive or negative values.
procedure Preset(const AMin, AMax: Integer; const ADivisor: Integer;
const ANegative: Boolean);
Reconfigure preset values.
function GetRandomValue(): Single; overload;
function GetRandomValue(const ANegative: Boolean): Single; overload;
Returns random value within configured range.
Usage:
var
LPreset: TParticlePreset;
LValue: Single;
begin
LPreset := TParticlePreset.Create(10, 50, 10, False);
LValue := LPreset.GetRandomValue(); // Returns 1.0 to 5.0
end;
function GetMinValue(): Single;
function GetMaxValue(): Single;
Returns minimum/maximum value after division.
Randomization preset for 3D vector particle properties.
Inheritance: TPersistent → TParticleVectorPreset
constructor Create(const AMin, AMax: Integer; const ADivisor: Integer;
const ADirection: TPoint3D; const AAxis: TAllowedAxisSet = [axX, axY, axZ]);
Parameters:
AMin, AMax, ADivisor - Range valuesADirection - Direction multiplierAAxis - Allowed axes ([axX, axY, axZ])property RangeX: TParticlePreset;
property RangeY: TParticlePreset;
property RangeZ: TParticlePreset;
Individual axis presets.
property Direction: TPosition3D;
Direction multiplier applied to randomized vector.
property Axis: TAllowedAxisSet;
Axes allowed for randomization. Set of [axX, axY, axZ].
procedure Preset(const AMin, AMax: Integer; const ADivisor: Integer;
const ADirection: TPoint3D; const AAxis: TAllowedAxisSet = [axX, axY, axZ]);
Reconfigure all axes with same values.
function GetRandomValue(): TPoint3D;
Returns random 3D vector.
Usage:
var
LPreset: TParticleVectorPreset;
LVec: TPoint3D;
begin
// Upward velocity with horizontal spread
LPreset := TParticleVectorPreset.Create(0, 100, 1000, Point3D(1, -10, 1));
LVec := LPreset.GetRandomValue();
end;
Base particle emitter class.
Inheritance: TGorillaMesh → TGorillaParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Emitter
constructor Create(AOwner: TComponent); override;
Creates particle emitter with default settings:
destructor Destroy(); override;
Stops emitter, clears particles, and frees resources.
property Active: Boolean read GetActive;
Returns True if emitter timer/thread is running.
property Time: Single read GetTime;
Total time in seconds since Start() was called.
property DeltaTime: Single read GetDeltaTime;
Time in seconds since last update tick.
property Particles: TGorillaParticleList read FParticles;
List of currently active particles.
property MeshData: TMeshData read GetMeshData;
Internal mesh data for particle vertices.
property Thread: TThread read GetThread;
Async computation thread if Async = True, otherwise nil.
property Emitted: Integer read GetEmitted;
Number of currently active particles.
property Camera: TCamera;
Linked camera for particle sorting. Required for correct transparency.
Usage:
LEmitter.Camera := GorillaViewport1.Camera;
property Async: Boolean;
Enable background thread processing. Recommended for > 5000 particles.
Default: False
property EmitTime: Integer;
Update interval in milliseconds.
Default: 16ms (~60 FPS)
Usage:
LEmitter.EmitTime := 33; // 30 FPS
property Reuse: Boolean;
Enable particle caching/reuse for better performance.
Default: True
property AutoEmit: Boolean;
Automatically emit particles each interval.
Default: True
property EmitParticles: Integer;
Number of particles to emit per interval (when AutoEmit = True).
Default: 10
property MaxParticles: Integer;
Maximum number of simultaneously active particles.
Default: 1000
Note: Cannot reduce below current particle count.
property MaxAutoEmitTime: Integer;
Maximum auto-emit duration in milliseconds. 0 = infinite.
Default: 0 (infinite)
Usage:
// Emit for 5 seconds then stop
LEmitter.MaxAutoEmitTime := 5000;
property AutoRotation: Single;
Automatic particle rotation per frame in shader.
Default: 0 (no rotation)
Usage:
LEmitter.AutoRotation := 0.5; // Gentle rotation
property ParticleFade: Single;
Fade particle edges to prevent clipping artifacts.
Default: 0 (no fading)
Usage:
LEmitter.ParticleFade := 2.5;
property ShowBounds: Boolean;
Show/hide emitter bounding box (debug).
Default: False
property ParticlePosition: TParticleVectorPreset;
Randomization preset for initial particle position.
property ParticleVelocity: TParticleVectorPreset;
Randomization preset for particle velocity.
property ParticleSize: TParticlePreset;
Randomization preset for particle size.
property ParticleAngle: TParticlePreset;
Randomization preset for particle rotation angle.
property ParticleWeight: TParticlePreset;
Randomization preset for particle weight.
property ParticleGrowth: TParticlePreset;
Randomization preset for particle growth/shrinkage.
property ParticleLifeTime: TParticlePreset;
Randomization preset for particle lifetime.
property BlendFunc: TBlendEquationFunc;
Blending equation function.
Usage:
LEmitter.BlendFunc := TBlendEquationFunc.befAdd;
property BlendSource: TBlendFactor;
Source blending factor.
property BlendDest: TBlendFactor;
Destination blending factor.
property AlphaBlendSource: TBlendFactor;
Alpha channel source blending factor.
property AlphaBlendDest: TBlendFactor;
Alpha channel destination blending factor.
property Influencers: TGorillaParticleInfluencerList;
List of active influencers affecting particles.
procedure Start(); virtual;
Start particle emitter timer/thread.
Triggers: OnStart event
procedure Stop(); virtual;
Stop particle emitter (particles remain visible).
Triggers: OnStop event
procedure Clear(); virtual;
Destroy all particles (active and cached).
procedure ClearUnused(); virtual;
Free cached particles only.
function EmitParticle(): PGorillaParticle; overload; virtual;
function EmitParticle(const APosition: TPoint3D): PGorillaParticle; overload; virtual;
Manually emit a single particle.
Returns: Pointer to emitted particle, or nil if MaxParticles reached
Usage:
// Random position
var LPart: PGorillaParticle;
begin
LPart := LEmitter.EmitParticle();
end;
// Specific position (e.g., mouse click)
var LPos: TPoint3D;
begin
LPos := ScreenToWorld(Mouse.X, Mouse.Y);
LEmitter.EmitParticle(LPos);
end;
procedure SortByEyeDistance(const APosition: TPoint3D); virtual;
Sort particles by distance to camera for correct transparency.
Called automatically when Camera is assigned.
procedure ForceUpdate();
Force immediate particle update independent of timer.
procedure AddInfluencer(AInfl: TGorillaParticleInfluencer);
procedure RemoveInfluencer(AInfl: TGorillaParticleInfluencer);
Manage influencers.
procedure ClearInfluencers();
Remove all influencers.
procedure LoadTexture(const AFilename: String; const AParticleSize: Integer;
const AIsSpriteSheet: Boolean; const ASpriteRows, ASpriteCols: Integer;
const AFrameWidth: Integer = 0; const AFrameHeight: Integer = 0); virtual;
Helper to load particle texture and configure sprite sheet.
Parameters:
AFilename - Texture file pathAParticleSize - Default particle sizeAIsSpriteSheet - True for animated spritesASpriteRows, ASpriteCols - Sprite sheet gridAFrameWidth, AFrameHeight - Optional frame sizesUsage:
LEmitter.LoadTexture('explosion.png', 64, True, 4, 4, 256, 256);
property OnStart: TNotifyEvent;
Fired when emitter starts.
property OnStop: TNotifyEvent;
Fired when emitter stops.
property OnProcess: TOnAutoEmitProcess;
Fired during each auto-emit update.
TOnAutoEmitProcess = procedure(ASender: TObject;
const AElapsedTime: Int64; const ADeltaTime: Double) of object;
property OnEmitted: TOnParticleEmittedEvent;
Fired when particle is emitted (including reused particles).
TOnParticleEmittedEvent = procedure(ASender: TObject;
const AParticle: PGorillaParticle) of object;
property OnDispose: TOnParticleNotifyEvent;
Fired before particle destruction.
TOnParticleNotifyEvent = procedure(ASender: TObject;
const AParticle: PGorillaParticle) of object;
var
LEmitter: TGorillaParticleEmitter;
begin
LEmitter := TGorillaParticleEmitter.Create(Self);
LEmitter.Parent := GorillaViewport1;
LEmitter.Camera := GorillaViewport1.Camera;
// Configure emission
LEmitter.EmitParticles := 20;
LEmitter.MaxParticles := 2000;
LEmitter.AutoEmit := True;
// Configure particles
LEmitter.ParticleSize.Preset(16, 32, 1, False);
LEmitter.ParticleLifeTime.Preset(2000, 5000, 1000, False);
LEmitter.Start();
end;
var
LExplosion: TGorillaParticleEmitter;
begin
LExplosion := TGorillaParticleEmitter.Create(Self);
LExplosion.Parent := GorillaViewport1;
LExplosion.Camera := Camera1;
LExplosion.EmitParticles := 100;
LExplosion.MaxAutoEmitTime := 100; // Emit for 0.1 second
LExplosion.ParticleLifeTime.Preset(500, 1500, 1000, False);
LExplosion.Start();
end;
procedure TForm1.ViewportMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
LPos: TPoint3D;
begin
LPos := ScreenToWorld(X, Y);
LEmitter.EmitParticle(LPos);
end;
Pre-configured volcanic eruption particle emitter with lava projectiles.
Realistic volcanic eruption effect with upward-launching lava particles.
Inheritance: TGorillaParticleEmitter → TGorillaEruptionParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Eruption
constructor Create(AOwner: TComponent); override;
Creates eruption emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up eruption emitter resources.
property Gravity: TGorillaGravityParticleInfluencer read FGravity;
Integrated gravity influencer for lava arc trajectories.
Default: Earth gravity (9.81 m/s²)
Usage:
// Stronger gravity (faster fall)
LEruption.Gravity.Ratio := 0.02;
// Weaker gravity (longer flight)
LEruption.Gravity.Ratio := 0.005;
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for lava textures.
The eruption emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 100 | Particles per interval |
| MaxParticles | 10000 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Continuous emission |
| Reuse | True | Particle caching enabled |
| ParticleSize | 2 | Uniform lava chunks |
| ParticleGrowth | 0 | No growth |
| ParticleLifeTime | 0.5-5 seconds | Lifetime range |
| ParticleWeight | 1.0 | Uniform weight |
| SpriteSheet | 7×7 | Animated sprites |
Velocity Configuration:
var
LEruption: TGorillaEruptionParticleEmitter;
begin
LEruption := TGorillaEruptionParticleEmitter.Create(Self);
LEruption.Parent := GorillaViewport1;
LEruption.Camera := Camera1;
LEruption.Position.Point := Point3D(0, 0, 0);
LEruption.Start();
end;
var
LViolent: TGorillaEruptionParticleEmitter;
begin
LViolent := TGorillaEruptionParticleEmitter.Create(Self);
LViolent.Parent := GorillaViewport1;
LViolent.Camera := Camera1;
// More particles
LViolent.EmitParticles := 200;
LViolent.MaxParticles := 15000;
// Higher velocity
LViolent.ParticleVelocity.RangeY.Preset(1500, 3000, 10000, False);
// Wider spread
LViolent.ParticleVelocity.RangeX.Preset(0, 100, 1000, True);
LViolent.ParticleVelocity.RangeZ.Preset(0, 100, 1000, True);
// Larger chunks
LViolent.ParticleSize.Preset(3, 5, 1, False);
LViolent.Start();
end;
var
LGentle: TGorillaEruptionParticleEmitter;
begin
LGentle := TGorillaEruptionParticleEmitter.Create(Self);
LGentle.Parent := GorillaViewport1;
LGentle.Camera := Camera1;
// Fewer particles
LGentle.EmitParticles := 30;
LGentle.MaxParticles := 3000;
// Lower velocity
LGentle.ParticleVelocity.RangeY.Preset(500, 1000, 10000, False);
// Narrow spread
LGentle.ParticleVelocity.RangeX.Preset(0, 20, 1000, True);
LGentle.ParticleVelocity.RangeZ.Preset(0, 20, 1000, True);
// Smaller particles
LGentle.ParticleSize.Preset(1, 2, 1, False);
LGentle.Start();
end;
var
LGeyser: TGorillaEruptionParticleEmitter;
begin
LGeyser := TGorillaEruptionParticleEmitter.Create(Self);
LGeyser.Parent := GorillaViewport1;
LGeyser.Camera := Camera1;
// Vertical column only
LGeyser.ParticleVelocity.RangeX.Preset(0, 5, 1000, True);
LGeyser.ParticleVelocity.RangeZ.Preset(0, 5, 1000, True);
LGeyser.ParticleVelocity.Direction.Point := Point3D(0, -1, 0);
// High velocity
LGeyser.ParticleVelocity.RangeY.Preset(2000, 2500, 10000, False);
// Small emission area
LGeyser.ParticlePosition.Preset(0, 10, 1000, Point3D(1, 1, 1), [axX, axZ]);
// Use blue/white for water
// (Would need custom color influencer)
LGeyser.Start();
end;
var
LIntermittent: TGorillaEruptionParticleEmitter;
LTimer: TTimer;
LActive: Boolean;
begin
LIntermittent := TGorillaEruptionParticleEmitter.Create(Self);
LIntermittent.Parent := GorillaViewport1;
LIntermittent.Camera := Camera1;
LIntermittent.AutoEmit := False;
LActive := False;
// Toggle eruption every 3 seconds
LTimer := TTimer.Create(Self);
LTimer.Interval := 3000;
LTimer.OnTimer := procedure(Sender: TObject)
begin
LActive := not LActive;
LIntermittent.AutoEmit := LActive;
if LActive then
LIntermittent.Start()
else
LIntermittent.Stop();
end;
LTimer.Enabled := True;
LIntermittent.Start();
end;
var
LFountain: TGorillaEruptionParticleEmitter;
begin
LFountain := TGorillaEruptionParticleEmitter.Create(Self);
LFountain.Parent := GorillaViewport1;
LFountain.Camera := Camera1;
LFountain.Position.Point := Point3D(0, 0, 0);
// Many particles
LFountain.EmitParticles := 150;
LFountain.MaxParticles := 8000;
// Moderate velocity
LFountain.ParticleVelocity.RangeY.Preset(1000, 1500, 10000, False);
// Circular spread
LFountain.ParticleVelocity.RangeX.Preset(0, 60, 1000, True);
LFountain.ParticleVelocity.RangeZ.Preset(0, 60, 1000, True);
// Additive blending for glow
LFountain.BlendFunc := TBlendEquationFunc.befAdd;
LFountain.BlendSource := TBlendFactor.bfOne;
LFountain.BlendDest := TBlendFactor.bfOne;
LFountain.Start();
end;
var
LBurst: TGorillaEruptionParticleEmitter;
begin
LBurst := TGorillaEruptionParticleEmitter.Create(Self);
LBurst.Parent := GorillaViewport1;
LBurst.Camera := Camera1;
// Single burst
LBurst.EmitParticles := 500;
LBurst.MaxAutoEmitTime := 100; // 0.1 second burst
// Very high velocity
LBurst.ParticleVelocity.RangeY.Preset(2500, 3500, 10000, False);
// Large spread
LBurst.ParticleVelocity.RangeX.Preset(0, 150, 1000, True);
LBurst.ParticleVelocity.RangeZ.Preset(0, 150, 1000, True);
LBurst.Start();
end;
Velocity vs Gravity:
Spread Pattern:
var
LEruption: TGorillaEruptionParticleEmitter;
LFlow: TGorillaParticleEmitter;
begin
LEruption := TGorillaEruptionParticleEmitter.Create(Self);
LEruption.Start();
// Ground lava flow
LFlow := TGorillaParticleEmitter.Create(Self);
LFlow.Parent := GorillaViewport1;
LFlow.Position.Y := 0;
// Horizontal spread
LFlow.ParticleVelocity.RangeX.Preset(0, 30, 1000, True);
LFlow.ParticleVelocity.RangeZ.Preset(0, 30, 1000, True);
LFlow.ParticleVelocity.RangeY.Preset(0, 0, 1, False);
LFlow.Start();
end;
var
LEruption: TGorillaEruptionParticleEmitter;
LSmoke: TGorillaSmokeParticleEmitter;
begin
LEruption := TGorillaEruptionParticleEmitter.Create(Self);
LEruption.Start();
// Volcanic smoke
LSmoke := TGorillaSmokeParticleEmitter.Create(Self);
LSmoke.Parent := GorillaViewport1;
LSmoke.Position := LEruption.Position;
LSmoke.Kind := TGorillaSmokeParticleKind.Style3;
// Dark smoke
LSmoke.Colored.StartColorF := TAlphaColorF.Create(0.2, 0.2, 0.2, 0.8);
LSmoke.Colored.EndColorF := TAlphaColorF.Create(0.1, 0.1, 0.1, 0.0);
LSmoke.Start();
end;
var
LEruption: TGorillaEruptionParticleEmitter;
LImpact: TGorillaSpotParticleEmitter;
begin
LEruption := TGorillaEruptionParticleEmitter.Create(Self);
LEruption.Start();
// Ground impacts
LImpact := TGorillaSpotParticleEmitter.Create(Self);
LImpact.Parent := GorillaViewport1;
LImpact.Position.Y := 0;
// Could be triggered when lava particles hit ground
// (requires custom collision detection)
end;
The default settings approximate realistic lava trajectories:
LEruption.Async := TruePre-configured explosion particle emitter with outward burst effect.
Dynamic explosion effect with configurable burst direction and intensity.
Inheritance: TGorillaParticleEmitter → TGorillaExplosionParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Explosion
constructor Create(AOwner: TComponent); override;
Creates explosion emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up explosion emitter resources.
property SpawnSize: Single;
Relative spawning area size (0.0 - 1.0) for explosion origin.
Default: 0.01 (1% - very concentrated)
Usage:
// Point explosion
LExplosion.SpawnSize := 0.01;
// Larger explosion origin
LExplosion.SpawnSize := 0.05;
property Speed: Single;
Explosion expansion speed multiplier.
Default: 1.0
Range: 0.1 - 10.0+
Usage:
// Fast explosion
LExplosion.Speed := 2.0;
// Slow explosion
LExplosion.Speed := 0.5;
property Axis: TPosition3D;
Direction vector controlling explosion axis.
Default: Point3D(1, -1, 1) - Upward with XZ spread
Usage:
// Spherical explosion (all directions)
LExplosion.Axis.Point := Point3D(1, 1, 1);
// Horizontal only
LExplosion.Axis.Point := Point3D(1, 0, 1);
// Upward cone
LExplosion.Axis.Point := Point3D(0.5, -2, 0.5);
property Gravity: TGorillaGravityParticleInfluencer read FGravity;
Integrated gravity influencer for downward arc.
Usage:
// Stronger gravity
LExplosion.Gravity.Ratio := 0.02;
// Disable gravity
LExplosion.Gravity.Enabled := False;
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for explosion textures.
The explosion emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 100 | Particles per burst |
| MaxParticles | 2000 | Maximum active particles |
| MaxAutoEmitTime | 1750ms | 1.75 second burst |
| AutoEmit | True | Auto-burst on Start() |
| Reuse | True | Particle caching enabled |
| ParticleSize | 1-2 | Small fragments |
| ParticleGrowth | 0-1 | Growing particles |
| ParticleLifeTime | 0.25-2.5 seconds | Lifetime range |
| Axis | (1, -1, 1) | Upward explosion |
| Speed | 1.0 | Normal speed |
| SpawnSize | 0.01 | Point origin |
| SpriteSheet | 8×8 | Animated sprites |
var
LExplosion: TGorillaExplosionParticleEmitter;
begin
LExplosion := TGorillaExplosionParticleEmitter.Create(Self);
LExplosion.Parent := GorillaViewport1;
LExplosion.Camera := Camera1;
LExplosion.Position.Point := Point3D(0, 0, 0);
LExplosion.Start();
// Auto-stops after 1.75 seconds
end;
var
LLargeExplosion: TGorillaExplosionParticleEmitter;
begin
LLargeExplosion := TGorillaExplosionParticleEmitter.Create(Self);
LLargeExplosion.Parent := GorillaViewport1;
LLargeExplosion.Camera := Camera1;
LLargeExplosion.Position.Point := Point3D(0, 0, 0);
// More particles
LLargeExplosion.EmitParticles := 300;
LLargeExplosion.MaxParticles := 5000;
// Larger particles
LLargeExplosion.ParticleSize.Preset(2, 5, 1, False);
// Faster expansion
LLargeExplosion.Speed := 2.0;
// Longer duration
LLargeExplosion.MaxAutoEmitTime := 3000;
LLargeExplosion.Start();
end;
var
LSphere: TGorillaExplosionParticleEmitter;
begin
LSphere := TGorillaExplosionParticleEmitter.Create(Self);
LSphere.Parent := GorillaViewport1;
LSphere.Camera := Camera1;
// All directions equally
LSphere.Axis.Point := Point3D(1, 1, 1);
// Disable gravity for perfect sphere
LSphere.Gravity.Enabled := False;
LSphere.Start();
end;
var
LGroundExp: TGorillaExplosionParticleEmitter;
begin
LGroundExp := TGorillaExplosionParticleEmitter.Create(Self);
LGroundExp.Parent := GorillaViewport1;
LGroundExp.Camera := Camera1;
LGroundExp.Position.Y := 0;
// Upward cone
LGroundExp.Axis.Point := Point3D(1, -3, 1);
// Strong upward velocity
LGroundExp.ParticleVelocity.RangeY.Preset(0, 2000, 10000, False);
LGroundExp.Start();
end;
var
LBlast: TGorillaExplosionParticleEmitter;
begin
LBlast := TGorillaExplosionParticleEmitter.Create(Self);
LBlast.Parent := GorillaViewport1;
LBlast.Camera := Camera1;
// Forward direction
LBlast.Axis.Point := Point3D(0, 0, -5);
// Concentrated cone
LBlast.SpawnSize := 0.05;
// Fast particles
LBlast.Speed := 3.0;
LBlast.Start();
end;
var
LFirework: TGorillaExplosionParticleEmitter;
begin
LFirework := TGorillaExplosionParticleEmitter.Create(Self);
LFirework.Parent := GorillaViewport1;
LFirework.Camera := Camera1;
LFirework.Position.Point := Point3D(0, 20, 0);
// Spherical burst
LFirework.Axis.Point := Point3D(1, 1, 1);
// Many colorful particles
LFirework.EmitParticles := 200;
// Additive blending for brightness
LFirework.BlendFunc := TBlendEquationFunc.befAdd;
LFirework.BlendSource := TBlendFactor.bfOne;
LFirework.BlendDest := TBlendFactor.bfOne;
// Longer trails
LFirework.ParticleLifeTime.Preset(1000, 3000, 1000, False);
LFirework.Start();
end;
var
LRepeat: TGorillaExplosionParticleEmitter;
LTimer: TTimer;
begin
LRepeat := TGorillaExplosionParticleEmitter.Create(Self);
LRepeat.Parent := GorillaViewport1;
LRepeat.Camera := Camera1;
// Timer for repeated bursts
LTimer := TTimer.Create(Self);
LTimer.Interval := 2000; // Every 2 seconds
LTimer.OnTimer := procedure(Sender: TObject)
begin
LRepeat.Clear(); // Clear previous particles
LRepeat.Stop();
LRepeat.Start(); // New explosion
end;
LTimer.Enabled := True;
LRepeat.Start();
end;
var
LColored: TGorillaExplosionParticleEmitter;
LColorInfl: TGorillaColoredParticleInfluencer;
begin
LColored := TGorillaExplosionParticleEmitter.Create(Self);
LColored.Parent := GorillaViewport1;
LColored.Camera := Camera1;
// Remove random color influencer
LColored.Influencers.Clear();
// Add specific color transition
LColorInfl := TGorillaColoredParticleInfluencer.Create(LColored);
LColorInfl.Emitter := LColored;
LColorInfl.StartColor := TAlphaColorRec.Yellow;
LColorInfl.EndColor := TAlphaColorRec.Red;
LColored.Start();
end;
Axis Examples:
(1, 1, 1) - Spherical(1, -2, 1) - Upward cone(1, 0, 1) - Horizontal disk(0, -1, 0) - Vertical columnvar
LExplosion: TGorillaExplosionParticleEmitter;
LFlash: TGorillaSpotParticleEmitter;
begin
LExplosion := TGorillaExplosionParticleEmitter.Create(Self);
// Configure explosion...
// Bright flash
LFlash := TGorillaSpotParticleEmitter.Create(Self);
LFlash.Position := LExplosion.Position;
LFlash.ParticleSize.Preset(100, 200, 1, False);
LFlash.ParticleLifeTime.Preset(50, 100, 1000, False);
LFlash.BlendFunc := TBlendEquationFunc.befAdd;
LExplosion.Start();
LFlash.EmitParticle(LFlash.Position.Point);
end;
var
LExplosion: TGorillaExplosionParticleEmitter;
LSmoke: TGorillaSmokeParticleEmitter;
begin
LExplosion := TGorillaExplosionParticleEmitter.Create(Self);
LExplosion.Start();
// Delayed smoke
TThread.CreateAnonymousThread(procedure
begin
TThread.Sleep(500);
TThread.Synchronize(nil, procedure
begin
LSmoke := TGorillaSmokeParticleEmitter.Create(Self);
LSmoke.Parent := GorillaViewport1;
LSmoke.Position := LExplosion.Position;
LSmoke.MaxAutoEmitTime := 3000;
LSmoke.Start();
end);
end).Start();
end;
Pre-configured fire particle emitter with multiple visual styles.
Realistic fire effect with integrated smoke and optional sparks.
Inheritance: TGorillaParticleEmitter → TGorillaFireParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Fire
constructor Create(AOwner: TComponent); override;
Creates fire emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up fire emitter and integrated smoke/spark emitters.
property Kind: TGorillaFireParticleKind;
Fire visual style.
Type: TGorillaFireParticleKind
Default - Standard fire textureAlternative - Alternative fire textureTorch - Torch-style fire textureDefault: Default
Usage:
LFire.Kind := TGorillaFireParticleKind.Torch;
Note: On non-Windows platforms, only one fire texture is available due to compiler limitations.
property Smoke: TGorillaSmokeParticleEmitter read FSmoke;
Integrated smoke emitter component automatically created with fire.
Usage:
// Enable smoke
LFire.Smoke.Visible := True;
LFire.Smoke.Kind := TGorillaSmokeParticleKind.Style2;
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for fire textures.
procedure Start(); override;
Starts fire and smoke emitters.
procedure Stop(); override;
Stops fire and smoke emitters.
procedure ClearUnused(); override;
Clears unused particles from fire and smoke caches.
procedure Clear(); override;
Destroys all particles in fire and smoke emitters.
The fire emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 10 | Particles per interval |
| MaxParticles | 200 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Automatic emission |
| Reuse | True | Particle caching enabled |
| AutoRotation | 1 | Gentle rotation |
| ParticleFade | 2.5 | Edge fading |
| ParticleSize | 64-96 | Size range |
| ParticleLifeTime | 1-2 seconds | Lifetime range |
| BlendMode | Additive | Bright fire effect |
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
LFire.Camera := Camera1;
LFire.Start();
end;
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
LFire.Camera := Camera1;
LFire.Kind := TGorillaFireParticleKind.Alternative;
// Enable and configure smoke
LFire.Smoke.Visible := True;
LFire.Smoke.Kind := TGorillaSmokeParticleKind.Style1;
LFire.Start();
end;
var
LTorch: TGorillaFireParticleEmitter;
begin
LTorch := TGorillaFireParticleEmitter.Create(Self);
LTorch.Parent := GorillaViewport1;
LTorch.Camera := Camera1;
LTorch.Position.Point := Point3D(5, 2, 0);
// Torch style
LTorch.Kind := TGorillaFireParticleKind.Torch;
// Smaller, concentrated flame
LTorch.Width := 0.5;
LTorch.Depth := 0.5;
LTorch.Height := 2;
LTorch.Start();
end;
var
LCampfire: TGorillaFireParticleEmitter;
begin
LCampfire := TGorillaFireParticleEmitter.Create(Self);
LCampfire.Parent := GorillaViewport1;
LCampfire.Camera := Camera1;
// Larger fire area
LCampfire.Width := 2;
LCampfire.Depth := 2;
LCampfire.Height := 3;
// More particles
LCampfire.EmitParticles := 20;
LCampfire.MaxParticles := 400;
// Enable smoke
LCampfire.Smoke.Visible := True;
LCampfire.Start();
end;
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
// Weak fire
LFire.EmitParticles := 5;
LFire.MaxParticles := 100;
LFire.ParticleSize.Preset(32, 64, 1, False);
// OR Strong fire
LFire.EmitParticles := 30;
LFire.MaxParticles := 500;
LFire.ParticleSize.Preset(96, 128, 1, False);
LFire.Start();
end;
Particle influencers for manipulating particle behavior at runtime.
Base influencer class for all particle manipulators.
Inheritance: TFmxObject → TGorillaParticleInfluencer
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Influencer
property Enabled: Boolean;
Enable/disable influencer. Disabled influencers don't affect particles.
Default: True
property Emitter: TComponent;
Linked particle emitter. Must be set for influencer to work.
Usage:
LInfluencer.Emitter := MyParticleEmitter;
procedure Interpolate(const ADeltaTime: Single; const AParticle: PGorillaParticle);
Called each frame for each particle. Override DoOnInterpolate in derived classes.
procedure EmitParticleCallback(const AParticle: PGorillaParticle);
Called when particle is emitted. Override DoOnEmitParticle in derived classes.
procedure DestroyParticleCallback(const AParticle: PGorillaParticle);
Called before particle destruction. Override DoOnDestroyParticle in derived classes.
Applies linear movement by adding velocity to position.
Inheritance: TGorillaParticleInfluencer → TGorillaLinearParticleInfluencer
Description: Default influencer automatically created with every emitter. Fastest influencer.
Algorithm:
Position += Velocity * DeltaTime
Size += Growth * DeltaTime
Usage:
// Automatically created, no manual setup needed
// To disable:
LEmitter.Influencers[0].Enabled := False;
Creates spiral/helical motion perfect for snowflakes.
Inheritance: TGorillaParticleInfluencer → TGorillaSpiralParticleInfluencer
property Spirals: Integer;
Number of spiral rotations during particle lifetime.
Default: 10
Range: 0-1000
Usage:
var
LSpiral: TGorillaSpiralParticleInfluencer;
begin
LSpiral := TGorillaSpiralParticleInfluencer.Create(LEmitter);
LSpiral.Emitter := LEmitter;
LSpiral.Spirals := 15;
LSpiral.Enabled := True;
end;
Simulates gravity force on particles.
Inheritance: TGorillaForceParticleInfluencer → TGorillaGravityParticleInfluencer
property Force: TPosition3D;
Gravity vector in meters/second².
Default: Point3D(0, 9.81, 0) (Earth gravity)
property Ratio: Single;
Gravity power multiplier.
Default: 0.01
Usage:
var
LGravity: TGorillaGravityParticleInfluencer;
begin
LGravity := TGorillaGravityParticleInfluencer.Create(LEmitter);
LGravity.Emitter := LEmitter;
LGravity.Force.Point := Point3D(0, 9.81, 0);
LGravity.Ratio := 0.02; // Stronger gravity
LGravity.Enabled := True;
end;
Creates wind zones affecting particles.
Inheritance: TGorillaForceParticleInfluencer → TGorillaWindParticleInfluencer
property Origin: TPosition3D;
Wind origin point (strongest wind location).
Default: Point3D(0, 0, 0)
property Size: TPosition3D;
Wind zone dimensions.
Default: Point3D(50, 20, 20)
property Force: TPosition3D;
Wind vector in meters/second (Beaufort scale). Direction defines wind direction.
Default: Point3D(-8.0, 0, 0)
function GetBoundingBox(): TBoundingBox;
Returns wind zone bounding box.
Usage:
var
LWind: TGorillaWindParticleInfluencer;
begin
LWind := TGorillaWindParticleInfluencer.Create(LEmitter);
LWind.Emitter := LEmitter;
LWind.Origin.Point := Point3D(0, 10, 0);
LWind.Size.Point := Point3D(100, 50, 50);
LWind.Force.Point := Point3D(-12.0, 0, 0); // Strong wind
LWind.Enabled := True;
end;
Beaufort Scale Reference:
| Speed (m/s) | Description |
|---|---|
| 0.0 - 0.2 | Calm |
| 0.3 - 1.6 | Light air |
| 1.6 - 3.4 | Light breeze |
| 3.4 - 5.5 | Gentle breeze |
| 5.5 - 8.0 | Moderate breeze |
| 8.0 - 10.8 | Fresh breeze |
| 10.8 - 13.9 | Strong breeze |
| 13.9 - 17.2 | Near gale |
| 17.2 - 20.8 | Gale |
| 20.8 - 24.5 | Strong gale |
| 24.5 - 28.5 | Storm |
| 28.5 - 32.7 | Violent storm |
| 32.7+ | Hurricane |
Creates gravitational attraction point (black hole effect).
Inheritance: TGorillaParticleInfluencer → TGorillaTraktorInfluencer
property Center: TPoint3D;
Attraction center point.
Default: Point3D(0, 0, 0)
property Radius: Single;
Attraction radius. Force is zero at radius edge, maximum at center.
Default: 1.0
property Acceleration: Single;
Attraction power.
Default: 0.25
Usage:
var
LTractor: TGorillaTraktorInfluencer;
begin
LTractor := TGorillaTraktorInfluencer.Create(LEmitter);
LTractor.Emitter := LEmitter;
LTractor.Center := Point3D(0, 0, 0);
LTractor.Radius := 100;
LTractor.Acceleration := 0.5;
LTractor.Enabled := True;
end;
Particles follow a predefined 3D path.
Inheritance: TGorillaParticleInfluencer → TGorillaTrailedParticleInfluencer
property Path: TGorillaPath3DData;
3D path definition. Particle age (0-1) maps to path position.
Usage:
var
LTrail: TGorillaTrailedParticleInfluencer;
begin
LTrail := TGorillaTrailedParticleInfluencer.Create(LEmitter);
LTrail.Emitter := LEmitter;
// Define curved path
LTrail.Path.MoveTo3D(Point3D(0, 0, 0));
LTrail.Path.LineTo3D(Point3D(10, 5, 0));
LTrail.Path.CurveTo3D(Point3D(20, 10, 5), Point3D(15, 7, 2));
LTrail.Enabled := True;
end;
Interpolates particle color from start to end over lifetime.
Inheritance: TGorillaParticleInfluencer → TGorillaColoredParticleInfluencer
property StartColor: TAlphaColor;
property StartColorF: TAlphaColorF;
Initial particle color (at birth).
Default: Blue
property EndColor: TAlphaColor;
property EndColorF: TAlphaColorF;
Final particle color (at death).
Default: Red
Usage:
var
LColor: TGorillaColoredParticleInfluencer;
begin
LColor := TGorillaColoredParticleInfluencer.Create(LEmitter);
LColor.Emitter := LEmitter;
LColor.StartColor := TAlphaColorRec.Yellow;
LColor.EndColor := TAlphaColorRec.Red;
LColor.Enabled := True;
end;
Randomizes particle color each frame.
Inheritance: TGorillaParticleInfluencer → TGorillaRandomColorParticleInfluencer
Usage:
var
LRandColor: TGorillaRandomColorParticleInfluencer;
begin
LRandColor := TGorillaRandomColorParticleInfluencer.Create(LEmitter);
LRandColor.Emitter := LEmitter;
LRandColor.Enabled := True;
end;
Simple collision with obstacles (sphere, cube, or mesh).
Inheritance: TGorillaParticleInfluencer → TGorillaObstacleInfluencer
property Center: TPoint3D;
Obstacle center position.
Default: Point3D(0, 0, 0)
property Radius: Single;
Obstacle radius (for sphere kind).
Default: 1.0
property Size: TPoint3D;
Obstacle dimensions (for cube kind).
property Kind: TParticleObstacleKind;
Obstacle type: Sphere, Cube, or Mesh.
Default: Sphere
property EmitInside: Boolean;
Allow particles to spawn inside obstacle.
Default: False
property Surface: TParticleObstacleSurface;
Surface interaction mode:
Flow - Particles flow around obstacleReflect - Particles bounce off surfaceDefault: Flow
property Acceleration: Single;
Collision acceleration force.
Default: 9.81
property Elasticity: Single;
Surface elasticity (collision threshold).
Default: 0.1
procedure SetMesh(const AValue: TMeshData; const ATransf: TMatrix3D);
Set obstacle mesh for Kind = Mesh.
Parameters:
AValue - Mesh dataATransf - Transformation matrixfunction Intersects(const APosition: TPoint3D): Boolean;
Test if position intersects obstacle.
Usage:
var
LObstacle: TGorillaObstacleInfluencer;
begin
LObstacle := TGorillaObstacleInfluencer.Create(LEmitter);
LObstacle.Emitter := LEmitter;
LObstacle.Kind := TParticleObstacleKind.Sphere;
LObstacle.Center := Point3D(0, 0, 0);
LObstacle.Radius := 10;
LObstacle.Surface := TParticleObstacleSurface.Reflect;
LObstacle.Acceleration := 15;
LObstacle.Elasticity := 0.2;
LObstacle.Enabled := True;
end;
Full physics engine integration for realistic particle collisions.
Inheritance: TGorillaParticleInfluencer → TGorillaPhysicsInfluencer
Requires: Q3 Physics package
property Physics: TComponent;
Linked TGorillaPhysicsSystem component.
property Restitution: Single;
Particle bounciness.
Default: 0.1
property Density: Single;
Particle mass density.
Default: 0.00001
property OnPhysicsBody: TOnPhysicsParticle;
Event fired when physics body is created for particle.
TOnPhysicsParticle = procedure(ASender: TObject;
const AParticle: PGorillaParticle;
const ABody: TGorillaPhysicsBody) of object;
Usage:
var
LPhysics: TGorillaPhysicsInfluencer;
begin
LPhysics := TGorillaPhysicsInfluencer.Create(LEmitter);
LPhysics.Emitter := LEmitter;
LPhysics.Physics := GorillaPhysicsSystem1;
LPhysics.Restitution := 0.3; // Bouncy particles
LPhysics.Density := 0.0001;
LPhysics.OnPhysicsBody := OnParticlePhysicsBody;
LPhysics.Enabled := True;
end;
procedure TForm1.OnParticlePhysicsBody(ASender: TObject;
const AParticle: PGorillaParticle; const ABody: TGorillaPhysicsBody);
begin
// Configure physics body
ABody.ApplyForce(Vector3D(0, -10, 0));
end;
List container for influencers.
Inheritance: TObjectList<TGorillaParticleInfluencer> → TGorillaParticleInfluencerList
procedure Notification(AComponent: TComponent; Operation: TOperation);
Handles component notifications for cleanup.
var
LEmitter: TGorillaParticleEmitter;
LGravity: TGorillaGravityParticleInfluencer;
LWind: TGorillaWindParticleInfluencer;
begin
LEmitter := TGorillaParticleEmitter.Create(Self);
LEmitter.Parent := GorillaViewport1;
// Gravity
LGravity := TGorillaGravityParticleInfluencer.Create(LEmitter);
LGravity.Emitter := LEmitter;
LGravity.Force.Point := Point3D(0, 15, 0);
LGravity.Ratio := 0.02;
// Wind
LWind := TGorillaWindParticleInfluencer.Create(LEmitter);
LWind.Emitter := LEmitter;
LWind.Force.Point := Point3D(-8, 0, 0);
LWind.Size.Point := Point3D(100, 50, 50);
LEmitter.Start();
end;
var
LEmitter: TGorillaParticleEmitter;
LColor: TGorillaColoredParticleInfluencer;
begin
LEmitter := TGorillaParticleEmitter.Create(Self);
LEmitter.Parent := GorillaViewport1;
// Yellow to red to black
LColor := TGorillaColoredParticleInfluencer.Create(LEmitter);
LColor.Emitter := LEmitter;
LColor.StartColorF := TAlphaColorF.Create(1.0, 1.0, 0.0, 1.0); // Yellow
LColor.EndColorF := TAlphaColorF.Create(0.2, 0.0, 0.0, 0.0); // Dark red, faded
LEmitter.Start();
end;
var
LEmitter: TGorillaParticleEmitter;
LGravity: TGorillaGravityParticleInfluencer;
LObstacle: TGorillaObstacleInfluencer;
begin
LEmitter := TGorillaParticleEmitter.Create(Self);
LEmitter.Parent := GorillaViewport1;
// Gravity
LGravity := TGorillaGravityParticleInfluencer.Create(LEmitter);
LGravity.Emitter := LEmitter;
// Ground obstacle
LObstacle := TGorillaObstacleInfluencer.Create(LEmitter);
LObstacle.Emitter := LEmitter;
LObstacle.Kind := TParticleObstacleKind.Cube;
LObstacle.Center := Point3D(0, -10, 0);
LObstacle.Size := Point3D(100, 1, 100);
LObstacle.Surface := TParticleObstacleSurface.Reflect;
LObstacle.Elasticity := 0.5;
LEmitter.Start();
end;
Pre-configured rain particle emitter with falling droplets and splash effects.
Realistic rain effect with integrated wind and splash emitters.
Inheritance: TGorillaParticleEmitter → TGorillaRainParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Rain
constructor Create(AOwner: TComponent); override;
Creates rain emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up rain emitter and integrated splash emitter.
property SpawnSize: Single;
Relative spawning area size (0.0 - 1.0) from top of emitter downwards.
Default: 0.05 (5% of emitter height)
Usage:
// Spawn in top 10% of emitter
LRain.SpawnSize := 0.1;
// Spawn across full height (not recommended)
LRain.SpawnSize := 1.0;
Note: Lower values create more natural rain appearance.
property Wind: TGorillaWindParticleInfluencer read FWind;
Integrated wind influencer for directing rain.
Usage:
// Enable wind
LRain.Wind.Enabled := True;
LRain.Wind.Force.Point := Point3D(-5, 0, 0); // Wind from right
LRain.Wind.Size.Point := Point3D(100, 50, 50);
property Colored: TGorillaColoredParticleInfluencer read FColored;
Integrated color influencer for raindrop fading.
Default: Light blue to transparent
property Splashes: TGorillaSpotParticleEmitter read FSplashes;
Integrated splash emitter for ground impacts.
Usage:
// Enable splashes
LRain.Splashes.Visible := True;
LRain.Splashes.Position.Y := -10; // Ground level
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for raindrop textures.
procedure Start(); override;
Starts rain and splash emitters.
procedure Stop(); override;
Stops rain and splash emitters.
procedure Splash(const APosition: TPoint3D); virtual;
Manually emit a splash particle at specified position.
Parameters:
APosition - 3D position for splashUsage:
// Create splash on raindrop collision
if RaindropHitsGround(LParticle) then
LRain.Splash(LParticle^.Position);
The rain emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 10 | Particles per interval |
| MaxParticles | 2000 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Automatic emission |
| Reuse | True | Particle caching enabled |
| ParticleSize | 1-4 | Small elongated droplets |
| ParticleLifeTime | 2-5 seconds | Lifetime range |
| BlendMode | Alpha | Transparent droplets |
| SpawnSize | 0.05 | 5% from top |
var
LRain: TGorillaRainParticleEmitter;
begin
LRain := TGorillaRainParticleEmitter.Create(Self);
LRain.Parent := GorillaViewport1;
LRain.Camera := Camera1;
// Cover large area
LRain.Width := 100;
LRain.Height := 50;
LRain.Depth := 100;
LRain.Start();
end;
var
LRain: TGorillaRainParticleEmitter;
begin
LRain := TGorillaRainParticleEmitter.Create(Self);
LRain.Parent := GorillaViewport1;
LRain.Camera := Camera1;
LRain.Width := 100;
LRain.Height := 50;
LRain.Depth := 100;
// Enable wind
LRain.Wind.Enabled := True;
LRain.Wind.Force.Point := Point3D(-8, 0, 0); // Strong wind
LRain.Wind.Origin.Point := Point3D(50, 25, 0);
LRain.Wind.Size.Point := Point3D(100, 50, 100);
LRain.Start();
end;
var
LRain: TGorillaRainParticleEmitter;
begin
LRain := TGorillaRainParticleEmitter.Create(Self);
LRain.Parent := GorillaViewport1;
LRain.Camera := Camera1;
LRain.Width := 50;
LRain.Height := 30;
LRain.Depth := 50;
// Configure splashes
LRain.Splashes.Visible := True;
LRain.Splashes.Position.Y := 0; // Ground level
LRain.Splashes.AutoEmit := True;
LRain.Splashes.EmitParticles := 5;
LRain.Start();
end;
var
LHeavyRain: TGorillaRainParticleEmitter;
begin
LHeavyRain := TGorillaRainParticleEmitter.Create(Self);
LHeavyRain.Parent := GorillaViewport1;
LHeavyRain.Camera := Camera1;
// Large coverage
LHeavyRain.Width := 200;
LHeavyRain.Height := 100;
LHeavyRain.Depth := 200;
// More particles
LHeavyRain.EmitParticles := 30;
LHeavyRain.MaxParticles := 5000;
// Faster falling
LHeavyRain.ParticleVelocity.RangeY.Preset(5000, 8000, 1000, False);
// Enable splashes
LHeavyRain.Splashes.Visible := True;
LHeavyRain.Splashes.EmitParticles := 10;
LHeavyRain.Start();
end;
var
LDrizzle: TGorillaRainParticleEmitter;
begin
LDrizzle := TGorillaRainParticleEmitter.Create(Self);
LDrizzle.Parent := GorillaViewport1;
LDrizzle.Camera := Camera1;
LDrizzle.Width := 50;
LDrizzle.Height := 30;
LDrizzle.Depth := 50;
// Fewer particles
LDrizzle.EmitParticles := 3;
LDrizzle.MaxParticles := 500;
// Slower falling
LDrizzle.ParticleVelocity.RangeY.Preset(2000, 3000, 1000, False);
LDrizzle.Start();
end;
Pre-configured smoke particle emitter with multiple visual styles.
Realistic smoke effect with various texture styles.
Inheritance: TGorillaParticleEmitter → TGorillaSmokeParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Smoke
constructor Create(AOwner: TComponent); override;
Creates smoke emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up smoke emitter resources.
property Kind: TGorillaSmokeParticleKind;
Smoke visual style.
Type: TGorillaSmokeParticleKind
Default - Standard smoke textureStyle1 - Alternative smoke style 1Style2 - Alternative smoke style 2Style3 - Alternative smoke style 3Default: Default
Usage:
LSmoke.Kind := TGorillaSmokeParticleKind.Style2;
Note: Each style uses a different sprite sheet texture.
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for smoke textures.
The smoke emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 10 | Particles per interval |
| MaxParticles | 200 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Automatic emission |
| Reuse | True | Particle caching enabled |
| AutoRotation | 1 | Gentle rotation |
| ParticleFade | 2.5 | Edge fading |
| ParticleSize | 128-192 | Size range |
| ParticleGrowth | 10-50 | Growing particles |
| ParticleLifeTime | 2-4 seconds | Lifetime range |
| BlendMode | Alpha | Transparent smoke |
| SpriteSheet | 4×4 | Animated sprites |
var
LSmoke: TGorillaSmokeParticleEmitter;
begin
LSmoke := TGorillaSmokeParticleEmitter.Create(Self);
LSmoke.Parent := GorillaViewport1;
LSmoke.Camera := Camera1;
LSmoke.Start();
end;
var
LChimney: TGorillaSmokeParticleEmitter;
begin
LChimney := TGorillaSmokeParticleEmitter.Create(Self);
LChimney.Parent := GorillaViewport1;
LChimney.Camera := Camera1;
LChimney.Kind := TGorillaSmokeParticleKind.Style1;
// Position at chimney top
LChimney.Position.Point := Point3D(0, 5, 0);
// Narrow emission area
LChimney.Width := 0.5;
LChimney.Depth := 0.5;
// Slow upward movement
LChimney.ParticleVelocity.RangeY.Preset(-50, -100, 1000, False);
LChimney.Start();
end;
var
LThickSmoke: TGorillaSmokeParticleEmitter;
begin
LThickSmoke := TGorillaSmokeParticleEmitter.Create(Self);
LThickSmoke.Parent := GorillaViewport1;
LThickSmoke.Camera := Camera1;
LThickSmoke.Kind := TGorillaSmokeParticleKind.Style3;
// More particles
LThickSmoke.EmitParticles := 20;
LThickSmoke.MaxParticles := 400;
// Larger particles
LThickSmoke.ParticleSize.Preset(192, 256, 1, False);
// Slower growth
LThickSmoke.ParticleGrowth.Preset(5, 20, 1, False);
LThickSmoke.Start();
end;
var
LFog: TGorillaSmokeParticleEmitter;
begin
LFog := TGorillaSmokeParticleEmitter.Create(Self);
LFog.Parent := GorillaViewport1;
LFog.Camera := Camera1;
LFog.Kind := TGorillaSmokeParticleKind.Style2;
// Ground level
LFog.Position.Y := 0;
// Large area coverage
LFog.Width := 100;
LFog.Depth := 100;
LFog.Height := 5;
// Horizontal movement
LFog.ParticleVelocity.RangeX.Preset(-10, 10, 1000, True);
LFog.ParticleVelocity.RangeY.Preset(-5, 5, 1000, True);
LFog.ParticleVelocity.RangeZ.Preset(-10, 10, 1000, True);
// Large, slow-moving particles
LFog.ParticleSize.Preset(256, 384, 1, False);
LFog.ParticleGrowth.Preset(1, 5, 1, False);
LFog.ParticleLifeTime.Preset(10000, 20000, 1000, False);
// Many particles
LFog.EmitParticles := 50;
LFog.MaxParticles := 1000;
LFog.Start();
end;
var
LExpSmoke: TGorillaSmokeParticleEmitter;
begin
LExpSmoke := TGorillaSmokeParticleEmitter.Create(Self);
LExpSmoke.Parent := GorillaViewport1;
LExpSmoke.Camera := Camera1;
// Burst emission
LExpSmoke.EmitParticles := 100;
LExpSmoke.MaxAutoEmitTime := 500; // 0.5 second burst
// Outward expansion
LExpSmoke.ParticleVelocity.RangeX.Preset(0, 200, 1000, True);
LExpSmoke.ParticleVelocity.RangeY.Preset(0, 200, 1000, True);
LExpSmoke.ParticleVelocity.RangeZ.Preset(0, 200, 1000, True);
// Rapid growth
LExpSmoke.ParticleGrowth.Preset(50, 100, 1, False);
LExpSmoke.Start();
end;
var
LFire: TGorillaFireParticleEmitter;
begin
LFire := TGorillaFireParticleEmitter.Create(Self);
LFire.Parent := GorillaViewport1;
// Fire automatically includes smoke
LFire.Smoke.Visible := True;
LFire.Smoke.Kind := TGorillaSmokeParticleKind.Style1;
LFire.Start();
end;
var
LSteam: TGorillaSmokeParticleEmitter;
LGravity: TGorillaGravityParticleInfluencer;
begin
LSteam := TGorillaSmokeParticleEmitter.Create(Self);
LSteam.Parent := GorillaViewport1;
LSteam.Kind := TGorillaSmokeParticleKind.Style2;
// Upward force (negative gravity)
LGravity := TGorillaGravityParticleInfluencer.Create(LSteam);
LGravity.Emitter := LSteam;
LGravity.Force.Point := Point3D(0, -5, 0);
// White/transparent color
LSteam.ParticleMaterial.Texture := nil; // Use solid color
LSteam.Start();
end;
Pre-configured snow particle emitter with spiral falling motion.
Realistic snowfall effect with integrated spiral and wind influencers.
Inheritance: TGorillaParticleEmitter → TGorillaSnowParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Snow
constructor Create(AOwner: TComponent); override;
Creates snow emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up snow emitter resources.
property SpawnSize: Single;
Relative spawning area size (0.0 - 1.0) from top of emitter downwards.
Default: 0.05 (5% of emitter height)
Usage:
// Spawn in top 10% of emitter
LSnow.SpawnSize := 0.1;
// Spawn across full height (not recommended)
LSnow.SpawnSize := 1.0;
Note: Lower values create more natural snowfall appearance.
property Spiral: TGorillaSpiralParticleInfluencer read FSpiral;
Integrated spiral influencer for realistic snowflake motion.
Usage:
// Adjust spiral intensity
LSnow.Spiral.Spirals := 15; // More spirals
// Disable spiral
LSnow.Spiral.Enabled := False;
property Wind: TGorillaWindParticleInfluencer read FWind;
Integrated wind influencer for directing snowfall.
Default: Disabled
Usage:
// Enable wind
LSnow.Wind.Enabled := True;
LSnow.Wind.Force.Point := Point3D(-3, 0, 0); // Gentle breeze
LSnow.Wind.Size.Point := Point3D(100, 50, 50);
property Colored: TGorillaColoredParticleInfluencer read FColored;
Integrated color influencer for snowflake fading.
Default: Light gray/white to transparent
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for snowflake textures.
The snow emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 1 | Particles per interval |
| MaxParticles | 1024 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Automatic emission |
| Reuse | True | Particle caching enabled |
| ParticleSize | 0.1-2 | Small snowflakes |
| ParticleLifeTime | 5-10 seconds | Lifetime range |
| ParticleWeight | 0.3-0.5 | Light particles |
| SpawnSize | 0.05 | 5% from top |
| SpriteSheet | 7×7 | Animated sprites |
var
LSnow: TGorillaSnowParticleEmitter;
begin
LSnow := TGorillaSnowParticleEmitter.Create(Self);
LSnow.Parent := GorillaViewport1;
LSnow.Camera := Camera1;
// Cover large area
LSnow.Width := 100;
LSnow.Height := 50;
LSnow.Depth := 100;
LSnow.Start();
end;
var
LSnow: TGorillaSnowParticleEmitter;
begin
LSnow := TGorillaSnowParticleEmitter.Create(Self);
LSnow.Parent := GorillaViewport1;
LSnow.Camera := Camera1;
LSnow.Width := 100;
LSnow.Height := 50;
LSnow.Depth := 100;
// Enable gentle wind
LSnow.Wind.Enabled := True;
LSnow.Wind.Force.Point := Point3D(-2, 0, 0); // Light breeze
LSnow.Wind.Origin.Point := Point3D(0, 25, 0);
LSnow.Wind.Size.Point := Point3D(100, 50, 100);
LSnow.Start();
end;
var
LHeavySnow: TGorillaSnowParticleEmitter;
begin
LHeavySnow := TGorillaSnowParticleEmitter.Create(Self);
LHeavySnow.Parent := GorillaViewport1;
LHeavySnow.Camera := Camera1;
LHeavySnow.Width := 100;
LHeavySnow.Height := 50;
LHeavySnow.Depth := 100;
// More particles
LHeavySnow.EmitParticles := 5;
LHeavySnow.MaxParticles := 3000;
// Larger flakes
LHeavySnow.ParticleSize.Preset(2, 4, 1, False);
// More spiraling
LHeavySnow.Spiral.Spirals := 20;
LHeavySnow.Start();
end;
var
LFlurries: TGorillaSnowParticleEmitter;
begin
LFlurries := TGorillaSnowParticleEmitter.Create(Self);
LFlurries.Parent := GorillaViewport1;
LFlurries.Camera := Camera1;
LFlurries.Width := 50;
LFlurries.Height := 30;
LFlurries.Depth := 50;
// Very few particles
LFlurries.EmitTime := 50; // Slower emission
LFlurries.EmitParticles := 1;
LFlurries.MaxParticles := 200;
// Tiny flakes
LFlurries.ParticleSize.Preset(0.5, 1, 10, False);
LFlurries.Start();
end;
var
LBlizzard: TGorillaSnowParticleEmitter;
begin
LBlizzard := TGorillaSnowParticleEmitter.Create(Self);
LBlizzard.Parent := GorillaViewport1;
LBlizzard.Camera := Camera1;
LBlizzard.Width := 150;
LBlizzard.Height := 75;
LBlizzard.Depth := 150;
// Many particles
LBlizzard.EmitParticles := 10;
LBlizzard.MaxParticles := 5000;
// Strong wind
LBlizzard.Wind.Enabled := True;
LBlizzard.Wind.Force.Point := Point3D(-15, 0, 5); // Strong diagonal wind
LBlizzard.Wind.Size.Point := Point3D(150, 75, 150);
// Less spiraling (wind-blown)
LBlizzard.Spiral.Spirals := 5;
// Faster falling
LBlizzard.ParticleVelocity.RangeY.Preset(4000, 7000, 1000, False);
LBlizzard.Start();
end;
var
LGentleSnow: TGorillaSnowParticleEmitter;
begin
LGentleSnow := TGorillaSnowParticleEmitter.Create(Self);
LGentleSnow.Parent := GorillaViewport1;
LGentleSnow.Camera := Camera1;
LGentleSnow.Width := 75;
LGentleSnow.Height := 40;
LGentleSnow.Depth := 75;
// Moderate emission
LGentleSnow.EmitParticles := 2;
LGentleSnow.MaxParticles := 1500;
// Slow falling
LGentleSnow.ParticleVelocity.RangeY.Preset(1500, 3000, 1000, False);
// Maximum spiraling
LGentleSnow.Spiral.Spirals := 25;
LGentleSnow.Start();
end;
Pre-configured spot/splash particle emitter for small area effects.
Simple spot effect perfect for splashes, impacts, and small localized particle bursts.
Inheritance: TGorillaParticleEmitter → TGorillaSpotParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Spot
constructor Create(AOwner: TComponent); override;
Creates spot emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up spot emitter resources.
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for spot textures.
The spot emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 1 | Particles per manual emit |
| MaxParticles | 1000 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | False | Manual emission only |
| Reuse | True | Particle caching enabled |
| ParticleSize | 1-2 | Small particles |
| ParticleLifeTime | 0.5-1.5 seconds | Short lifetime |
| ParticleWeight | 0.1-1.0 | Light particles |
| SpriteSheet | 4×4 | Animated sprites |
Key Features:
var
LSplash: TGorillaSpotParticleEmitter;
begin
LSplash := TGorillaSpotParticleEmitter.Create(Self);
LSplash.Parent := GorillaViewport1;
LSplash.Camera := Camera1;
LSplash.Start();
// Trigger splash at specific position
LSplash.EmitParticle(Point3D(0, 0, 0));
end;
var
LRain: TGorillaRainParticleEmitter;
begin
LRain := TGorillaRainParticleEmitter.Create(Self);
LRain.Parent := GorillaViewport1;
LRain.Camera := Camera1;
// Spot emitter is automatically created
LRain.Splashes.Visible := True;
LRain.Splashes.Position.Y := 0; // Ground level
// Configure splash appearance
LRain.Splashes.ParticleSize.Preset(2, 4, 1, False);
LRain.Splashes.ParticleLifeTime.Preset(300, 800, 1000, False);
LRain.Start();
end;
var
LImpact: TGorillaSpotParticleEmitter;
begin
LImpact := TGorillaSpotParticleEmitter.Create(Self);
LImpact.Parent := GorillaViewport1;
LImpact.Camera := Camera1;
// More particles per impact
LImpact.EmitParticles := 10;
// Stronger outward burst
LImpact.ParticleVelocity.RangeX.Preset(0, 100, 1000, True);
LImpact.ParticleVelocity.RangeZ.Preset(0, 100, 1000, True);
// Larger particles
LImpact.ParticleSize.Preset(4, 8, 1, False);
LImpact.Start();
// Trigger on collision
if BulletHitsWall then
LImpact.EmitParticle(CollisionPoint);
end;
var
LDust: TGorillaSpotParticleEmitter;
begin
LDust := TGorillaSpotParticleEmitter.Create(Self);
LDust.Parent := GorillaViewport1;
LDust.Camera := Camera1;
LDust.Position.Y := 0.1; // Slightly above ground
// Few particles
LDust.EmitParticles := 3;
// Small, slow particles
LDust.ParticleSize.Preset(1, 3, 1, False);
LDust.ParticleVelocity.RangeX.Preset(0, 20, 1000, True);
LDust.ParticleVelocity.RangeZ.Preset(0, 20, 1000, True);
// Quick fade
LDust.ParticleLifeTime.Preset(200, 600, 1000, False);
LDust.Start();
// Trigger on footstep
procedure OnFootstep(APosition: TPoint3D);
begin
LDust.EmitParticle(APosition);
end;
end;
var
LSparkle: TGorillaSpotParticleEmitter;
begin
LSparkle := TGorillaSpotParticleEmitter.Create(Self);
LSparkle.Parent := GorillaViewport1;
LSparkle.Camera := Camera1;
// Burst of particles
LSparkle.EmitParticles := 15;
// Upward + outward motion
LSparkle.ParticleVelocity.RangeX.Preset(0, 50, 1000, True);
LSparkle.ParticleVelocity.RangeY.Preset(-50, -100, 1000, False);
LSparkle.ParticleVelocity.RangeZ.Preset(0, 50, 1000, True);
// Bright, small particles
LSparkle.ParticleSize.Preset(1, 3, 1, False);
// Additive blending
LSparkle.BlendFunc := TBlendEquationFunc.befAdd;
LSparkle.BlendSource := TBlendFactor.bfOne;
LSparkle.BlendDest := TBlendFactor.bfOne;
LSparkle.Start();
// Trigger on spell cast
LSparkle.EmitParticle(MagicCastPosition);
end;
var
LDrip: TGorillaSpotParticleEmitter;
LTimer: TTimer;
begin
LDrip := TGorillaSpotParticleEmitter.Create(Self);
LDrip.Parent := GorillaViewport1;
LDrip.Camera := Camera1;
LDrip.Position.Point := Point3D(0, 5, 0); // Drip source
// Single particle
LDrip.EmitParticles := 1;
// Downward motion
LDrip.ParticleVelocity.RangeY.Preset(50, 100, 1000, False);
LDrip.Start();
// Timer for periodic drips
LTimer := TTimer.Create(Self);
LTimer.Interval := 2000; // Every 2 seconds
LTimer.OnTimer := procedure(Sender: TObject)
begin
LDrip.EmitParticle(LDrip.Position.Point);
end;
LTimer.Enabled := True;
end;
Pre-configured waterfall particle emitter with cascading water effect.
Realistic waterfall effect with forward projection and gravity.
Inheritance: TGorillaParticleEmitter → TGorillaWaterfallParticleEmitter
Platforms: All Gorilla platforms
Unit: Gorilla.Particle.Waterfall
constructor Create(AOwner: TComponent); override;
Creates waterfall emitter with preconfigured settings:
destructor Destroy(); override;
Cleans up waterfall emitter resources.
property SpawnSize: Single;
Relative spawning area size (0.0 - 1.0) from top of emitter downwards.
Default: 0.05 (5% of emitter height)
Usage:
// Spawn in top 10% of emitter
LWaterfall.SpawnSize := 0.1;
property Power: Single;
Water projection power controlling Z-axis expansion.
Default: 0.025
Range: 0.0 - 1.0
Usage:
// Stronger water projection
LWaterfall.Power := 0.05;
// Weak projection (straight down)
LWaterfall.Power := 0.01;
Note: Zero power makes particles fall straight down like rain.
property Spread: Single;
Horizontal spreading of particles on X-axis.
Default: 0.05
Range: 0.0 - 1.0
Usage:
// Wide waterfall
LWaterfall.Spread := 0.1;
// Narrow stream
LWaterfall.Spread := 0.02;
property Speed: Single;
Falling speed on Y-axis, boosting gravity influence.
Default: 0.1
Range: 0.0 - 1.0
Usage:
// Faster waterfall
LWaterfall.Speed := 0.2;
// Slower cascade
LWaterfall.Speed := 0.05;
property Colored: TGorillaColoredParticleInfluencer read FColored;
Integrated color influencer for water color transition.
Default: Blue to transparent
Usage:
// Change water color
LWaterfall.Colored.StartColorF := TAlphaColorF.Create(0.0, 0.8, 1.0, 0.9); // Cyan
LWaterfall.Colored.EndColorF := TAlphaColorF.Create(0.0, 0.5, 0.8, 0.0); // Dark cyan fade
property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;
Attached particle material source for water textures.
The waterfall emitter is preconfigured with these settings:
| Property | Value | Description |
|---|---|---|
| EmitParticles | 100 | Particles per interval |
| MaxParticles | 2500 | Maximum active particles |
| EmitTime | 16ms | ~60 FPS updates |
| AutoEmit | True | Automatic emission |
| Reuse | True | Particle caching enabled |
| ParticleSize | 4-16 | Water droplet size |
| ParticleGrowth | 1-2 | Growing particles |
| ParticleLifeTime | 2.5-5 seconds | Lifetime range |
| UseLighting | True | Affected by scene lighting |
| SpriteSheet | 4×4 | Animated sprites |
var
LWaterfall: TGorillaWaterfallParticleEmitter;
begin
LWaterfall := TGorillaWaterfallParticleEmitter.Create(Self);
LWaterfall.Parent := GorillaViewport1;
LWaterfall.Camera := Camera1;
// Position at cliff edge
LWaterfall.Position.Point := Point3D(0, 10, 0);
// Size of water source
LWaterfall.Width := 3;
LWaterfall.Depth := 1;
LWaterfall.Height := 0.5;
LWaterfall.Start();
end;
var
LLargeWaterfall: TGorillaWaterfallParticleEmitter;
begin
LLargeWaterfall := TGorillaWaterfallParticleEmitter.Create(Self);
LLargeWaterfall.Parent := GorillaViewport1;
LLargeWaterfall.Camera := Camera1;
LLargeWaterfall.Position.Point := Point3D(0, 20, 0);
// Wide waterfall
LLargeWaterfall.Width := 10;
LLargeWaterfall.Depth := 2;
// More particles
LLargeWaterfall.EmitParticles := 200;
LLargeWaterfall.MaxParticles := 5000;
// Strong projection
LLargeWaterfall.Power := 0.04;
LLargeWaterfall.Spread := 0.08;
LLargeWaterfall.Speed := 0.15;
LLargeWaterfall.Start();
end;
var
LStream: TGorillaWaterfallParticleEmitter;
begin
LStream := TGorillaWaterfallParticleEmitter.Create(Self);
LStream.Parent := GorillaViewport1;
LStream.Camera := Camera1;
// Narrow stream
LStream.Width := 0.5;
LStream.Depth := 0.3;
// Fewer particles
LStream.EmitParticles := 30;
LStream.MaxParticles := 800;
// Gentle flow
LStream.Power := 0.015;
LStream.Spread := 0.02;
LStream.Speed := 0.08;
// Smaller droplets
LStream.ParticleSize.Preset(2, 8, 1, False);
LStream.Start();
end;
var
LFountain: TGorillaWaterfallParticleEmitter;
begin
LFountain := TGorillaWaterfallParticleEmitter.Create(Self);
LFountain.Parent := GorillaViewport1;
LFountain.Camera := Camera1;
LFountain.Position.Y := 0;
// Circular base
LFountain.Width := 1;
LFountain.Depth := 1;
// Upward initial velocity
LFountain.ParticleVelocity.RangeY.Preset(-200, -300, 1000, False);
// Outward spread
LFountain.ParticleVelocity.RangeX.Preset(0, 100, 1000, True);
LFountain.ParticleVelocity.RangeZ.Preset(0, 100, 1000, True);
// Disable forward power
LFountain.Power := 0;
// Strong gravity to pull down
LFountain.Gravity.Ratio := 0.03;
LFountain.Start();
end;
var
LCascade: TGorillaWaterfallParticleEmitter;
begin
LCascade := TGorillaWaterfallParticleEmitter.Create(Self);
LCascade.Parent := GorillaViewport1;
LCascade.Camera := Camera1;
LCascade.Position.Point := Point3D(0, 15, 0);
LCascade.Width := 5;
LCascade.Depth := 1.5;
// Very fast falling
LCascade.Speed := 0.25;
LCascade.Gravity.Ratio := 0.02;
// Strong projection
LCascade.Power := 0.06;
// Many particles
LCascade.EmitParticles := 150;
LCascade.MaxParticles := 4000;
LCascade.Start();
end;
var
LTrickle: TGorillaWaterfallParticleEmitter;
begin
LTrickle := TGorillaWaterfallParticleEmitter.Create(Self);
LTrickle.Parent := GorillaViewport1;
LTrickle.Camera := Camera1;
// Very narrow
LTrickle.Width := 0.2;
LTrickle.Depth := 0.2;
// Few particles
LTrickle.EmitParticles := 10;
LTrickle.MaxParticles := 300;
// Weak flow
LTrickle.Power := 0.01;
LTrickle.Spread := 0.01;
LTrickle.Speed := 0.05;
// Tiny droplets
LTrickle.ParticleSize.Preset(1, 4, 1, False);
LTrickle.Start();
end;
Power vs Spread:
Speed vs Gravity:
var
LWaterfall: TGorillaWaterfallParticleEmitter;
LMist: TGorillaSmokeParticleEmitter;
begin
LWaterfall := TGorillaWaterfallParticleEmitter.Create(Self);
// Configure waterfall...
// Add mist at base
LMist := TGorillaSmokeParticleEmitter.Create(Self);
LMist.Parent := GorillaViewport1;
LMist.Position := LWaterfall.Position;
LMist.Position.Y := 0; // Bottom of waterfall
// White mist
LMist.Colored.StartColorF := TAlphaColorF.Create(0.9, 0.9, 1.0, 0.3);
LMist.Colored.EndColorF := TAlphaColorF.Create(0.8, 0.8, 0.9, 0.0);
LWaterfall.Start();
LMist.Start();
end;
The Gorilla.Physics unit provides TGorillaPhysicsSystem, the main physics simulation component in Gorilla3D. It supports multiple physics drivers (Q3, JOLT), various collider shapes, joints, forces, impulses, and collision events. Place it in a viewport and call Step() on a timer to run the simulation.
TComponent
└── TControl3D
└── TGorillaControl
└── TGorillaPhysicsSystem
| Property | Type | Description |
|---|---|---|
Driver |
TGorillaPhysicsDriverType |
Physics engine driver: Q3Physics, JOLTPhysics, CustomPhysics |
Active |
Boolean |
Activate/deactivate physics. Still requires calling Step() |
Async |
Boolean |
Enable asynchronous (background thread) computation |
RenderColliders |
Boolean |
Render collider shapes at runtime for debugging |
Accuracy |
Integer |
Computation accuracy (1..25). Higher = more accurate but slower. Default: 10 |
Gravity |
TPoint3D |
Global gravity vector |
Colliders |
TGorillaPhysicsColliderPrefabs |
Design-time collider prefab collection |
Joints |
TGorillaPhysicsJointPrefabs |
Design-time joint prefab collection |
| Event | Type | Description |
|---|---|---|
OnBeginContact |
TOnGorillaPhysicsNotifyContact |
Fired when two bodies begin colliding |
OnEndContact |
TOnGorillaPhysicsNotifyContact |
Fired when two bodies stop colliding |
OnBeginStep |
TNotifyEvent |
Start of a computation cycle (not synchronized) |
OnEndStep |
TNotifyEvent |
End of a computation cycle (not synchronized) |
OnBeginUpdate |
TNotifyEvent |
Start of bodies update (not synchronized) |
OnEndUpdate |
TNotifyEvent |
End of bodies update (not synchronized) |
OnCollidersRegistered |
TNotifyEvent |
All collider prefabs registered |
OnCollidersUnregistered |
TNotifyEvent |
All collider prefabs unregistered |
OnJointsRegistered |
TNotifyEvent |
All joint prefabs registered |
OnJointsUnregistered |
TNotifyEvent |
All joint prefabs unregistered |
| Property | Type | Description |
|---|---|---|
DriverInstance |
TGorillaPhysicsDriver |
Direct access to the physics driver instance |
Engine |
TObject |
Internal physics engine object |
EventCache |
TGorillaPhysicsEventCache |
Collider/joint event cache for fast body-event mapping |
| Method | Description |
|---|---|
AddBoxCollider(AControl, APrefab) |
Add box collider, auto-sized from control |
AddBoxCollider(AControl, APrefab, ASize) |
Add box collider with explicit size |
AddSphereCollider(AControl, APrefab, ARadius) |
Add sphere collider |
AddCapsuleCollider(AControl, APrefab, ARadius, AHeight) |
Add capsule collider |
AddCylinderCollider(AControl, APrefab, AHalfHeight, ARadius, AConvexRadius) |
Add cylinder collider (Q3 + JOLT) |
AddConeCollider(AControl, APrefab, AHeight, ARadius) |
Add cone collider (Q3 + JOLT) |
AddConvexHullCollider(AControl, APrefab, APointCount, APoints) |
Add convex hull collider (Q3 + JOLT) |
AddTerrainCollider(AMesh, APrefab) |
Add terrain collider (TCustomMesh or TGorillaMesh) |
AddMeshCollider(AMesh, APrefab) |
Add mesh collider (experimental) |
AddParticleCollider(AData, AType, APrefab, ATransformation, ARadius, ABody) |
Add particle collider |
RemoveCollider(AMesh) |
Remove collider by control |
RemoveCollider(ABody) |
Remove collider by body reference |
| Method | Description |
|---|---|
RemoteMeshTransform(ACtrl) |
Sync control transform to physics |
RemoteBodyTransform(ABody/ACtrl, ATranslation, ARotationAngle) |
Set body position and rotation |
RemoteBodyTransform(ABody/ACtrl, ATranslation, ARotation) |
Set body position and rotation matrix |
| Method | Description |
|---|---|
RemoteBodyImpulse(ABody/ACtrl, AImpulse) |
Apply instantaneous impulse |
RemoteBodyForce(ABody/ACtrl, AForce, ADirect) |
Apply continuous force |
RemoteBodyVelocity(ABody/ACtrl, AVelocity, ADirect) |
Set linear velocity directly |
RemoteBodyAngularVelocity(ABody/ACtrl, AVelocity) |
Set angular velocity directly |
RemoteBodyAngularImpulse(ABody/ACtrl, AImpulse, APt) |
Apply angular impulse |
| Method | Description |
|---|---|
Step() |
Execute one physics simulation step. Call on a ~33ms timer |
GetDeltaTime() |
Returns time since last step in milliseconds |
Block() |
Block physics system for thread-safe body access (async mode) |
Unblock() |
Unblock after Block() |
| Method | Description |
|---|---|
RegisterDriverClass(AEngineName, AClass) |
Register a custom physics driver |
UnregisterDriverClass(AEngineName/AClass) |
Unregister a physics driver |
GetDriverClass(AEngineName/AType) |
Get registered driver class |
The Gorilla.Physics.Types unit defines all types, enumerations, and records used by the Gorilla3D physics system: driver types, body types, collider kinds, collider settings, joint types, motor types, and joint prefabs.
| Value | Description |
|---|---|
Q3Physics |
Q3 Physics Engine (default) |
JOLTPhysics |
JOLT Physics Engine |
CustomPhysics |
Custom physics driver |
| Value | Description |
|---|---|
ckBox |
Box collider |
ckSphere |
Sphere collider |
ckCapsule |
Capsule collider |
ckParticle |
Particle collider |
ckMesh |
Mesh collider |
ckTerrain |
Terrain collider |
ckCylinder |
Cylinder collider (Q3 + JOLT) |
ckCone |
Cone collider (Q3 + JOLT) |
ckConvexHull |
Convex hull collider (Q3 + JOLT) |
| Value | Description |
|---|---|
eStaticBody |
Immovable body. Use for floors, walls |
eKinematicBody |
Moved by code, not affected by forces. Use for platforms, character controllers |
eDynamicBody |
Fully simulated by physics. Use for most interactive objects |
Set type (TGorillaPhysicsBodyStates) with flags:
| Value | Description |
|---|---|
eAwake |
Body is awake |
eActive |
Body is active |
eAllowSleep |
Body can sleep |
eIsland |
Body is in an island |
eStatic |
Static body |
eDynamic |
Dynamic body |
eKinematic |
Kinematic body |
eLockRotAxisX/Y/Z |
Lock rotation on X/Y/Z axis |
eLockMoveAxisX/Y/Z |
Lock translation on X/Y/Z axis |
All joint types are supported by both the Q3 and JOLT backends.
| Value | Description | Q3 | JOLT |
|---|---|---|---|
Fixed |
Constrains two bodies together | Yes | Yes |
BallAndSocket |
Free rotation on all axes (shoulder/hip) | Yes | Yes |
Hinge |
Free rotation on one axis (wheel, carousel) | Yes | Yes |
LimitedHinge |
Limited rotation on one axis (finger, knee) | Yes | Yes |
Prismatic |
Sliding motion on one axis (sliding door) | Yes | Yes |
StiffSpring |
Soft spring maintaining a distance between two bodies | Yes | Yes |
Magnet |
Magnetic attraction based on mass | Yes | Yes |
Buoyancy |
Floating body on a fluid surface (soft, per-step) | Yes | Yes |
Point |
Point-to-point pin (like BallAndSocket) | Yes | Yes |
SixDOF |
Six degrees of freedom (per-axis limits) | Yes | Yes |
SwingTwist |
Swing cone + twist limit (ragdoll) | Yes | Yes |
Distance |
Rigid distance constraint (rope/rod) | Yes | Yes |
Cone |
Pin with a swing cone limit | Yes | Yes |
RackAndPinion |
Couples pinion rotation to rack translation (needs Ratio) |
Yes | Yes |
Gear |
Couples two bodies' rotation (needs Ratio) |
Yes | Yes |
Pulley |
Rope of fixed total length over two pulley points | Yes | Yes |
Point,Distance,Cone,SwingTwist,SixDOF,Gear,RackAndPinionandPulleywere originally JOLT-only; they now have native Q3 solvers as well. Buoyancy is also implemented for JOLT (nativeApplyBuoyancyImpulse).
| Value | Description |
|---|---|
NoMotor |
Motor deactivated |
RotationMotor |
Constant rotation via quaternion |
AngularVelocityMotor |
Increasing angular velocity |
PositionMotor |
Drive toward a position |
LinearVelocityMotor |
Drive at constant velocity |
VelocityMotor |
Combined angular + linear velocity (wheels, paddlewheels) |
| Field | Type | Description |
|---|---|---|
Friction |
Single |
Surface friction coefficient |
Restitution |
Single |
Bounciness (0 = no bounce, 1 = full) |
Density |
Single |
Mass density |
Sensor |
Boolean |
If True, detects collisions but does not react physically |
Main configuration record for creating colliders.
| Field | Type | Description |
|---|---|---|
_Type |
TGorillaPhysicsBodyType |
Body type (static/dynamic/kinematic) |
LockRotAxisX/Y/Z |
Boolean |
Lock rotation per axis |
LockMoveAxisX/Y/Z |
Boolean |
Lock translation per axis |
LinearDamping |
Single |
Linear velocity damping |
AngularDamping |
Single |
Angular velocity damping |
Radius |
Single |
Override radius for capsule/sphere colliders |
Size |
TPoint3D |
Override size (non-zero overrides auto-detection) |
MinLinearVelocity |
TPoint3D |
Minimum linear velocity limit |
MaxLinearVelocity |
TPoint3D |
Maximum linear velocity limit |
MinAngularVelocity |
TPoint3D |
Minimum angular velocity limit |
MaxAngularVelocity |
TPoint3D |
Maximum angular velocity limit |
Slop |
Single |
Penetration depth slop |
Layers |
Integer |
Collision layer mask (max 8 layers) |
AllowSubColliders |
Boolean |
Allow sub-colliders |
AllowSleep |
Boolean |
Allow body to sleep |
Active |
Boolean |
Enable for physics computation |
Data |
TGorillaPhysicsColliderData |
Friction, restitution, density, sensor |
OnBeginContact |
TOnGorillaPhysicsCollisionEvent |
Per-collider begin contact event |
OnEndContact |
TOnGorillaPhysicsCollisionEvent |
Per-collider end contact event |
class function Create(AType: TGorillaPhysicsBodyType): TGorillaColliderSettings; static;
class function AutoDetectSize(APrefab, AControl, ACollType, ASize): TPoint3D; static;
class function AutoDetectRadius(APrefab, AControl, ACollType, ARadius): Single; static;
class function AutoDetectHeight(APrefab, AControl, ACollType, AHeight): Single; static;
Design-time joint configuration (collection item).
| Property | Type | Description |
|---|---|---|
DisplayName |
String |
Joint name |
Enabled |
Boolean |
Enable/disable the joint |
LocalSpace |
Boolean |
Use local space coordinates |
JointType |
TGorillaPhysicsJointType |
Joint type |
ControlA |
TControl3D |
First body |
ControlB |
TControl3D |
Second body |
AnchorA |
TPosition3D |
Anchor on body A |
AnchorB |
TPosition3D |
Anchor on body B |
AxisA |
TPosition3D |
Axis for body A |
AxisB |
TPosition3D |
Axis for body B |
NormalA |
TPosition3D |
Normal for body A |
NormalB |
TPosition3D |
Normal for body B |
AntiGravity |
Boolean |
Negate gravity on joint |
MinValue |
TPosition3D |
Minimum limits (LimitedHinge/Prismatic) |
MaxValue |
TPosition3D |
Maximum limits (LimitedHinge/Prismatic) |
BreakForce |
TPosition3D |
Force threshold for breaking |
BreakTorque |
TPosition3D |
Torque threshold for breaking |
Motor |
TGorillaPhysicsMotorType |
Motor type |
MotorForce |
TPosition3D |
Motor force value |
Stiffness |
Single |
Spring stiffness (Buoyancy JOLT: buoyancy factor) |
Damping |
Single |
Spring damping / fluid drag (Buoyancy) |
RestLength |
Single |
Spring rest length; rope length for Pulley/Distance |
Ratio |
Single |
Transmission ratio for Gear / RackAndPinion / Pulley |
HalfConeAngle |
Single |
Swing cone half-angle (radians) for Cone / SwingTwist |
PlaneHalfConeAngle |
Single |
Second (perpendicular) swing half-angle for an elliptical cone |
FixedPointA |
TPosition3D |
World-space rope endpoint A (Pulley) |
FixedPointB |
TPosition3D |
World-space rope endpoint B (Pulley) |
ConstraintA |
TGorillaPhysicsJointPrefab |
Sub-joint A (pinion hinge / wheel hinge) for Gear / RackAndPinion |
ConstraintB |
TGorillaPhysicsJointPrefab |
Sub-joint B (rack slider / wheel hinge) for Gear / RackAndPinion |
TOnGorillaPhysicsCollisionEvent = procedure(ASender: TObject;
const AOffset, ANormal: TPoint3D;
ABody1, ABody2: TGorillaPhysicsBody) of object;
Main terrain component for rendering planar terrain from heightmaps or procedural algorithms.
Simple terrain component for rendering from heightmaps or procedural algorithms.
Inheritance: TGorillaSingletonMesh → TGorillaTerrain
Platforms: All Gorilla platforms
Unit: Gorilla.Terrain
constructor Create(AOwner: TComponent); override;
Creates a new terrain instance with default settings:
destructor Destroy; override;
Frees all resources including heightmap and material objects.
property TwoFace: Boolean read FTwoFace write SetTwoFace;
Defines if front and back of triangles will be rendered. Default: False.
Remarks: Keep disabled for better performance. Only enable if viewing terrain from below.
property ResolutionX: Integer read GetResolutionX write SetResolutionX;
Columns of the terrain grid. Larger values create more vertices.
See also: ResolutionY, Resolution, SetXYResolution
property ResolutionY: Integer read GetResolutionY write SetResolutionY;
Rows of the terrain grid. Larger values create more vertices.
See also: ResolutionX, Resolution, SetXYResolution
property Resolution: TPoint read GetResolution write SetResolution;
Gets/sets both X and Y resolution simultaneously.
Storage: Not stored (use ResolutionX/ResolutionY in IDE)
property HeightMap: TBitmap read FHeightMap write SetHeightMap;
Heightmap bitmap used to compute Y-value of each vertex. Grayscale images work best (uses luminance for color images).
Triggers: Automatically rebuilds terrain when changed
property Smoothing: Integer read FSmoothing write SetSmoothing;
Number of smoothing iterations applied to heightmap before generating vertices. Range: 0-20.
Default: 0 (no smoothing)
Use case: Smooth low-resolution heightmaps when upscaling to higher terrain resolution
property ShowVertices: Boolean read FShowVertices write FShowVertices;
Displays vertices as dots after rendering (debug only).
Warning: Only works when StaticBuffering = False. Significantly reduces performance.
property ShowGrid: Boolean read FShowGrid write FShowGrid;
Displays polygon grid as lines after rendering (debug only).
Warning: Only works when StaticBuffering = False. Significantly reduces performance.
property VerticeColor: TAlphaColor read GetVerticeColor write SetVerticeColor;
Color for vertices and grid lines when debug visualization is enabled.
Default: Yellow (TAlphaColorRec.Yellow)
property StaticBuffering: Boolean read FStaticBuffering write SetStaticBuffering;
When enabled, vertex data is uploaded to GPU memory and local data is cleared.
Default: True
Benefits: Faster rendering, lower memory usage Drawbacks: Cannot show grid/vertices, cannot use Decimate() after rebuild
property AutoDecimate: Boolean read FAutoDecimate write SetAutoDecimate;
Automatically reduce vertex data during terrain rebuild.
Default: False
property HeightScale: Single read GetHeightScale write SetHeightScale; deprecated;
Deprecated: Use the Height property instead for Y-axis scaling.
procedure SetXYResolution(const X, Y: Integer); virtual;
Sets resolution for both axes in one call.
Parameters:
X - Column count (ResolutionX)Y - Row count (ResolutionY)Recommended values: 16, 32, 64, 128, 256, 512, 1024, 2048
Example:
LTerrain.SetXYResolution(256, 256);
procedure RebuildTerrain(const AStaticBuffering: Boolean = true;
const ADecimate: Boolean = false); virtual;
Clears previous terrain and rebuilds from current heightmap and settings.
Parameters:
AStaticBuffering - Upload to GPU and clear local dataADecimate - Automatically decimate mesh with default parametersExample:
// Standard rebuild with GPU buffering
LTerrain.RebuildTerrain(True, False);
// Rebuild with automatic decimation
LTerrain.RebuildTerrain(True, True);
// Keep data in memory for manual decimation
LTerrain.RebuildTerrain(False, False);
procedure RandomTerrain(const AAlgorithm: TRandomTerrainAlgorithmType;
const AStaticBuffering: Boolean = true;
const ADecimate: Boolean = false); overload;
Builds heightmap using specified procedural algorithm type with default parameters.
Parameters:
AAlgorithm - Algorithm type (Hill, DiamondSquare, Mandelbrot, PerlinNoise, Plateau, Brownian, Planar)AStaticBuffering - Upload to GPUADecimate - Auto-decimateExample:
LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.PerlinNoise);
See also: Gorilla.Terrain.Algorithm
procedure RandomTerrain(const AAlgorithm: TRandomTerrainAlgorithm;
const AStaticBuffering: Boolean = true;
const ADecimate: Boolean = false); overload;
Builds heightmap using configured algorithm instance.
Parameters:
AAlgorithm - Configured algorithm instanceAStaticBuffering - Upload to GPUADecimate - Auto-decimateExample:
var
LAlg: TPerlinNoiseTerrain;
begin
LAlg := TPerlinNoiseTerrain.Create;
try
LAlg.Size := 8;
LAlg.Intensity := 0.5;
LAlg.Interpolation := TPerlinNoiseInterpolation.Cosine;
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
See also: Gorilla.Terrain.Algorithm
procedure Decimate(const ARatio: Single = 0.2;
const AAgression: Single = 3.0;
const ATolerance: Single = 0.0001); virtual;
Reduces terrain mesh complexity using simplification algorithm.
Parameters:
ARatio - Target reduction ratio (0.2 = reduce to 20% of original)AAgression - How aggressively to remove vertices (higher = more reduction)ATolerance - Minimum error threshold for vertex removalRemarks: Terrain must have StaticBuffering = False with mesh data in memory.
Workflow:
LTerrain.RebuildTerrain(False, False); // Keep in memory
LTerrain.Decimate(0.3, 4.0, 0.0001);
LTerrain.StaticBuffering := True; // Upload to GPU
procedure BeginUpdate; override;
procedure EndUpdate; override;
Batch multiple property changes to rebuild terrain only once.
Example:
LTerrain.BeginUpdate;
try
LTerrain.Width := 200;
LTerrain.Depth := 200;
LTerrain.Resolution := Point(512, 512);
LTerrain.Smoothing := 5;
finally
LTerrain.EndUpdate; // Rebuilds once
end;
function GetMeshMatrix: TMatrix3D; override;
Returns the mesh transformation matrix for the terrain vertices.
Returns: 4×4 transformation matrix
function GetBodySize: TPoint3D; override;
Returns terrain dimensions.
Returns: TPoint3D with Width, Height, Depth
procedure LoadFromDefinition(const ADef: TCustomDef); override;
procedure StoreToDefinition(const ADef: TCustomDef); override;
Load/save terrain configuration from/to definition objects.
procedure Resize3D; override;
Called when terrain is resized. Triggers terrain rebuild.
var
LTerrain: TGorillaTerrain;
LHeightMap: TBitmap;
begin
LTerrain := TGorillaTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Width := 100;
LTerrain.Height := 20;
LTerrain.Depth := 100;
LTerrain.SetXYResolution(256, 256);
LTerrain.HeightMap.LoadFromFile('terrain.png');
end;
var
LTerrain: TGorillaTerrain;
begin
LTerrain := TGorillaTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.BeginUpdate;
try
LTerrain.Width := 200;
LTerrain.Height := 40;
LTerrain.Depth := 200;
LTerrain.SetXYResolution(512, 512);
LTerrain.HeightMap := MyHeightMap;
LTerrain.Smoothing := 5;
finally
LTerrain.EndUpdate;
end;
// Optimize with decimation
LTerrain.StaticBuffering := False;
LTerrain.Decimate(0.3, 3.5, 0.0001); // Reduce to 30%
LTerrain.StaticBuffering := True;
end;
// Enable for debugging (disable StaticBuffering first)
LTerrain.StaticBuffering := False;
LTerrain.RebuildTerrain(False);
LTerrain.ShowGrid := True;
LTerrain.ShowVertices := True;
LTerrain.VerticeColor := TAlphaColorRec.Yellow;
Procedural terrain generation algorithms for creating realistic landscapes without heightmap images.
Unit: Gorilla.Terrain.Algorithm
const
GORILLA_TERRAIN_SMOOTHING_MIN = 0;
GORILLA_TERRAIN_SMOOTHING_MAX = 20;
Valid range for terrain smoothing iterations.
type
TRandomTerrainAlgorithmType = (Hill, DiamondSquare, Mandelbrot,
PerlinNoise, Plateau, Brownian, Planar);
Enumeration of built-in procedural terrain algorithms.
Values:
Hill - Smooth rolling hillsDiamondSquare - Realistic peaks and valleysMandelbrot - Fractal pattern terrainPerlinNoise - Smooth natural terrain with noisePlateau - Flat elevated plateausBrownian - Particle-based simulationPlanar - Completely flat terraintype
TPerlinNoiseInterpolation = (Linear, Cosine, Cubic);
Interpolation methods for Perlin noise terrain.
Values:
Linear - Fast, sharp edgesCosine - Smooth, natural (recommended)Cubic - Very smooth, slowerBase class for procedural terrain algorithms.
Inheritance: TObject → TRandomTerrainAlgorithm
property Size: Integer read FSize write FSize;
Grid size parameter used during computation. Actual size is typically (2^Size + 1).
Example: Size = 9 produces 513×513 grid
function GetHeightMap: TBitmap; virtual;
Generates and returns heightmap bitmap from internal data array.
Returns: TBitmap with grayscale height data (0=black/low, 255=white/high)
Remarks: Called automatically by TGorillaTerrain.RandomTerrain()
Extend this class to create custom terrain algorithms:
type
TMyCustomTerrain = class(TRandomTerrainAlgorithm)
protected
procedure Generate;
public
function GetHeightMap: TBitmap; override;
end;
procedure TMyCustomTerrain.Generate;
var
x, y: Integer;
begin
FWidth := 513;
FHeight := 513;
SetLength(FData, FWidth);
for x := 0 to FWidth - 1 do
begin
SetLength(FData[x], FHeight);
for y := 0 to FHeight - 1 do
FData[x][y] := YourHeightFunction(x, y); // 0.0 to 1.0
end;
end;
function TMyCustomTerrain.GetHeightMap: TBitmap;
begin
Generate;
Result := inherited GetHeightMap;
end;
Generates smooth procedural hills using radius-based height calculations.
Inheritance: TRandomTerrainAlgorithm → THillRandomTerrain
property Hills: Integer read FHills write FHills;
Number of hills to generate.
Default: 20
property MinRadius: Integer read FMinRadius write FMinRadius;
Minimum radius for generated hills.
Default: 10
property MaxRadius: Integer read FMaxRadius write FMaxRadius;
Maximum radius for generated hills. Algorithm interpolates between min and max.
Default: 100
var
LAlg: THillRandomTerrain;
begin
LAlg := THillRandomTerrain.Create;
try
LAlg.Size := 9;
LAlg.Hills := 30;
LAlg.MinRadius := 20;
LAlg.MaxRadius := 150;
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
Popular algorithm for realistic random terrain with peaks and valleys.
Inheritance: TRandomTerrainAlgorithm → TDiamondSquareTerrain
property MSeed: Integer read FMSeed write FMSeed;
Seed value for random number generation.
Default: 1000
Range: Affects randomness range (0 to MSeed)
var
LAlg: TDiamondSquareTerrain;
begin
LAlg := TDiamondSquareTerrain.Create;
try
LAlg.Size := 9;
LAlg.MSeed := 2000; // More variation
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
Generates the Mandelbrot fractal set as terrain.
Inheritance: TRandomTerrainAlgorithm → TMandelbrotTerrain
Remarks: Produces fixed pattern (no randomness), useful as base for further processing.
LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Mandelbrot);
Base class for algorithms combining diamond-square with other techniques.
Inheritance: TRandomTerrainAlgorithm → TDiamondSquareBasedTerrain
property MSeed: Integer read FMSeed write FMSeed;
Random seed value.
Default: 1000
property DiamondSquareFactor: Single read FDiamondSquareFactor write FDiamondSquareFactor;
Multiplication factor for diamond-square contribution.
Default: 1.0
Range: 0.0 = no diamond-square, higher = more influence
property DiamondSquareEnabled: Boolean read FDiamondSquareEnabled write FDiamondSquareEnabled;
Enable/disable diamond-square processing.
Default: True
Generates smooth terrain using Perlin noise with configurable interpolation.
Inheritance: TDiamondSquareBasedTerrain → TPerlinNoiseTerrain
property Intensity: Single read FIntensity write FIntensity;
Controls height intensity of noise. Higher = taller peaks.
Default: 0.25
property Interpolation: TPerlinNoiseInterpolation read FInterpolation write FInterpolation;
Interpolation method for smoothing.
Values:
TPerlinNoiseInterpolation.Linear - Fast, sharpTPerlinNoiseInterpolation.Cosine - Smooth, natural (default)TPerlinNoiseInterpolation.Cubic - Very smooth, slowerDefault: Cosine
var
LAlg: TPerlinNoiseTerrain;
begin
LAlg := TPerlinNoiseTerrain.Create;
try
LAlg.Size := 8;
LAlg.Intensity := 0.4;
LAlg.Interpolation := TPerlinNoiseInterpolation.Cosine;
LAlg.DiamondSquareFactor := 0.6;
LAlg.DiamondSquareEnabled := True;
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
Creates high flat plateaus surrounded by lower terrain.
Inheritance: TDiamondSquareTerrain → TPlateauTerrain
property Plateaus: Integer read FPlateaus write FPlateaus;
Number of plateaus to generate. May overlap due to random placement.
Default: 3
property MinSize: Integer read FMinSize write FMinSize;
Minimum plateau radius in pixels.
Default: 50
property MaxSize: Integer read FMaxSize write FMaxSize;
Maximum plateau radius in pixels.
Default: 250
property MinHeight: Single read FMinHeight write FMinHeight;
Minimum height factor for plateaus.
Default: 0.25
Range: 0.0 to 1.0
property MaxHeight: Single read FMaxHeight write FMaxHeight;
Maximum height factor for plateaus.
Default: 1.0
Range: 0.0 to 1.0
property Inverted: Boolean read FInverted write FInverted;
When True, creates flat lowlands instead of plateaus.
Default: False
var
LAlg: TPlateauTerrain;
begin
LAlg := TPlateauTerrain.Create;
try
LAlg.Size := 9;
LAlg.Plateaus := 5;
LAlg.MinSize := 80;
LAlg.MaxSize := 300;
LAlg.MinHeight := 0.5;
LAlg.MaxHeight := 0.9;
LAlg.Inverted := False;
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
Generates terrain using Brownian motion particle simulation.
Inheritance: TDiamondSquareBasedTerrain → TBrownianTerrain
property Particles: Integer read FParticles write FParticles;
Number of particles for simulation. More = more detail but slower.
Default: 3000
property MinHeight: Single read FMinHeight write FMinHeight;
Minimum height factor for computed peaks.
Default: 0.01
property MaxHeight: Single read FMaxHeight write FMaxHeight;
Maximum height factor for computed peaks.
Default: 0.05
var
LAlg: TBrownianTerrain;
begin
LAlg := TBrownianTerrain.Create;
try
LAlg.Size := 9;
LAlg.Particles := 5000;
LAlg.MinHeight := 0.02;
LAlg.MaxHeight := 0.08;
LAlg.DiamondSquareFactor := 0.3;
LTerrain.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
Generates completely flat terrain.
Inheritance: TRandomTerrainAlgorithm → TPlanarTerrain
Remarks: Useful as starting point for custom terrain modification. Generates 32×32 grid by default.
LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Planar);
| Algorithm | Characteristics | Best For | Performance |
|---|---|---|---|
| Hill | Smooth, rounded hills | Gentle landscapes, valleys | Fast |
| DiamondSquare | Realistic peaks and valleys | General terrain, mountains | Medium |
| Mandelbrot | Fixed fractal pattern | Artistic, alien landscapes | Fast |
| PerlinNoise | Natural, organic smoothness | Realistic terrain, rolling hills | Medium |
| Plateau | Flat elevated areas | Mesa terrain, plateaus | Medium |
| Brownian | Particle-based randomness | Rough, chaotic terrain | Slow |
| Planar | Completely flat | Testing, custom base | Very Fast |
Level-of-detail terrain with dynamic mesh optimization.
Unit: Gorilla.Terrain.CVLOD
Status: Experimental - clustering system not fully implemented
TGorillaCVLODTerrain provides level-of-detail optimization for large terrains by adjusting mesh density based on distance from camera. This reduces vertex count while maintaining visual quality.
Current Implementation:
CurrentLOD property works welltype
TTerrainCluster = record
GridX, GridY: Integer;
Size: Integer;
LODLevel: Integer;
DistanceToCamera: Single;
StartIndex: Integer;
EndIndex: Integer;
IsDirty: Boolean;
end;
Represents a quad cluster in the LOD terrain system.
Fields:
GridX, GridY - Position in cluster gridSize - Size in verticesLODLevel - Current detail level (0 = highest)DistanceToCamera - Cached distance for sortingStartIndex, EndIndex - Index range in mesh bufferIsDirty - Needs regeneration flagManages asynchronous mesh updates for the LOD terrain.
Status: Not fully implemented. Async updates currently disabled.
Level-of-detail terrain with dynamic mesh optimization.
Inheritance: TGorillaTerrain → TGorillaCVLODTerrain
property Camera: TCamera read FCamera write SetCamera;
Camera reference for distance-based LOD calculations.
Required: Must be set for automatic LOD updates (clustering mode)
Note: Not required for simple LOD mode using CurrentLOD
property CurrentLOD: Integer read FCurrentLOD write SetCurrentLOD default 0;
Current LOD level for entire terrain (simple mode without clustering).
Range: 0 (highest detail) to LODLevels-1 (lowest detail)
Default: 0
LOD to Resolution Mapping:
Example:
// Test different detail levels
LLODTerrain.CurrentLOD := 0; // Highest
LLODTerrain.RebuildTerrain;
LLODTerrain.CurrentLOD := 2; // Quarter resolution
LLODTerrain.RebuildTerrain;
property LODLevels: Integer read FLODLevels write SetLODLevels default 4;
Number of detail levels.
Range: 1 to 8
Default: 4
property ClusterSize: Integer read FClusterSize write SetClusterSize default 32;
Size of each cluster in vertices (clustering mode only).
Range: 8 to 128
Default: 32
Trade-off: Smaller = more granular LOD but more overhead
Note: Only used in experimental clustering mode
property AsyncUpdate: Boolean read FAsyncUpdate write SetAsyncUpdate default false;
Enable asynchronous mesh updates on background thread.
Status: Not fully implemented, keep disabled
Default: False
property CameraMovementThreshold: Single read FCameraMovementThreshold write FCameraMovementThreshold;
Minimum camera movement (units) to trigger LOD update (clustering mode).
Default: 5.0
Trade-off: Lower = smoother transitions, higher CPU usage
property UpdateInterval: Integer read FUpdateInterval write FUpdateInterval default 100;
Minimum time between LOD updates in milliseconds (clustering mode).
Default: 100ms
Purpose: Prevents excessive updates during rapid camera movement
procedure RebuildTerrain(const AStaticBuffering: Boolean = true;
const ADecimate: Boolean = false); override;
Overridden to generate terrain at specified CurrentLOD level.
Behavior:
CurrentLOD value to determine mesh densityExample:
LLODTerrain.CurrentLOD := 1; // Half resolution
LLODTerrain.RebuildTerrain;
procedure ForceUpdateLOD;
Immediately updates all clusters based on current camera position (clustering mode).
Note: Only useful in clustering mode (experimental)
procedure SetCustomLODDistances(const ADistances: array of Single);
Sets custom distance thresholds for each LOD level (clustering mode).
Parameters:
ADistances - Array of distances (length must equal LODLevels)Example:
LLODTerrain.SetCustomLODDistances([10.0, 30.0, 100.0, 300.0]);
Note: Only used in clustering mode (experimental)
procedure GetLODStatistics(out ATotalVertices, ATotalIndices: Integer;
out ALODDistribution: TArray<Integer>);
Returns current LOD statistics.
Parameters:
ATotalVertices - Total vertex count (output)ATotalIndices - Total index count (output)ALODDistribution - Clusters per LOD level (output)Example:
var
LVerts, LIndices: Integer;
LDist: TArray<Integer>;
begin
LLODTerrain.GetLODStatistics(LVerts, LIndices, LDist);
ShowMessage(Format('Vertices: %d, Indices: %d', [LVerts, LIndices]));
end;
Use CurrentLOD property to manually control detail level:
var
LTerrain: TGorillaCVLODTerrain;
begin
LTerrain := TGorillaCVLODTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Width := 200;
LTerrain.Height := 40;
LTerrain.Depth := 200;
LTerrain.SetXYResolution(512, 512);
LTerrain.HeightMap := MyHeightMap;
// Set LOD level manually
LTerrain.CurrentLOD := 0; // Full detail when close
LTerrain.RebuildTerrain;
end;
When to change LOD:
procedure TForm1.UpdateTerrainLOD(ATerrain: TGorillaCVLODTerrain; ACamera: TCamera);
var
LDistance: Single;
LNewLOD: Integer;
begin
// Calculate distance from camera to terrain
LDistance := ATerrain.AbsolutePosition.Distance(ACamera.AbsolutePosition);
// Determine LOD level
if LDistance < 50 then
LNewLOD := 0 // Full detail
else if LDistance < 150 then
LNewLOD := 1 // Half detail
else if LDistance < 400 then
LNewLOD := 2 // Quarter detail
else
LNewLOD := 3; // Eighth detail
// Update if changed
if ATerrain.CurrentLOD <> LNewLOD then
begin
ATerrain.CurrentLOD := LNewLOD;
ATerrain.RebuildTerrain;
end;
end;
type
TTerrainTile = record
Terrain: TGorillaCVLODTerrain;
Position: TPoint3D;
end;
var
FTiles: array of TTerrainTile;
procedure UpdateAllTerrainLODs(ACamera: TCamera);
var
i: Integer;
LDistance: Single;
LLODLevel: Integer;
begin
for i := 0 to High(FTiles) do
begin
LDistance := FTiles[i].Position.Distance(ACamera.AbsolutePosition);
// Calculate appropriate LOD
LLODLevel := Trunc(LDistance / 100); // Simple distance-based
LLODLevel := Min(LLODLevel, 3); // Clamp to max LOD
if FTiles[i].Terrain.CurrentLOD <> LLODLevel then
begin
FTiles[i].Terrain.CurrentLOD := LLODLevel;
FTiles[i].Terrain.RebuildTerrain;
end;
end;
end;
For a 512×512 terrain:
| LOD | Resolution | Vertices | Triangles | Reduction |
|---|---|---|---|---|
| 0 | 512×512 | 263,169 | 524,288 | 0% |
| 1 | 256×256 | 66,049 | 131,072 | 75% |
| 2 | 128×128 | 16,641 | 32,768 | 93% |
| 3 | 64×64 | 4,225 | 8,192 | 98% |
Benefits:
Costs:
LOD changes can cause visible "popping". Mitigation strategies:
Distance Fog:
// Use fog to hide distant terrain details
GorillaViewport1.FogEnabled := True;
GorillaViewport1.FogDistance := 300;
GorillaViewport1.FogColor := TAlphaColorRec.Skyblue;
Hysteresis:
const
LOD_THRESHOLDS_DECREASE = [0, 40, 120, 350]; // Going to lower detail
LOD_THRESHOLDS_INCREASE = [0, 60, 180, 450]; // Going to higher detail
var
LLastLOD: Integer = 0;
procedure UpdateLODWithHysteresis(ADistance: Single);
var
LNewLOD: Integer;
LThresholds: array[0..3] of Single;
begin
// Use different thresholds based on current LOD direction
if LDistance > FPreviousDistance then
LThresholds := LOD_THRESHOLDS_DECREASE // Moving away
else
LThresholds := LOD_THRESHOLDS_INCREASE; // Moving closer
// Calculate LOD (simplified)
LNewLOD := CalculateLOD(ADistance, LThresholds);
if LNewLOD <> LLastLOD then
begin
LTerrain.CurrentLOD := LNewLOD;
LTerrain.RebuildTerrain;
LLastLOD := LNewLOD;
end;
FPreviousDistance := LDistance;
end;
Morphing (Advanced): Blend between LOD levels in vertex shader (not built-in, requires custom shader).
The clustering system divides terrain into chunks with independent LOD levels.
Status: Not recommended for production use. Has known issues:
If you want to experiment:
var
LTerrain: TGorillaCVLODTerrain;
begin
LTerrain := TGorillaCVLODTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Camera := Camera1; // Required for clustering
LTerrain.Width := 500;
LTerrain.Height := 50;
LTerrain.Depth := 500;
LTerrain.SetXYResolution(256, 256);
// Clustering configuration
LTerrain.LODLevels := 4;
LTerrain.ClusterSize := 32;
LTerrain.CameraMovementThreshold := 5.0;
LTerrain.UpdateInterval := 100;
LTerrain.AsyncUpdate := False; // Keep disabled
LTerrain.RebuildTerrain;
LTerrain.ForceUpdateLOD; // Update clusters
end;
CurrentLOD property is stable and effectiveSpherical terrain component for planetary surfaces.
Unit: Gorilla.Terrain.Sphere
Spherical terrain component that deforms a sphere surface using heightmaps or procedural algorithms.
Inheritance: TGorillaMesh → TGorillaSphereTerrain
Platforms: All Gorilla platforms
TGorillaSphereTerrain creates planetary terrain by:
This is ideal for creating planets, moons, asteroids, and other spherical celestial bodies.
constructor Create(AOwner: TComponent); override;
Creates a sphere terrain instance with default settings.
destructor Destroy; override;
Frees resources.
procedure AfterConstruction; override;
Initializes default values:
All properties from TGorillaTerrain are available with these differences:
property HeightScale: Single read FHeightScale write SetHeightScale;
Multiplier for height deformation from sphere surface.
Default: 0.1
Range: 0.0 (no deformation) to higher values
Note: Unlike planar terrain, this property is not deprecated for sphere terrain.
Behavior:
property ResolutionX: Integer read GetResolutionX write SetResolutionX;
property ResolutionY: Integer read GetResolutionY write SetResolutionY;
For sphere terrain:
Default: 512×512
Recommended: Higher values for larger spheres, lower for small objects
Same methods as TGorillaTerrain:
SetXYResolution(X, Y: Integer)RebuildTerrain(AStaticBuffering, ADecimate: Boolean)RandomTerrain(...)Decimate(...)BeginUpdate / EndUpdateInternally uses TGorillaTerrainHelper.BuildSphereTerrainFromHeightMap() instead of planar method.
var
LPlanet: TGorillaSphereTerrain;
LHeightMap: TBitmap;
begin
LPlanet := TGorillaSphereTerrain.Create(Self);
LPlanet.Parent := GorillaViewport1;
// Configure sphere
LPlanet.Width := 50; // Radius in all directions
LPlanet.Height := 50;
LPlanet.Depth := 50;
LPlanet.SetXYResolution(512, 512);
LPlanet.HeightScale := 0.15; // 15% deformation
// Load planet heightmap
LHeightMap := TBitmap.Create;
try
LHeightMap.LoadFromFile('mars_heightmap.png');
LPlanet.HeightMap := LHeightMap;
LPlanet.RebuildTerrain;
finally
LHeightMap.Free;
end;
end;
var
LMoon: TGorillaSphereTerrain;
LAlg: TPerlinNoiseTerrain;
begin
LMoon := TGorillaSphereTerrain.Create(Self);
LMoon.Parent := GorillaViewport1;
LMoon.Width := 30;
LMoon.Height := 30;
LMoon.Depth := 30;
LMoon.SetXYResolution(256, 256);
LMoon.HeightScale := 0.08;
// Generate procedural surface
LAlg := TPerlinNoiseTerrain.Create;
try
LAlg.Size := 8;
LAlg.Intensity := 0.3;
LAlg.Interpolation := TPerlinNoiseInterpolation.Cosine;
LMoon.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
var
LAsteroid: TGorillaSphereTerrain;
LAlg: TPlateauTerrain;
begin
LAsteroid := TGorillaSphereTerrain.Create(Self);
LAsteroid.Parent := GorillaViewport1;
LAsteroid.Width := 10;
LAsteroid.Height := 10;
LAsteroid.Depth := 10;
LAsteroid.SetXYResolution(128, 128);
LAsteroid.HeightScale := 0.2;
// Use inverted plateaus to create craters
LAlg := TPlateauTerrain.Create;
try
LAlg.Size := 7;
LAlg.Plateaus := 15;
LAlg.MinSize := 10;
LAlg.MaxSize := 50;
LAlg.MinHeight := 0.3;
LAlg.MaxHeight := 0.8;
LAlg.Inverted := True; // Create indentations (craters)
LAsteroid.RandomTerrain(LAlg);
finally
LAlg.Free;
end;
end;
procedure CreateDetailedPlanet(APlanet: TGorillaSphereTerrain);
var
LBase, LDetail: TBitmap;
LCombined: TBitmap;
begin
LBase := TBitmap.Create;
LDetail := TBitmap.Create;
LCombined := TBitmap.Create;
try
// Load base terrain (large features)
LBase.LoadFromFile('planet_base.png');
// Load detail map (small features)
LDetail.LoadFromFile('planet_detail.png');
// Combine with different intensities
CombineHeightMaps(LBase, LDetail, LCombined, 0.7, 0.3);
APlanet.BeginUpdate;
try
APlanet.SetXYResolution(512, 512);
APlanet.HeightScale := 0.12;
APlanet.Smoothing := 2;
APlanet.HeightMap := LCombined;
finally
APlanet.EndUpdate;
end;
finally
LBase.Free;
LDetail.Free;
LCombined.Free;
end;
end;
var
LEarth: TGorillaSphereTerrain;
begin
LEarth := TGorillaSphereTerrain.Create(Self);
LEarth.Parent := GorillaViewport1;
LEarth.BeginUpdate;
try
LEarth.Width := 100;
LEarth.Height := 100;
LEarth.Depth := 100;
LEarth.SetXYResolution(1024, 1024); // High detail
LEarth.HeightScale := 0.05; // Subtle terrain
LEarth.HeightMap := EarthHeightMap;
finally
LEarth.EndUpdate;
end;
// Optimize with decimation
LEarth.StaticBuffering := False;
LEarth.Decimate(0.4, 3.0, 0.0001); // Reduce to 40%
LEarth.StaticBuffering := True;
end;
Sphere terrain uses UV mapping, so heightmaps should be in equirectangular projection (also called lat/long projection):
0° 180° 360°
┌─────────────────────────────────┐ 90°N
│ North Pole │
│ │
│ │ 0° (Equator)
│ │
│ South Pole │
└─────────────────────────────────┘ 90°S
Creating Equirectangular Maps:
U (horizontal): 0.0 (left) to 1.0 (right) → Longitude (0° to 360°)
V (vertical): 0.0 (top) to 1.0 (bottom) → Latitude (90°N to 90°S)
| HeightScale | Effect | Use Case |
|---|---|---|
| 0.01 - 0.05 | Subtle | Earth-like planets |
| 0.05 - 0.15 | Moderate | Rocky planets, moons |
| 0.15 - 0.30 | Dramatic | Asteroids, extreme terrain |
| 0.30+ | Extreme | Artistic/alien worlds |
Sphere terrain requires more vertices than equivalent planar terrain:
| Resolution | Vertices | Triangles | Memory |
|---|---|---|---|
| 128×128 | ~16,000 | ~32,000 | ~1.5 MB |
| 256×256 | ~66,000 | ~131,000 | ~6.3 MB |
| 512×512 | ~263,000 | ~524,000 | ~25 MB |
| 1024×1024 | ~1,050,000 | ~2,097,000 | ~100 MB |
For mobile devices:
If you see a seam where longitude 0° meets 360°:
// Ensure heightmap wraps correctly
// Left edge (0°) should match right edge (360°)
Most procedural algorithms handle this automatically.
Vertices bunch up at poles (90°N and 90°S). This is normal for UV-spheres.
Solutions:
Heightmap pixels stretch more at poles than equator.
Solutions:
Helper classes for terrain mesh generation.
Unit: Gorilla.Terrain.Utils
Static helper class for low-level terrain generation.
Usage: Called internally by terrain components. Advanced users can use these methods directly for custom terrain generation.
class procedure BuildTerrainFromHeightMap(
const AMeshData: TMeshData;
const ASize: TPoint3D;
const ASubDivWidth, ASubDivHeight: Integer;
const ATwoFace: Boolean;
const AHeightMap: TBitmap;
const AHeightScale: Single;
const ASmoothing: Integer);
Builds planar terrain mesh from heightmap.
Parameters:
AMeshData - Target mesh data for vertices/indicesASize - Terrain dimensions (Width, Height, Depth)ASubDivWidth - X-axis subdivisions (columns)ASubDivHeight - Z-axis subdivisions (rows)ATwoFace - Generate back faces (two-sided rendering)AHeightMap - Source heightmap bitmap (grayscale or color)AHeightScale - Y-axis multiplier for height valuesASmoothing - Smoothing iterations (0-20)Remarks:
Example:
var
LMeshData: TMeshData;
LHeightMap: TBitmap;
begin
LMeshData := TMeshData.Create;
LHeightMap := TBitmap.Create;
try
LHeightMap.LoadFromFile('heightmap.png');
TGorillaTerrainHelper.BuildTerrainFromHeightMap(
LMeshData,
Point3D(100, 20, 100), // Size
256, 256, // Resolution
False, // TwoFace
LHeightMap,
1.0, // HeightScale
5 // Smoothing
);
// Use LMeshData for custom rendering
finally
LHeightMap.Free;
LMeshData.Free;
end;
end;
class procedure BuildSphereTerrainFromHeightMap(
const AMeshData: TMeshData;
const ASubDivAxes, ASubDivHeight: Integer;
const ATwoFace: Boolean;
const AHeightMap: TBitmap;
const AHeightScale: Single;
const ASmoothing: Integer);
Builds spherical terrain mesh from heightmap.
Parameters:
AMeshData - Target mesh data for vertices/indicesASubDivAxes - Sphere axes subdivisions (longitude)ASubDivHeight - Height subdivisions (latitude)ATwoFace - Generate back facesAHeightMap - Source heightmap bitmapAHeightScale - Deformation scale from sphere surfaceASmoothing - Smoothing iterations (0-20)Remarks:
Example:
var
LMeshData: TMeshData;
LHeightMap: TBitmap;
begin
LMeshData := TMeshData.Create;
LHeightMap := TBitmap.Create;
try
LHeightMap.LoadFromFile('planet_heightmap.png');
TGorillaTerrainHelper.BuildSphereTerrainFromHeightMap(
LMeshData,
512, // Axes
512, // Height
False, // TwoFace
LHeightMap,
0.1, // HeightScale
3 // Smoothing
);
// Use LMeshData for custom planet rendering
finally
LHeightMap.Free;
LMeshData.Free;
end;
end;
The helper methods sample heightmap values using normalized coordinates:
// Normalized grid position (0..1)
LNormX := VertexX / SubdivisionsWidth;
LNormZ := VertexZ / SubdivisionsHeight;
// Map to heightmap pixel
LPixelX := Round(LNormX * HeightMap.Width);
LPixelY := Round(LNormZ * HeightMap.Height);
// Get height from pixel luminance
LHeight := PixelLuminance / 255.0;
When smoothing is enabled, a 3×3 blur kernel is applied:
1 2 1
2 4 2
1 2 1
Each smoothing iteration averages neighboring pixels weighted by this kernel.
Planar Terrain:
Spherical Terrain:
Both methods generate triangles with counter-clockwise winding:
v0---v1
| \ |
| \|
v2---v3
Triangle 1: v0, v2, v1
Triangle 2: v1, v2, v3
You can use these helpers for custom terrain systems:
type
TMyTerrainComponent = class(TCustomMesh3D)
private
procedure GenerateCustomTerrain;
end;
procedure TMyTerrainComponent.GenerateCustomTerrain;
var
LMeshData: TMeshData;
LHeightMap: TBitmap;
begin
LMeshData := GetMeshData();
if not Assigned(LMeshData) then Exit;
LHeightMap := GenerateProceduralHeightMap(); // Your method
try
TGorillaTerrainHelper.BuildTerrainFromHeightMap(
LMeshData,
Point3D(Width, Height, Depth),
FResolutionX, FResolutionY,
False,
LHeightMap,
1.0,
0
);
// Post-processing
ApplyCustomShading(LMeshData);
OptimizeMesh(LMeshData);
finally
LHeightMap.Free;
end;
end;
Combine multiple heightmaps:
procedure GenerateMultiLayerTerrain(AMeshData: TMeshData);
var
LBase, LDetail1, LDetail2: TBitmap;
LCombined: TBitmap;
begin
// Load separate heightmaps
LBase := LoadHeightMap('base_terrain.png');
LDetail1 := LoadHeightMap('detail_rocks.png');
LDetail2 := LoadHeightMap('detail_erosion.png');
try
// Combine heightmaps
LCombined := BlendHeightMaps([LBase, LDetail1, LDetail2],
[0.7, 0.2, 0.1]); // Weights
TGorillaTerrainHelper.BuildTerrainFromHeightMap(
AMeshData, TerrainSize, ResX, ResY, False,
LCombined, 1.0, 5
);
finally
LBase.Free;
LDetail1.Free;
LDetail2.Free;
LCombined.Free;
end;
end;
The helper methods allocate vertex and index buffers based on resolution:
Planar Terrain:
(SubDivWidth + 1) × (SubDivHeight + 1)SubDivWidth × SubDivHeight × 6Spherical Terrain:
(SubDivAxes + 1) × (SubDivHeight + 1)SubDivAxes × SubDivHeight × 6The Gorilla.Material.Water unit provides the water material system for Gorilla3D, implementing realistic water rendering through specialized shader programs. This unit includes the TGorillaWaterMaterialSource component and the internal TGorillaWaterMaterial class, which together create animated water surfaces with reflections, refractions, foam, depth effects, and interactive ripples.
The water material extends the default material system with specialized shader nodes:
TGorillaWaterMaterialSource (Component)
└─ TGorillaWaterMaterial (Internal Material)
├─ Vertex Shader (with displacement)
├─ Fragment Shader (water surface computation)
├─ Texture Pool (DUDV, foam, shore, specular, normal, displacement)
└─ Uniform Buffers (water parameters, ripples)
Primary water material source component for design-time and runtime configuration.
Inheritance: TGorillaDefaultMaterialSource → TGorillaWaterMaterialSource
Platforms: All Gorilla3D supported platforms
Version: Available since v0.8.3+
| Property | Type | Default | Description |
|---|---|---|---|
| WaveSpeed | Single | 1.0 | Wave animation speed multiplier. Higher values = faster wave movement over DUDV texture. |
| WaveSize | Single | 1.0 | Wave distortion amplitude. Higher values = stronger displacement effect. |
| Property | Type | Description |
|---|---|---|
| Diffuse | TAlphaColorF | Base water color (RGB + alpha transparency). Inherited from TGorillaDefaultMaterialSource. |
| Specular | TAlphaColorF | Specular highlight color. Inherited from TGorillaDefaultMaterialSource. |
| Ambient | TAlphaColorF | Ambient color contribution. Inherited from TGorillaDefaultMaterialSource. |
| Emissive | TAlphaColorF | Self-illumination color. Inherited from TGorillaDefaultMaterialSource. |
| Shininess | Single | Specular shininess exponent (higher = sharper highlights). Inherited from TGorillaDefaultMaterialSource. |
| DiffusePower | Single | Mix ratio between diffuse color and refraction channel. |
| Property | Type | Default | Description |
|---|---|---|---|
| FoamTexture | TBitmap | - | Foam overlay texture displayed on water surface. |
| FoamDirection | TPointF | (0, 0) | Foam movement direction vector (normalized). Stored as FoamDirectionVector in DFM. |
| FoamIntensity | Single | 0.0 | Foam color intensity multiplier (0.0-10.0). |
| Property | Type | Range | Description |
|---|---|---|---|
| ShoreTexture | TBitmap | - | Shore foam texture displayed at shallow water edges. |
| ShoreWidth | Single | 0.0001-100.0 | Shore effect range. Calculation: pow(water_depth, shore_width). |
| ShoreIntensity | Single | 0.0-10.0 | Shore foam brightness multiplier. |
| Property | Type | Range | Description |
|---|---|---|---|
| DepthIntensity | Single | 0.001-10.0 | Depth map influence on water transparency and blending. |
| Property | Type | Description |
|---|---|---|
| DisplacementMap | TBitmap | Height map texture for vertex displacement. |
| Displacement | TVector3D | Displacement direction vector (typically (0,1,0) for Y-axis). Stored as DisplacementVector in DFM. |
| DisplIntensity | Single | Displacement strength multiplier (0.0-100.0). |
| Property | Type | Description |
|---|---|---|
| DUDVTexture | TBitmap | DUDV displacement map (red/green channels for distortion). |
| NormalMap | TBitmap | Normal map for surface detail and lighting. |
| SpecularMap | TBitmap | Specular intensity map (controls highlight strength). |
| Property | Type | Range | Description |
|---|---|---|---|
| Reflections | Boolean | - | Enable reflection mapping. |
| ReflectionPass | TGorillaRenderPassController | - | Linked reflection render pass. |
| ReflectionPower | Single | 0.0-1.0 | Reflection intensity multiplier. |
| ReflCorrection | TVector3D | - | RGB color correction for reflection channel. Stored as ReflCorrectionVector in DFM. |
| Property | Type | Range | Description |
|---|---|---|---|
| Refractions | Boolean | - | Enable refraction mapping. |
| RefractionPass | TGorillaRenderPassController | - | Linked refraction render pass. |
| RefractionPower | Single | 0.0-1.0 | Refraction intensity multiplier. |
| RefrCorrection | TVector3D | - | RGB color correction for refraction channel. Stored as RefrCorrectionVector in DFM. |
| Property | Type | Description |
|---|---|---|
| RipplesActive | Boolean | Enable/disable ripple computation. |
| RippleAmplification | Single | Ripple height/amplitude. |
| RippleProximity | Single | Ripple width (basis value for ripple spread). |
| RippleDecay | Single | Ripple fade-out speed (0.0-1.0, higher = slower decay). |
| Property | Type | Description |
|---|---|---|
| OutputLayer | TWaterOutputLayer | Debug visualization mode (see TWaterOutputLayer enum). |
| Tonemapping | TGorillaTonemapping | Tonemapping operator. Inherited from TGorillaDefaultMaterialSource. |
| TonemappingExposure | Single | Tonemapping exposure value. Inherited from TGorillaDefaultMaterialSource. |
| Shadows | Boolean | Enable shadow reception. Inherited from TGorillaDefaultMaterialSource. |
| ShadowMethod | TGorillaShadowMethod | Shadow mapping method. Inherited from TGorillaDefaultMaterialSource. |
| DepthPass | TGorillaRenderPassController | Depth render pass (if not using refraction depth). Inherited from TGorillaDefaultMaterialSource. |
constructor Create(AOwner: TComponent); override;
Creates a new water material source instance.
Example:
var WaterMaterial := TGorillaWaterMaterialSource.Create(Self);
destructor Destroy(); override;
Destroys the water material source and releases resources.
procedure LoadFromDefinition(const ADef: TCustomDef); override;
Loads material configuration from definition file.
Parameters:
ADef - Definition data structureprocedure StoreToDefinition(const ADef: TCustomDef); override;
Stores material configuration to definition file.
Parameters:
ADef - Definition data structureprocedure AddRipple(APos: TVector3D); overload;
Adds a ripple at the specified 3D position. If the ripple list exceeds maximum capacity (32 ripples), the oldest ripple is removed.
Parameters:
APos - World-space position for the ripple center (TVector3D)Example:
WaterMaterial.AddRipple(Vector3D(10.0, 0.0, 5.0));
procedure AddRipple(APos: TPoint3D); overload;
Adds a ripple at the specified 3D position. Overload accepting TPoint3D.
Parameters:
APos - World-space position for the ripple center (TPoint3D)Example:
WaterMaterial.AddRipple(Point3D(10.0, 0.0, 5.0));
procedure AddRipples(const AArr: TArray<TVector3D>);
Adds multiple ripples from an array of positions. If the total exceeds maximum capacity, oldest ripples are removed.
Parameters:
AArr - Array of world-space ripple positionsExample:
var Positions: TArray<TVector3D>;
SetLength(Positions, 3);
Positions[0] := Vector3D(0, 0, 0);
Positions[1] := Vector3D(5, 0, 5);
Positions[2] := Vector3D(-5, 0, 5);
WaterMaterial.AddRipples(Positions);
procedure SetRipples(const AArr: TArray<TVector3D>);
Clears all existing ripples and sets new ripples from the provided array.
Parameters:
AArr - Array of world-space ripple positions (replaces all existing ripples)Example:
var NewRipples: TArray<TVector3D>;
SetLength(NewRipples, 2);
NewRipples[0] := Vector3D(0, 0, 0);
NewRipples[1] := Vector3D(10, 0, 0);
WaterMaterial.SetRipples(NewRipples);
procedure ClearRipples();
Removes all active ripples from the water surface.
Example:
WaterMaterial.ClearRipples();
Internal material class that performs shader compilation and rendering. Not directly instantiated by user code.
Inheritance: TGorillaDefaultMaterial → TGorillaWaterMaterial
| Property | Type | Description |
|---|---|---|
| WaveSpeed | Single | Wave animation speed (read/write). |
| WaveSize | Single | Wave distortion amplitude (read/write). |
| DiffusePower | Single | Diffuse/refraction mix ratio (read/write). |
| FoamDirection | TPointF | Foam movement direction (read/write). |
| FoamIntensity | Single | Foam brightness (read/write). |
| OutputLayer | TWaterOutputLayer | Debug output mode (read/write). |
| ReflCorrection | TVector3D | Reflection color correction (read/write). |
| RefrCorrection | TVector3D | Refraction color correction (read/write). |
| DepthIntensity | Single | Depth influence (read/write). |
| ShoreWidth | Single | Shore effect range (read/write). |
| ShoreIntensity | Single | Shore foam brightness (read/write). |
| DisplIntensity | Single | Displacement strength (read/write). |
| DUDVTexture | TTexture | DUDV texture reference (read/write). |
| FoamTexture | TTexture | Foam texture reference (read/write). |
| ShoreTexture | TTexture | Shore texture reference (read/write). |
| RipplesActive | Boolean | Ripple computation enabled (read/write). |
| RippleAmplification | Single | Ripple height (read/write). |
| RippleProximity | Single | Ripple width (read/write). |
| RippleDecay | Single | Ripple fade speed (read/write). |
constructor Create(const ASource: TGorillaDefaultMaterialSource); override;
Creates internal water material instance. Called automatically by TGorillaWaterMaterialSource.
destructor Destroy(); override;
Destroys material and releases GPU resources.
procedure AddRipple(APos: TVector3D); overload;
procedure AddRipple(APos: TPoint3D); overload;
procedure AddRipples(const AArr: TArray<TVector3D>);
procedure SetRipples(const AArr: TArray<TVector3D>);
procedure ClearRipples();
Ripple management methods (identical to TGorillaWaterMaterialSource methods).
Packed uniform buffer structure for water shader parameters (std140 layout).
Platform: {$IFDEF GL_ES_VERSION_3_0} and higher
TWaterParams = packed record
Time : Single; // Current animation time
WaveSize : Single; // Wave distortion strength
WaveSpeed : Single; // Wave animation speed
DiffusePower : Single; // Diffuse/refraction mix
ReflCorrection : TVector3D; // Reflection color correction (RGB)
RefrCorrection : TVector3D; // Refraction color correction (RGB)
FoamDirection : TPointF; // Foam movement direction
FoamIntensity : Single; // Foam brightness
OutputLayer : Single; // Debug output layer index
DepthIntensity : Single; // Depth influence factor
ShoreWidth : Single; // Shore effect range
ShoreIntensity : Single; // Shore foam brightness
DisplIntensity : Single; // Displacement strength
RippleCount : Single; // Number of active ripples
RippleAmplification : Single; // Ripple height
RippleProximity : Single; // Ripple width
RippleDecay : Single; // Ripple fade speed
Ripples : Array[0..31] of TVector3D; // Ripple positions (X, Y, Z, W=time)
end;
Memory Layout: Aligned to std140 specification for GPU uniform buffers.
Debug visualization modes for water shader output.
TWaterOutputLayer = (
wolAll, // Normal rendering (all layers combined)
wolDUDV, // DUDV displacement map only
wolNormal, // Normal map only
wolSpecular, // Specular highlights only
wolFoam, // Foam layer only
wolDepth, // Depth map visualization
wolRefraction, // Refraction pass only
wolReflection, // Reflection pass only
wolReflPlusRefr, // Reflection + refraction blend
wolTexCoords // Texture coordinates visualization
);
Usage:
WaterMaterial.OutputLayer := wolDepth; // Visualize depth map
WATER_TEX_DUDV = 0; // DUDV displacement texture
WATER_TEX_FOAM = 1; // Foam texture
WATER_TEX_SHORE = 2; // Shore foam texture
WATER_TEX_SPEC = 3; // Specular map
WATER_TEX_NRML = 4; // Normal map
WATER_TEX_DSPL = 5; // Displacement map
WATER_TEX_DPTH = 6; // Depth map (from pass)
WATER_TEX_REFR = 7; // Refraction texture
WATER_TEX_REFL = 8; // Reflection texture
WATER_TEX_ENVM = 7; // Environment map (cubemap)
MAX_RIPPLES = 32; // Maximum simultaneous ripples (platform-dependent)
Platform Notes:
GORILLA_WATER_EXTENSION_DEF = 'Water'; // Material extension name
The water shader implements a multi-stage rendering pipeline:
Vertex Shader:
Fragment Shader:
// Get distorted texture coordinates
vec4 getDistortedTexCoord(
in sampler2D p_Tex,
in vec2 p_OrigTexCoord,
in vec2 p_OrigTiling,
in float p_MoveFac,
in float p_Strength
);
// Compute depth from depth/refraction texture
float getDepth(in sampler2D tex, in WaterSurfaceInput p_Input);
// Get reflection color
vec4 getReflection(in sampler2D tex, in WaterSurfaceInput p_Input);
vec4 getReflection(in samplerCube tex, in WaterSurfaceInput p_Input); // Cubemap variant
// Get refraction color
vec4 getRefraction(in sampler2D tex, in WaterSurfaceInput p_Input);
vec4 getRefraction(in samplerCube tex, in WaterSurfaceInput p_Input); // Cubemap variant
// Main water surface computation
void WaterSurface(
in sampler2D depthTex,
in sampler2D reflTex,
in sampler2D refrTex,
in sampler2D dudvTex,
in sampler2D foamTex,
in sampler2D shoreTex,
in sampler2D normalMap,
in sampler2D specMap,
inout WaterSurfaceInput p_Input,
out WaterSurfaceOutput p_Output
);
var
WaterMaterial: TGorillaWaterMaterialSource;
begin
WaterMaterial := TGorillaWaterMaterialSource.Create(Self);
// Configure appearance
WaterMaterial.Diffuse := TAlphaColorF.Create(0.1, 0.3, 0.5, 0.8);
WaterMaterial.Specular := TAlphaColorF.Create(1.0, 1.0, 1.0, 1.0);
WaterMaterial.Shininess := 128.0;
// Load textures
WaterMaterial.DUDVTexture.LoadFromFile('water_dudv.png');
WaterMaterial.NormalMap.LoadFromFile('water_normal.png');
WaterMaterial.SpecularMap.LoadFromFile('water_spec.png');
// Configure waves
WaterMaterial.WaveSpeed := 1.0;
WaterMaterial.WaveSize := 1.2;
end;
var
WaterMaterial: TGorillaWaterMaterialSource;
ReflectionPass: TGorillaRenderPassReflection;
RefractionPass: TGorillaRenderPassRefraction;
begin
// Create render passes (see TGorillaRenderPassReflection/Refraction docs)
ReflectionPass := CreateReflectionPass();
RefractionPass := CreateRefractionPass();
WaterMaterial := TGorillaWaterMaterialSource.Create(Self);
// Enable reflection
WaterMaterial.Reflections := True;
WaterMaterial.ReflectionPass := ReflectionPass;
WaterMaterial.ReflectionPower := 0.6;
WaterMaterial.ReflCorrection := Vector3D(1.0, 1.0, 1.0);
// Enable refraction
WaterMaterial.Refractions := True;
WaterMaterial.RefractionPass := RefractionPass;
WaterMaterial.RefractionPower := 0.8;
WaterMaterial.RefrCorrection := Vector3D(1.0, 1.0, 1.05); // Slight blue tint
// Depth configuration
WaterMaterial.DepthIntensity := 1.0;
end;
WaterMaterial.FoamTexture.LoadFromFile('foam.png');
WaterMaterial.FoamDirection := PointF(0.5, 0.5);
WaterMaterial.FoamIntensity := 1.5;
WaterMaterial.ShoreTexture.LoadFromFile('shore_foam.png');
WaterMaterial.ShoreWidth := 3.0;
WaterMaterial.ShoreIntensity := 2.5;
// Enable ripples
WaterMaterial.RipplesActive := True;
WaterMaterial.RippleAmplification := 0.5;
WaterMaterial.RippleProximity := 2.0;
WaterMaterial.RippleDecay := 0.92;
// Add ripple on mouse click
procedure TForm1.DoOnViewportMouseUp(ASender : TObject; AButton : TMouseButton; AShift : TShiftState; X, Y : Single);
var LPt3D : TPoint3D;
begin
/// add a ripple by clicking with the left mouse button onto the water plane (Caution: HitTest needs to be activated)
if (ssLeft in fShiftState) then
begin
LPt3D := Viewport.ScreenToWorld(PointF(X, Y));
WaterMaterial.AddRipple(Point3D(LPt3D.X, LPt3D.Z, -LPt3D.Y));
end;
end;
WaterMaterial.DisplacementMap.LoadFromFile('water_height.png');
WaterMaterial.Displacement := Vector3D(0, 1, 0); // Y-axis displacement
WaterMaterial.DisplIntensity := 0.5;
// Adjust render pass planes for displacement offset
ReflectionPass.MirrorPosition.Point := TPoint3D(WaterPlane.AbsolutePosition) + Point3D(0, -WaterMaterial.DisplIntensity, 0);
RefractionPass.SurfacePosition.Point := TPoint3D(WaterPlane.AbsolutePosition) + Point3D(0, -WaterMaterial.DisplIntensity, 0);
// Visualize different shader layers
WaterMaterial.OutputLayer := wolDepth; // Show depth map
WaterMaterial.OutputLayer := wolReflection; // Show reflections only
WaterMaterial.OutputLayer := wolDUDV; // Show DUDV displacement
WaterMaterial.OutputLayer := wolAll; // Return to normal rendering
Render Pass Requirements: Water material REQUIRES both reflection and refraction passes. Water will appear black or incorrect without properly configured passes.
Plane Exclusion: The water mesh MUST be excluded from reflection and refraction passes using IgnoreControl() to prevent self-rendering artifacts.
Displacement Offset: When using displacement mapping, adjust reflection/refraction plane positions to compensate for vertex offset.
Ripple Limits: Maximum 32 simultaneous ripples on most platforms. Older platforms may have lower limits or no ripple support.
Uniform Buffers: On OpenGL ES 3.0+, water parameters use uniform buffer objects for efficiency.
Texture Requirements: Minimum required textures are DUDV and Normal maps. Other textures (specular, foam, shore, displacement) are optional.
Performance: Water rendering is shader-intensive. Use lower resolution render passes on mobile platforms.
Platform Differences: Some features (uniform buffers, ripple count) vary by platform and OpenGL version.