Generated on 2026-11-08 11:34:22
Bugfix: formats path delimiter fixes from "/" to "\" on windows platform
Bugfix: animation unification normalized of time span basis for a more stable look
Bugfix: FBX import of some models with animations leading to jittering animations due to duplicated interpolator import
Bugfix: FBX unit normalization
Bugfix: FBX emissive color strength not considered correctly
Bugfix: FBX import of some models with animations leading to jittering animations due to duplicated interpolator import
Bugfix: FBX import finds duplicated mesh and joint id's on certain models
Feature: glTF/GLB material variants extension implemented
Bugfix: glTF/GLB emission strength not considered correctly > DamagedHelmet display texture issue
Bugfix: gltf/glb memory leaks closed
Bugfix: ply triangulation of quad faces fixed
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?
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.
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.
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;
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)
Viewport.UseFixedFrameRate := True;
Viewport.FixedFrameRate := 60; // 60 FPS
When enabled, the viewport attempts to maintain a consistent frame rate. This is only available on Windows platforms.
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. 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.
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;
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;
// Get current FPS estimate
var CurrentFPS := Viewport.FPS;
Note: This measures Delphi rendering mechanism performance, not actual output FPS.
// Enable detailed diagnostics
Viewport.DiagnosticsActive := True;
// Access diagnostics data
var Diag := Viewport.Diagnostics;
ShowMessage(Format(
'FPS: %.2f, Draw Calls: %d, Objects: %d',
[Diag.AverageFramesPerSecond, Diag.DrawCalls, Diag.RenderedObjects]
));
Diagnostic information includes:
FireMonkey's TAnimation base class limits animation frame rates to 30 FPS. This is a FireMonkey limitation, not a Gorilla3D limitation.
Translucent rendering uses weighted color values requiring special GLSL calculations. The WBOIT algorithm provides order-independent transparency for correct rendering regardless of draw order.
ALLOW_FIXEDFRAMERATE_RENDERING)| Feature | Gorilla Materials | FMX Materials |
|---|---|---|
| Fog | ✓ Yes | ✗ No |
| Forward Renderer | ✓ Full Support | ○ Limited |
| Legacy Renderer | ○ Limited | ✓ Full Support |
| WBOIT Transparency | ✓ Yes | ○ Partial |
Renderers 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;
// Render at lower resolution for performance
procedure SetRenderScale(AViewport: TGorillaViewport; AScale: Single);
begin
if Assigned(AViewport.MainPassRenderer) then
begin
AViewport.MainPassRenderer.Scale := AScale; // 0.5 = half resolution
end;
end;
// 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.MSAA := TMSAASamples.None;
AViewport.FXAA := 2;
AViewport.EmissiveBlur := 0;
AViewport.GlobalIllumDetail := 0;
AViewport.FragmentDepthRendering := False;
end;
procedure ApplyMediumQuality(AViewport: TGorillaViewport);
begin
AViewport.MSAA := TMSAASamples.Samples2X;
AViewport.FXAA := 2;
AViewport.EmissiveBlur := 2;
AViewport.GlobalIllumDetail := 2;
AViewport.FragmentDepthRendering := True;
end;
procedure ApplyHighQuality(AViewport: TGorillaViewport);
begin
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.
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:
// 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;
// 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);
// 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
// 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);
Lighting 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 |
| 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 |
| glTF/GLB | 2.0 format only | ✓ Yes | ✗ 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 |
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;
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;
Use instancing to render the same model multiple times efficiently:
var
Mesh: TGorillaMesh;
Transform: TMatrix3D;
begin
Mesh := GorillaModel1.Meshes[0];
// Add instances
for var x := 0 to 9 do
for var z := 0 to 9 do
begin
Transform := TMatrix3D.CreateTranslation(Point3D(x * 2, 0, z * 2));
Mesh.Instances.AddInstance(Transform, False);
end;
end;
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.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;
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 files| 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 |
VertexPosition flag for balanced performance/memoryMaterials 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 provides two audio systems: a Legacy Audio Manager for simple sound playback using FMX's TMediaPlayer, and a modern Audio Manager (TGorillaAudioManager) with backends for FMOD and OpenAL, supporting 3D spatial audio, channels, DSP effects, and streaming.
| Feature | Legacy Audio Manager | Modern Audio Manager |
|---|---|---|
| Class | TGorillaLegacyAudioManager |
TGorillaAudioManager (abstract) |
| Backend | FMX TMediaPlayer |
FMOD or OpenAL |
| 3D Audio | No | Yes (FMOD) |
| DSP Effects | No | Yes (FMOD) |
| Streaming | No | Yes |
| Threading | Background thread | Configurable |
| Complexity | Simple | Advanced |
The legacy audio manager is a thread-based component that uses FMX's TMediaPlayer for each audio file. It's simple to use but not built for performance.
A global instance is available as AudioManager (from the Gorilla.Audio.Manager unit).
uses Gorilla.Audio.Manager;
// Cache audio files for faster playback
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();
// Play a cached sound
AudioManager.Play(1); // play once
AudioManager.Play(2, TGorillaAudioMode.Loop, 0.3); // loop at 30% volume
// Control playback
AudioManager.Pause(2); // pause/resume toggle
AudioManager.Stop(1); // stop
AudioManager.StopAll(); // stop all
AudioManager.PauseAll(); // pause all
The audio manager checks for finished audio files at regular intervals and restarts looped tracks automatically.
AudioManager.LoopCheckInterval := 100; // check every 100ms (default)
AudioManager.QueueTimeout := 250; // queue wait timeout in ms
AudioManager.Mute := True; // mute all
AudioManager.Mute := False; // unmute
The abstract TGorillaAudioManager class provides a more capable audio system with concrete implementations for FMOD and OpenAL.
FMOD provides professional-grade audio with 3D spatialization, DSP effects, reverb, and geometry-based occlusion.
Key units:
Gorilla.Audio.FMOD — Main FMOD wrapperGorilla.Audio.FMOD.System — FMOD system initializationGorilla.Audio.FMOD.Sound — Sound loading and playbackGorilla.Audio.FMOD.Channel — Audio channel managementGorilla.Audio.FMOD.ChannelGroup — Channel group managementGorilla.Audio.FMOD.DSP — Digital signal processing effectsGorilla.Audio.FMOD.Reverb3D — 3D reverb effectsGorilla.Audio.FMOD.Geometry — Geometry-based audio occlusionOpenAL provides a lighter-weight 3D audio option. Key units:
Gorilla.Audio.OpenAL — Main OpenAL wrapperGorilla.Audio.OpenAL.Loader — DLL loadingGorilla.Audio.OpenAL.API — Low-level API bindingsCodec support: MP3 (Gorilla.Audio.MP3.API), OGG Vorbis (Gorilla.Audio.OGG.API).
Using the modern audio manager:
var
AudioMgr: TGorillaAudioManager; // concrete FMOD or OpenAL instance
SoundItem: TGorillaSoundItem;
begin
// Load sound from file
SoundItem := AudioMgr.LoadSoundItemFromFile('sounds/explosion.wav');
// Load sound from stream
SoundItem := AudioMgr.LoadSoundItemFromStream(MyStream);
// Play
AudioMgr.PlaySound(SoundItem);
// or by index
AudioMgr.PlaySound(0);
// Control individual sound items
SoundItem.Play();
SoundItem.Pause();
SoundItem.Resume();
SoundItem.Stop();
// Check state
if SoundItem.IsPlaying then ...;
// Get playback info
var Pos := SoundItem.PlaybackPosition; // current position in ms
var Len := SoundItem.PlaybackLength; // total length in ms
// Stop all channels
AudioMgr.StopAllChannels();
// Update (call periodically for streaming)
AudioMgr.Update();
end;
With the FMOD backend, you can position sounds in 3D space relative to a listener:
// FMOD Geometry for audio occlusion
// Gorilla.Audio.FMOD.Geometry provides geometry-based audio
// where sound is occluded by walls and objects
// FMOD Reverb3D for spatial reverb zones
// Gorilla.Audio.FMOD.Reverb3D allows defining reverb zones in 3D space
| Platform | Legacy Audio | FMOD | OpenAL |
|---|---|---|---|
| Windows | Yes | Yes | Yes |
| macOS | Yes | Yes | — |
| iOS | Yes | Yes | — |
| Android | Yes | Yes (via JNI) | — |
| Linux | Limited | — | Yes |
empty.mp3 in the temp directory for TMediaPlayer initializationAndroid.JNI.FMOD)TMediaPlayer per sound — high memory usage for many filesBeginCaching()/EndCaching() when loading multiple files with the legacy managerUpdate() periodically on the modern audio manager for streaming supportAllowSleep and use reasonable LoopCheckInterval valuesThe 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 memoryGorilla3D 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.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 storage |
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
TGorillaTextureBitmap supports PNG-based texture compression for reducing memory when textures are stored (e.g., in asset packages):
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 |
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 |
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 creatingRender 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
ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;
Use Cases:
ReflectionPass.OverwriteViewportSize := False; // Use main viewport as base
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 0.5; // Half resolution
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
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.
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 | .usdz, .usdc |
Yes | Yes | — | — | Binary Crate + Archive |
| 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 | Notes |
|---|---|---|
| G3D | .g3d |
Full round-trip (materials, animation, skeleton) |
| OBJ | .obj |
Mesh + MTL materials |
| STL | .stl |
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.Format.GLTFAutodesk'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.OBJIndustry-standard CAD format with B-Spline surface tessellation.
Gorilla.Format.STEPPixar's scene description format.
.usdc) and Archive (.usdz) formats.usda) support currentlyGorilla.Format.USD| 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');
// 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');
// Export to OBJ
uses Gorilla.Exporter;
// Use the exporter for OBJ and STL export
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
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
Manager := TGorillaAnimationManager.Create(Self);
Manager.Mesh := GorillaModel1;
// Load animation from definition
Animation := TGorillaAnimation.CreateEx(Manager);
Animation.LoadFromAnimationDef(AnimationDef);
Manager.AddAnimation('Walk', Animation);
end;
// 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;
// Play next animation in sequence
Manager.PlayNextAnimation();
// Play previous animation
Manager.PlayPreviousAnimation();
// Get current animation
var CurrentAnim := Manager.Current;
if Assigned(CurrentAnim) then
begin
// Start animation
CurrentAnim.Start();
// Stop animation
CurrentAnim.Stop();
// Reset to first frame
CurrentAnim.Reset();
// Adjust playback speed (1.0 = normal, 2.0 = double speed)
CurrentAnim.SetSpeed(1.5);
// Check animation state
if CurrentAnim.IsRunning then
ShowMessage('Animation playing');
if CurrentAnim.IsPaused then
ShowMessage('Animation paused');
end;
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
]));
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
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: Use ForceStep() in rendering loops to avoid FMX timer jitter
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
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;
// Use ForceStep for smoother updates
TGorillaAnimationManager.ForceStep(0.01);
// Or adjust interpolation
Animation.Skeleton.Interpolation := TInterpolationType.Cubic;
// Adjust speed
Animation.SetSpeed(0.5); // Half speed
Animation.SetSpeed(2.0); // Double speed
// 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.
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;
// 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 timeY = current timeZ = previous frame timeW = delta timeYour custom shader must implement:
vec3 SurfaceShader(inout TLocals DATA)
| Method | Description |
|---|---|
ResetTime |
Resets the internal time counter |
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 packagesThe 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 boxesVersion: 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 neededGorilla3D 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
└─ TGorillaAnimation
└─ TSkeletonKeyAnimation
└─ TPropertyKeyAnimation (abstract base)
├─ TPoint3DKeyAnimation
├─ TVector3DKeyAnimation
├─ TQuaternion3DKeyAnimation
├─ TTransformationKeyAnimation
└─ TCoordinateKeyAnimation
Abstract base class for all keyframe-based animations in Gorilla3D.
Inheritance: TCustomPropertyAnimation → TPropertyKeyAnimation
Platforms: All Gorilla3D supported platforms
| 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). |
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;
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). |
| Property | Type | Default | Description |
|---|---|---|---|
| AutoRepaint | Boolean | True | Automatically call Repaint() after each ProcessAnimation(). |
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 - Speed multiplier (1.0 = normal, 2.0 = double speed, 0.5 = half speed)Example:
SkeletonAnim.SetSpeed(1.5); // 50% faster playback
procedure Start(); override;
procedure Stop(); override;
Start/stop all child animations synchronously.
procedure ProcessAnimationRemote(ATime, ADeltaTime: Single);
Manually process animation tick (for external control).
Parameters:
ATime - Current animation timeADeltaTime - Time delta since last tickprocedure 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). |
| FrameCount | Integer | Total number of frames (read-only). |
| FrameRate | Integer | Frames per second (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;
procedure Stop(); virtual;
procedure Reset(); virtual;
Control animation playback.
procedure SetSpeed(const ASpeed: Single);
Sets playback speed.
Parameters:
ASpeed - Speed multiplierprocedure 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
Central manager for all animations associated with a 3D model or character.
Inheritance: TComponent → TGorillaAnimationManager
Platforms: All Gorilla3D supported platforms
Interfaces: IDuplicatable
| Property | Type | Description |
|---|---|---|
| Mesh | TObject | Associated mesh/model object. |
| Animations | TGorillaAnimationMap | Hashmap of id-to-animation relationships (read-only). |
| Current | TGorillaAnimation | Currently active animation instance. |
| Property | Type | Description |
|---|---|---|
| CurrentAnimationName | String | Name of currently active animation. |
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Clear(); virtual;
Clears all animations from manager.
function GetFirstAnimation(): TGorillaAnimation;
Returns first animation in collection (order not guaranteed).
Returns: First animation or nil
function GetLastAnimation(): TGorillaAnimation;
Returns last animation in collection (order not guaranteed).
Returns: Last animation or nil
function GetAnimation(const AId: String = ''): TGorillaAnimation; overload;
Returns animation by identifier.
Parameters:
AId - Animation identifier (empty string returns Current)Returns: Animation instance or nil
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 identifierReturns: Playing animation or nil if not found
Behavior:
Example:
Manager.PlayAnimation('Run');
function PlayAnimation(const AAnim: TGorillaAnimation): TGorillaAnimation; overload;
Plays specific animation instance.
Parameters:
AAnim - Animation instanceReturns: Playing animation
function PlayNextAnimation(): TGorillaAnimation;
Plays next animation in sequence.
Returns: Next animation or first animation if at end
function PlayPreviousAnimation(): TGorillaAnimation;
Plays previous animation in sequence.
Returns: Previous animation or last animation if at beginning
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
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 | - | Animation duration. |
| Interpolation | TInterpolationType | Linear | Interpolation type. |
| Inverse | Boolean | False | Reverse direction. |
| Loop | Boolean | False | Loop playback. |
| PropertyName | String | - | Target property. |
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;
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.
TElementCoordinates = TDictionary<TComponent, TPoint3DDynArray>;
Component-to-vertex-array hashmap for keys.
Synchronization: Use TSkeletonKeyAnimation to group related animations for synchronized playback without timing offsets.
Performance: Use ForceStep() in rendering loops to avoid FMX timer jitter for smoother animation.
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 main thread via FMX timer or DisplayLink service.
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.Audio.Manager unit provides audio management for Gorilla3D. It contains two main classes: TGorillaLegacyAudioManager (thread-based, uses FMX TMediaPlayer) and TGorillaAudioManager (abstract base for modern backends like FMOD and OpenAL).
TThread
└── TGorillaLegacyAudioManager
TFmxObject
└── TGorillaAudioManager (abstract)
TCollectionItem
└── TGorillaSoundItem (abstract)
└── TGorillaChannelItem
└── TGorillaAudioEffectItem
| 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) |
Thread-based audio manager using FMX TMediaPlayer. Simple but not high-performance. Each audio file gets its own TMediaPlayer instance.
| Property | Type | Default | Description |
|---|---|---|---|
LoopCheckInterval |
Integer |
100 | Loop check interval in ms |
QueueTimeout |
Integer |
250 | Queue wait timeout in ms |
Mute |
Boolean |
False | Mute all audio |
| Method | Description |
|---|---|
BeginCaching() |
Start batch caching (boosts load performance) |
EndCaching() |
End batch caching |
AudioAlreadyCached(AId) |
Check if audio is cached |
Add(AId, AFilename, AVolume) |
Cache an audio file |
Play(AId, AMode, AVolume) |
Play a cached audio file |
Stop(AId) |
Stop playback |
Pause(AId) |
Pause/resume playback |
PauseAll() |
Pause all playing audio |
StopAll() |
Stop all playing audio |
Abstract base class for modern audio backends. Subclassed by FMOD and OpenAL implementations.
| Property | Type | Description |
|---|---|---|
OnUpdate |
TNotifyEvent |
Fired when Update() is called (main-thread synchronized) |
OnListenerUpdated |
TNotifyEvent |
Fired when listener settings change |
| Method | Description |
|---|---|
ClearSounds() |
Remove all sound handles |
LoadSoundFromFile(AFilename) |
Load sound from file |
LoadSoundFromStream(AStream) |
Load sound from stream |
LoadSoundFromStream(AMemStream) |
Load sound from memory stream (streaming) |
LoadSoundItemFromFile(AFilename) |
Load and return a TGorillaSoundItem |
LoadSoundItemFromStream(AStream) |
Load from stream and return a TGorillaSoundItem |
Abstract collection item representing a single sound.
| Property | Type | Description |
|---|---|---|
FileName |
TFileName |
Sound file path |
PlaybackPosition |
UInt32 |
Current playback position (read-only) |
PlaybackLength |
UInt32 |
Total length (read-only) |
| Method | Description |
|---|---|
IsPlaying() |
Check if sound is playing |
Play() |
Start playback |
Pause() |
Pause playback |
Resume() |
Resume playback |
Stop() |
Stop playback |
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 | Returns the current perspective projection matrix. |
| Property | Type | Description |
|---|---|---|
| FOV | Single | Get or set the field of view angle in degrees. |
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.
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. |
| LimitUpAndDownMax | Single | Maximum position on Y-axis for up/down movement. |
| 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. |
| 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.
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.
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.
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.
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 | - | Apply ViewportScale factor to viewport dimensions. |
| 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);
// Render at half resolution for performance
BlurPass.ScaleViewportSize := True;
BlurPass.ViewportScale := 0.5; // 50% of viewport dimensions
// Or fixed size
BlurPass.OverwriteViewportSize := True;
BlurPass.ViewportWidth := 512;
BlurPass.ViewportHeight := 512;
// 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. |
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. |
| 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).
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.
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.
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. |
| 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 GetInstance(AIndex: Integer): TMatrix3D;
procedure SetInstance(AIndex: Integer; const AValue: TMatrix3D);
Get or set transformation matrix for specific instance by index.
Example:
// Modify instance position
var Transform := Mesh.GetInstance(0);
Transform := Transform * TMatrix3D.CreateTranslation(Point3D(10, 0, 0));
Mesh.SetInstance(0, Transform);
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 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 referenceThe 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. |
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.
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.
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.
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. |
| Scale | Single | Read/Write | Rendering scale factor. |
| 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.
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.
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 | Returns the potential frames per second count. Measures performance in Delphi rendering mechanism. |
| ViewportScale | Single | Returns the viewport scaling value. |
| 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 | Access rendering diagnostics information. |
| 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. |
| UseFixedFrameRate | Boolean | True (Windows) | Enable fixed framerate rendering. |
| 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 | Use high resolution if available (primarily benefits Android). |
| 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 |
|---|---|---|---|
| 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 | Description |
|---|---|---|
| DiagnosticsActive | Boolean | Enable or disable rendering diagnostics collection. |
| 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.
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.
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.
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 calculationRecord containing rendering performance diagnostics.
Fields:
Enabled - Boolean indicating if diagnostics are activeTotalFrames - Total number of frames renderedAverageFrameTime - Average time per frame in millisecondsAverageFramesPerSecond - Average FPSDrawCalls - 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.
Frustum Culling: Improves performance but may affect render passes using different view matrices.
Global Illumination: Only available in GAME_PACKAGE edition.
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 | Resets the internal time counter 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 (timestamp when the pass was created or last reset) |
_TimeInfo.y |
Current time |
_TimeInfo.z |
Previous frame time |
_TimeInfo.w |
Delta time (time elapsed since previous frame) |
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 sets _TimeInfo.x to the current timestamp, 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 |
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 |
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>;
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.