Gorilla3D Framework - Documentation - Version v1.4

Generated on 2026-11-08 11:34:22

Changelist v1.4.0.3867

Formats

Materials:

CSM:

Animations:

Volume Rendering:

Physics:

Utils:

Vulkan:

Viewport:

IDE:

Installation

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.

GetIt Package Manager

Embarcadero integrated Gorilla3D inside the IDE GetIt-Package-Manager for an easy installation process.

  1. Simply open up the GetIt-Package Manager dialog under: Tools > GetIt-Package-Manager
  2. Search for "Gorilla3D" in the top right search edit
  3. Select the item and click on "Install" to start the process

Embarcader GetIt Package Manager

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.

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.

Gorilla3D Installer Tool (1) Gorilla3D Installer Tool (2)

  1. Select the desired IDE version you want a package to install for.
  2. Click "Install" to start the process.
  3. The application will download, extract and configure everything for you.

Manual Installation

To install Gorilla3D packages correctly you have to follow the instructions.

Download

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.

Unpack and Install

  1. Unpack the downloaded zip-archive anywhere (<installation-directory>).
  2. Inside the Delphi IDE go to:

IDE Installation

Configure

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.

Delphi 10.3.0 - Delphi 13.0+

To insert DCU's go to:

  1. Menu: Tools > Options > Language > Delphi-Options > Library
  2. Select "Windows 32-Bit" platform on top
  3. Go to "Library-Path" input field and add the <installation-directory>\Win32\Release\
  4. Repeat this analog for "Windows 64-Bit" and "Android" platforms

g3d-dcu-install

Delphi 10.1.1 - 10.2.3

To insert DCU's go to:

  1. Menu: Tools > Options > Environmentoptions > Delphi-Options > Library
  2. Select "Windows 32-Bit" platform on top
  3. Go to "Library-Path" input field and add the <installation-directory>\Win32\Release\
  4. Repeat this analog for "Windows 64-Bit" and "Android" platforms

Libraries

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\

OpenSSL Library

Copy OpenSSL DLL files to BDS directory or ensure the system is able to find them automatically by environment variables:

WebView2 Library

FMOD Audio Library

JOLT Physics Library

Mayo File Import Library

SketchUp Library

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"!

Restart

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!

System Requirements

This guide outlines the hardware and software requirements for running the Gorilla3D Framework on different platforms.

Supported Delphi IDE Versions

Gorilla3D Framework is compatible with the following Delphi versions:

C++ Support

The framework includes C++ headers and library files for C++Builder compatibility. But we've tested support only since 11.3.

Need a Different Version?

If you require packages for an IDE version not listed above (Delphi 10.1.1 or higher), please contact us through our support channels.

Windows Platform Requirements

Graphics API Requirements

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.

Verified Graphics Cards

The framework has been successfully tested on the following GPUs:

NVIDIA Graphics Cards

AMD Graphics Cards

Intel Integrated Graphics

Compatibility Feedback

If you experience issues with your specific graphics hardware, please report them to help us improve compatibility and documentation.

Android Platform Requirements

Tested Devices

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

Additional Information

For detailed Android development setup, deployment instructions, and troubleshooting, please refer to the Android documentation.

Linux Platform Requirements

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.

Linux 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.

macOS Platform Requirements

Gorilla3D supports macOS 64-Bit (Intel x64) through Apple's Metal graphics API (OpenGL is deprecated on macOS).

macOS 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.

Virtual Machine Support

Running Gorilla3D in virtual machines requires special configuration due to OpenGL requirements.

GPU Passthrough Required

Virtual machines need GPU passthrough enabled to provide proper OpenGL support. Without passthrough, the framework may not function correctly.

Tested VM Solutions

Microsoft Hyper-V

VMWare

KVM (QNAP NAS)

Virtual Machine Best Practices

  1. Always enable GPU passthrough in your VM settings
  2. Verify OpenGL 4.3+ support before installation
  3. Allocate sufficient video memory to the VM
  4. Test graphics performance before deploying production applications

Minimum System Summary

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

Next Steps

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.

Need Help?

If you have questions about system compatibility or encounter issues with your hardware configuration, please:

Pricing & Licensing

Gorilla3D Framework offers flexible licensing options to suit different development needs, from free development licenses to commercial packages for production applications.

License Editions

Developer Edition (Free)

The Developer Edition is perfect for learning, prototyping, non-commercial and non-published development.

Features:

Limitations:

Best For:

Commercial/Release Edition (Paid)

The Commercial Edition removes all restrictions and enables you to publish production-ready applications.

Features:

Licensing Requirements:

Best For:

Package Bundles

Choose the package that matches your project requirements. Both packages include the same licensing terms.

BASIC PACKAGE

Core 3D rendering capabilities for general-purpose 3D applications.

Included Features:

Ideal For:

GAME PACKAGE

Everything in the BASIC PACKAGE plus game-specific features and systems.

Additional Features:

Ideal For:

Supported Platforms

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)

Updates & Support

Update Subscriptions (Optional)

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.

Customer Portal

All Commercial Edition customers receive access to:

Refund Policy

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.

Special Discounts

Academic Discounts

Educational institutions and students may qualify for special pricing:

Regional Discounts

Pricing adjustments available for certain regions:

How to Purchase

Ready to upgrade to the Commercial Edition?

  1. Visit gorilla3d.de/purchase
  2. Select your desired package (BASIC or GAME)
  3. Choose number of licenses needed
  4. Apply any discount codes if eligible
  5. Complete checkout process
  6. Receive license key via email
  7. Access customer portal for downloads

Comparison Summary

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)

Frequently Asked Questions

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.

Need Help Choosing?

Not sure which edition or package is right for you?

Next Steps

Using AI Assistants

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

Claude Skill

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.

Download

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

Install in Claude Code

Unzip the archive so that the gorilla3d-v1-5 folder lies in one of the skill directories of Claude Code:

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.

Install in the Claude app (Desktop and claude.ai)

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.

Updating

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.

llms.txt for other AI tools

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:

llms-full is large. If your tool has a small context window, prefer the index or upload only the pages you need.

Tips for working with an AI assistant

Windows (x86 / x64)

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.

System Requirements

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.

Selecting the Graphics API

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.

Build & Deployment

Required runtime DLLs

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.

Mayo file import & SketchUp

Verified Feature Matrix

The following matrix lists features that have been explicitly tested on Windows for the current release. Legend:

OpenGL (Win32 + Win64)

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 (Win64)

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.

Troubleshooting

Next Steps

Android (32-Bit / 64-Bit)

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.

OpenGL ES Versions by Delphi

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.

NDK Configuration

Gorilla3D needs OpenGL ES 3.1, which requires NDK API level 18 at minimum and API level 21+ for Order-Independent Transparency.

  1. Open Tools > Options > Deployment > SDK Manager.
  2. Select your Android SDK and switch to the NDK tab.
  3. For every entry below android-18, replace it with at least android-18.
  4. For Gorilla3D ≥ 0.8.1 set the minimum to 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.

image

AndroidManifest Configuration

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.

Build & Deployment

Native libraries

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.

Verified Feature Matrix

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 ❌ ❌

Known Issues

Common Errors

Next Steps

Linux (x64)

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.

Prerequisites

To build and run Gorilla3D applications on Linux you need:

Setting up Linux / WSL2

Native Linux

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

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.

Embarcadero FMXLinux

FireMonkey on Linux requires Embarcadero's FMXLinux library. It is distributed via GetIt:

  1. Download the FMXLinux zip from your Embarcadero account.
  2. In the IDE open Tools > GetIt Package Manager.
  3. Click Load Local Package and select the FMXLinux zip.
  4. Restart the IDE after installation.

Without FMXLinux the Linux64 platform will be available, but FireMonkey forms cannot be created and Gorilla3D will not link.

SKIA4Delphi

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:

  1. Get the latest release from the official SKIA4Delphi GitHub releases.
  2. Pick the linux-x64 archive and extract libsk4d.so.
  3. Add the .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

PAServer is the Embarcadero Platform Assistant — the IDE talks to it over TCP to push binaries, debug and run on the target.

  1. Copy PAServer-XX.X.tar.gz from your Delphi installation (PAServer/) to the Linux machine.

  2. Extract and start it:

    tar xzf PAServer-XX.X.tar.gz
    cd PAServer-XX.X
    ./paserver
  3. 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.

Building & Deploying

  1. Add Linux 64-Bit as a target platform in your project.
  2. Select your PAServer connection profile and the matching SDK (auto-imported on first connect).
  3. Add deployment entries for libsk4d.so, your assets, and any third-party .so files you depend on.
  4. Build in Release for production — Debug builds are useful for stepping through code via PAServer.

Verified Feature Matrix

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.

Troubleshooting

For a deeper introduction to Linux deployment with Delphi, see Embarcadero's Linux Application Development documentation.

Solving Issue Example

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

Next Steps

macOS (Metal / OSX64)

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.

Prerequisites

Apple Silicon (M1 / M2 / M3 / …)

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.

Setting up PAServer on macOS

  1. Copy the matching PAServer-XX.X.pkg from your Delphi installation to the Mac and run it.
  2. Launch PAServer (it lives in /Applications) and note the password printed in the terminal window.
  3. In the IDE go to Tools > Options > Deployment > Connection Profile Manager and create a new macOS profile pointing at the Mac's hostname / IP and that password.
  4. Use SDK Manager to import the macOS SDK on first connection — PAServer will copy the required headers / frameworks back to the IDE.

Building & Deploying

  1. Add macOS 64-Bit as a target platform.
  2. Pick the macOS connection profile and SDK.
  3. Configure code-signing under Project > Options > Provisioning (required for distribution; ad-hoc signing is enough during development).
  4. Add deployment entries for your assets and any third-party .dylib files.
  5. Build in Release for store / notarized distribution; Debug lets you step through code via PAServer.

Shaders on Metal — GLSL Translation vs. Hand-written MSL

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.

Shader Architectures

Each material / render pass stores its shaders in a list of architectures. Two are relevant on macOS:

When the Metal backend prepares a shader, it picks the architecture in the following order:

  1. If a Metal-Arch is registered → compile that MSL directly (fastest, no parsing).
  2. Else if a GLSL-Arch is registered → run the GLSL→MSL parser, compile the generated MSL.
  3. If both are missing the pipeline state is 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.

Path A — Translating GLSL to MSL

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:

Translator limitations to be aware of

The parser cannot represent every GLSL idiom. The cases below are the ones you are most likely to run into:

Path B — Hand-written MSL (Metal-Arch)

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:

The framework also takes care of:

Example — registering a Metal-Arch fragment 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.

When to use which path

Diagnosing shader problems on Metal

The framework writes MSL compile errors to FMX.Types.Log together with the generated source. Typical patterns:

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.

Verified Feature Matrix

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 ❌

Known Issues & Recommendations

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.

Troubleshooting

Next Steps

Viewport

The TGorillaViewport is the primary container for Gorilla3D scenes. It replaces FireMonkey's standard TViewport3D and TForm3D components and serves as the main rendering surface for 3D content.

Important: Gorilla3D is not compatible with TForm3D and TViewport3D. Always use TGorillaViewport for Gorilla3D applications.

Creating a Viewport

Design-Time Creation

  1. Locate TGorillaViewport in the tool palette under the Gorilla3D section
  2. Drag and drop it onto your form
  3. The viewport will typically be set to align client by default

Runtime Creation

var
  Viewport: TGorillaViewport;
begin
  Viewport := TGorillaViewport.Create(Self);
  Viewport.Parent := Self;
  Viewport.Align := TAlignLayout.Client;
  Viewport.Color := TAlphaColors.Black;
end;

Rendering Pipeline

TGorillaViewport uses a sophisticated rendering pipeline based on Weighted-Blended-Order-Independent-Transparency (WBOIT). The pipeline processes scenes through multiple stages:

Pipeline Stages

  1. Pre-processing Render Passes - Custom render passes executed before main rendering
  2. Main Render Pass
  3. Post-processing Render Passes - Custom render passes executed after main rendering

Renderer Types

The viewport supports two renderer types:

Forward Renderer (Recommended)

Viewport.RendererType := TRendererType.ForwardRenderer;

The default renderer using WBOIT with multiple framebuffers and textures. Provides:

Legacy Renderer

Viewport.RendererType := TRendererType.LegacyRenderer;

A simple renderer with a single framebuffer. Use this when:

Note: Legacy renderer has limited support for Gorilla3D default materials.

Key Properties

Frame Rate Control

Fixed Frame Rate

// Enable fixed framerate rendering (default on Windows)
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.

VSync

Viewport.VSync := True;

Synchronizes rendering with the monitor's refresh rate, limiting the frame rate between FixedFrameRate and the monitor's maximum refresh rate.

Manual Rendering

Viewport.ManualRendering := True;

// Later, trigger rendering manually
Viewport.RenderManual();

Disables automatic rendering on property changes. 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;

Performance Optimization

Frustum Culling

Viewport.FrustumCulling := True;  // Default

Automatically culls objects outside the camera's view frustum. Significantly improves performance in large scenes.

Warning: May affect render passes using different view matrices.

Batching Updates

Viewport.BeginUpdate();
try
  // Modify multiple properties
  Viewport.FogDensity := 0.5;
  Viewport.FogStart := 10.0;
  Viewport.FogEnd := 100.0;
  Viewport.FogColor := TAlphaColors.White;
finally
  Viewport.EndUpdate();
end;

Batches multiple property changes into a single render instruction, improving performance.

Clipping Planes

Viewport.NearPlane := 0.1;    // Default
Viewport.FarPlane := 10000.0; // Default

Controls the rendering clipping distances. Objects closer than NearPlane or farther than FarPlane are not rendered.

Fog Configuration

Fog is a scene-wide atmospheric effect that requires TGorillaDefaultMaterialSource materials.

Enabling Fog

Viewport.Fog := True;
Viewport.FogKind := TGorillaFogKind.fkLinear;
Viewport.FogStart := 50.0;
Viewport.FogEnd := 200.0;
Viewport.FogColor := TAlphaColors.Lightgray;

Fog Modes

Mode Description Use Case
fkLinear Linear fog calculation Outdoor scenes, precise control
fkExp Exponential fog Atmospheric effects, realistic fog
fkExp2 Exponential squared Dense fog, underwater effects

Fog Parameters

// For linear fog
Viewport.FogStart := 50.0;   // Distance where fog starts
Viewport.FogEnd := 200.0;    // Distance where fog is maximum

// For exponential fog (fkExp, fkExp2)
Viewport.FogDensity := 0.05; // Density of fog

// Fog appearance
Viewport.FogColor := TAlphaColors.Lightgray;

Important: Fog only works with TGorillaDefaultMaterialSource materials, not standard FMX materials.

Rendering Effects

Saturation Control

Control color saturation for different rendering stages:

// Opaque objects saturation
Viewport.OpaqueSaturation := 0.0;  // 0 = no saturation effect

// Translucent objects saturation
Viewport.TranslucentSaturation := 1.5;

// Final composition saturation
Viewport.CompositeSaturation := 0.0;

Note: Saturation only affects ForwardRenderer and DeferredRenderer, not LegacyRenderer.

Emissive Blur

Viewport.EmissiveBlur := 3;  // 0 = disabled

Controls the intensity of emissive material blurring. Higher values create a stronger glow effect but significantly impact performance by increasing blur iterations and wideness.

Anti-Aliasing (FXAA)

Viewport.FXAA := 4;  // 0-8, 0 = disabled

Fast Approximate Anti-Aliasing. Higher values = smoother edges but lower performance. Alternative to MSAA.

Viewport.MSAA := TMSAASamples.Samples4X;  // Hardware MSAA

Fragment Depth Rendering

Viewport.FragmentDepthRendering := True;

Enables a pre-render pass that stores fragment depth for improved translucent rendering. Enhances visual quality but adds a render pass.

Tip: Disable if your scene has no transparent objects to improve performance.

Global Illumination

Global illumination provides realistic lighting with shadows and reflections through voxel-based rendering.

Availability: Only available in GAME_PACKAGE edition.

Configuration

// Set detail level (0-7)
Viewport.GlobalIllumDetail := 3;  // 0 = off, 7 = highest quality

// Adjust rendering quality
Viewport.GlobalIllumSoftness := 1.0;    // 0.0-5.0
Viewport.ShadowStrength := 0.4;         // 0.0-10.0
Viewport.ReflectionStrength := 0.5;     // 0.0-10.0

Detail Levels

Level Voxel Size GPU Requirement Min Texture3D Size
0 - - Global Illumination Off
1 32 Elder GPUs 256
2 64 Elder GPUs 512
3 128 Normal GPUs 1024
4 192 Normal GPUs 2048
5 256 Better GPUs 2048
6 384 High-performance GPUs 4096
7 512 High-performance GPUs 4096

Parameters

Advanced Features

Native OpenGL Rendering

You can implement custom OpenGL rendering via TDummy containers' OnRender events:

procedure TForm1.Dummy1Render(Sender: TObject; Context: TContext3D);
begin
  // Your custom OpenGL code here
  // You must manage transformation and projection matrices independently
  Context.SetMatrix(TMatrix3D.Identity);
  // ... custom rendering
end;

Graphics Library Selection

Modify the graphics library in your .dpr file before viewport initialization:

program MyApp;

uses
  Gorilla.Context.Types;

begin
  // Switch to OpenGL ES
  GORILLA_CONTEXT_GRAPHICS_SETTINGS := TGorillaGraphicsLibrary.OpenGLES;

  Application.Initialize;
  Application.CreateForm(TMainForm, MainForm);
  Application.Run;
end.

Available options (v1.1+):

Design Camera

The viewport includes a built-in design camera for development:

// Use design camera (default at design-time)
Viewport.UsingDesignCamera := True;

// Access design camera
var DesignCam := Viewport.GetDesignCamera();

// Access camera controller
var Controller := Viewport.GetDesignCameraController();

Edit Mode

Viewport.EditMode := True;

Enables interactive object manipulation at design-time and runtime with the gizmo tool.

Gizmo Control

// Show gizmo for an object
Viewport.ShowGizmo(MyMesh);

// Change gizmo mode
Viewport.ChangeGizmoMode(0);  // 0=Translate, 1=Rotation, 2=Scale

// Check if active
if Viewport.IsGizmoActive() then
  ShowMessage('Gizmo is active');

// Hide gizmo
Viewport.HideGizmo();

Coordinate System Conversion

Screen to World

var
  ScreenPoint: TPointF;
  WorldPoint: TPoint3D;
begin
  ScreenPoint := PointF(100, 100);
  WorldPoint := Viewport.ScreenToWorld(ScreenPoint);
end;

World to Screen

var
  WorldPoint: TPoint3D;
  ScreenPoint: TPointF;
begin
  WorldPoint := Point3D(10, 0, 0);
  ScreenPoint := Viewport.WorldToScreen(WorldPoint);
end;

Object Selection

Ray Casting

var
  ClickedObject: TControl3D;
  MousePos: TPointF;
begin
  MousePos := PointF(X, Y);  // Mouse coordinates
  ClickedObject := Viewport.RayCastIntersect(MousePos);

  if Assigned(ClickedObject) then
    ShowMessage('Clicked: ' + ClickedObject.Name);
end;

Screenshots

var
  Screenshot: TBitmap;
begin
  Screenshot := Viewport.MakeScreenshot();
  try
    Screenshot.SaveToFile('screenshot.png');
  finally
    Screenshot.Free;
  end;
end;

Performance Monitoring

FPS Counter

// Get current FPS estimate
var CurrentFPS := Viewport.FPS;

Note: This measures Delphi rendering mechanism performance, not actual output FPS.

Diagnostics

// 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:

Important Considerations

Animation Frame Rate Limitation

FireMonkey's TAnimation base class limits animation frame rates to 30 FPS. This is a FireMonkey limitation, not a Gorilla3D limitation.

Translucent Rendering

Translucent rendering uses weighted color values requiring special GLSL calculations. The WBOIT algorithm provides order-independent transparency for correct rendering regardless of draw order.

Platform-Specific Features

Material Compatibility

Feature Gorilla Materials FMX Materials
Fog ✓ Yes ✗ No
Forward Renderer ✓ Full Support ○ Limited
Legacy Renderer ○ Limited ✓ Full Support
WBOIT Transparency ✓ Yes ○ Partial

Best Practices

  1. Use BeginUpdate/EndUpdate when modifying multiple properties
  2. Enable FrustumCulling for large scenes
  3. Use ManualRendering with TGorillaTimer for consistent frame timing
  4. Disable FragmentDepthRendering if you have no transparent objects
  5. Start with GlobalIllumDetail level 3 and adjust based on performance
  6. Use ForwardRenderer unless you specifically need legacy compatibility
  7. Monitor Diagnostics during development to identify performance issues
  8. Keep EmissiveBlur low (0-3) unless you specifically need strong effects

See Also

Renderer

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.

Renderer Types

Forward Renderer (Recommended)

The default renderer using Weighted Blended Order Independent Transparency (WBOIT) for correct translucent object rendering regardless of draw order.

Features:

Use When:

Legacy Renderer

Simple single-framebuffer renderer for maximum compatibility.

Features:

Use When:

Accessing the Renderer

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;

Rendering Pipeline

Forward Renderer Pipeline

  1. Fragment Depth Pre-Pass (optional)

  2. Opaque Rendering

  3. Translucent Rendering

  4. Post-Processing Passes

  5. Compositing

Legacy Renderer Pipeline

  1. Opaque Rendering

  2. Translucent Rendering

  3. Output

Render Target Access

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;

Advanced Rendering Features

Emissive Blur

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.

Global Illumination

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:

Fast Approximate Anti-Aliasing (FXAA)

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.

Screen Space Shadows

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.

Screen Space Ambient Occlusion (SSAO)

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);

Saturation Control

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;

Debugging Render Targets

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:

Performance Optimization

Rendering Pipeline Optimization

// 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;

Resolution Scaling

// 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;

MSAA vs FXAA Trade-offs

// 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;

Common Patterns

Quality Settings Presets

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;

Screenshot/Video Recording Setup

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;

Best Practices

  1. Start with Forward Renderer: Use TRendererType.ForwardRenderer unless you have specific reasons for Legacy.

  2. Enable Fragment Depth: Keep FragmentDepthRendering := True if you have any close up transparent objects.

  3. 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]));
  4. Scale Effects to Hardware: Test on minimum spec hardware and provide quality settings.

  5. Debug with Output Layers: Use render target visualization during development to understand what's being rendered.

  6. Global Illumination Requires Tuning: GI settings are scene-dependent. Experiment with softness and strength values.

  7. Batch Rendering Changes: Use BeginUpdate/EndUpdate when changing multiple renderer settings.

See Also

Camera

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

TGorillaCamera extends FireMonkey's TCamera with additional Gorilla3D-specific features and better integration with the rendering pipeline.

Creating a Camera

Design-Time

  1. Drop a TGorillaCamera onto your viewport from the tool palette
  2. Set it as the active camera in the viewport's Camera property
  3. Deactivate the design time camera by Viewport.UsingDesignCamera := False;
  4. Configure position and field of view as needed

Runtime

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;

Field of View

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:

Camera Positioning

// 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);

Target Focus

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.

TGorillaSmoothCameraController

The smooth camera controller provides interactive camera navigation with physics-based movement, perfect for viewers, object inspectors, and interactive 3D applications.

Basic Setup

Design-Time Setup

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;

Runtime Setup

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;

Navigation Profiles

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

Orbiting vs. Non-Orbiting

Non-Orbiting (Default)

Controller.Orbiting := False;

Orbiting Mode

Controller.Orbiting := True;

Customizing Movement

Intensity (Sensitivity)

// 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;

Damping (Smoothness)

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;

Movement Limits

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;

Programmatic Control

Adding Impulses

// 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));

Zooming

// Zoom in
Controller.Zoom(1.0);

// Zoom out
Controller.Zoom(-1.0);

// Stronger zoom
Controller.Zoom(2.0);

Shifting

// Shift on all axes
Controller.Shift(Point3D(1, 0, 0.5));

Direct Positioning

// Set exact position and angle
Controller.SetPositionAndAngle(
  Point3D(0, 5, 0),      // Position
  Point3D(0, 45, 0)      // Rotation angles
);

Custom Input Controls

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];

Enabling/Disabling Controls

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 := [];

Events

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;

Advanced Techniques

Object Inspector Pattern

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;

First-Person Camera

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;

Animated Camera Movement

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

Camera Shake Effect

procedure AddCameraShake(AController: TGorillaSmoothCameraController;
  AIntensity: Single);
begin
  AController.AddImpulse(PointF(
    Random * AIntensity * 2 - AIntensity,  // Random X
    Random * AIntensity * 2 - AIntensity   // Random Y
  ));
end;

Best Practices

  1. Always Link Viewport: Set the Viewport property for automatic mouse event handling

  2. Choose Appropriate Profile: Use preset profiles when possible instead of custom configurations

  3. Set Reasonable Limits: Always define min/max limits to prevent users from getting lost

  4. Adjust Damping for Feel: Lower damping (0.7-0.8) for responsive controls, higher damping (0.9-0.95) for smooth, cinematic movement

  5. Test on Target Platform: Camera feel can differ between desktop (mouse) and mobile (touch) platforms

  6. Consider Scene Scale: Adjust intensity and zoom limits based on your scene size

  7. Provide Visual Feedback: Show controller position with ShowController := True during development

Troubleshooting

Camera Not Responding

// 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!');

Movement Too Fast/Slow

// Adjust intensity
Controller.IntensityRotate := 0.5;  // Slower
Controller.IntensityZoom := 2.0;    // Faster

Camera Drifts Continuously

// 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);

See Also

Light

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.

Light Types

Point Light

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:

Directional Light

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:

Spot Light

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:

Creating Lights

Design-Time

  1. Drop TGorillaLight onto your viewport from the tool palette
  2. Set the LightType in the Object Inspector
  3. Position and configure the light
  4. Adjust color, intensity, and attenuation properties

Runtime

function 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;

Light Properties

Color Components

Gorilla3D lights have three color components:

Diffuse Color

The main light color affecting directly lit surfaces.

Light.Color := TAlphaColors.White;

Ambient Color

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);

Specular Color

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);

Intensity

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

Attenuation controls how light intensity decreases with distance. Only affects Point and Spot lights.

Formula

Attenuation = 1 / (Constant + Linear × Distance + Quadratic × Distance²)

Attenuation Components

// 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;

Common Presets

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;

Visual Effect

// 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

Light scattering creates volumetric "god rays" effects visible in global illumination rendering.

Availability: Requires Global Illumination enabled (GAME_PACKAGE only)

Basic Setup

// 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

Parameters

Scattering Intensity (0.0-10.0)

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

Scattering Exposure (0.0-1.0)

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

Scattering Decay (0.0-2.0)

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

Scattering Density (0.0-10.0)

Density of the scattering medium.

Light.ScatteringDensity := 0.3;     // Thin atmosphere
Light.ScatteringDensity := 0.84;    // Normal atmosphere
Light.ScatteringDensity := 2.0;     // Dense fog/haze

Scattering Effects

Sunbeams Through Window

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;

Volumetric Spotlight

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;

Atmospheric Haze

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;

Shadow Casting

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;

Per-Light Shadow Properties

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 — not Viewport.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, set Light.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).

Lighting Scenarios

Three-Point Lighting

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;

Outdoor Daylight

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;

Indoor Room

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;

Campfire Scene

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;

Animated Lighting

Flickering Light

procedure TForm1.TimerFlickerTimer(Sender: TObject);
var
  BaseIntensity: Single;
begin
  BaseIntensity := 1.5;
  TorchLight.Intensity := BaseIntensity + Random * 0.3 - 0.15;
end;

Rotating Light (Lighthouse, Alarm)

procedure TForm1.TimerRotateTimer(Sender: TObject);
begin
  SpotLight.RotationAngle.Y := SpotLight.RotationAngle.Y + 2;
end;

Pulsing Light

var
  PulseTime: Single = 0;

procedure TForm1.TimerPulseTimer(Sender: TObject);
begin
  PulseTime := PulseTime + 0.05;
  Light.Intensity := 1.0 + Sin(PulseTime) * 0.5;
end;

Day/Night Cycle

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;

Performance Considerations

Light Count

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;

Dynamic vs Static

// 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;

Light Types Performance

Performance Ranking (best to worst):

  1. Directional Light - No attenuation calculations
  2. Point Light - Simple attenuation
  3. Spot Light - Attenuation + cone calculations

Best Practices

  1. Start Simple: Begin with one directional light, add more as needed

  2. Use Realistic Values: Real-world lighting is often dimmer than you think:

    Sun.Intensity := 1.5;  // Not 10.0
  3. Balance Color Components:

  4. Match Attenuation to Scene Scale: If your scene is in meters, use real-world attenuation ranges

  5. Limit Light Count:

  6. Use Global Illumination Wisely: Enable only when the scene benefits from it

  7. Test on Target Hardware: Lighting performance varies greatly between devices

Troubleshooting

Lights Not Affecting Objects

// 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!');

Scene Too Dark

// 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

Harsh Shadows/High Contrast

// Increase ambient to fill shadows
Light.Ambient := TAlphaColorF.Create(0.3, 0.3, 0.3, 1);

// Add fill light from opposite direction

Light Too Dim at Distance

// Reduce attenuation for longer range
Light.LinearAttenuation := 0.07;
Light.QuadraticAttenuation := 0.017;

// Or increase intensity
Light.Intensity := 3.0;

See Also

Models

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 TGorillaViewport instance to be rendered.

Supported File Formats

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

Loading Models

Design-Time Loading

Embedded Models

Store model data directly in .fmx files for quick prototyping:

  1. Add a TGorillaModel component to your form
  2. Set the Source property to your model file path
  3. The model data will be embedded in binary format

Warning: 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 .fmx file storing process, which is performed on making changes at design time.

Asset Packages

Link external ZIP archives for better development workflow:

  1. Add a TGorillaAssetsManager component
  2. Create or link an asset package
  3. Set the model's AssetsManager and PackageName properties
  4. Set the Source property to the model filename
// Design-time setup
GorillaModel1.AssetsManager := GorillaAssetsManager1;
GorillaModel1.PackageName := 'MyAssets';
GorillaModel1.Source := 'character.dae';

Runtime Loading

Method 1: LoadNewModelFromFile

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;

Method 2: LoadFromFile

Loads data into an existing model instance:

GorillaModel1.LoadFromFile(nil, 'models\character.dae', []);

Method 3: Advanced Loading with TGorillaLoadOptions

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;

Loading from Stream

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;

Animation Management

Loading Additional Animations

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.

Playing Animations

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

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_DEFAULT is recommended for usage.

Model Hierarchy

Understanding the Structure

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)

Accessing Sub-Components

// 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;

Debug Output

Print the model hierarchy to the event log:

GorillaModel1.DebugOut(False);  // FMX hierarchy
GorillaModel1.DebugOut(True);   // Component hierarchy

Material Management

Applying Materials

// 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.

Rendering Features

Wireframe Rendering

// Enable wireframe
GorillaModel1.Wireframe := True;
GorillaModel1.WireframeMaterial := MyWireframeMaterial;

Performance: Wireframe rendering is costly. Use only for debugging.

Normal Visualization

GorillaModel1.ShowNormals := True;
GorillaModel1.NormalsColor := TAlphaColors.Green;

Joint Visualization

GorillaModel1.ShowJoints := True;
GorillaModel1.JointsColor := TAlphaColors.Yellow;

Instancing

Use instancing to render the same model multiple times efficiently:

GPU Instancing

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;

Model Cloning

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;

Model Export

Export models to supported formats:

G3D Export (Internal Format)

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;

OBJ Export

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;

STL Export

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;

Bounding Box

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;

Ray Casting and Triangle Picking

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.

Using RayCastIntersect

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;

Using PickTriangle with Screen Coordinates

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;

Using PickTriangle with Result Structure

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;

Using PickTriangle with Absolute Ray

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;

Key Differences

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.

Performance Optimization

Static Meshes

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;

Hit-Testing

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;

Texture Size Limiting

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;

Frustum Culling

Enable per-mesh frustum culling:

for var i := 0 to GorillaModel1.Meshes.Count - 1 do
  GorillaModel1.Meshes[i].FrustumCullingCheck := True;

Sketchfab Integration

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;

Important Considerations

Memory Management

Asset Packages vs. Embedded

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

File Format Selection

Best Practices

  1. Use asset packages during development for better IDE performance
  2. Cache animations with VertexPosition flag for balanced performance/memory
  3. Limit texture sizes for mobile platforms
  4. Use GPU instancing for rendering many identical objects
  5. Enable frustum culling for large scenes
  6. Prefer G3D format for final deployment
  7. Test on target platform before deploying
  8. Use LoadFromStream for loading from resources or compressed archives

See Also

Materials

Materials in Gorilla3D define how 3D objects appear when rendered, controlling colors, textures, lighting, and advanced effects like normal mapping, PBR (Physically-Based Rendering), and shadows. The framework provides a comprehensive material system centered around TGorillaDefaultMaterialSource with 18+ specialized material types.

Important: Materials must be assigned to meshes via the MaterialSource property to be rendered.

Material Architecture

Node-Based Shader System

Gorilla3D uses a node-based architecture to automatically generate GLSL shaders at runtime. This system:

Key Components

TGorillaDefaultMaterialSource (Component)
└─ TGorillaDefaultMaterial (Material)
   ├─ Vertex Shader (TGorillaGLSLVertexShader)
   │  └─ Nodes (position, displacement, transforms)
   └─ Fragment Shader (TGorillaGLSLFragmentShader)
      └─ Nodes (lighting, textures, PBR, effects)

Default Material Source

The TGorillaDefaultMaterialSource is the primary material component providing:

Creating a Material

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.

Design-Time

  1. Add a TGorillaCustomMaterialSource component to your form
  2. Configure properties in the Object Inspector
  3. Assign textures via Texture properties
  4. Link to meshes via MaterialSource property

Runtime

var
  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

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.

Lambert Shading

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);

Phong Shading

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;

Blinn-Phong Shading

Improved Phong model with better performance and visual quality.

Material.ShadingModel := TGorillaShadingModel.smBlinnPhong;
Material.Shininess := 32.0;

PBR (Physically-Based Rendering)

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.

Texture Mapping

Diffuse Texture

Base color/albedo map:

Material.UseTexturing := True;
Material.UseTexture0 := True;
Material.Texture.LoadFromFile('diffuse.png');

Texture Tiling

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 be Repeated or MirroredRepeat. If WrapS / WrapT (or WrapR for 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 set Repeated explicitly when Tiling > 1.

See Default Material → The Bitmaps Property for the full property list.

Normal Mapping

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

Parallax Occlusion Mapping (POM)

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

Specular Mapping

Controls specular highlights per-pixel:

Material.UseSpecular := true;
Material.UseSpecularMapping := True;
Material.SpecularMap.LoadFromFile('specular.png');

Emissive Mapping

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);

Opacity Mapping

Transparency control via texture:

Material.UseOpacityMapping := True;
Material.OpacityMap := LoadBitmapFromFile('opacity.png');

Displacement Mapping

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);

PBR Texture Workflow

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');

Advanced Features

Shadow Mapping

Recommended: For shadows, use the Cascaded Shadow Maps (CSM) system. It is enabled per-viewport via Viewport.Shadows.Enabled and supports directional, spot and point lights — see Cascaded Shadow Maps. The legacy material-level ShadowMethod flags 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;

Reflections and Refractions

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;

Environment Mapping

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;

Depth Mapping

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;

Vertex Coloring

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;

Alpha Cutoff

Discard fragments below threshold (for foliage, chains, etc.):

Material.UseAlphaCutoff := True;
Material.AlphaCutoff := 0.5;  // 0-1

Tonemapping

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;

Color Clipping

Discard pixels matching specific color:

Material.UseColorClipping := True;
Material.ClippingColor := TAlphaColorF.Create(1, 0, 1, 1);  // Magenta

Material Behaviours

Material behaviours (v1.1+) provide modular, reusable shader functionality that can be attached to any material source.

Built-in Behaviours

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

Using Behaviours

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;

Behaviour Advantages

Specialized Material Types

Gorilla3D includes specialized materials for specific use cases:

TGorillaLambertMaterialSource

Simple Lambert shading without specular.

TGorillaPhongMaterialSource

Phong shading with specular highlights.

TGorillaBlinnMaterialSource

Blinn-Phong shading (optimized Phong).

TGorillaPBRMaterialSource

Dedicated PBR material.

TGorillaBumpMapMaterialSource

Bump mapping without normal maps.

TGorillaNormalMapMaterialSource

Normal mapping only.

TGorillaPOMMaterialSource

Parallax occlusion mapping.

TGorillaRimLightingMaterialSource

Rim/edge lighting effects.

TGorillaVertexColorMaterialSource

Vertex color only (no textures).

TGorillaWaterMaterialSource

Animated water surface.

TGorillaGrassMaterialSource

Grass rendering with wind.

TGorillaParticleMaterialSource

Particle system rendering.

TGorillaTerrainMaterialSource

Terrain with height-based texturing.

TGorillaSplatMapMaterialSource

Multi-texture terrain blending.

TGorillaLayeredMaterialSource

Multiple texture layers with blending.

TGorillaAtlasMaterialSource

Texture atlas support.

TGorillaGridMaterialSource

Debug grid rendering.

TGorillaSharedMaterialSource

Share material data across instances.

TGorillaRuntimeMaterialSource

Create materials at runtime.

TGorillaCustomMaterialSource

Custom shader code.

Uniform Buffer System

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;

Performance Optimization

Material Batching

Use BeginChange/EndChange to batch property updates:

Material.BeginChange();
try
  Material.Diffuse := NewDiffuse;
  Material.Specular := NewSpecular;
  Material.Shininess := NewShininess;
finally
  Material.EndChange();
end;

Texture Management

// Efficient texture loading
Material.Texture := LoadBitmapFromFile('texture.png');

// Share textures across materials
Material2.Texture := Material1.Texture;

Shader Caching

Shaders are automatically cached by the engine based on active features.

Light Limits

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

Best Practices

  1. Use Default Material: Start with TGorillaCustomMaterialSource for maximum flexibility
  2. Enable Only Needed Features: Unnecessary features impact performance
  3. Batch Property Changes: Use BeginChange/EndChange for multiple updates
  4. Use Behaviours: Leverage behaviours for reusable effects
  5. PBR for Realism: Use PBR shading model for realistic rendering
  6. Test on Target Platform: Verify performance and light limits
  7. Use Appropriate Shading: Lambert for matte, Phong for shiny, PBR for realistic
  8. Optimize Texture Sizes: Use appropriate resolutions for target platform
  9. Monitor Shader Rebuilds: Changing material properties may trigger shader recompilation

Common Patterns

Metallic Surface

Material.ShadingModel := TGorillaShadingModel.smPBR;
Material.MetallicBias := 1.0;
Material.RoughnessBias := 0.1;
Material.Diffuse := TAlphaColorF.Create(0.9, 0.9, 0.9, 1.0);

Rough Stone

Material.ShadingModel := TGorillaShadingModel.smPBR;
Material.MetallicBias := 0.0;
Material.RoughnessBias := 0.9;
Material.UseNormalMapping := True;

Glowing Object

Material.UseEmissiveColoring := True;
Material.Emissive := TAlphaColorF.Create(1.0, 0.5, 0.0, 1.0);
Material.UseEmissiveMapping := True;
Material.EmissiveTexture := GlowTexture;

Transparent Glass

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;

See Also

Audio

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.

Table of Contents

Overview

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

Legacy Audio Manager

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).

Caching and Playback

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

Looping

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

Muting

AudioManager.Mute := True;  // mute all
AudioManager.Mute := False; // unmute

Modern Audio Manager

The abstract TGorillaAudioManager class provides a more capable audio system with concrete implementations for FMOD and OpenAL.

FMOD Backend

FMOD provides professional-grade audio with 3D spatialization, DSP effects, reverb, and geometry-based occlusion.

Key units:

OpenAL Backend

OpenAL provides a lighter-weight 3D audio option. Key units:

Codec support: MP3 (Gorilla.Audio.MP3.API), OGG Vorbis (Gorilla.Audio.OGG.API).

Loading and Playing Sounds

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;

3D Spatial Audio

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 Notes

Platform Legacy Audio FMOD OpenAL
Windows Yes Yes Yes
macOS Yes Yes —
iOS Yes Yes —
Android Yes Yes (via JNI) —
Linux Limited — Yes

Best Practices

Prefabs

The 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.

Table of Contents

Overview

The prefab system consists of two classes:

Class Description
TGorillaPrefabSystem Component that manages a collection of prefabs
TGorillaPrefab Individual prefab template (collection item)

Getting Started

Design-Time

  1. Drop a TGorillaPrefabSystem onto your form
  2. Open the Prefabs collection in the Object Inspector
  3. Add a new prefab item
  4. Set OwnerComponent to the root component of your template
  5. Set FileName to the file path for the prefab

Runtime

var
  PrefabSys: TGorillaPrefabSystem;
  Prefab: TGorillaPrefab;
begin
  PrefabSys := TGorillaPrefabSystem.Create(Self);

  Prefab := PrefabSys.AddPrefab('Tree', GorillaViewport1, 'prefabs/tree.prefab');
end;

Creating Prefabs

Saving a Scene Element as Prefab

// 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;

Embedded DFM Content

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.

Loading Prefabs

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;

From Stream

LComponents := LPrefab.LoadFromStream(MyStream);
// For compressed .prefabz files:
LComponents := LPrefab.LoadFromStream(MyStream, True); // AIsPrefabZ = True

Load All Prefabs at Once

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;

Saving Prefabs

// Save individual prefab
LPrefab.Save();
LPrefab.SaveToFile('prefabs/enemy_v2.prefab');

// Save all prefabs
PrefabSystem1.SaveAllPrefabs();

Prefab Properties

TGorillaPrefab Properties

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)

TGorillaPrefab Events

Event Type Description
OnLoaded TOnPrefabLoadedEvent Fired after prefab components are loaded
OnStored TNotifyEvent Fired after prefab is saved
OnCreateComponent TOnCreateComponentEvent Custom component creation callback

TGorillaPrefabSystem Methods

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();

Working with Multiple Prefabs

// 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;

Best Practices

Assets Manager

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.

Table of Contents

Overview

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

Asset Types

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

Getting Started

Design-Time

  1. Drop a TGorillaAssetsManager onto your form
  2. Use the IDE Assets Manager editor to create packages and import files

Runtime

uses Gorilla.AssetsManager;

var
  AssetsMgr: TGorillaAssetsManager;
begin
  AssetsMgr := TGorillaAssetsManager.Create(Self);
end;

Asset Packages

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
//   ...

Importing Assets

From File

var LAsset: TGorillaAsset;
begin
  // Import auto-detects the asset type by file extension
  LAsset := TGorillaAsset.ImportFromFile(SomeGroup, 'models/character.g3d');
end;

From Stream

LAsset := TGorillaAsset.ImportFromStream(SomeGroup, 'character.g3d', MyStream);

Import Flags

Flag Description
StrictFileName Match filename exactly (no path normalization)
Cached Mark asset as cached immediately

Asset Groups and Subgroups

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);

Loading and Accessing Assets

Asset Properties

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

Asset States

State Description
asUndef Undefined
asLoading Currently loading
asLoaded Loaded and available
asStoring Currently saving
asStored Saved to package

Extension Detection

// Check if a file extension is supported
if TGorillaAsset.IsExtensionSupported('.g3d') then ...;

// Get the asset class for an extension
var LClass := TGorillaAsset.GetSupportedAssetClass('.png');

Package Versioning

Asset packages include version information (current version: 1.3):

Best Practices

Camera Controllers

Gorilla3D provides pre-built camera and character controllers for common 3D navigation patterns. These components handle keyboard, mouse, and gamepad input to move and rotate a camera or character in 3D space, saving you from implementing movement logic from scratch.

Table of Contents

Overview

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.

Class Hierarchy

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.

Character Controller (Base)

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.

States

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);

HotKeys

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];

Movement Properties

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

Events

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)

First-Person Controller

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.

First-Person Setup

Design-Time

  1. Drop a TGorillaInputController onto your form
  2. Drop a TGorillaFirstPersonController onto your viewport
  3. Set InputController to link to the input controller
  4. Set Camera to link to your TGorillaCamera
  5. Configure speed, drag modes, and angle limits as needed

Runtime

var
  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;

Mouse Configuration

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

Rotation and Movement Drag Modes

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)

First-Person Example

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;

Third-Person Controller

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.

Third-Person Setup

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;

Orbit Camera

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:

Third-Person Example

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;

Trigger Points

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.

Static vs Dynamic

Kind Description
StaticTriggerPoint Fixed 3D world coordinate that never moves
DynamicTriggerPoint Follows a linked TControl3D, with the trigger point position as offset

Trigger Point Setup

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;

Trigger Point Properties

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)

Trigger Point Events

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;

Trigger Point Example

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;

Combining with Input System

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;

Best Practices

TGorillaTextureBitmap

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.

Table of Contents

Why TGorillaTextureBitmap?

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:

TGorillaTextureBitmap solves all of these by extending TTextureBitmap with the missing GPU texture parameters while staying compatible with FMX's rendering pipeline.

FMX Texture Pipeline Recap

In standard FMX, the texture pipeline works like this:

TBitmap (CPU image data)
  └── TTextureBitmap (extends TBitmap, owns a TTexture)
        └── TTexture (GPU texture handle)
  1. TBitmap holds pixel data in CPU memory
  2. TTextureBitmap extends TBitmap and internally creates a TTexture when the Texture property is accessed
  3. TTexture 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.

What Gorilla3D Adds

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.

Class Hierarchy

// FMX base classes
FMX.Graphics.TBitmap
  └── FMX.Graphics.TTextureBitmap
        └── Gorilla.Context.Texturing.TGorillaTextureBitmap

FMX.Types3D.TTexture
  └── Gorilla.Context.Texturing.TGorillaTexture

Creating Textures

Basic Creation

uses Gorilla.Context.Texturing;

// Create a standard RGBA texture bitmap
var LBmp := TGorillaTextureBitmap.Create(512, 512);
try
  // Use it...
finally
  LBmp.Free;
end;

Creating with Custom Format

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;

Creating a Depth Texture (for Shadow Maps)

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;

Texture Properties

Core Properties

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

Filtering

Property Type Description
MinFilter TTextureFilter Minification filter: Nearest or Linear
MagFilter TTextureFilter Magnification filter: Nearest or Linear

Wrapping

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

Advanced Properties

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)

Pixel Formats

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 vs Gorilla Format Comparison

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

Wrapping and Filtering

Wrapping Modes

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: TGorillaTextureBitmap defaults to ClampToEdge on all three axes, whereas the underlying TGorillaTexture defaults to Repeated. 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.

Tiling and Seamless Repeats

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 (and WrapR for 3D textures) must not be Clamp, ClampToEdge or ClampToBorder — otherwise dark / black lines appear along the tile edges. Use Repeated (or MirroredRepeat) 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).

Filtering

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

3D Textures and Cube Maps

3D Textures

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;

Cube Maps

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

Compressed Textures

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

Multisampled Textures

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.

The Buffer Workaround

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:

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

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

Best Practices

Render Pass Controller

Render 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.

Overview

A render pass controller (TGorillaRenderPassController) manages a separate rendering stage with its own:

Common applications include:

Render Pass Types

Render passes execute at different stages of the rendering pipeline:

Pre-Pass (TRenderPassType.Pre)

Executes before the main rendering loop.

Use Cases:

Example:

ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass._Type := TRenderPassType.Pre;  // Executes before main scene

Post-Pass (TRenderPassType.Post)

Executes after the main rendering loop.

Use Cases:

Example:

BlurPass := TGorillaRenderPassCustomBlur.Create(Self);
BlurPass._Type := TRenderPassType.Post;  // Executes after main scene

Intermediate Pass (TRenderPassType.Intermediate)

Executes during the main rendering loop.

Use Cases:

Example:

CustomPass := TMyCustomRenderPass.Create(Self);
CustomPass._Type := TRenderPassType.Intermediate;

Render Methods

RenderListToFBO

Renders all 3D objects from the scene to the render pass FBO.

Behavior:

Use Cases:

Example:

DepthPass.Method := TRenderPassMethod.RenderListToFBO;

RectToFBO

Renders a fullscreen quad with a shader material to the FBO.

Behavior:

Use Cases:

Example:

BlurPass.Method := TRenderPassMethod.RectToFBO;
BlurPass.Shader := BlurShaderMaterial;

Render Procedures

The RenderProc property controls how objects are rendered within a pass:

DefaultRendering

Uses complete WBOIT (Weighted Blended Order Independent Transparency) pipeline:

Use When:

Example:

ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering;

ListRendering

Renders all objects straight forward without separation:

Use When:

Example:

DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering;

Basic Configuration

Linking to Viewport

Every render pass must be linked to a viewport:

var
  ReflectionPass: TGorillaRenderPassReflection;
begin
  ReflectionPass := TGorillaRenderPassReflection.Create(Self);
  ReflectionPass.Viewport := GorillaViewport1;

  // Rest of configuration...
end;

Unique ID

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.


Basic Properties

// 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

Viewport Size Configuration

Render passes can use custom viewport sizes different from the main viewport.

Using Main Viewport Size

ReflectionPass.OverwriteViewportSize := False;  // Use main viewport dimensions

Custom Fixed Size

ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;

Use Cases:


Scaled Size

ReflectionPass.OverwriteViewportSize := False;  // Use main viewport as base
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 0.5;  // Half resolution

Use Cases:


Combining Custom Size and Scale

ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 512;
ReflectionPass.ViewportHeight := 512;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 2.0;  // Results in 1024x1024

Control Filtering

Control filtering allows selective rendering of scene objects in a render pass.

Ignoring Controls

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

Allowing Specific Controls

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:

Example Scenario:

// Allow terrain and props
BackfacePass.AllowControl(Terrain);
BackfacePass.AllowControl(Props);

// But ignore specific prop
BackfacePass.IgnoreControl(TransparentWindow);  // Excluded from allowed props

Checking If Control Is Ignored

if ReflectionPass.IsControlIgnored(WaterPlane) then
  ShowMessage('Water plane will not be rendered in reflection');

Background Color

Using Viewport Color

ReflectionPass.OverwriteColor := False;  // Use viewport's background color

Custom Background Color

ReflectionPass.OverwriteColor := True;
ReflectionPass.BackgroundColor := TAlphaColorRec.Skyblue;

Use Cases:

Pass Chaining

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);

Events and Callbacks

Render passes provide events for custom logic at various stages:

OnBeginSetup

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;

OnEndSetup

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;

OnBeginRender

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

OnEndRender

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;

Accessing Output Texture

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;

Built-In Render Passes

Gorilla3D includes several ready-to-use render pass implementations:

TGorillaRenderPassReflection

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


TGorillaRenderPassRefraction

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


TGorillaRenderPassCustomDepth

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


TGorillaRenderPassCascadedShadows

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


TGorillaRenderPassCustomBlur

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)


TGorillaRenderPassFXAA

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


TGorillaRenderPassEnvironment

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


TGorillaRenderPassFace

Renders front- or back-face vertex positions into a float texture — the entry/exit geometry for ray-cast volumetric rendering.

Features:

Example:

var
  FacePass: TGorillaRenderPassFace;
begin
  FacePass := TGorillaRenderPassFace.Create(Self);
  FacePass.Viewport := Viewport;
  FacePass.FaceKind := FrontFace;
  FacePass.FaceOutput := ModelSpace;
end;

→ API reference: TGorillaRenderPassFace


TGorillaRenderPassUnderwater

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

Advanced Techniques

Conditional Pass Execution

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;

Dynamic Resolution Scaling

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;

Create Your Own Render Pass

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:

Render All Elements With The Same Material

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.

Render All Elements With Their Original Material

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;

Render Once With A Render Material

For post effects this mode is the intended way.


Performance Considerations

  1. Resolution Matters: Lower resolution passes are much faster. Use scaled viewports for non-critical passes.

  2. Minimize Passes: Each render pass has overhead. Combine effects when possible.

  3. Use ListRendering for Depth: When transparency doesn't matter (depth/shadow passes), use TRenderPassRenderingProc.ListRendering.

  4. Control Filtering: Exclude unnecessary objects. Every object tested has a small cost.

  5. Conditional Execution: Skip passes when not visible or needed (use SkipRendering()).

  6. Iterations Cost: Each iteration re-renders. Use sparingly.

  7. Pass Order: Pre-passes execute first. Minimize pre-pass count.

Troubleshooting

Pass Not Executing

Problem: Render pass doesn't seem to run.

Solutions:


Black/Empty Output Texture

Problem: OutputTexture is black or empty.

Solutions:


Objects Not Filtered Correctly

Problem: Ignored controls still render.

Solutions:


Performance Issues

Problem: Render passes cause slowdown.

Solutions:

Best Practices

  1. Always Exclude Self: Water reflections should exclude the water plane itself.

  2. Use Pre-Passes Sparingly: Each pre-pass delays the main render. Minimize count.

  3. Match Resolution to Use: Shadow maps can be lower res. Reflections should match quality needs.

  4. Unique IDs: Use descriptive, unique IDs like 'WaterReflection' not 'Pass1'.

  5. Event Usage: Use events for dynamic configuration, not fixed setup.

  6. Chain When Possible: Link passes with SetInputPass() for cleaner code.

  7. Profile First: Measure performance impact before optimizing.

See Also

API Reference: Built-In Render Passes

3D Model Formats

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.

Table of Contents

Supported Formats Overview

Natively Parsed 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

Mayo CLI-Based Formats

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

Export Formats

Format Extension Notes
G3D .g3d Full round-trip (materials, animation, skeleton)
OBJ .obj Mesh + MTL materials
STL .stl Mesh only

Native Format (G3D)

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');

Common Formats

glTF / GLB

The GL Transmission Format is the modern standard for 3D content. GLB is the binary variant.

FBX

Autodesk's FBX format is widely used in game and film production.

COLLADA (DAE)

An XML-based interchange format.

OBJ (Wavefront)

Simple and widely supported.

CAD Formats

STEP

Industry-standard CAD format with B-Spline surface tessellation.

USD (Universal Scene Description)

Pixar's scene description format.

Game/Legacy Formats

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

Image/Texture Formats

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)

Loading Models

// 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;

Loading Specific Formats

// 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');

Exporting Models

// Export to G3D (preserves everything)
GorillaModel1.SaveToFile('output/model.g3d');

// Export to OBJ
uses Gorilla.Exporter;
// Use the exporter for OBJ and STL export

Best Practices

Primitives

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.

Table of Contents

Overview

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

Basic Shapes

Cube

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;

Sphere

uses Gorilla.Sphere;

var Sphere := TGorillaSphere.Create(Self);
Sphere.Parent := GorillaViewport1;
Sphere.Width := 2;
Sphere.Height := 2;
Sphere.Depth := 2;

Cylinder

uses Gorilla.Cylinder;

var Cyl := TGorillaCylinder.Create(Self);
Cyl.Parent := GorillaViewport1;
Cyl.Width := 1;
Cyl.Height := 3;
Cyl.Depth := 1;

Cone

uses Gorilla.Cone;

var Cone := TGorillaCone.Create(Self);
Cone.Parent := GorillaViewport1;
Cone.Width := 2;
Cone.Height := 3;

Capsule

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;

Hemisphere

uses Gorilla.Hemisphere;

var HS := TGorillaHemisphere.Create(Self);
HS.Parent := GorillaViewport1;
HS.Width := 2;
HS.Height := 1;

Torus

uses Gorilla.Torus;

var Torus := TGorillaTorus.Create(Self);
Torus.Parent := GorillaViewport1;
Torus.Width := 3;
Torus.Height := 3;

Disk

uses Gorilla.Disk;

var Disk := TGorillaDisk.Create(Self);
Disk.Parent := GorillaViewport1;
Disk.Width := 2;

Plane

uses Gorilla.Plane;

var Plane := TGorillaPlane.Create(Self);
Plane.Parent := GorillaViewport1;
Plane.Width := 10;
Plane.Depth := 10;

Tube

A hollow cylinder.

uses Gorilla.Tube;

var Tube := TGorillaTube.Create(Self);
Tube.Parent := GorillaViewport1;
Tube.Width := 2;
Tube.Height := 3;

RoundCube

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;

Advanced Shapes

ExtrudedMesh

Creates 3D geometry by extruding a 2D polygon profile along an axis.

uses Gorilla.ExtrudedMesh;

var Extr := TGorillaExtrudedMesh.Create(Self);
Extr.Parent := GorillaViewport1;

ProfileMesh

Creates 3D geometry by sweeping a 2D profile along a path (lathe/revolution).

uses Gorilla.ProfileMesh;

var Prof := TGorillaProfileMesh.Create(Self);
Prof.Parent := GorillaViewport1;

GearMesh

Generates gear/cog geometry with configurable teeth.

uses Gorilla.GearMesh;

var Gear := TGorillaGearMesh.Create(Self);
Gear.Parent := GorillaViewport1;

Utility Objects

Grid

Displays a visual grid for scene orientation and scale reference.

uses Gorilla.Grid;

var Grid := TGorillaGrid.Create(Self);
Grid.Parent := GorillaViewport1;

SkyBox

Renders a skybox or sky dome around the scene.

uses Gorilla.SkyBox;

var Sky := TGorillaSkyBox.Create(Self);
Sky.Parent := GorillaViewport1;
// Assign skybox textures

Gizmo

3D manipulation gizmo for translate/rotate/scale operations.

uses Gorilla.Gizmo;

OrientationCube

A small orientation cube shown in a viewport corner.

uses Gorilla.OrientationCube;

Volumetric Objects

Volumetric Mesh

Base mesh for volumetric rendering effects (fog, clouds, etc.).

uses Gorilla.Volumetric.Mesh;

var Vol := TGorillaVolumetricMesh.Create(Self);
Vol.Parent := GorillaViewport1;

Volumetric Noise

Noise-based volumetric effects using procedural noise generation.

uses Gorilla.Volumetric.Noise;

Common Operations

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

Best Practices

Animation

Gorilla3D 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.

Animation Architecture

Key Components

TGorillaAnimationManager (Component)
└─ TGorillaAnimation Collection
   └─ TSkeletonKeyAnimation (Container)
      └─ TPropertyKeyAnimation instances
         ├─ TPoint3DKeyAnimation
         ├─ TVector3DKeyAnimation
         ├─ TQuaternion3DKeyAnimation
         ├─ TTransformationKeyAnimation
         └─ TCoordinateKeyAnimation

Animation Types

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

Animation Manager

The TGorillaAnimationManager is the central component for managing all animations associated with a 3D model or character.

Basic Setup

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.

Runtime

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;

Playing Animations

By Name

// Play a specific animation
Manager.PlayAnimation('Walk');

// Check current animation
if Manager.CurrentAnimationName = 'Run' then
  ShowMessage('Character is running');

By Instance

var
  WalkAnim: TGorillaAnimation;
begin
  WalkAnim := Manager.GetAnimation('Walk');
  if Assigned(WalkAnim) then
    Manager.PlayAnimation(WalkAnim);
end;

Sequential Playback

// Play next animation in sequence
Manager.PlayNextAnimation();

// Play previous animation
Manager.PlayPreviousAnimation();

Animation Control

// 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

Property key animations allow you to animate specific properties of 3D objects using keyframes.

TPoint3DKeyAnimation

Animates TPoint3D properties like Position, Scale, or Rotation.

Basic Example

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;

Animating Multiple Objects

// 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);

Animation Properties

// 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

TVector3DKeyAnimation

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;

TQuaternion3DKeyAnimation

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;

TTransformationKeyAnimation

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 Animation

Skeletal (or armature) animation uses bones/joints to deform a mesh. This is the standard approach for character animation.

TSkeletonKeyAnimation

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;

Skeleton Animation Control

// 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;

AutoRepaint

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 Animation

Vertex (or mesh) animation directly modifies mesh vertices over time, useful for organic deformations and morph targets.

TCoordinateKeyAnimation

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;

Loading Animations from Files

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;

Animation Transformation

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;

Animation Caching

For performance optimization, Gorilla3D can cache animated frames:

Frame Caching

// 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;

Fixed Frame Debugging

// Set specific frame for debugging
Animation.SetFixedCacheFrame(15);  // Show frame 15

// Release fixed frame
Animation.UnsetFixedCacheFrame();

Frame Information

// Get animation frame info
ShowMessage(Format('Frames: %d, FPS: %d', [
  Animation.FrameCount,
  Animation.FrameRate
]));

Force Stepping

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:

Returns: True if step was forced and viewport needs updating

Animation Events

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;

Simple Property Animation

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;

Best Practices

  1. Use Skeleton Animation for Characters: Group related joint animations in TSkeletonKeyAnimation for synchronized playback

  2. Cache Complex Animations: Enable frame caching for CPU-intensive vertex animations

  3. Control AutoRepaint: Disable AutoRepaint and manually control viewport updates for better performance

  4. Use Quaternions for Rotation: TQuaternion3DKeyAnimation provides smoother rotation than Euler angles

  5. Optimize Keyframe Count: Use only necessary keyframes; interpolation handles in-between frames

  6. Force Stepping for Smoothness: Use ForceStep() in rendering loops to avoid FMX timer jitter

  7. Check Animation State: Always verify IsRunning before operations that depend on active animation

  8. Proper Cleanup: Always stop animations before destroying animated objects

  9. Use Animation Manager: Centralize animation control through TGorillaAnimationManager

  10. Test Playback Speed: Adjust animation speed based on target platform performance

Common Patterns

Continuous Rotation

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;

Bounce Effect

Anim := TPoint3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Position.Point';
Anim.Interpolation := TInterpolationType.Bounce;
Anim.AnimationType := TAnimationType.Out;
Anim.Duration := 1.0;
// ... add keys
Anim.Start();

Ping-Pong Animation

Anim := TPoint3DKeyAnimation.Create(Self);
Anim.Loop := True;
Anim.AutoReverse := True;  // Plays forward then backward
// ... configure and start

Troubleshooting

Animation Not Playing

// 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;

Jerky Playback

// Use ForceStep for smoother updates
TGorillaAnimationManager.ForceStep(0.01);

// Or adjust interpolation
Animation.Skeleton.Interpolation := TInterpolationType.Cubic;

Animation Too Fast/Slow

// Adjust speed
Animation.SetSpeed(0.5);  // Half speed
Animation.SetSpeed(2.0);  // Double speed

Memory Issues with Vertex Animation

// Enable caching to reduce real-time computation
// Ensure proper cleanup of cached frames

See Also

Creating Custom Meshes

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.

Mesh Geometry

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

Simple Polygon Method

The straightforward approach involves creating a custom mesh class and defining geometry using polygon vertices.

Basic Example: Triangle Mesh

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;

Creating a Cube

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;

Helper Methods

After defining geometry with AddPolygon(), use these helper methods:

CalcTextureCoordinates()

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
CalcFaceNormals()

Computes surface normals for lighting:

LDef.CalcFaceNormals();
CalcTangentBinormals()

Calculates tangent and binormal vectors required for normal mapping:

LDef.CalcTangentBinormals();

Making Mesh Static

Transfer mesh data to GPU memory for rendering:

LDef.IsStatic := True;

Important: Set IsStatic := True only after all geometry is finalized. Once static, vertex data cannot be modified.

Direct TMeshData Manipulation

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;

Advanced Technique: TVertexCache

For complex meshes requiring custom normals, multiple texture coordinates, vertex colors, or skeletal animation, use TVertexCache.

TVertexCache Architecture

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

Workflow

  1. Create TVertexCache instance
  2. Populate source buffers (positions, normals, UVs, colors)
  3. Define triangles/polygons using vertex indices
  4. Create mesh definition from cache
  5. Load into TGorillaModel

Basic Example: Custom Mesh with TVertexCache

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;

Adding Data to TVertexCache

Individual Append Methods

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);
Batch Set Methods

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;

Multiple Texture Coordinates

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

Vertex Colors

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

Generate Triangles / Polygons

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; const AIndices : TList; const AVertexOrder : TVertexOrder = TVertexOrder.CCW) : Integer; 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; const AIndices : TList; const AVertexOrder : TVertexOrder = TVertexOrder.CCW) : Integer; 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

Hierarchy and Transforms

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;

Vertex Groups

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.

Materials

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;

Animations

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.

Armature & SkinController

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;

Verify mesh vertex weights

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;

Add a Skin-Animation

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.

TPoint3DInterpolatorDef

Control TPoint3D properties like Position, RotationAngle or Scale by interpolators of that kind. Each 3D point consists of a X, Y and Z value.

TVector3DInterpolatorDef

Control TVector3D properties by interpolators of that kind. Each 3D vector consists of a X, Y, Z and W value.

TTransformationInterpolatorDef

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.

TQuaternionInterpolatorDef (Rotation Only)

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;

TMeshInterpolatorDef (Vertex Animation)

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;

Materialization

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;

Complete Example: Animated Triangle

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;

Best Practices

  1. Choose the Right Approach: Use simple polygon method for basic shapes or TVertexCache for complex geometry

  2. Normalize Weights: Ensure vertex weights sum to 1.0 for skeletal animation

  3. Validate Skin: Always call CheckMeshVerticesToBeAttachedCorrectly() after defining skin weights

  4. Set IsStatic Appropriately: Only set IsStatic := True for geometry that won't change

  5. Use Appropriate Index Format: Gorilla3D automatically uses UInt16 on mobile, UInt32 on desktop

  6. Avoid Vertex Groups with Animation: Vertex groups currently don't support skeletal/vertex animation

  7. Cache Animations: Use caching flags for better animation performance

  8. Proper Hierarchy: Use AddChild() to maintain correct parent-child relationships

  9. Test Normals: Verify normals point in correct direction for proper lighting

Troubleshooting

Mesh Not Visible

// 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;

Black/Incorrectly Lit Mesh

// Recalculate normals
Model.CalcFaceNormals();

// For normal mapping
Model.CalcTangentBinormals();

Animation Not Working

// 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');

Memory Issues

// Clear cache after use
Cache.ClearBuffers();

See Also

Default Material

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.

Node-Based Shader Architecture

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.

Shader Structure

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

Node Classes

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

Important Fragment Shader Nodes

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

Shader Define System

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);

Available Defines

Shader Type:

Lighting & Shading:

Mapping Techniques:

Shadows & Effects:

Texturing:

Uniform Buffer: TGorillaShaderData

All shader parameters are transmitted via a packed record (TGorillaShaderData) as a Uniform Buffer Object (UBO). This is more efficient than submitting variables individually.

Key Fields

Matrices:

Camera & Timing:

Material & Lighting:

Fog:

Scene Bounds:

Special:

GLSL Variables

Vertex Attributes

Sixteen 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

Varying Parameters (vars.*)

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

TLocals Structure (Vertex Shader)

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

TLocals Structure (Fragment Shader)

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

Default Textures

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

Render Targets (MRT)

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

Custom VertexShader and SurfaceShader

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.

VertexShader Function

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
}

SurfaceShader Function

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;
}

Design-Time Usage

In the Object Inspector, expand the VertexShader or SurfaceShader property and write your GLSL code directly in the Text subproperty.

Runtime Usage

Important: The VertexShader and SurfaceShader properties are dynamic properties (published as TStrings). You cannot simply assign a string to .Text at runtime. Instead, you must assign a TStringList instance 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 := '...' or Material.VertexShader.Text := '...' at runtime. Since these are dynamic properties, writing to .Text directly will not trigger the necessary internal update mechanism. Always assign a TStrings/TStringList instance.

Example: Spritesheet Animation

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;
}

Extending the Material at Runtime

Adding Custom Uniform Buffers

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.

Registering Custom Textures

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.

Declaring Custom Shader Variables

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;

Adding Custom GLSL Functions

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)
);

Replacing Existing Nodes

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;

The Bitmaps Property (Texture Pool)

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.

TGorillaBitmapPoolEntry Properties

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 Bitmap property is therefore the raw image source of a texture entry, while Format, DataType, WrapS/T/R, the filters and Tiling describe how that image is uploaded to the GPU and sampled in the shader.

Texture Tiling

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 Tiling alone does not change the wrap mode. Because the tiling is computed with mod(texcoord * tiling, 1.0), it works even with a clamping wrap mode — but with WrapS/WrapT (and WrapR for 3D textures) set to Clamp, ClampToEdge or ClampToBorder, 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) to TGorillaTextureWrap.Repeated (or MirroredRepeat). Note that a fresh bitmap pool entry defaults to a clamping wrap mode, so this step is required whenever Tiling > 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

Design-Time Texture Management

  1. Open the Bitmaps property editor in the Object Inspector
  2. Add an item with a unique name (e.g., MyTexture)
  3. Select the shader target (PixelShader / VertexShader)
  4. Configure properties:

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).

See Also

Material Behaviours

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 TGorillaDefaultMaterialSource and derived Gorilla3D materials. They do not work with FireMonkey's embedded materials like TLightMaterialSource or TColorMaterialSource.

Concept

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 vs. Behaviours

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;

Architecture

How Behaviours Work

  1. Shader Injection: Behaviours add custom shader code to materials during shader compilation
  2. Uniform Buffers: Each behaviour manages its own GPU uniform buffer (std140 layout)
  3. Per-Material State: Each material maintains separate uniform buffer instances
  4. Centralized Control: Single behaviour instance controls parameters for all attached materials

Component Hierarchy

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)

Built-in Behaviours

TGorillaMaterialWindBehaviour

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;

TGorillaMaterialWobbleBehaviour

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;

TGorillaMaterialRimLightBehaviour

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;

TGorillaMaterialCausticsBehaviour

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;

TGorillaMaterialColorAdjustBehaviour

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;

TGorillaMaterialDesignTimeBehaviour

Special behaviour for design-time shader customization without coding.

Use Cases: Quick prototyping, designer-friendly customization, runtime experiments

Features:

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;

Usage Patterns

Attaching Behaviours at Design-Time

  1. Add material behaviour component to form (e.g., TGorillaMaterialWindBehaviour)
  2. Configure behaviour properties in Object Inspector
  3. Select material source component
  4. Expand Behaviours collection in Object Inspector
  5. Add new behaviour item
  6. Set Behaviour property to your behaviour component

Attaching Behaviours at Runtime

var
  Behaviour: TGorillaMaterialWindBehaviour;
begin
  Behaviour := TGorillaMaterialWindBehaviour.Create(Self);
  Behaviour.WindPower := 2.0;

  // Attach behaviour to material
  Material.AttachMaterialBehaviour(Behaviour);
end;

Detaching Behaviours

// Remove specific behaviour
Material.DetachMaterialBehaviour(WindBehaviour);

// Remove all behaviours
Material.ClearMaterialsBehaviours();

Checking Behaviour Attachment

// 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));

Sharing Behaviours Across Materials

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;

Multiple Behaviours per Material

// Combine multiple effects
Material.AttachMaterialBehaviour(WindBehaviour);
Material.AttachMaterialBehaviour(RimLightBehaviour);
Material.AttachMaterialBehaviour(ColorAdjustBehaviour);

Creating Custom Behaviours

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;

Advanced Topics

Uniform Buffer std140 Layout

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;

Shader Node System

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;

Viewport Integration

Some behaviours require viewport for rendering debug visualizations:

WindBehaviour.Viewport := Viewport;
WindBehaviour.ShowVisualizer := True;  // Shows wind direction arrow

Performance Considerations

  1. Uniform Buffer Updates: Behaviours update GPU buffers every frame. Minimize parameter changes.

  2. Shader Compilation: Adding/removing behaviours triggers shader recompilation. Attach behaviours once at initialization.

  3. Multiple Behaviours: Each behaviour adds shader code. Too many behaviours increase shader complexity.

  4. Shared Behaviours: One behaviour instance for multiple materials is more efficient than multiple instances.

  5. Memory Layout: Incorrect std140 alignment causes GPU errors. Always pad structs properly.

Limitations

  1. Gorilla Materials Only: Behaviours don't work with FireMonkey materials (TLightMaterialSource, TColorMaterialSource, etc.)

  2. Shader Complexity: Too many behaviours may exceed shader complexity limits on older hardware

  3. Platform Differences: Some GLSL features may behave differently across platforms (OpenGL vs OpenGL ES vs Metal)

  4. Design-Time: Behaviour changes at design-time may not update immediately; recompile project

Best Practices

  1. Share Behaviours: Create one behaviour instance per effect type, attach to multiple materials

  2. Initialize Early: Attach behaviours during form creation, not runtime loops

  3. Use Events: Handle OnAttached/OnDetached events for cleanup

  4. Batch Updates: Use Material.BeginChange()/EndChange() when modifying multiple properties

  5. Debug Visualization: Enable visualizers during development, disable for production

  6. Test on Target: Verify behaviour effects on target platform before deployment

  7. Monitor Shader Size: Check generated shader code size; excessive complexity impacts performance

  8. Profile Performance: Measure GPU performance impact, especially with multiple behaviours

Common Patterns

Wind System for Vegetation

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;

Character Rim Lighting

var Rim: TGorillaMaterialRimLightBehaviour;
begin
  Rim := TGorillaMaterialRimLightBehaviour.Create(Self);
  Rim.RimColor := TAlphaColorRec.Cyan;
  Rim.RimIntensity := 0.25;

  CharacterSkinMaterial.AttachMaterialBehaviour(Rim);
  CharacterArmorMaterial.AttachMaterialBehaviour(Rim);
end;

Underwater Scene

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;

See Also

Water Material

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.

Overview

Water rendering in Gorilla3D uses a specialized material that combines:

Basic Setup

Required Components

A complete water surface requires:

  1. Mesh: TGorillaPlane or custom water mesh
  2. Material: TGorillaWaterMaterialSource
  3. Reflection Pass: TGorillaRenderPassReflection
  4. Refraction Pass: TGorillaRenderPassRefraction
  5. Depth Pass: Provided by refraction pass or separate depth pass

Minimal Configuration

var
  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;

Required Textures

DUDV Map (Displacement)

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');

Normal Map

Surface normal information for lighting calculations and wave detail.

Characteristics:

Property: NormalMap: TBitmap

Example:

WaterMaterial.NormalMap.LoadFromFile('water_normal.png');

Specular Map

Controls specular highlight intensity across the water surface.

Characteristics:

Property: SpecularMap: TBitmap

Example:

WaterMaterial.SpecularMap.LoadFromFile('water_spec.png');

Displacement Map (Optional)

Vertex displacement for actual geometry deformation (wave height).

Characteristics:

Properties:

Example:

WaterMaterial.DisplacementMap.LoadFromFile('water_height.png');
WaterMaterial.Displacement := Vector3D(0, 1, 0);  // Y-axis displacement
WaterMaterial.DisplIntensity := 0.5;

Foam Texture (Optional)

Surface foam overlay texture.

Property: FoamTexture: TBitmap

Related Properties:

Example:

WaterMaterial.FoamTexture.LoadFromFile('foam.png');
WaterMaterial.FoamDirection := PointF(0.5, 0.5);
WaterMaterial.FoamIntensity := 1.0;

Shore Texture (Optional)

Shore foam texture displayed at shallow water edges.

Property: ShoreTexture: TBitmap

Related Properties:

Example:

WaterMaterial.ShoreTexture.LoadFromFile('shore_foam.png');
WaterMaterial.ShoreWidth := 2.0;
WaterMaterial.ShoreIntensity := 3.0;

Material Properties

Wave Animation

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

Color and Appearance

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;

Depth Effects

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;

Reflection and Refraction

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

Debug Output Layers

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

Ripples System

Interactive ripples were introduced in v0.8.3.2265 for dynamic water surface disturbances.

Configuration

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.

Adding Ripples

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();

Render Pass Configuration

Reflection Pass Setup

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;

Refraction Pass Setup

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;

Displacement Offset Compensation

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);

Complete Example

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;

Performance Considerations

  1. Subdivision Density: Higher mesh subdivision improves displacement mapping but increases vertex processing cost.

  2. Render Pass Resolution: Lower resolution reflection/refraction textures improve performance significantly.

  3. Ripple Count: Each active ripple adds computation cost. Limit simultaneous ripples for best performance.

  4. Texture Sizes: Use power-of-two textures (256x256, 512x512) for optimal GPU performance.

  5. Platform Differences: Mobile platforms have lower limits regarding texture performance.

Troubleshooting

Water Appears Black or Incorrect

Cause: Missing or incorrectly configured render passes.

Solution:


Reflections/Refractions Show Water Surface

Cause: Water plane not excluded from render passes.

Solution:

ReflectionPass.IgnoreControl(WaterPlane);
RefractionPass.IgnoreControl(WaterPlane);

Ripples Not Visible

Cause: RipplesActive is false or ripple parameters too subtle.

Solution:

WaterMaterial.RipplesActive := True;
WaterMaterial.RippleAmplification := 1.0;  // Increase for visibility

Displacement Offset Issues

Cause: Render pass planes don't account for displacement offset.

Solution: Adjust reflection/refraction plane positions by displacement amount.

See Also

Volumetric Mesh

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.

Table of Contents

Overview

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);

Required Setup: Front / Back Face Passes

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.

Loading Volume Data

The volume texture is filled from raw binary data. Wrap size/type changes in BeginUpdate / EndUpdate so the texture is only rebuilt once.

From a RAW file

Vol.BeginUpdate;
try
  Vol.Sizes    := TGorillaVolumetricMeshSize.vms256x256x256;
  Vol.DataType := TGorillaVolumetricMeshDataType.vmdtUInt8;
finally
  Vol.EndUpdate;
end;

Vol.LoadFromRawFile('teapot.raw', 256, 256, 178,
  TGorillaVolumetricMeshDataType.vmdtUInt8);

From an NRRD file

NRRD headers carry size, spacing and data type, so no extra parameters are needed:

Vol.LoadFromNRRDFile('skull.nrrd');

From image slices

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
);

From memory

Push your own buffer directly. The data layout must match Sizes and DataType:

Vol.SetRawData(MyBufferPtr, MyBufferSizeInBytes);

Volume Size & Data Type

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 LinearFiltering for smooth trilinear interpolation between voxels. With it off, integer textures are point-sampled and every voxel shows as a hard cube.

Rendering Modes: Solid Surface vs. Translucent Medium

The mesh composites samples along each ray. Two blend models are available, and choosing the right one is the single most important decision:

Linear blend — solid / opaque objects (default)

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;

Emission-absorption blend — fog / clouds / smoke / translucent media

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:

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.

Lighting & Iso-Surfaces

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.

Transfer Functions (Gamut)

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

Quality & Performance

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.

Details is the main quality/performance dial. 1–2 is a good range for medical data; higher only when you zoom in close.

Clipping & Ray Control

// 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.

Flying Inside the Volume

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.

Best Practices

See Also

Volumetric Noise

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.

Table of Contents

Quick Start

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.

Presets

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

Shaping the Noise

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 & the Emission-Absorption Model

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 vms32x32x32 looks comparably dense to one at vms64x64x64 for the same Density.

Flying Through the Body

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.

Animating Smoke & Clouds

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:

How It Works

The density stored per voxel is built as:

  1. FBM — Octaves of Perlin noise summed with Persistence and Lacunarity, base scale Frequency. Billowy uses abs(noise).
  2. Coverage — a soft threshold that carves the body into separate puffs.
  3. EdgeFalloff — a radial fade toward the border so the body is a rounded blob.

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.

Best Practices

See Also

Render Passes

Introduction

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:

Passes use two rendering strategies:

Table of Contents

  1. Anti-Aliasing (FXAA)
  2. Shadow Mapping
  3. Screen-Space Ambient Occlusion (SSAO)
  4. Global Illumination
  5. Reflections and Refractions
  6. Depth of Field (Bokeh)
  7. Blur Passes
  8. Post-Processing (PostFX)
  9. Underwater Effect
  10. Composite Pass
  11. Deferred Composite

Anti-Aliasing (FXAA)

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.

Key Methods

Method Description
SetCompositeInputTexture Assigns the input texture from the composite pass
GetFinalOutputTexture Returns the anti-aliased output texture

Runtime Setup

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.


Shadow Mapping

Standard Shadow Map (SM)

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.

Published Properties

Property Type Default Description
Light TLight nil The light source for shadow projection

Inherited from TGorillaRenderPassCustomDepth

Property Type Default Description
DepthMethod TDepthMethod dmDefault Depth calculation method: dmDefault, dmMVPPosZ, dmModelViewPosZ

Public Properties

Property Type Description
MapSize Integer Shadow map resolution
BiasMatrix TMatrix3D Light-space bias matrix for shadow lookup
DefaultDepth Single Default depth value for clear

Variance Shadow Map (VSM)

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.

Published Properties

Property Type Default Description
Light TLight nil The light source for shadow projection

VSM Blur

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.

Published Properties

Property Type Description
VSMStoreDepth TGorillaRenderPassVSMStoreDepth The VSM depth pass to blur (via GetInputPass/SetInputPass)

Screen-Space Shadows

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).

Published Properties

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

Screen-Space Ambient Occlusion (SSAO)

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).

Published Properties

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

Runtime Setup

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.


Global Illumination

Voxelization

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).

Published Properties

Property Type Default Description
VoxelSize Integer -- Voxel grid resolution (32..512, multiples of 32)
FocalLength Single -- Focal length for voxel projection

Public Properties

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 TGorillaRenderPassEmbeddedVoxelize for internal use by the deferred pipeline.

Global Illumination Pass

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.

Published Properties

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 TGorillaRenderPassEmbeddedGlobalIllum for internal deferred pipeline use.

Global Illumination Blur

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.

Public Properties

Property Type Description
GlobalIllumPass TGorillaRenderPassGlobalIllum The GI pass to blur
UpdateTexture Method Updates the input texture reference

Reflections and Refractions

Planar Reflection

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.

Published Properties

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

Runtime Setup

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;

Refraction

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.

Published Properties

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

Public Properties

Property Type Description
OutputDepthTexture Texture Depth texture output for refraction calculations

Environment Mapping

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.

Published Properties

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

Public Properties

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

Public Methods

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

Runtime Setup

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;

Depth of Field (Bokeh)

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.

Published Properties

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

Convenience Component: TGorillaBokeh

Unit: Gorilla.Bokeh

A design-time convenience component that wraps TGorillaRenderPassCustomDepth and TGorillaRenderPassBokeh together. Drop it onto a viewport to enable depth of field.

Runtime Setup

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;

Blur Passes

Custom Blur

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.

Published Properties

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: FastBlur may produce unexpected artefacts on some NVIDIA GPUs.

Emissive Blur

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.

Public Properties

Property Type Description
EmissiveTexture Texture The emissive G-buffer texture to blur

Post-Processing (PostFX)

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.

Published Properties

Property Type Default Description
SurfaceShader TStrings nil Custom GLSL shader code
MaskTexture TBitmap nil Optional mask texture

Available Shader Uniforms

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

UBO Time Data

The _TimeInfo vec4 uniform provides:

Surface Shader Signature

Your custom shader must implement:

vec3 SurfaceShader(inout TLocals DATA)

Public Methods

Method Description
ResetTime Resets the internal time counter
UpdateShader Recompiles the shader after changing SurfaceShader

Runtime Setup

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;

Underwater Effect

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).


Composite Pass

Unit: Gorilla.Controller.Passes.Composite Class: TGorillaRenderPassComposite Type: Post-pass, RectToFBO

Combines two render pass outputs using a configurable blending method.

Published Properties

Property Type Default Description
Method TCompositeMethod -- Blend operation: Add, Subtract, Multiply, Divide, Mix, Input1, Input2
BlendFactor Single -- Blending factor for Mix method

Public Methods

Method Description
SetInput2Pass Assigns the second input render pass

Deferred Composite

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.

Output Layer Flags

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

Key Material Textures

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

Key Properties

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

Dialogue System

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.

Table of Contents

Overview

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

Core Concepts

Item Kinds

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

Event Kinds

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

Event Triggers

Trigger Description
OnBegin Executed when the item is displayed
OnEnd Executed when the item is hidden
OnTimeout Executed when a timer expires

Getting Started

Design-Time

  1. Drop a TGorillaDialogueSystem onto your form
  2. Use the dialogue editor (IDE integration) to create dialogues visually
  3. Define characters, questions, answers, and events in the flow chart

Runtime

var
  DlgSys: TGorillaDialogueSystem;
begin
  DlgSys := TGorillaDialogueSystem.Create(Self);

  // Load a dialogue from file
  // Use Gorilla.Utils.Dialogue.Reader to load JSON files
end;

Dialogue Structure

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"

Events

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:

Characters

Characters represent speakers in the dialogue:

// Characters are managed in the TGorillaDialogueCharacterCollection
// Each character has an identifier and can be linked to dialogue items

Runtime Execution

Callbacks

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

Loading and Saving

The dialogue system uses JSON for serialization:

Dialogues can also be managed via the Assets Manager as DIALOGUE asset type.

Best Practices

Inventory System

The 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.

Table of Contents

Overview

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

Core Concepts

The inventory follows a template-instance pattern:

  1. Groups organize items into categories
  2. Templates define item blueprints (weight, max quantity, parameters)
  3. Collectables are runtime instances created from templates
  4. Manufacturers define crafting recipes using ingredients

Collect States

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

Getting Started

uses Gorilla.Utils.Inventory;

var
  Inventory: TGorillaInventory;
begin
  Inventory := TGorillaInventory.Create(Self);
end;

Item Groups

Groups categorize your items:

// Groups are collections within the inventory
// Example groups: Weapons, Armor, Consumables, Keys, Notes

Item Templates

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

Creating Templates

// Templates are prototypes - build collectables from them
var LCollectable := SomeTemplate.Build();

Dependencies

Templates can require other items to be present before collection:

// Add a dependency: need 2x "Key" to collect "Treasure"
TreasureTemplate.AddDependency('Key', 2);

Upgrade/Downgrade Chains

// Create an upgrade chain: Sword → BetterSword → BestSword
SwordTemplate.UpgradeItem := BetterSwordTemplate;
BetterSwordTemplate.UpgradeItem := BestSwordTemplate;
BestSwordTemplate.DowngradeItem := BetterSwordTemplate;

Collecting Items

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)

Manufacturing (Crafting)

The manufacturing system allows combining items:

Class Description
TGorillaInventoryManufacturer Contains crafting processes
TGorillaInventoryManufacturingProcess A single recipe
TGorillaInventoryIngredient An ingredient in a recipe

Manufacturing States

State Description
Undefined Not started
Processing Currently crafting
Completed Crafting finished
Failed Crafting failed

Serialization

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.

Best Practices

Skill System

The 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.

Table of Contents

Overview

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

Core Concepts

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)

Enabled vs Activated

Getting Started

uses Gorilla.Utils.SkillSystem;

var
  SkillSys: TGorillaSkillSystem;
begin
  SkillSys := TGorillaSkillSystem.Create(Self);
end;

Skill Groups

Groups organize skills into categories:

var LGroup := SkillSys.AddGroup(); // creates a TGorillaSkillGroup
LGroup.Name := 'Combat';
LGroup.Enabled := True;

Group Methods

function AddSkill(): TGorillaSkill;
function FindSkillByName(const ASkillName: String): TGorillaSkill;
function FindSkillByGUID(const AGUID: TGUID): TGorillaSkill;
procedure GetActivatedSkills(var AMap: TGorillaSkillMap);

Skills

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)

Level Interpolation

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

Leveling

Async Leveling Process

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.

Skill Switching

The system validates skill switching — ensuring that leveling constraints (like required sub-skills being activated) are respected.

Serialization

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.

Best Practices

Pathfinding

Gorilla3D 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.

Table of Contents

Overview

Class Description
TGorillaPathfindingAlgorithm Abstract base for pathfinding algorithms (obstacle and agent management)
TGorillaPathfindingAStar A* pathfinding implementation (in Gorilla.Utils.Pathfinding.AStar)

Getting Started

Design-Time

  1. Drop a TGorillaPathfindingAStar (or custom algorithm) onto your viewport
  2. Set the Agent property to the character/NPC that needs to navigate
  3. Add obstacles via code

Runtime

uses Gorilla.Utils.Pathfinding, Gorilla.Utils.Pathfinding.AStar;

var
  Pathfinder: TGorillaPathfindingAStar;
begin
  Pathfinder := TGorillaPathfindingAStar.Create(Self);
  Pathfinder.Parent := GorillaViewport1;
  Pathfinder.Agent := CharacterModel;
end;

Obstacles

Obstacles are 3D controls that block pathfinding. Each obstacle has a bounding box and can be static (optimized) or dynamic (recalculated each query).

Adding Obstacles

// 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);

Managing Obstacles

// 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();

Obstacle Margin

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

Obstacle Properties

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

Custom Obstacle Bounds

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;

A* Algorithm

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.

Finding Paths

// The pathfinder uses the Agent property to determine the start position
var AgentPos := Pathfinder.AgentPosition; // returns (0,0,0) if no agent set

Best Practices

GorillaScript Language Specification

Version: 1.1 (Bytecode Version: 0x00010001)

Last Updated: December 2025

Copyright: 2017-2025 Eric Berger, gorilla3d.de Gorilla3D Framework


Table of Contents

  1. Overview
  2. Architecture
  3. Syntax Specification
  4. Type System
  5. Control Flow Structures
  6. Functions and Procedures
  7. Classes and Interfaces
  8. Native Interoperability
  9. Bytecode Execution Model
  10. Performance Characteristics
  11. Known Limitations
  12. Example Scripts

1. Overview

1.1 What is GorillaScript?

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.

1.2 Key Features

1.3 Design Philosophy

GorillaScript is designed to provide a balance between performance and flexibility for scripting scenarios within the Gorilla3D Framework.

It prioritizes:


2. Architecture

2.1 Component Overview

GorillaScript consists of three main components:

  1. Parser (TGorillaScriptParserDelphi)

  2. Compiler (TGorillaScriptCompiler)

  3. Executor (TGorillaScriptExecutor)

2.2 Execution Pipeline

Source Code (.pas)
    ↓
Parser (Lexer + Syntax Analysis)
    ↓
Abstract Syntax Tree (AST)
    ↓
Compiler (Code Generation)
    ↓
Bytecode Stream
    ↓
Executor (VM Interpretation)
    ↓
Execution Result

2.3 Engine Architecture

The TGorillaScriptEngine component orchestrates all scripting activities:

2.4 Memory Model

Stack:

Call Stack:

Heap:


3. Syntax Specification

3.1 Language Basics

GorillaScript uses Pascal/Delphi syntax:

Case Sensitivity: Case-insensitive for keywords and identifiers Comments:

Statement Terminator: Semicolon (;)

3.2 Program Structure

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.

3.3 Variable Declarations

var
  MyInteger: Integer;
  MyString: String;
  MyBoolean: Boolean;
  MyObject: TMyClass;
  MyArray: TArray;

3.4 Constant Declarations

const
  MAX_VALUE = 100;
  APP_NAME = 'MyApp';
  PI_VALUE = 3.14159;

3.5 Operators

Arithmetic Operators:

Comparison Operators:

Logical Operators:

Bitwise Operators:

Special Operators:


4. Type System

4.1 Primitive Types

GorillaScript supports standard Delphi primitive types:

Integer Types:

Floating-Point Types:

Boolean Types:

String Types:

String Helper Methods:

Numeric Type Helpers:

All numeric types (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double) provide:

Special Types:

4.2 Structured Types

Arrays:

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:

Records (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;

4.3 Class Types

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:

4.4 Interface Types

type
  IMyInterface = interface
    ['{GUID}']
    procedure DoSomething;
    function GetValue: Integer;
  end;

  TMyClass = class(TInterfacedObject, IMyInterface)
  public
    procedure DoSomething;
    function GetValue: Integer;
  end;

4.5 Type Aliases

type
  TComponentName = String;
  TCallback = procedure(ASender: TObject) of object;

5. Control Flow Structures

5.1 If-Then-Else Statement

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;

5.2 Case Statement

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;

5.3 For Loop

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.

5.4 While Loop

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.

5.5 Repeat-Until Loop

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.

5.6 Try-Except-Finally

// 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;

5.7 Break and Continue

for i := 0 to 100 do
begin
  if ShouldSkip(i) then
    Continue;

  if ShouldStop(i) then
    Break;

  ProcessItem(i);
end;

6. Functions and Procedures

6.1 Procedure Declaration

procedure MyProcedure(Param1: Integer; Param2: String);
begin
  // Implementation
end;

6.2 Function Declaration

function MyFunction(Param1: Integer): String;
begin
  Result := IntToStr(Param1);
end;

6.3 Parameter Modifiers

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;

6.4 Function Overloading

function Calculate(A, B: Integer): Integer; overload;
begin
  Result := A + B;
end;

function Calculate(A, B: Double): Double; overload;
begin
  Result := A + B;
end;

6.5 Method Directives

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;

7. Classes and Interfaces

7.1 Class Definition

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;

7.2 Constructors and Destructors

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;

7.3 Properties

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;

7.4 Inheritance

type
  TBaseClass = class(TObject)
  public
    procedure BaseMethod;
  end;

  TDerivedClass = class(TBaseClass)
  public
    procedure DerivedMethod;
    procedure BaseMethod; override;
  end;

7.5 Interface Implementation

type
  IMyInterface = interface
    ['{GUID-HERE}']
    procedure InterfaceMethod;
  end;

  TMyClass = class(TInterfacedObject, IMyInterface)
  public
    procedure InterfaceMethod;
  end;

implementation

procedure TMyClass.InterfaceMethod;
begin
  // Implementation
end;

7.6 Object Lifetime

var
  MyObject: TMyClass;
begin
  // Create object
  MyObject := TMyClass.Create;
  try
    MyObject.DoWork;
  finally
    // Destroy object
    MyObject.Free;
  end;
end;

8. Native Interoperability

8.1 Overview

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.

8.2 Registering Native Classes

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;

8.3 Registering Enumerations

// In Delphi host code
Engine.RegisteredEnums.Add(
  TGorillaScriptRegisteredType.From(
    'MyUnit.TMyEnum',
    TypeInfo(TMyEnum)
  )
);

8.4 Registering Records

// In Delphi host code
Engine.RegisteredStructs.Add(
  TGorillaScriptRegisteredType.From(
    'MyUnit.TMyRecord',
    TypeInfo(TMyRecord)
  )
);

8.5 Registering Interfaces

// In Delphi host code
Engine.RegisteredInterfaces.Add('MyUnit.IMyInterface');

8.6 Native Method Calls

Native methods are called through RTTI with automatic type conversion:

8.7 Event Handling

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.

8.8 Default Native Types

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

8.9 Default Native Units

Pre-registered units available without explicit "uses" clause:


9. Bytecode Execution Model

9.1 Bytecode Structure

File Format:

Instruction Format:

OPERATION [OPERANDS...] DELIMITER

9.2 Bytecode Operations

The VM supports the following operation categories:

Control Flow:

Stack Operations:

Arithmetic Operations:

Comparison Operations:

Logical Operations:

Bitwise Operations:

Object Operations:

Control Structures:

9.3 Execution Model

Interpreter Loop:

  1. Read bytecode instruction
  2. Decode operation
  3. Execute operation via lookup table
  4. Update instruction pointer
  5. Repeat until HALT or RETURN

Method Dispatch:

Stack Frame: Each function call creates a stack frame containing:

9.4 Lookup Table Optimization

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);

10. Performance Characteristics

10.1 Loop Performance

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:

  1. Reading bytecode instruction (I/O operation)
  2. Looking up handler in table
  3. Function call overhead
  4. Stack frame creation
  5. Optional locking (thread-safe mode)
  6. Optional try-except (safe mode)

Workarounds:

  1. Minimize loop iterations where possible
  2. Move computation-heavy work to native methods
  3. Consider using native code for performance-critical loops
  4. Disable safe-mode and thread-safe mode if not needed

10.2 General Performance Guidelines

Execution Speed:

Memory Usage:

Optimization Tips:

  1. Use native methods for heavy computation
  2. Minimize loop iterations
  3. Cache method lookups when possible
  4. Use local variables instead of fields when possible
  5. Avoid deep call hierarchies
  6. Consider compilation overhead for short-lived scripts

11. Known Limitations

11.1 Critical Limitations

11.1.1 Self Context Issue

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.

11.1.2 For Loop Performance

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.

11.2 Language Limitations

11.2.1 Limited Generic Support

Generic types are supported only for pre-defined native types like TArray<T>. User-defined generic types are not supported.

11.2.2 No Inline Assembly

Inline assembly (asm blocks) is not supported and will cause compilation errors.

11.2.3 Limited Preprocessor

Compiler directives support is limited:

11.2.4 No Advanced RTTI Attributes

Custom attributes beyond basic system attributes may not be accessible in scripts.

11.2.5 Limited Variant Support

The Variant type has limited support. Use TValue for dynamic typing instead.

11.3 Implementation Limitations

11.3.1 Thread Safety

Thread-safe mode adds significant performance overhead (~600ms per million iterations). For single-threaded scenarios, disable with:

// In source code, remove {$DEFINE THREADSAFE}

11.3.2 Memory Limits

Hard-coded memory limits:

These limits require recompilation to change.

11.3.3 Error Reporting

Error messages may not always provide accurate line numbers or context, especially for complex expressions.

11.3.4 Debugging Support

Limited debugging capabilities:

11.4 Interoperability Limitations

11.4.1 Pointer Arithmetic

Pointer arithmetic is not supported. Pointers can be stored and passed but not manipulated.

11.4.2 Raw Memory Access

Direct memory access functions (like Move, FillChar) may have limited or no support.

11.4.3 External Library Calls

No support for calling external DLLs directly. Must be wrapped in native Delphi code first.


Appendix A: Bytecode Reference

Complete Bytecode Operation List

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

Appendix B: Troubleshooting

Common Issues and Solutions

Issue: "Field not found in class method"

Issue: "Script runs slowly with loops"

Issue: "Stack overflow error"

Issue: "Out of stack space"

Issue: "Cannot access native class member"


Appendix C: Version History

Version 1.1 (Current)

Known Issues in Current Version


Appendix D: References

Source Files

Core Files:

Library Files:

External Dependencies


End of Specification

Input Polling System

Comprehensive input handling for keyboard, mouse, and gamepad devices.

Component: TGorillaInputController

Table of Contents

Introduction

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:

Getting Started

Design-Time Setup

  1. Drop a TGorillaInputController component onto your form
  2. Set the Enabled property to True
  3. Configure Supported property to enable desired devices:

Example:

// Enable all devices
GorillaInputController1.Supported := [Keyboard, Mouse, GamePad];
GorillaInputController1.Enabled := True;

Runtime Setup

var
  LController: TGorillaInputController;
begin
  LController := TGorillaInputController.Create(Self);
  LController.Supported := [Keyboard, Mouse, GamePad];
  LController.Enabled := True;
end;

HotKeys

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.

Creating HotKeys

HotKeys consist of:

Design-Time HotKeys

  1. Select your TGorillaInputController component
  2. Find the HotKeys property in Object Inspector
  3. Click [...] to open the collection editor
  4. Click Add to create a new HotKey
  5. Set the Name property (e.g., "Jump", "Fire", "Sprint")
  6. Expand the Combinations property
  7. Add input items for each key/button:

Example: 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

Runtime HotKeys

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

Trigger Modes

TriggerOnActivate:

TriggerOnDeactivate:

Both Modes:

// 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

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

Sequences detect ordered combinations of HotKeys (like fighting game combos). You can chain up to 16 HotKeys in a sequence.

Creating Sequences

Sequences consist of:

Design-Time Sequences

  1. First, create individual HotKeys for each input
  2. Select your TGorillaInputController component
  3. Find the Sequences property in Object Inspector
  4. Click [...] to open the collection editor
  5. Click Add to create a new Sequence
  6. Set the Name property (e.g., "Combo1", "CheatCode")
  7. Expand the HotKeys property
  8. Add sequence items linking to existing HotKeys:
  9. Set Sensitivity (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"

Runtime Sequences

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

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)

Input Devices

Keyboard

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;

Mouse

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;

GamePad

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

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

Mouse 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;

GamePad Triggers

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;

GamePad Thumbsticks

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;

Raw Input Events

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 Support

Platform Keyboard Mouse GamePad Notes
Windows ✓ ✓ ✓ (XInput) Low-level hooks for keyboard/mouse
Linux ✓ ✓ ✓ (SDL2) Requires SDL2 library
Android ✓ ✓ ✓ Touch events mapped to mouse

High-Performance Hooks (Windows)

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:

  1. Open RegEdit.exe (Windows)
  2. Move to the path: “HKEY_CURRENT_USER\Control Panel\Desktop\”
  3. Add a new value of type DWORD with the name “LowLevelHooksTimeout”
  4. Enter a value which stands for the timeout in milliseconds (f.e. 50ms)
  5. A system restart is required!

Linux SDL Installation

Since v1.1.16.+ Linux support is available for input polling. Gamepad/joystick handling is solved by using SDL2.

Install SDL2 on your system

Debian/Ubuntu:

sudo apt-get install libsdl2-2.0-0

Fedora/RHEL:

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

On Windows PowerShell as Admin

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.

Performance

Sensitivity

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:

Thread Safety

All operations are thread-safe:

Memory Usage

Best Practices

1. Use Descriptive Names

// Good
AddHotKey('PlayerJump');
AddHotKey('WeaponReload');
AddSequence('SuperCombo');

// Bad
AddHotKey('HK1');
AddHotKey('Input2');
AddSequence('Seq1');

2. Set Lock Times for Actions

// Prevent spam
LHotKey := AddHotKey('Attack');
LHotKey.LockTime := 250;  // Match animation duration

3. Enable Only Needed Devices

// Desktop game - keyboard + mouse only
GorillaInputController1.Supported := [Keyboard, Mouse];

// Console game - gamepad only
GorillaInputController1.Supported := [GamePad];

4. Disable Debug Hooks

{$IFDEF DEBUG}
GorillaInputController1.HighPerformanceHooks := False;
{$ENDIF}

5. Use TriggerOnDeactivate for Hold Actions

// Charge shot
LHotKey.TriggerOnActivate := True;   // Start charge
LHotKey.TriggerOnDeactivate := True; // Release

6. Keep Sequences Short

7. Test Cross-Platform

{$IFDEF MSWINDOWS}
  // Windows-specific code
{$ENDIF}
{$IFDEF LINUX}
  // Linux-specific code
{$ENDIF}

See Also

Particle System

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.

Table of Contents

Overview

The particle system supports:

Getting Started

Creating a Basic Emitter

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;

Pre-built Emitters

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

particles2

Fire Effect Example:

var
  LFire: TGorillaFireParticleEmitter;
begin
  LFire := TGorillaFireParticleEmitter.Create(Self);
  LFire.Parent := GorillaViewport1;
  LFire.Camera := Camera1;
  LFire.Kind := TGorillaFireParticleKind.Torch;
  LFire.Start();
end;

Core Concepts

Particles

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

Emitters create and manage particles. The base class TGorillaParticleEmitter provides:

Influencers

Influencers manipulate particle behavior at runtime:

Presets

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]);

Configuration

Particle Properties

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);

Emission Settings

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;

Rendering Options

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

Influencers

Movement Influencers

Linear Movement

The default influencer that applies velocity to position:

// Automatically created with every emitter
// Applies: Position += Velocity * DeltaTime

Spiral Movement

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;

Gravity

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;

Wind

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

Tractor (Attractor)

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;

Trailed (Path Following)

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;

Visual Influencers

Colored Particles

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;

Random Color

Apply random colors to particles:

var
  LRandColor: TGorillaRandomColorParticleInfluencer;
begin
  LRandColor := TGorillaRandomColorParticleInfluencer.Create(LEmitter);
  LRandColor.Emitter := LEmitter;
  LRandColor.Enabled := True;
end;

Physics Influencers

Obstacle

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:

Surface Modes:

Physics Integration

Full 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;

particles3

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;

Advanced Features

Sprite Sheets

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
);

Particle Caching

Reuse expired particles for better performance:

LEmitter.Reuse := True;  // Enable caching (default)

// Clear cached particles
LEmitter.ClearUnused();

// Clear all particles
LEmitter.Clear();

Async Processing

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.

Mouse Interaction

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.

particles1

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;

Pre-built Effects

Fire

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;

Rain

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;

Snow

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;

Explosion

var
  LExplosion: TGorillaExplosionParticleEmitter;
begin
  LExplosion := TGorillaExplosionParticleEmitter.Create(Self);
  LExplosion.Parent := GorillaViewport1;
  LExplosion.Camera := Camera1;
  LExplosion.MaxAutoEmitTime := 1000;  // 1 second burst
  LExplosion.Start();
end;

Performance Optimization

Particle Count

Update Frequency

// 60 FPS updates
LEmitter.EmitTime := 16;

// 30 FPS updates (better performance)
LEmitter.EmitTime := 33;

Particle Reuse

// Always enable for performance
LEmitter.Reuse := True;

Influencer Count

Async Mode

// Enable for > 5000 particles
if LEmitter.MaxParticles > 5000 then
  LEmitter.Async := True;

Texture Size

Best Practices

Camera Assignment

Always link emitter to active camera for proper sorting:

LEmitter.Camera := GorillaViewport1.Camera;

Lifetime vs MaxAutoEmitTime

// 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);

Manual Update

Force particle update independently of timer:

LEmitter.ForceUpdate();

Event Handling

LEmitter.OnStart := OnEmitterStart;
LEmitter.OnStop := OnEmitterStop;
LEmitter.OnEmitted := OnParticleEmitted;
LEmitter.OnDispose := OnParticleDispose;
LEmitter.OnProcess := OnAutoEmitProcess;

Cleanup

// Stop emitter
LEmitter.Stop();

// Clear all particles
LEmitter.Clear();

// Remove influencers
LEmitter.ClearInfluencers();

Troubleshooting

Particles not visible

Particles appear as squares

Performance issues

Transparency sorting issues

Particles not affected by influencers

See Also

API Reference

Related Topics

Terrain System

The 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.

Table of Contents

Overview

The terrain system offers three main components:

Getting Started

Creating a Basic Terrain

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;

Loading a Heightmap

Heightmaps are grayscale images where pixel brightness determines terrain height.

Runtime Loading

var
  LHeightMap: TBitmap;
begin
  LHeightMap := TBitmap.Create;
  try
    LHeightMap.LoadFromFile('terrain_heightmap.png');
    LTerrain.HeightMap := LHeightMap;
    LTerrain.RebuildTerrain;
  finally
    LHeightMap.Free;
  end;
end;

Design-Time Loading

You can load heightmaps directly in the IDE:

  1. Select the terrain component in the Structure View
  2. In the Object Inspector, find the HeightMap property
  3. Click the [...] button to open the bitmap editor
  4. Load your heightmap image
  5. The heightmap will be embedded in your form file (.fmx)

Benefits of Design-Time Loading:

Note: After loading a heightmap at design-time, click the viewport to refresh the display.

Resolution and Performance

Understanding Resolution

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);

Mobile Considerations

Important: Android has a maximum of 65,536 indices per mesh. Keep resolutions below 256×256 for mobile platforms.

Performance Optimization

Static Buffering

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).

Mesh Decimation

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:

Procedural Terrain Generation

Generate realistic terrain without heightmap images using procedural algorithms.

Available Algorithms

Hill Algorithm

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);

Diamond Square Algorithm

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;

Perlin Noise

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:

Plateau Terrain

Creates 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;

Brownian Terrain

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;

Mandelbrot and Planar

Design-Time Generation

You can generate procedural terrain directly in the IDE without writing code:

  1. Drop a TGorillaTerrain component onto your viewport
  2. Right-click the terrain component in the Structure View
  3. Navigate to the "Random Terrain" submenu
  4. Select one of the available algorithms:
  5. Click the viewport to refresh the display

Benefits:

Customization: The design-time generators use default parameters. For fine-tuned control, use the runtime approach with custom algorithm properties.

g3d-ide-terrain

Advanced Features

Smoothing

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.

Two-Sided Rendering

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.

Debug Visualization

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.

Update Management

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;

Planting System

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.

How Planting Works

The planting algorithm:

  1. Divides terrain into a grid of cells
  2. Places instances inside of grid cells regularly or randomly
  3. Adjusts each instance's Y-position to match terrain height
  4. Optionally randomizes scale and rotation
  5. Treats all submeshes in the source model equally

Important: All submeshes inside the source model are treated equally when creating instances.

Design-Time Planting

Configure planting directly in the IDE:

  1. Select your terrain component
  2. Right-click the component and select the Planting option
  3. Select the source mesh on top
  4. Setup parameters for automatic placement

g3d-ide-planting-1

Source Models

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.

Configuration

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.

g3d-ide-planting-2

Spherical Terrain

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.

LOD Terrain

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.

Materials and Texturing

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).

Custom Algorithms

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;

Best Practices

Memory Management

  1. Use appropriate resolution for your target platform
  2. Enable StaticBuffering for terrains that don't change
  3. Free heightmap bitmaps after loading if not needed
  4. Use decimation to reduce polygon count

Visual Quality

  1. Start with resolution matching your heightmap size
  2. Use smoothing for upscaled heightmaps
  3. Apply normal maps for enhanced detail without geometry
  4. Combine multiple algorithms for varied terrain

Performance

  1. Keep mobile terrain under 256×256 resolution
  2. Disable TwoFace unless absolutely needed
  3. Turn off debug visualization in production
  4. Use LOD terrain for large landscapes
  5. Profile vertex/triangle counts with GetLODStatistics

Workflow

  1. Prototype with procedural algorithms
  2. Fine-tune with custom heightmaps
  3. Optimize with decimation
  4. Apply materials and lighting
  5. Test on target hardware

Troubleshooting

Terrain appears flat

Performance issues

Heightmap not loading

Debug visualization not showing

See Also

API Reference

Related Topics

Physics

Gorilla3D 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.

Table of Contents

Overview

The physics system (TGorillaPhysicsSystem) is the central component that:

Getting Started

Design-Time

  1. Drop a TGorillaPhysicsSystem onto your viewport
  2. Set Active := True
  3. Set Gravity (default: (0, 9.81, 0) — downward in FMX Y-up)
  4. Add collider prefabs via the Colliders collection in the Object Inspector
  5. Call Step() from a timer (recommended interval: 33ms for ~30 Hz)

Runtime

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;

Physics Drivers

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 Types

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)

Collider Settings

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;

Body Types

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.

Adding Colliders

Box Collider

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;

Sphere Collider

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

Capsule Collider

Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.LockRotAxisX := True;
Settings.LockRotAxisZ := True; // keep upright
GorillaPhysicsSystem1.AddCapsuleCollider(CharacterModel, Settings, 0.5, 1.8);

Terrain Collider

Settings := TGorillaColliderSettings.Create(eStaticBody);
GorillaPhysicsSystem1.AddTerrainCollider(GorillaTerrain1, Settings);

Removing Colliders

GorillaPhysicsSystem1.RemoveCollider(CrateModel);

Joints and Constraints

Joints connect two bodies together. Configure them via the Joints collection at design-time or add them programmatically.

Joint Types

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

Motor Types

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

Buoyancy Example

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.

Forces, Impulses and Velocity

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));

Collision Events

Global Events

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;

Per-Collider Events

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;

Step Events

GorillaPhysicsSystem1.OnBeginStep := HandleBeginStep;  // before simulation
GorillaPhysicsSystem1.OnEndStep := HandleEndStep;        // after simulation
GorillaPhysicsSystem1.OnBeginUpdate := HandleBeginUpdate; // before body sync
GorillaPhysicsSystem1.OnEndUpdate := HandleEndUpdate;     // after body sync

Design-Time Collider Prefabs

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.

Async Physics

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;

Physics Character Controller

TGorillaPhysicsCharacterController (in Gorilla.PhysicsCharacterController) provides a physics-driven character that works with the physics system for ground detection, slopes, and collision response.

Performance Tips

Best Practices

Gorilla.Animation Unit Reference

Overview

The 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.

Architecture

The animation system is built on a hierarchical structure:

TGorillaAnimationManager
└─ TGorillaAnimation
   └─ TSkeletonKeyAnimation
      └─ TPropertyKeyAnimation (abstract base)
         ├─ TPoint3DKeyAnimation
         ├─ TVector3DKeyAnimation
         ├─ TQuaternion3DKeyAnimation
         ├─ TTransformationKeyAnimation
         └─ TCoordinateKeyAnimation

Core Classes

TPropertyKeyAnimation

Abstract base class for all keyframe-based animations in Gorilla3D.

Inheritance: TCustomPropertyAnimation → TPropertyKeyAnimation

Platforms: All Gorilla3D supported platforms

Public Properties

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).

Published Properties

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).

Public Methods

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:

Example:

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:

Example:

Animation.AddElement(Cube1, True);

procedure LoadFromInterpolatorDef(ADef: TCustomDef); virtual; abstract;

Loads animation from a definition structure. Must be implemented by derived classes.

Parameters:


procedure ResetCaching();

Resets animation values manipulated during caching.


procedure ProcessCachingTick(time, deltaTime: Single);

Processes animation tick during caching operations.

Parameters:


procedure Transform(const AMat: TMatrix3D); virtual; abstract;

Transforms all keyframe data by a matrix (e.g., for mirroring).

Parameters:

Example:

var
  MirrorMatrix: TMatrix3D;
begin
  MirrorMatrix := TMatrix3D.CreateScaling(Point3D(-1, 1, 1));
  Animation.Transform(MirrorMatrix);
end;

TPoint3DKeyAnimation

Keyframe animation for TPoint3D properties (Position, Rotation, Scale).

Inheritance: TPropertyKeyAnimation → TPoint3DKeyAnimation

Platforms: All Gorilla3D supported platforms

Public Methods

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.


Usage Example

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;

TVector3DKeyAnimation

Keyframe animation for TVector3D properties.

Inheritance: TPropertyKeyAnimation → TVector3DKeyAnimation

Platforms: All Gorilla3D supported platforms

Public Methods

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.


TQuaternion3DKeyAnimation

Keyframe animation for quaternion-based rotations.

Inheritance: TPropertyKeyAnimation → TQuaternion3DKeyAnimation

Platforms: All Gorilla3D supported platforms

Features:

Public Methods

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.


Usage Example

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;

TTransformationKeyAnimation

Keyframe animation for TMatrix3D transformations (primarily skeletal animation).

Inheritance: TPropertyKeyAnimation → TTransformationKeyAnimation

Platforms: All Gorilla3D supported platforms

Use Cases:

Public Methods

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.


Usage Example

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;

TCoordinateKeyAnimation

Keyframe animation for vertex positions (mesh morphing).

Inheritance: TPropertyKeyAnimation → TCoordinateKeyAnimation

Platforms: All Gorilla3D supported platforms

Use Cases:

Public Methods

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.


Usage Example

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;

TSkeletonKeyAnimation

Container for synchronized animation of multiple property key animations.

Inheritance: TPropertyKeyAnimation → TSkeletonKeyAnimation

Platforms: All Gorilla3D supported platforms

Purpose:

Public Properties

Property Type Description
Interpolators TGorillaPropertyKeyAnimationList Collection of grouped property animations (read-only).

Published Properties

Property Type Default Description
AutoRepaint Boolean True Automatically call Repaint() after each ProcessAnimation().

Public Methods

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:

Example:

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:

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:


procedure Transform(const AMat: TMatrix3D); override;

Transforms all child interpolators by matrix.

Parameters:


TGorillaAnimation

High-level animation instance representing a complete animation (e.g., "Walk", "Run").

Inheritance: TFmxObject → TGorillaAnimation

Platforms: All Gorilla3D supported platforms

Interfaces: IDuplicatable

Public Properties

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).

Published Properties

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.

Public Methods

constructor Create(AOwner: TComponent); override;

Standard constructor.


constructor CreateEx(const AManager: TGorillaAnimationManager); virtual;

Creates animation with linked manager.

Parameters:


destructor Destroy(); override;

procedure LoadFromAnimationDef(ADef: TAnimationDef); virtual;

Loads animation from definition structure.

Parameters:

Example:

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:


procedure SetFixedCacheFrame(AFrameNr: Integer);

Sets a fixed frame number for cache debugging.

Parameters:


procedure UnsetFixedCacheFrame();

Deactivates fixed frame rendering.


function GetCurrentCachedFrame(const AMeshDef: TMeshDef): TMeshBufferObject;

Returns current mesh buffer object if caching is active.

Parameters:

Returns: Cached mesh buffer for current frame, or nil


TGorillaAnimationManager

Central manager for all animations associated with a 3D model or character.

Inheritance: TComponent → TGorillaAnimationManager

Platforms: All Gorilla3D supported platforms

Interfaces: IDuplicatable

Public Properties

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.

Published Properties

Property Type Description
CurrentAnimationName String Name of currently active animation.

Public Methods

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:

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:

Returns: Animation instance or nil


function AddAnimation(const AId: String; const AAnimation: TGorillaAnimation): TGorillaAnimation;

Adds animation to manager.

Parameters:

Returns: 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:

Returns: Playing animation or nil if not found

Behavior:

Example:

Manager.PlayAnimation('Run');

function PlayAnimation(const AAnim: TGorillaAnimation): TGorillaAnimation; overload;

Plays specific animation instance.

Parameters:

Returns: 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:

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();

TPoint3DAnimation

Simple property animation for TPoint3D without keyframes.

Inheritance: TCustomPropertyAnimation → TPoint3DAnimation

Platforms: All Gorilla3D supported platforms

Published Properties

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.

Usage Example

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;

Data Structures

TPoint3DKey

Single keyframe for TPoint3D animation.

Inheritance: TKey → TPoint3DKey

Properties

Property Type Description
Value[Index: TComponent] TPoint3D Point value for specific component.

Methods

procedure SetDefaultValue(AValue: TPoint3D);
function GetDefaultValue(): TPoint3D;

TVector3DKey

Single keyframe for TVector3D animation.

Inheritance: TKey → TVector3DKey

Properties

Property Type Description
Value[Index: TComponent] TVector3D Vector value for specific component.

TQuaternion3DKey

Single keyframe for quaternion animation.

Inheritance: TKey → TQuaternion3DKey

Properties

Property Type Description
Value[Index: TComponent] TQuaternion3D Quaternion value for specific component.

TTransformationKey

Single keyframe for matrix transformation.

Inheritance: TKey → TTransformationKey

Properties

Property Type Description
Value[Index: TComponent] TMatrix3D Matrix value for specific component.

TCoordinateKey

Single keyframe for vertex positions.

Inheritance: TKey → TCoordinateKey

Properties

Property Type Description
Vertices[Index: TComponent] TPoint3DDynArray Vertex array for specific component.

Type Definitions

TGorillaInterpolatorList

TGorillaInterpolatorList = TDictionary<String, TPropertyKeyAnimation>;

Hashmap of identifier-to-animation pairs.


TGorillaAnimationMap

TGorillaAnimationMap = TDictionary<String, TGorillaAnimation>;

Hashmap of identifier-to-TGorillaAnimation pairs.


TElementPoints

TElementPoints = TDictionary<TComponent, TPoint3D>;

Component-to-Point3D hashmap for keys.


TElementVectors

TElementVectors = TDictionary<TComponent, TVector3D>;

Component-to-Vector3D hashmap for keys.


TElementQuaternions

TElementQuaternions = TDictionary<TComponent, TQuaternion3D>;

Component-to-Quaternion3D hashmap for keys.


TElementMatrices

TElementMatrices = TDictionary<TComponent, TMatrix3D>;

Component-to-Matrix3D hashmap for keys.


TElementCoordinates

TElementCoordinates = TDictionary<TComponent, TPoint3DDynArray>;

Component-to-vertex-array hashmap for keys.


Important Notes

  1. Synchronization: Use TSkeletonKeyAnimation to group related animations for synchronized playback without timing offsets.

  2. Performance: Use ForceStep() in rendering loops to avoid FMX timer jitter for smoother animation.

  3. Caching: Complex vertex animations benefit from frame caching to reduce CPU load.

  4. Property Names: Supports dot notation for nested properties (e.g., "Position.Point.X").

  5. Multiple Elements: Single animation can control multiple components with different values per keyframe.

  6. Interpolation: All animations support standard FireMonkey interpolation types (Linear, Quadratic, Cubic, etc.).

  7. Transform Matrices: Animations can be transformed (mirrored, scaled) by applying matrices to all keyframes.

  8. AutoRepaint: Disable AutoRepaint on TSkeletonKeyAnimation for manual viewport control and better performance.

  9. Memory Management: Always properly stop and free animations to prevent memory leaks.

  10. Thread Safety: Animation updates occur on main thread via FMX timer or DisplayLink service.

See Also

Gorilla.AssetsManager Unit Reference

Overview

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.

Constants

Asset Type IDs

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

Package Version

GORILLA_PACKAGE_VERSION = '1.3' — Current package format version.

Enumerations

TGorillaLevelOfDetail

Value Description
LowQuality Low quality assets
MediumQuality Medium quality assets
HighQuality High quality assets
ExcellentQuality Excellent quality assets

Note: Currently reserved for future use.

TAssetImportFlag

Value Description
StrictFileName Match full filename (not just extension)
Cached Cache asset data in memory

TAssetState

Value Description
asUndef Undefined state
asLoading Currently loading
asLoaded Loaded successfully
asStoring Currently storing
asStored Stored successfully

Class Hierarchy

TPersistent
  └── TGorillaAsset
        ├── TGorillaTextureAsset
        ├── TGorillaModelAsset
        ├── TGorillaAudioAsset
        └── ... (other asset types)

TOwnedCollection
  └── TGorillaAssetsGroupCollection

TComponent
  └── TGorillaAssetsManager

TGorillaAsset

Base class for all assets.

Public Properties

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

Published Properties

Property Type Description
SubGroups TGorillaAssetsGroupCollection Nested asset groups (e.g., textures within a model)

Public Methods

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

TGorillaTextureAsset

Stores texture/image data as TBitmap. Supports BMP, JPG, JPEG, DDS, GIF, PNG, TIF, TIFF, TGA.

Public Properties

Property Type Description
Bitmap TBitmap Buffered bitmap image
CachedBitmap TGorillaTextureBitmap Cached GPU texture bitmap
OriginalFilename String Original file path before import

TGorillaModelAsset

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.

TGorillaAssetsManager

Main component for managing asset packages.

Key Methods

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

See Also

Gorilla.Audio.Manager Unit Reference

Overview

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).

Class Hierarchy

TThread
  └── TGorillaLegacyAudioManager

TFmxObject
  └── TGorillaAudioManager (abstract)

TCollectionItem
  └── TGorillaSoundItem (abstract)
  └── TGorillaChannelItem
  └── TGorillaAudioEffectItem

Enumerations

TGorillaAudioAction

Value Description
Cache Cache audio file to memory
Play Start playback
Stop Stop playback
Pause Pause or resume playback

TGorillaAudioMode

Value Description
Once Play audio once
Loop Play audio in a loop

Records

TCacheAudioEntry

Field Type Description
Id Integer Unique audio identifier
Mode TGorillaAudioMode Playback mode
Volume Single Volume level
Player TMediaPlayer FMX media player instance

TQueueAudioEntry

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)

TGorillaLegacyAudioManager

Thread-based audio manager using FMX TMediaPlayer. Simple but not high-performance. Each audio file gets its own TMediaPlayer instance.

Public Properties

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

Public Methods

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

TGorillaAudioManager

Abstract base class for modern audio backends. Subclassed by FMOD and OpenAL implementations.

Public Properties

Property Type Description
OnUpdate TNotifyEvent Fired when Update() is called (main-thread synchronized)
OnListenerUpdated TNotifyEvent Fired when listener settings change

Abstract Methods

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

TGorillaSoundItem

Abstract collection item representing a single sound.

Published Properties

Property Type Description
FileName TFileName Sound file path
PlaybackPosition UInt32 Current playback position (read-only)
PlaybackLength UInt32 Total length (read-only)

Abstract Methods

Method Description
IsPlaying() Check if sound is playing
Play() Start playback
Pause() Pause playback
Resume() Resume playback
Stop() Stop playback

See Also

Gorilla.Camera Unit Reference

Overview

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.

Classes

TGorillaCamera

Extended camera component inheriting from FireMonkey's TCamera with additional functionality for Gorilla3D rendering.

Inheritance: TCamera → TGorillaCamera

Platforms: All Gorilla3D supported platforms

Public Properties

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.

Published Properties

Property Type Description
FOV Single Get or set the field of view angle in degrees.

Public Methods

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.


TGorillaSmoothCameraController

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

Public Properties

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.

Published Properties

Control Types
Property Type Description
Types TGorillaSmoothCameraControlTypes Enable or disable control types: rotation, movement, zooming, and shifting.
Impulse Limits
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.
Intensity Settings
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.
Damping Settings
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.
Movement Limits
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.
Shift Settings
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.
References
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.
Behavior Settings
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).
Input Control Settings
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).
Events
Property Type Description
OnBeforeModify TOnCameraControllerEvent Callback event before a control type is modified.
OnAfterModify TOnCameraControllerEvent Callback event after a control type was modified.

Public Methods

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.

Types

TGorillaSmoothCameraControlType

Enumeration defining types of camera controls.

Values:

TGorillaSmoothCameraControlTypes

Set of TGorillaSmoothCameraControlType values.

TGorillaCameraNavigationProfile

Enumeration of preset navigation profiles.

Values:

TCameraShiftStateItem

Mouse and keyboard state items for input control.

Values:

TCameraShiftState

Set of TCameraShiftStateItem values.

TOnCameraControllerEvent

Event callback for camera controller modifications.

TOnCameraControllerEvent = procedure(
  ASender: TObject;
  AType: TGorillaSmoothCameraControlType;
  var AValue: Single
) of object;

Parameters:

Constants

INITIAL_CAMERA_ZOFFSET = -1.0;

Default Z-offset for camera positioning.

Usage Notes

  1. Camera Reference: Always set the Camera property of TGorillaSmoothCameraController to link it to a camera component.

  2. Viewport Integration: Set the Viewport property for automatic mouse event handling. Without this, you must manually call AddImpulse(), Zoom(), and Shift().

  3. Impulse System: The controller uses a physics-like impulse system with damping. Impulses gradually decrease over time based on damping settings.

  4. Orbiting Mode: In orbiting mode, the camera rotates around the controller position rather than rotating in place. This is useful for object inspection.

  5. Navigation Profiles: Use preset profiles for familiar navigation schemes from other 3D applications (Blender, Sketchfab, etc.).

  6. Limits: Set min/max limits to constrain camera movement within specific bounds.

See Also

Gorilla.Controller Unit Reference

Overview

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.

Architecture

The controller system uses a hierarchical structure:

TGorillaController (Base)
├─ TGorillaComponentController
└─ TGorillaRenderPassController
   ├─ Own Renderer
   ├─ Frame Buffer Object (FBO)
   ├─ Shader Material (optional)
   └─ Control Collections (allowed/ignored)

Core Classes

TGorillaController

Base controller class for all Gorilla3D controllers.

Inheritance: TFmxObject → TGorillaController

Platforms: All Gorilla3D supported platforms

Published Properties

Property Type Default Description
Enabled Boolean True Enable/disable controller.

Public Methods

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;

Standard component lifecycle management.


TGorillaComponentController

Controller with target component link.

Inheritance: TGorillaController → TGorillaComponentController

Platforms: All Gorilla3D supported platforms

Published Properties

Property Type Description
Target TControl3D Target 3D control for controller operations.

TGorillaRenderPassMaterialSource

Base class for render pass shader materials.

Inheritance: TMaterialSource → TGorillaRenderPassMaterialSource

Platforms: All Gorilla3D supported platforms

Public Properties

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.

Public Methods

constructor Create(AOwnerPass: TGorillaRenderPassController); reintroduce; virtual;

Creates material source owned by a render pass controller.

Parameters:


procedure PassesChanged(Sender: TObject);

Notification that render pass configuration changed.


TGorillaRenderPassMaterial

Internal material class for render pass shaders.

Inheritance: TCustomMaterial → TGorillaRenderPassMaterial

Public Properties

Property Type Description
Source TGorillaRenderPassMaterialSource Parent material source.
ShaderUpdateCounter NativeUInt Shader rebuild counter.

Public Methods

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:

Returns: Previous pass output texture, or current context texture if none


TGorillaManagedControl

Collection item representing a managed (allowed/ignored) control.

Inheritance: TCollectionItem → TGorillaManagedControl

Published Properties

Property Type Description
DisplayName String Display name in collection editor.
Control TControl3D Reference to managed 3D control.

Public Methods

procedure Notification(AComponent: TComponent; Operation: TOperation);

Handles component notifications for lifetime management.


TGorillaManagedControls

Collection of managed controls for allow/ignore filtering.

Inheritance: TOwnedCollection → TGorillaManagedControls

Public Methods

function GetManagedControl(ACtrl: TControl3D): TGorillaManagedControl;

Finds collection item for a specific control.

Parameters:

Returns: 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.


TGorillaRenderPassController

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

Published Properties

Identity and Configuration
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.

Viewport Configuration
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.

Background Color
Property Type Description
OverwriteColor Boolean Use custom background color instead of viewport color.
BackgroundColor TAlphaColor Custom background color (if OverwriteColor is True).

Control Filtering
Property Type Description
AllowedControls TGorillaManagedControls Collection of explicitly allowed controls. Empty = allow all.
IgnoredControls TGorillaManagedControls Collection of controls to exclude from rendering.

Events
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.

Public Properties

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).

Public Methods

Construction and Lifecycle
constructor Create(AOwner: TComponent; const AId: String); reintroduce; virtual;

Creates render pass controller with unique identifier.

Parameters:

Example:

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.


Renderer Management
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:


procedure EndRenderPassRendering(AContext: TContext3D); virtual;

Ends render pass rendering cycle.


Control Management
procedure AllowControl(ACtrl: TControl3D); virtual;

Adds control to allowed list. Automatically includes sub-meshes and child components.

Parameters:

Example:

ReflectionPass.AllowControl(Skybox);
ReflectionPass.AllowControl(Mountains);

procedure IgnoreControl(ACtrl: TControl3D); virtual;

Adds control to ignored list. Automatically includes sub-meshes and child components.

Parameters:

Example:

ReflectionPass.IgnoreControl(WaterPlane);

function IsControlIgnored(ACtrl: TControl3D): Boolean; virtual;

Checks if control is ignored by this pass.

Parameters:

Returns: True if control will not be rendered

Logic:

Example:

if not ReflectionPass.IsControlIgnored(TreeModel) then
  ShowMessage('Tree will be rendered in reflection');

Pass Management
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:

Returns: 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:

Returns: True by default. Override to restrict primitive types.


Pass Chaining
procedure SetInputPass(const APass: TGorillaRenderPassController); virtual;

Sets input pass for chaining passes together.

Parameters:

Example:

BlurVertical.SetInputPass(BlurHorizontal);

function GetInputPass(): TGorillaRenderPassController; virtual;

Returns currently set input pass.

Returns: Input pass controller, or nil if none


Output and Textures
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:

Returns: Texture coordinate transformation matrix

Note: Override for custom matrix computation (e.g., shadow map projection).


Matrix Management
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).


Rendering Control
procedure RenderToContext(const AContext: TContext3D; const ATexture: TTexture;
  const ARect: TRect; const ADstPos: TPoint);

Renders pass output to context using a fullscreen quad.

Parameters:

Use 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:

Returns: 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:

Use Case: Batch configuration updates


Frame Control
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).


Enumerations

TRenderPassType

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

TRenderPassMethod

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.

TRenderPassRenderingProc

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

Type Definitions

TRenderPassEvent

Event callback signature for render pass events.

TRenderPassEvent = procedure(ASender: TObject; const AContext: TContext3D;
  const ACount: Integer; const APass: TRenderPass) of object;

Parameters:

Example:

procedure TForm1.OnPassBegin(ASender: TObject; const AContext: TContext3D;
  const ACount: Integer; const APass: TRenderPass);
begin
  // Custom setup logic
end;

ReflectionPass.OnBeginRender := OnPassBegin;

TGorillaRenderPassControllerClass

Class reference type for render pass controllers.

TGorillaRenderPassControllerClass = class of TGorillaRenderPassController;

Usage Examples

Basic Render Pass Setup

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;

Control Filtering

// Exclude water from reflection
ReflectionPass.IgnoreControl(WaterPlane);
ReflectionPass.IgnoreControl(UnderwaterRocks);

// Allow only sky and terrain
BackfacePass.AllowControl(SkyDome);
BackfacePass.AllowControl(Terrain);

Custom Viewport Scaling

// 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;

Pass Chaining

// Blur pipeline: Horizontal → Vertical → Output
BlurHorizontal.SetInputPass(SourcePass);
BlurVertical.SetInputPass(BlurHorizontal);
OutputPass.SetInputPass(BlurVertical);

Event Handling

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.

Creating Custom Render Passes

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;

Important Notes

  1. Unique IDs Required: Each render pass must have a unique Id. Duplicate IDs overwrite existing passes.

  2. Viewport Assignment: Pass must have Viewport assigned before use. Renderer is created automatically on assignment.

  3. Control Filtering Order: If AllowedControls is not empty, it acts as a whitelist. Only controls in AllowedControls render, then IgnoredControls is checked.

  4. Automatic Children: Calling IgnoreControl() or AllowControl() automatically includes sub-meshes and child components.

  5. Matrix Caching: View and projection matrices are cached and recalculated only when needed. Set FRecalcViewMatrix/FRecalcProjMatrix when custom changes require recomputation.

  6. Abstract Class: TGorillaRenderPassController is abstract. Use specialized subclasses like TGorillaRenderPassReflection or create your own.

  7. Renderer Ownership: Pass owns its renderer (FOwnsRenderer). Don't manually free renderer.

  8. FBO Auto-Creation: FBO and textures are created automatically based on ViewportSize.

  9. Event Timing: OnBeginSetup/OnEndSetup called once per frame. OnBeginRender/OnEndRender called per iteration.

  10. Skip Persistence: SkipRendering() affects only the current frame. Call each frame to continuously skip.

See Also

Gorilla.Controller.Input.Character Unit Reference

Overview

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.

Types

TGorillaCharacterControllerHotKeyCode

Record for hotkey registration.

TGorillaCharacterControllerHotKeyCode = record
  Name: String;
  Code: Integer;
  Device: TGorillaInputDeviceType;
end;

TOnCharacterControllerHotKeyTriggered

TOnCharacterControllerHotKeyTriggered = procedure(ASender: TObject;
  const AKind: TGorillaCharacterControllerHotKey;
  const AHotKey: TGorillaHotKeyItem;
  const AStates: TGorillaCharacterControllerStates;
  const AMode: TGorillaInputMode) of object;

TOnCharacterControllerMoveEvent

TOnCharacterControllerMoveEvent = procedure(ASender: TObject;
  AKind: TGorillaCharacterControllerHotKey;
  ADir: TPoint3D;
  ACurrentSpeed: Single) of object;

TOnCharacterControllerRotateEvent

TOnCharacterControllerRotateEvent = procedure(ASender: TObject;
  ACurrentRotation: TQuaternion3D;
  ANewRotation: TQuaternion3D;
  ADelta: TPointF) of object;

TOnCharacterControllerEvent

TOnCharacterControllerEvent = procedure(ASender: TObject;
  AState: TGorillaCharacterControllerState;
  AMode: TGorillaInputMode) of object;

TOnCharacterControllerTriggerPoint

TOnCharacterControllerTriggerPoint = procedure(ASender: TObject;
  AManager: TGorillaTriggerPointManager;
  APt: TGorillaTriggerPoint;
  ADist: Single) of object;

Classes

TGorillaCharacterController

Abstract base class for character controllers. Inherits from TDummy.

Inheritance: TDummy → TGorillaCharacterController

Public Properties

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

Published Properties

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

Published Events

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

Public Methods

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.

Gorilla.Controller.Input.FirstPerson Unit Reference

Overview

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.

Classes

TGorillaFirstPersonController

First-person camera and character controller with mouse look, keyboard movement, and gamepad support.

Inheritance: TDummy → TGorillaCharacterController → TGorillaFirstPersonController

Platforms: All Gorilla3D supported platforms

Inherited Published Properties

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).

Published Properties

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.

Public Methods

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.

Gorilla.Controller.Input.ThirdPerson Unit Reference

Overview

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.

Classes

TGorillaThirdPersonController

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

Default Overrides

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).

Published Properties

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.

Public Methods

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;

Behavior Details

Orbit Mode (UseCameraDirection = False, default):

Camera Direction Mode (UseCameraDirection = True):

Gorilla.DefTypes Unit Reference

Overview

The 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.

Architecture

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)

Core Constants

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 Types

TCustomDef

Base class for all definition types.

Properties

Property Type Description
Id String Unique identifier for this definition.

Methods

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.


TModelDef

Root definition for complete 3D models. Contains all sub-components including meshes, materials, animations, lights, cameras, and armatures.

Inheritance: TCustomDef → TTransformDef → TModelDef

Properties

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.

TMeshDef

Mesh geometry definition containing vertices, indices, and material references.

Inheritance: TCustomDef → TTransformDef → TCustomMeshDef → TMeshDef

Properties

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.

TMaterialDef

Material definition with textures and properties.

Inheritance: TCustomDef → TMaterialDef

Properties

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.).

Data Structures

TGorillaLoadOptions

Configuration structure for loading models with fine-grained control.

Fields

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.

Methods

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();

Example

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;

TGorillaFileInfo

File information record for model loading.

Fields

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.

Methods

procedure CopyTo(var ADest: TGorillaFileInfo);
procedure Clear();

TVertexData

Vertex data record containing all vertex attributes.

Fields

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.

Methods

class function Create(): TVertexData; static;
procedure Clear();
function ToJSON(): TJSONObject;
procedure FromJSON(const AValue: TJSONObject);
function GetHash(): UInt64;
function Equals(const V: TVertexData): Boolean;

TTriangleRayCastResult

Ray casting intersection result.

Fields

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.

Enumerations

TAnimationCachingFlag

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]

TVertexDataFlag

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).

TColorChannelDef

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.

TGorillaFileOpenFormat

File opening mode.

Value Description
fofLocal Load from local filesystem (default).
fofDownload Download format (Sketchfab, etc.).

TVertexOrder

Vertex winding order for triangles.

Value Description
CW Clockwise vertex order [0, 2, 1].
CCW Counter-clockwise vertex order [1, 2, 0].

TFaceOrientation

Face culling mode.

Value Description
FrontFace Render front faces only.
BackFace Render back faces only.
TwoFace Render both sides (no culling).

Utility Classes

TGorillaBitmapCache

Collection for caching texture bitmaps at design-time.

Inheritance: TOwnedCollection → TGorillaBitmapCache

Methods

function FindBitmap(AFilename: String): TGorillaBitmapCacheEntry;

Finds cached bitmap by filename.


TGorillaBitmapCacheEntry

Individual cached bitmap entry.

Inheritance: TCollectionItem → TGorillaBitmapCacheEntry

Properties

Property Type Description
Filename String Original filename of bitmap.
Bitmap TBitmap Bitmap data (embedded or referenced).

TCacheList<T>

Memory-efficient list for caching with fixed-size growth steps.

Properties

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.

Methods

function Add(AValue: T): Integer;
procedure AddRange(AArray: TArray<T>);
procedure Clear();
function ToArray(): TArray<T>;
function GetMemorySize(): Int64;

TProperties

Dictionary for storing extended properties.

Inheritance: TDictionary<String, TValue> → TProperties

Methods

function GetSize(): Int64;
procedure ToJSON(AJSON: TJSONObject);
procedure FromJSON(const AValue: TJSONObject);

Helper Types

// 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>;

Usage Examples

Creating Load Options

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;

Working with Vertex Data

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;

Using Bitmap Cache

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;

Important Notes

  1. 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.

  2. Serialization: All definition types support JSON serialization via ToJSON/FromJSON methods. Binary serialization uses BSON format (G3D files).

  3. Caching: Animation caching significantly improves playback performance. Use VertexPosition flag for best balance.

  4. Index Format: Platform-dependent (UInt32 on desktop, UInt16 on Android) for memory optimization.

  5. Texture Limits: Essential for mobile platforms to prevent memory exhaustion from high-resolution textures.

  6. Extensions: Material extensions (PBR, custom properties) stored in TExtensionDefList for format compatibility.

See Also

Gorilla.Light Unit Reference

Overview

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.

Classes

TGorillaLight

Extended light source component with additional properties for Gorilla3D shaders.

Inheritance: TLight → TGorillaLight

Platforms: All Gorilla3D supported platforms

Public Properties

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.

Published Properties

Color Properties
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.
Intensity
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

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 (Global Illumination)

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.

Public Methods

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:

Light Types (Inherited)

From FireMonkey's TLight, accessible via the LightType property:

Attenuation Presets

Common attenuation configurations for different light ranges:

No Attenuation (Directional Light)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.0;
Light.QuadraticAttenuation := 0.0;

Short Range (7 units)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.7;
Light.QuadraticAttenuation := 1.8;

Medium Range (13 units)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.35;
Light.QuadraticAttenuation := 0.44;

Long Range (20 units)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.22;
Light.QuadraticAttenuation := 0.20;

Very Long Range (50 units)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.07;
Light.QuadraticAttenuation := 0.017;

Extremely Long Range (100 units)

Light.ConstantAttenuation := 1.0;
Light.LinearAttenuation := 0.045;
Light.QuadraticAttenuation := 0.0075;

Usage Notes

  1. Ambient vs Diffuse:

  2. Intensity: Use intensity to control light strength without changing color. More intuitive than adjusting color brightness.

  3. Attenuation:

  4. Light Scattering:

  5. Performance: Each additional light increases rendering cost. Use the minimum number of lights necessary and disable lights when not visible.

  6. Gorilla3D Materials Required: Advanced light properties only affect Gorilla3D default materials, not standard FMX materials.

See Also

Gorilla.Material.Default Unit Reference

Overview

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.

Architecture

The material system uses a hierarchical node structure to compose shaders:

TGorillaDefaultMaterialSource
└─ TGorillaDefaultMaterial
   ├─ TGorillaGLSLVertexShader (Node Builder)
   │  └─ Shader Nodes
   └─ TGorillaGLSLFragmentShader (Node Builder)
      └─ Shader Nodes

Core Classes

TGorillaDefaultMaterialSource

Primary material source component providing comprehensive rendering features.

Inheritance: TCustomMaterialSource → TGorillaDefaultMaterialSource

Platforms: All Gorilla3D supported platforms

Published Properties

Basic Material Properties
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).
Shading Configuration
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.
Texture Properties
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.
Texture Control Flags
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.
PBR Texture Properties
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.
PBR Texture Flags
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.
PBR Parameters
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.
Advanced Mapping
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).
Effects and Features
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.
Alpha and Transparency
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.
Tonemapping
Property Type Default Description
Tonemapping TGorillaTonemapping tmNone Tonemapping operator: tmNone, tmReinhard, tmACESFilmic, etc.
TonemappingExposure Single 1.0 Exposure adjustment for tonemapping.
Material Behaviours
Property Type Description
Behaviours TGorillaMaterialBehaviourCollection Collection of attached material behaviours.
Time Management
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).
Render Pass Integration
Property Type Description
ShadowMapPass[Index] TGorillaRenderPassController Shadow map render pass (0-7).
Inputs TGorillaInputRenderPassMap Render pass inputs map.

Public Methods

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;

Material Behaviour Management

function MaterialBehaviourAttached(ABehaviour: TGorillaMaterialBehaviour): Boolean;

Returns True if a specific behaviour is attached to this material source.

Parameters:

Returns: 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:

Returns: 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:

Example:

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:

Example:

Material.DetachMaterialBehaviour(WindBehaviour);

procedure ClearMaterialsBehaviours();

Detaches all attached material behaviours from this material source.

Example:

Material.ClearMaterialsBehaviours();

TGorillaDefaultMaterial

Internal material class that performs actual rendering.

Inheritance: TCustomMaterial → TGorillaDefaultMaterial

Public Properties

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.

Public Methods

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.


Data Structures

TGorillaShaderData

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).

Fields

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.

TGorillaShaderPassData

Data specific to render passes (shadows, reflections, refractions).

Fields

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.

Enumerations

TGorillaShadingModel

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.

TGorillaTonemapping

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.

TGorillaShadowMethod

Shadow mapping techniques.

Value Description
smShadowMapping Standard shadow mapping.
smVSM Variance Shadow Mapping.

Constants

Light Limits

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

Usage Examples

Basic Material Setup

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;

Textured Material

Material.UseTexturing := True;
Material.UseTexture0 := True;
Material.Texture.LoadFromFile('diffuse.png');

Material.UseNormalMapping := True;
Material.NormalMap.LoadFromFile('normal.png');
Material.NormalIntensity := 1.0;

PBR Material

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;

Using Material Behaviours

var
  WindBehaviour: TGorillaWindBehaviour;
  Item: TGorillaMaterialBehaviourItem;
begin
  WindBehaviour := TGorillaWindBehaviour.Create(Self);
  WindBehaviour.Viewport := Viewport;

  Material.AttachMaterialBehaviour(WindBehaviour);
end;

Batching Changes

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;

Important Notes

  1. Shader Rebuilding: Changing material properties may trigger shader recompilation. Use BeginChange/EndChange to batch updates.

  2. Platform Light Limits: Number of supported lights varies by platform and graphics API version.

  3. Texture Units: Each texture type uses a specific texture unit. Ensure hardware supports required number of units.

  4. PBR Requirements: PBR shading requires modern graphics hardware. Fallback to Blinn-Phong on older devices.

  5. Uniform Buffer Alignment: TGorillaShaderData uses std140 layout. Manual modifications require understanding of GPU memory alignment.

  6. Material Behaviours: Behaviours are v1.1+ feature. Provide modular shader functionality without subclassing.

  7. Fog Integration: Fog properties are controlled by viewport, not material. Material must support fog rendering.

See Also

Gorilla.Mesh Unit Reference

Overview

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.

Classes

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)

Public Properties

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.

Published Properties

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 & Destructor

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;

Public Methods

Geometry Access
function GetBoundingBox(): TBoundingBox; override;

Returns absolute bounding box with applied mesh and local matrices.


Instancing
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);

Ray Casting and Triangle Picking
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:

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:

Example:

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:

Example:

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:

Example:

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;

Material Management
procedure ApplyMaterialSource(AValue: TMaterialSource);

Applies material source to mesh and all submeshes recursively.


Utility Methods
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.


Helper Classes

TGorillaMeshInstances

Collection managing mesh instances for GPU instancing.

Inheritance: TOwnedCollection → TGorillaMeshInstances

Properties

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.

Methods

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.


TGorillaMeshInstance

Individual mesh instance with transform properties.

Inheritance: TCollectionItem → TGorillaMeshInstance

Published Properties

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.

Public Properties

Property Type Description
Transform TMatrix3D Computed transformation matrix.
OwnerMesh TGorillaMesh Returns owning mesh.

Methods

procedure UpdateTransform();
procedure SetTransform(const ATransform: TMatrix3D);
procedure ResetRotationAngle();

TGorillaMeshMaterialCollection

Read-only design-time collection showing linked material sources.

Inheritance: TGorillaReadOnlyCollection → TGorillaMeshMaterialCollection

Methods

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.


TGorillaMeshCollection

Read-only design-time collection showing submeshes.

Inheritance: TGorillaReadOnlyCollection → TGorillaMeshCollection

Methods

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.


TGorillaMeshBehaviourCollection

Collection managing material behaviours attached to mesh.

Inheritance: TGorillaReadOnlyCollection → TGorillaMeshBehaviourCollection

Methods

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.


Helper Types

TGorillaMeshList

List of TGorillaMesh instances.

TGorillaMeshList = TObjectList<TGorillaMesh>;

TVertexJointsList

List managing vertex joint information for skeletal animation.

Usage Examples

Creating a Mesh

var
  Mesh: TGorillaMesh;
begin
  Mesh := TGorillaMesh.Create(Self);
  Mesh.Parent := Viewport;
  Mesh.MaterialSource := MyMaterial;
end;

GPU Instancing

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;

Accessing Sub-Meshes

// 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;

Static Mesh Optimization

// 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

Flat Shading

// Enable flat shading for hard-edge look
Mesh.FlatShading := True;

// Normals recalculated per-face instead of per-vertex

Wireframe Rendering

Mesh.Wireframe := True;
Mesh.WireframeMaterial := WireframeMaterialSource;

// Warning: Performance intensive, use for debugging only

Normal Visualization

Mesh.ShowNormals := True;
Mesh.NormalsColor := TAlphaColors.Green;

// Shows normal directions for debugging

Ray Casting and Triangle Picking

Using RayCastIntersect

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;

Using PickTriangle with Screen Coordinates

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;

Using PickTriangle with Result Structure

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;

Using PickTriangle with Absolute Ray

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;

Modifying Instances

// 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();

Accessing Vertex Data

// 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;

Material Management

// Apply material to mesh and all submeshes
Mesh.ApplyMaterialSource(MyMaterial);

// Apply to specific mesh only
Mesh.MaterialSource := MyMaterial;

Constants

Mesh Defaults

GORILLA_POLYGON_MAXSIZE = 16;  // Maximum polygon size

Usage Notes

  1. Static Meshes: Set IsStatic = True for meshes with unchanging geometry to improve performance and reduce memory.

  2. GPU Instancing: Use AddInstance with ACreateItem = False for memory-efficient instancing at runtime.

  3. Wireframe/Normals: Both features are performance intensive. Use for debugging only.

  4. Flat Shading: Recalculates normals per-face. Use for hard-edge modeling style.

  5. Sub-Meshes: Complex models contain mesh hierarchies. Iterate through Meshes collection to access all parts.

  6. Vertex Data Access: Static meshes may have empty CPU vertex data. Check IsStatic before accessing.

  7. Ray Casting and Triangle Picking:

See Also

Gorilla.Model Unit Reference

Overview

The Gorilla.Model unit provides the core model component for loading and managing 3D models in Gorilla3D. It contains the TGorillaModel class, which automatically manages sub-meshes, materials, animations, lights, cameras, and armatures.

Classes

TGorillaModel

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)

Public Properties

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).

Published Properties

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: TGorillaModel inherits Shadows (receives cascaded shadows) and CastShadows (default True; 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-applies Shadows once loading completes — so setting Shadows := True in the form designer (where it is streamed before Source) correctly switches every loaded material to CascadedShadowMapping. To stop a model from throwing a shadow, set CastShadows := False.

Constructor & Destructor

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;

Standard component lifecycle methods.

Public Methods

Model Loading
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:

Example:

// 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:


class 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.


Animation Management
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.


Interpolator Management

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.


Search Methods
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.


Utility Methods
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:


function GetBoundingBox(): TBoundingBox; override;
function GetAbsoluteBoundingBox(): TBoundingBox; override;

Returns ABSOLUTE bounding box with applied mesh and local matrices. Union of all submeshes.


Helper Types

TGorillaInterpolatorList

Dictionary mapping interpolator names to TPropertyKeyAnimation instances.

TGorillaInterpolatorList = TDictionary<String, TPropertyKeyAnimation>;

Usage Examples

Basic Model Loading

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;

Loading with Asset Package

var
  Model: TGorillaModel;
begin
  Model := TGorillaModel.LoadNewModelFromFile(
    Viewport,
    AssetsPackage1,
    'character.g3d',
    [TAnimationCachingFlag.VertexPosition]
  );
  Model.Parent := Viewport;
end;

Adding Animation

// 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');

Advanced Loading Options

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;

Searching Hierarchy

// 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;

Debug Output

// Output FMX hierarchy
GorillaModel1.DebugOut(False);

// Output component hierarchy
GorillaModel1.DebugOut(True);

Constants

Animation Caching

GORILLA_ANIMATION_CACHING_DEFAULT = [];

Default animation caching configuration (no caching).

Usage Notes

  1. Loading Order: Model data must be loaded before adding animations for proper vertex-animation linking.

  2. Asset Packages: Using asset packages improves IDE performance and enables model reuse across instances.

  3. Memory Management: Models stored in packages are managed by TGorillaAssetsManager. Standalone models own their definitions.

  4. Animation Caching: VertexPosition flag recommended for balanced performance/memory. AllAttributes uses more memory but provides maximum speed.

  5. Binary Data: Design-time models stored as compressed G3D format in FMX files for efficient storage.

  6. Deep Search: FindControlByDeepSearch methods search entire hierarchy including interpolators, useful for accessing specific parts.

See Also

Gorilla.Prefab Unit Reference

Overview

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).

Class Hierarchy

TCollectionItem
  └── TGorillaPrefab

TComponent
  └── TGorillaPrefabSystem

TGorillaPrefab

A single prefab entry in the prefab collection. Stores DFM data and can load/save component hierarchies.

Published Properties

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)

Published Events

Event Type Description
OnLoaded TOnPrefabLoadedEvent Fired after prefab components are loaded
OnStored TNotifyEvent Fired after prefab is saved

Public Properties

Property Type Description
OnCreateComponent TOnCreateComponentEvent Custom component creation callback

Public Methods

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

Callback Types

TOnCreateComponentEvent = function(AComponentClass: TComponentClass;
  AParent: TComponent; ALeft, ATop, AWidth, AHeight: Integer): TComponent of object;

TOnPrefabLoadedEvent = procedure(ASender: TObject;
  AComponents: TList<TComponent>) of object;

TGorillaPrefabSystem

The manager component that holds a collection of prefabs. Drop onto a form or data module.

Published Properties

Property Type Description
Prefabs TGorillaPrefabCollection Collection of TGorillaPrefab items

Public Methods

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

See Also

Gorilla.Renderer Unit Reference

Overview

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.

Classes

TRenderer

Base renderer class for all renderer types.

Inheritance: TObject → TRenderer

Public Properties

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.

Public Methods

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.


TLegacyRenderer

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:


TCompositeRenderer

Base class for forward and deferred renderers with WBOIT 3-phase rendering.

Inheritance: TRenderer → TCompositeRenderer

Public Properties

Render Target Textures
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.
Embedded Render Pass Controllers
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.
Rendering Settings
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.).
Global Illumination Settings
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.
Screen Space Effects (if enabled in build)
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.

Public Methods

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.


TForwardRenderer

Forward renderer with WBOIT for order-independent transparency.

Inheritance: TRenderer → TCompositeRenderer → TForwardRenderer

The recommended renderer providing:


TDeferredRenderer

Deferred renderer with multiple color channels and final composite pass.

Inheritance: TRenderer → TCompositeRenderer → TDeferredRenderer

Additional Public Properties

Property Type Description
ComponentsTexture TTexture Material component properties output.
AmbientTexture TTexture Ambient lighting output.
SpecularTexture TTexture Specular lighting output.

Public Methods

procedure Composite(const ARenderContext: PRenderContext); override;

Deferred compositing combining all G-buffer layers.

Types

TRendererType

Enumeration of renderer types.

Values:

TRendererFlag

Flags controlling renderer behavior.

Values:

TRendererFlags

Set of TRendererFlag values.

TRendererOutputLayer

Enumeration of output layers for debugging.

Values:

TOnRendererCreateCompositeTexture

Event type for custom composite texture creation.

TOnRendererCreateCompositeTexture = procedure(
  ASender: TObject;
  const ASize: TPoint;
  const AScale: Single;
  out ATexture: TGorillaTextureBitmap
) of object;

Global Illumination Detail Levels

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

Usage Notes

  1. Renderer Selection: Use TForwardRenderer for most cases. Only use TLegacyRenderer when you need maximum FMX compatibility or are doing extensive native OpenGL rendering.

  2. MSAA: Set multisample level in constructor or via the Multisample property. Not all platforms support all MSAA levels.

  3. Render Targets: The composite renderer creates multiple render targets for different rendering stages. Access these via properties like AlbedoTexture, NormalsTexture, etc.

  4. Performance: Higher EmissiveBlur and FXAA values significantly impact performance. Start with low values and increase as needed.

  5. Debugging: Use OutputLayer to visualize individual render passes during development.

  6. Global Illumination: Only available in GAME_PACKAGE edition. Requires significant GPU resources at higher detail levels.

See Also

Gorilla.Viewport Unit Reference

Overview

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.

Classes

TGorillaViewport

Main viewport class for rendering 3D scenes using Gorilla3D.

Inheritance: TControl → TGorillaViewport

Platforms: All Gorilla3D supported platforms (Windows, macOS, Linux, Android, iOS)

Public Properties

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.

Published Properties

Viewport Settings
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.
Fog Settings
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).
Rendering Effects
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.
Global Illumination (GAME_PACKAGE only)
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.
Design Settings
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.
Diagnostics
Property Type Description
DiagnosticsActive Boolean Enable or disable rendering diagnostics collection.
RendererOutputLayer TRendererOutputLayer Control which renderer output layers to display.
Standard Component Properties

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.

Events

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.

Public Methods

Rendering Control
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.

Render List Management
procedure RebuildRenderingList(); virtual;
procedure RenderRenderList(const ARenderContext: PRenderContext);
procedure RenderRenderListByMode(AOpaque: Boolean);

Manage and render the list of 3D objects.

Render Pass Management
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.

Coordinate Conversion
function ScreenToWorld(const APoint2D: TPointF): TPoint3D; virtual;
function WorldToScreen(const APoint3D: TPoint3D): TPointF; virtual;

Convert between screen and world coordinates.

Object Selection
function ObjectAtPoint(P: TPointF): IControl; override;
function RayCastIntersect(const P: TPointF): TControl3D; virtual;

Find objects at specific screen positions using raycasting.

Camera Access
function GetDesignCamera(): TCamera; virtual;
function GetDesignCameraController(): TGorillaSmoothCameraController; virtual;

Access the built-in design camera and controller.

Screenshot
function MakeScreenshot(): FMX.Graphics.TBitmap;

Capture the current viewport rendering as a bitmap.

Gizmo Management
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.

Design Mode
procedure StartDesignMode();
procedure EndDesignMode();

Enter and exit design mode programmatically.

Display Settings
procedure UpdateDisplayRefreshRate(); virtual;

Update the cached display refresh rate.

Helper Classes

TGorillaRenderingHelper

Helper class for rendering operations.

Public Class Methods

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.

Types

TGorillaFogKind

Enumeration for fog modes (wrapper for TGorillaFogMode).

Values:

TRenderingDiagnostics

Record containing rendering performance diagnostics.

Fields:

Constants

Default Frame Rates

GORILLA_FRAMERATE_FIXED_DEFAULT = 60;  // All platforms

Usage Notes

  1. Compatibility: TGorillaViewport replaces FireMonkey's TViewport3D and TForm3D. They are not compatible.

  2. Fog Requirements: Fog effect requires TGorillaDefaultMaterialSource materials and is incompatible with standard FMX materials.

  3. Performance: Use BeginUpdate/EndUpdate to batch property changes. Enable ManualRendering for better control over rendering cycles.

  4. Frustum Culling: Improves performance but may affect render passes using different view matrices.

  5. Global Illumination: Only available in GAME_PACKAGE edition.

See Also

Gorilla.Volumetric.Mesh Unit Reference

Overview

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.

Class Hierarchy

TGorillaSingletonMesh
  └── TGorillaVolumetricMesh
        └── TGorillaVolumetricNoise   (see separate reference)

Enumerations

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);

TGorillaVolumetricMesh

Published Properties — Data & Size

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)

Published Properties — Blending & Quality

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

Published Properties — Lighting & Iso-Surface

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

Published Properties — Gamut / Transfer Function

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

Published Properties — Overlay & Ray Intensity

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)

Published Properties — Render Passes & Events

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

Public Properties

Property Type Description
CustomSize TSize3D Non-adjusted custom volume size (not stored in DFM)

Public Methods — Blend Mode

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).

Public Methods — Data Loading

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

Public Methods — Utility

Method Returns Description
GetSizeAsVector() TPoint3D Current volume resolution as width/height/depth
BeginUpdate() / EndUpdate() — Batch Sizes / DataType changes to rebuild the texture once

Callback Types

TOnUpdateTexture3D = procedure(ASender: TObject;
  ATexture: TGorillaTextureBitmap) of object;

Notes

See Also

Gorilla.Volumetric.Noise Unit Reference

Overview

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.

Class Hierarchy

TGorillaSingletonMesh
  └── TGorillaVolumetricMesh
        └── TGorillaVolumetricNoise

Enumerations

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.

TGorillaVolumetricNoise

Published Properties — Noise Shaping

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.

Public Properties

Property Type Description
Offset TPoint3D Sampling offset added to every voxel. Animate it (and call Regenerate) to make the body drift like moving smoke.

Public Methods

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.

Inherited Highlights

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)

Notes

See Also

Gorilla.Controller.Passes.SSAO

Overview

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:

Architecture

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.

Core Classes

TGorillaRenderPassSSAO

Inherits from: TGorillaRenderPassController

Published Properties

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.

Public Methods

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;

TGorillaRenderPassEmbeddedSSAO

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.

Runtime Setup

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;

Technical Details

Gorilla.Controller.Passes.FXAA

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassFXAA

Inherits from: TGorillaRenderPassController

Public Methods

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.

Runtime Setup

uses
  Gorilla.Controller.Passes.FXAA;

var
  LFXAAPass: TGorillaRenderPassFXAA;
begin
  LFXAAPass := TGorillaRenderPassFXAA.Create(nil);
  LFXAAPass.Viewport := GorillaViewport1;
  LFXAAPass.Enabled := True;
end;

Technical Details

Gorilla.Controller.Passes.Reflection

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassReflection

Inherits from: TGorillaRenderPassController

Published Properties

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.

Key Internal Methods

Method Description
CalcMirrorMatrix Computes the mirror transformation matrix using ray-plane intersection. Called internally before each render.

Runtime Setup

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.

Technical Details

Gorilla.Controller.Passes.Bokeh

Overview

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.

Architecture

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.

Types

TGorillaBokehType

TGorillaBokehType = (btDefault, btGlow);
Value Description
btDefault Standard depth-of-field blur
btGlow Bokeh with enhanced glow effect

Core Classes

TGorillaRenderPassBokeh

Inherits from: TGorillaRenderPassController

Published Properties

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.

Key Methods

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure SetInputPass(AValue: TGorillaRenderPassController);

Convenience Component: TGorillaBokeh

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.

Published Properties

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

Public Properties

Property Type Description
DepthPass TGorillaRenderPassCustomDepth The internal depth pass
MainPass TGorillaRenderPassBokeh The internal bokeh pass

Runtime Setup

Using TGorillaBokeh (Recommended)

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;

Using TGorillaRenderPassBokeh Directly

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;

Technical Details

Gorilla.Controller.Passes.GlobalIllumination

Overview

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:

Architecture

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:

  1. Shadow cone tracing -- Traces cones toward light sources through the voxel grid to compute soft indirect shadows.
  2. Reflection cone tracing -- Traces cones along reflection vectors for indirect specular reflections.
  3. Light scattering -- Simulates light diffusion through the voxelized scene.

Light data (up to 8 lights) is transferred to the GPU via a Uniform Buffer Object (UBO).

Core Classes

TGorillaRenderPassGlobalIllum

Inherits from: TGorillaRenderPassController

Published Properties

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.

Public Methods

constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;

TGorillaRenderPassEmbeddedGlobalIllum

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.

Related Units

Gorilla.Controller.Passes.Voxelize

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.

Gorilla.Controller.Passes.GlobalIllumBlur

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.

Runtime Setup

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;

Technical Details

Gorilla.Controller.Passes.PostFX

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassPostFX

Inherits from: TGorillaRenderPassController

Published Properties

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.

Public Methods

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.

Shader Interface

Surface Shader Signature

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.

Available Texture Uniforms

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.

UBO Time Data

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)

Runtime Setup

Basic Grayscale Example

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;

Animated Wave Distortion Example

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;

Updating Shader at Runtime

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;

Technical Details

Gorilla.Controller.Passes.Refraction

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassRefraction

Inherits from: TGorillaRenderPassController

Default pass id: 'Refraction'

Published Properties

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.

Public Properties

Property Type Description
OutputDepthTexture TTexture Read-only. The position/depth texture produced by the refraction renderer.

Key Public Methods

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.

Runtime Setup

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).

Technical Details

See Also

Gorilla.Controller.Passes.CustomDepth

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassCustomDepth

Inherits from: TGorillaRenderPassController

Default pass id: 'CustomDepth'

Published Properties

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).

Public Properties

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.

Key Public Methods

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 Enumeration

TDepthMethod = (dmDefault, dmMVPPosZ, dmModelViewPosZ);

Runtime Setup

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;

Technical Details

See Also

Gorilla.Controller.Passes.CustomBlur

Overview

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.

Architecture

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().

Core Classes

TGorillaRenderPassBlur

Inherits from: TGorillaRenderPassController

Default pass id: 'Blur'

Published Properties

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.

Key Public Methods

function GetOutputTexture() : TTexture; override;
function GetFinalOutputTexture() : TTexture;

Enumerations

TPassBlurType = (RadialBlur, FastBlur, GaussianBlur);
TPassBlurMode = (Horizontal, Vertical);

Note: FastBlur can produce artefacts on some NVIDIA GPUs. Prefer GaussianBlur (kernel size 35) when quality matters.

TBlurMaterial / TBlurMaterialSource

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.

Runtime Setup

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;

Technical Details

See Also

Gorilla.Controller.Passes.Environment

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassEnvironment

Inherits from: TGorillaRenderPassController

Default pass id: 'Environment'

Published Properties

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.

Public Properties

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.

Key Public Methods

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.

Runtime Setup

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).

Technical Details

See Also

Gorilla.Controller.Passes.Face

Overview

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.

Architecture

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).

Core Classes

TGorillaRenderPassFace

Inherits from: TGorillaRenderPassController

Default pass id: 'Face'

Published Properties

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.

Public Properties

Property Type Description
VertexUserFunc TStrings User-defined GLSL vertex code that can modify the position before output.
BiasMatrix TMatrix3D Read-only texture bias matrix.

Key Public Methods

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;

Enumerations

TFaceKind   = (FrontFace, BackFace);
TFaceOutput = (Default, ModelSpace, ViewSpace, ViewProjSpace, FragDepth);

TGorillaRenderPassEmbeddedFace

Inherits from: TGorillaRenderPassFace

An internal variant (IsInternalRenderPass returns True) managed by higher-level systems rather than used standalone.

TFaceMaterial / TFaceMaterialSource

Internal material classes holding the per-space vertex shaders. They expose FaceKind, FaceOutput and VertexUserFunc; configure the pass rather than these directly.

Runtime Setup

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;

Technical Details

See Also

Gorilla.Controller.Passes.Underwater

Overview

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.

Architecture

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.

Core Classes

TGorillaRenderPassUnderwater

Inherits from: TGorillaRenderPassController

Default pass id: 'Underwater'

Published Properties

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.

Key Public Methods

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.

TUnderwaterMaterial / TUnderwaterMaterialSource

Internal material classes holding the post-process shader and the TUnderwaterShaderData record. TUnderwaterMaterialSource exposes a TransfPosition texture input.

TUnderwaterShaderData (packed record)

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)

Runtime Setup

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;

Technical Details

See Also

Gorilla.Controller.Passes.CascadedShadows

Overview

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 / smVSM material flags noted as incomplete in Materials → Shadow Mapping.

Enabling Shadows

// 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.

Excluding objects from casting

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.

TGorillaShadowSystemSettings

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.

Methods

function ComputeAtlasLayerCount() : Integer;

Returns the total atlas-layer budget: MaxDirLights × CascadeCount (directional) + MaxSpotLights × 1 (spot) + MaxPointLights × 6 (point cube faces).

TGorillaShadowFilter

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

TGorillaPointShadowMethod = (CubeMap, DualParaboloid);

CubeMap (default) records six perspective faces; DualParaboloid uses two hemispheres as a fallback for restricted GPUs.

TGorillaShadowResolution

TGorillaShadowResolution = (Res512 = 512, Res1024 = 1024, Res2048 = 2048, Res4096 = 4096);

Shadow Darkness

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 (no Shadows. 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.

Cascade Fitting

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:

  1. Auto-fit (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.
  2. Manual override (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

Per-Light Shadow Properties (TGorillaLight)

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.

Core Classes

TGorillaRenderPassCascadedShadows

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.

Notable Public Members

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.

Supporting Types

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.

Technical Details

See Also

Gorilla.Utils.Dialogue.System Unit Reference

Overview

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.

Class Hierarchy

TComponent
  └── TGorillaDialogueSystem

TCollectionItem
  └── TGorillaDialogueCustomItem
        └── TGorillaDialogueParameterizedItem
              ├── TGorillaDialogueItemEvent
              └── TGorillaDialogueParentItem
                    ├── TGorillaDialogueItem
                    ├── TGorillaDialogueCharacter
                    └── TGorillaDialogue

Callback Types

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;

TGorillaDialogueCustomItem

Base class for all dialogue entities.

Published Properties

Property Type Description
Ident String Unique identifier
Enabled Boolean Whether the item can be used/executed

Public Properties

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)

Public Methods

Method Description
GetRandomId() Generate a random identifier
Clone() Clone this item (abstract)

TGorillaDialogueParameterizedItem

Extends TGorillaDialogueCustomItem with a parameter list.

Published Properties

Property Type Description
Parameters TGorillaDialogueParameters Custom key-value parameters

Public Methods

Method Description
AddParameter(AName, AValue) Add or overwrite a parameter
RemoveParameter(AName) Remove parameter by name
GetParameter(AName) Get parameter value by name

TGorillaDialogueItemEvent

An event attached to a dialogue item.

Published Properties

Property Type Description
Kind TGorillaDialogueItemEventKind Event kind (Message, Sound, Animation, etc.)
Trigger TGorillaDialogueItemEventTrigger When to fire (OnBegin, OnEnd, OnTimeout, etc.)
Value String Event payload

TGorillaDialogueItem

A single dialogue entry (question, answer, or text).

Published Properties

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

TGorillaDialogueCharacter

A named character participating in dialogues.

Published Properties

Property Type Description
Items TGorillaDialogueItemCollection Character's dialogue items
ImageIndex Integer Character icon index

TGorillaDialogue

A complete dialogue tree.

Published Properties

Property Type Description
Items TGorillaDialogueItemCollection Root dialogue items
Characters TGorillaDialogueCharacterCollection Participating characters
ImageIndex Integer Dialogue icon index

TGorillaDialogueSystem

Main component managing all dialogues.

Published Properties

Property Type Description
Dialogues TGorillaDialogueCollection Collection of dialogues
Language String Current language for text display
ImageList TImageList Linked image list for icons

Published Events

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

See Also

Gorilla.Utils.Inventory Unit Reference

Overview

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.

Class Hierarchy

TComponent
  └── TGorillaInventory

TCollectionItem
  └── TGorillaInventoryCustomItem
        └── TGorillaInventoryItem
              ├── TGorillaInventoryItemTemplate
              └── TGorillaInventoryCollectable
        └── TGorillaInventoryGroup

TObjectList<TGorillaInventoryIngredient>
  └── TGorillaInventoryCustomIngredientList
        ├── TGorillaInventoryIngredientList
        ├── TGorillaInventoryDependencyList
        └── TGorillaInventoryResultItemList

Enumerations

TGorillaInventoryCollectState

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

TGorillaInventoryManufacturingState

Value Description
Undefined Not started
Processing Crafting in progress
Completed Crafting finished
Failed Crafting failed

TGorillaInventoryCustomItem

Base class for all inventory items.

Published Properties

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

Public Properties

Property Type Description
Inventory TGorillaInventory Parent inventory component

TGorillaInventoryItem

Extends base item with custom parameters.

Published Properties

Property Type Description
Parameters TGorillaInventoryParameters Custom key-value parameters

TGorillaInventoryItemTemplate

Blueprint/prototype for collectible items.

Published Properties

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

Public Methods

Method Description
Build() Create a TGorillaInventoryCollectable from this template
AddDependency(AId, AQuantity) Add a collection dependency

TGorillaInventoryCollectable

A runtime instance of a template in the player's inventory.

Published Properties

Inherits Id, Name, Parameters, Data from parent classes.

TGorillaInventoryGroup

Category for organizing item templates.

Published Properties

Property Type Description
Templates TGorillaInventoryItemCollection Item templates in this group

TGorillaInventoryManufacturer

Crafting system for combining items.

Classes

Class Description
TGorillaInventoryManufacturer Contains crafting processes
TGorillaInventoryManufacturingProcess A single recipe with ingredients and results
TGorillaInventoryIngredient An ingredient (template reference + quantity)

TGorillaInventory

Main inventory component.

Published Properties

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

Serialization Methods

Method Description
ToXml(AParent) Serialize to XML element
FromXml(ANode, ACache) Deserialize from XML element

Helper Classes

TGorillaInventoryLanguageMap

Multi-language string map extending TGorillaLanguageMap with XML serialization.

TGorillaInventoryParameters

Custom key-value parameter map extending TGorillaParametersMap with XML serialization.

TGorillaInventoryLoadingCache

Resolves circular references during XML loading (templates referencing other templates for upgrade/downgrade chains).

See Also

Gorilla.Utils.Pathfinding Unit Reference

Overview

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.

Class Hierarchy

TComponent
  └── TControl3D
        └── TGorillaControl
              └── TGorillaPathfindingAlgorithm
                    └── TGorillaPathfindingAStar (in Gorilla.Utils.Pathfinding.AStar)

Exception Classes

EPathFindingException = class(Exception);   // General pathfinding error
EPathFindingAbort = class(EAbort);          // Pathfinding abort (silent)

Callback Types

TOnPathfindingObstacleUpdate = procedure(const AControl: TControl3D;
  out ABounds: TBoundingBox) of object;

Records

TGorillaPathfindingObstacle

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

Methods

Method Description
Create(AControl, AIsStatic) Constructor
Reset() Reset computed state, forcing recalculation

TGorillaPathfindingAlgorithm

Abstract base class for pathfinding algorithms. Manages obstacles and the navigating agent.

Published Properties

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

Public Properties

Property Type Description
AgentPosition TPoint3D Current agent position (returns (0,0,0) if no agent)

Public Methods

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

TGorillaPathfindingAStar

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.

Usage

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);

See Also

Gorilla.Utils.SkillSystem Unit Reference

Overview

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.

Class Hierarchy

TComponent
  └── TGorillaSkillSystem

TCollectionItem
  └── TGorillaCustomSkillEntity
        └── TGorillaSkillGroup
              └── TGorillaSkill (extends group, so skills can have sub-skills)

Enumerations

TGorillaSkillLevelInterpolation

Value Description
LinearInterpolation Value = BaseValue + Level * Factor
LogarithmicInterpolation Logarithmic growth curve
ExponentialInterpolation Exponential growth curve
ExponentialMinus1Interpolation Exponential minus 1 curve

TGorillaCustomSkillEntity

Base class for skills and groups.

Published Properties

Property Type Description
Enabled Boolean Whether this entity is unlocked
Icon Integer Icon index in TImageList
Position TPointF Flow chart position (editor layout)

Public Properties

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

Public Methods

Method Description
FromXml(ANode) Load from XML
ToXml(AParent) Save to XML

TGorillaSkillGroup

A category of skills.

Published Properties

Property Type Description
Skills TGorillaSkillCollection Contained skill entities

Public Methods

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)

TGorillaSkill

A single skill with leveling support. Extends TGorillaSkillGroup, so skills can contain sub-skills forming a hierarchy.

Published Properties

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)

Public Properties

Property Type Description
Data TValue Custom runtime data (not serialized)
SkillGroup TGorillaSkillGroup Parent group

Public Methods

Method Returns Description
StartLevelingUp() TGorillaSkillProcess Start async leveling (targets first sub-skill)
StartLevelingUp(ADest) TGorillaSkillProcess Start async leveling toward specific sub-skill

TGorillaSkillProcess

Manages an async leveling operation.

TGorillaSkillSystem

Main component managing all skill groups.

Published Properties

Property Type Description
Groups TGorillaSkillGroupCollection Collection of skill groups
Language String Current language for display names
ImageList TImageList Linked image list for icons

Public Methods

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

Serialization

Method Description
ToXml(AParent) Serialize to XML element
FromXml(ANode) Deserialize from XML element

Type Aliases

TGorillaSkillMap = TDictionary<String, TGorillaSkill>;

See Also

Gorilla.Controller.Input Unit Reference

Main input controller component for keyboard, mouse, and gamepad handling.

Unit: Gorilla.Controller.Input

TGorillaInputController

High-performance, asynchronous input polling controller.

Inheritance: TGorillaController → TGorillaInputController

Platforms: All Gorilla platforms

Overview

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/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates input controller with default settings:

Destroy

destructor Destroy; override;

Stops all handler threads, clears collections, and frees resources.

Properties

Enabled

property Enabled: Boolean read GetEnabled write SetEnabled;

Enables or disables input polling.

Default: False

Behavior:

Supported

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];

HighPerformanceHooks

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}

HotKeys

property HotKeys: TGorillaHotKeyCollection read FHotKeys write SetHotKeys;

Collection of input combination HotKeys.

See: TGorillaHotKeyCollection

Sequences

property Sequences: TGorillaInputSequenceCollection read FSequences write SetSequences;

Collection of ordered HotKey Sequences.

See: TGorillaInputSequenceCollection

Handlers

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;

Methods

AddHotKey

function AddHotKey(const AName: String): TGorillaHotKeyItem; virtual;

Creates and adds a new HotKey to the collection.

Parameters:

Returns: 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;

FindHotKey

function FindHotKey(const AName: String): TGorillaHotKeyItem; virtual;

Searches for a HotKey by name.

Parameters:

Returns: TGorillaHotKeyItem if found, nil otherwise

GetOrAddHotKey

function GetOrAddHotKey(const AName: String): TGorillaHotKeyItem; virtual;

Gets existing HotKey or creates new one if it doesn't exist.

Parameters:

Returns: Existing or new TGorillaHotKeyItem

Usage: Safely ensures HotKey exists without checking.

IndexOfHotKey

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

HotKeyExists

function HotKeyExists(const AName: String): Boolean; virtual;

Checks if HotKey with specified name exists.

RemoveHotKey

procedure RemoveHotKey(const AName: String); overload; virtual;
procedure RemoveHotKey(const AKey: TGorillaHotKeyItem); overload; virtual;

Removes HotKey from collection by name or instance.

AddSequence

function AddSequence(const AName: String;
  const AHotKeys: TArray<TGorillaHotKeyItem>): TGorillaInputSequenceItem; virtual;

Creates and adds a new Sequence to the collection.

Parameters:

Returns: 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;

GetHandler

function GetHandler(const ADevice: TGorillaInputDeviceType): TGorillaInputHandler; virtual;

Retrieves handler for specified device type.

Parameters:

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;

GetPersistentMessage

function GetPersistentMessage(const ADevice: TGorillaInputDeviceType;
  const ACode: TGorillaInputCode; out AMessage: TGorillaInputMessage): Boolean; virtual;

Retrieves persistent message (mouse position, gamepad triggers/thumbsticks).

Parameters:

Returns: True if message available

Persistent Codes:

Example:

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;

GetLastMousePosition

function GetLastMousePosition(out APos: TPoint): Boolean;

Convenience method to get last mouse position.

Parameters:

Returns: True if position available

GetLastGamePadTriggers

function GetLastGamePadTriggers(out APos: TPoint): Boolean;

Convenience method to get gamepad trigger values.

Parameters:

Returns: True if values available

GetLastGamePadThumbstickPosLeft

function GetLastGamePadThumbstickPosLeft(out APos: TPointF): Boolean;

Convenience method to get left thumbstick position.

Parameters:

Returns: True if position available

GetLastGamePadThumbstickPosRight

function GetLastGamePadThumbstickPosRight(out APos: TPointF): Boolean;

Convenience method to get right thumbstick position.

Parameters:

Returns: True if position available

SetCursorPos

procedure SetCursorPos(APoint: TPoint);

Sets mouse cursor position asynchronously (thread-safe).

Parameters:

Events

OnMouseDown

property OnMouseDown: TGorillaInputMouseEvent read FOnMouseDown write FOnMouseDown;

Fired when mouse button is pressed.

Signature:

TGorillaInputMouseEvent = procedure(ASender: TObject;
  AStates: TGorillaMouseStates; APos: TPointF) of object;

Parameters:

OnMouseUp

property OnMouseUp: TGorillaInputMouseEvent read FOnMouseUp write FOnMouseUp;

Fired when mouse button is released.

OnMouseDblClick

property OnMouseDblClick: TGorillaInputMouseEvent read FOnMouseDblClick write FOnMouseDblClick;

Fired on mouse button double-click.

OnMouseMove

property OnMouseMove: TGorillaInputMouseMoveEvent read FOnMouseMove write FOnMouseMove;

Fired when mouse moves.

Signature:

TGorillaInputMouseMoveEvent = procedure(ASender: TObject;
  AStates: TGorillaMouseStates; APos: TPointF) of object;

OnMouseWheel

property OnMouseWheel: TGorillaInputMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;

Fired when mouse wheel scrolls.

Signature:

TGorillaInputMouseWheelEvent = procedure(ASender: TObject; APos: TPointF;
  const AWheelDelta: Integer) of object;

OnKeyDown

property OnKeyDown: TGorillaInputKeyEvent read FOnKeyDown write FOnKeyDown;

Fired when keyboard key is pressed.

Signature:

TGorillaInputKeyEvent = procedure(ASender: TObject;
  AKeyCode: Integer) of object;

OnKeyUp

property OnKeyUp: TGorillaInputKeyEvent read FOnKeyUp write FOnKeyUp;

Fired when keyboard key is released.

OnGamePadConnect

property OnGamePadConnect: TGorillaInputGamePadEvent read FOnGamePadConnect
  write FOnGamePadConnect;

Fired when gamepad is connected.

Signature:

TGorillaInputGamePadEvent = procedure(ASender: TObject;
  AState: TGorillaInputCode; AUser: Integer) of object;

Parameters:

OnGamePadDisconnect

property OnGamePadDisconnect: TGorillaInputGamePadEvent read FOnGamePadDisconnect
  write FOnGamePadDisconnect;

Fired when gamepad is disconnected.

OnGamePadButtonDown

property OnGamePadButtonDown: TGorillaInputGamePadButtonEvent
  read FOnGamePadButtonDown write FOnGamePadButtonDown;

Fired when gamepad button is pressed.

Signature:

TGorillaInputGamePadButtonEvent = procedure(ASender: TObject;
  AState: TGorillaInputCode; AButtons: TGorillaGamePadButtons) of object;

OnGamePadButtonUp

property OnGamePadButtonUp: TGorillaInputGamePadButtonEvent
  read FOnGamePadButtonUp write FOnGamePadButtonUp;

Fired when gamepad button is released.

OnGamePadTrigger

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:

OnGamePadFeedback

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:

TGorillaHotKeyItem

Individual HotKey item representing an input combination.

Properties

Name

property Name: String read FName write FName;

Unique HotKey identifier.

Enabled

property Enabled: Boolean read FEnabled write SetEnabled default true;

Enables or disables HotKey detection.

Default: True

TriggerOnActivate

property TriggerOnActivate: Boolean read FTriggerOnActivate
  write SetTriggerOnActivate;

Triggers event when all inputs are pressed.

Default: False

TriggerOnDeactivate

property TriggerOnDeactivate: Boolean read FTriggerOnDeactivate
  write SetTriggerOnDeactivate;

Triggers event when all inputs are released.

Default: False

Combinations

property Combinations: TGorillaHotKeyCombinations read FCombinations
  write SetCombinations;

Collection of input codes forming the HotKey combination.

LockTime

property LockTime: UInt32 read FLockTime write FLockTime;

Milliseconds before HotKey can trigger again after activation.

Default: 0 (no lock)

Use Cases:

Action

property Action: TAction read FAction write FAction;

Optional FMX TAction to execute on trigger.

OnTriggered

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:

Tag

property Tag: NativeInt read FTag write FTag;

Application-specific data storage.

Methods

AddInput

function AddInput(const AKind: TGorillaInputDeviceType;
  const ACode: TGorillaInputCode): TGorillaHotKeyInputItem;

Adds an input to the HotKey combination.

Parameters:

Returns: 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);

GetOrAddInput

function GetOrAddInput(const AKind: TGorillaInputDeviceType;
  const ACode: TGorillaInputCode): TGorillaHotKeyInputItem;

Gets existing input or adds new one if it doesn't exist.

IndexOfInput

function IndexOfInput(const AKind: TGorillaInputDeviceType;
  const ACode: TGorillaInputCode): Integer;

Returns index of input in combinations.

Returns: Index or -1 if not found

ClearInputs

procedure ClearInputs();

Removes all inputs from combination.

Update

procedure Update();

Rebuilds internal raw key map after changing inputs.

Usage: Call after modifying combinations to ensure changes take effect.

Trigger

procedure Trigger(const ACurrentInput: TGorillaHotKeyRaw;
  const AMode: TGorillaInputMode); virtual;

Manually triggers HotKey (simulation/testing).

TriggerSync

function TriggerSync(const ACurrentInput: TGorillaHotKeyRaw;
  const AMode: TGorillaInputMode): Boolean; virtual;

Manually triggers HotKey synchronized with main thread.

TGorillaHotKeyCollection

Collection of HotKey items.

Methods

SetUpdateRawMap

procedure SetUpdateRawMap();

Flags collection for raw map update on next detection cycle.

UpdateRawMap

procedure UpdateRawMap();

Rebuilds internal hash map for HotKey detection. Called automatically by input thread.

TGorillaInputSequenceItem

Sequence item representing ordered HotKey chain.

Properties

Name

property DisplayName: String read GetDisplayName write SetDisplayName;

Unique Sequence identifier.

Enabled

property Enabled: Boolean read FEnabled write FEnabled default true;

Enables or disables Sequence detection.

Default: True

Sensitivity

property Sensitivity: Integer read FSensitivity write FSensitivity;

Maximum milliseconds between HotKey activations.

Default: 500ms (GORILLA_INPUT_SEQUENCE_SENSITIVITY)

HotKeys

property HotKeys: TGorillaInputSequenceHotKeyCollection read FHotKeys write SetHotKeys;

Ordered collection of HotKey links (max 16).

Action

property Action: TAction read FAction write FAction;

Optional FMX TAction to execute on trigger.

OnTriggered

property OnTriggered: TOnGorillaInputSequenceTriggered read FOnTriggered write FOnTriggered;

Event callback on Sequence trigger.

Signature:

TOnGorillaInputSequenceTriggered = procedure(
  const ASequence: TGorillaInputSequenceItem) of object;

Methods

AddHotKeyItem

function AddHotKeyItem(AHotKey: TGorillaHotKeyItem): TGorillaInputSequenceHotKeyItem;

Adds HotKey to sequence.

Parameters:

Returns: New sequence link item

GetHotKeyItem

function GetHotKeyItem(AHotKey: TGorillaHotKeyItem): TGorillaInputSequenceHotKeyItem;

Retrieves sequence link for HotKey.

HotKeyItemExists

function HotKeyItemExists(AHotKey: TGorillaHotKeyItem): Boolean;

Checks if HotKey exists in sequence.

IndexOfHotKeyItem

function IndexOfHotKeyItem(AHotKey: TGorillaHotKeyItem): Integer;

Returns index of HotKey in sequence.

Returns: Index or -1 if not found

RemoveHotKeyItem

procedure RemoveHotKeyItem(AHotKey: TGorillaHotKeyItem);

Removes HotKey from sequence.

Trigger

procedure Trigger(); virtual;

Manually triggers Sequence (simulation/testing).

TriggerSync

procedure TriggerSync(); virtual;

Manually triggers Sequence synchronized with main thread.

TGorillaInputSequenceCollection

Collection of Sequence items.

Methods

GetSequence

function GetSequence(const AIndex: Integer): TGorillaInputSequenceItem;

Gets Sequence by index.

Returns: Sequence item or nil if invalid index

FindSequence

function FindSequence(const AName: String): TGorillaInputSequenceItem;

Searches for Sequence by name.

Returns: First matching Sequence or nil

SequenceExists

function SequenceExists(const AName: String): Boolean;

Checks if Sequence with name exists.

IndexOfSequence

function IndexOfSequence(const AName: String): Integer;

Returns index of Sequence.

Returns: Index or -1 if not found

RemoveSequence

procedure RemoveSequence(const AName: String);

Removes Sequence by name.

Constants

Input Limits

// 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

Timing

// 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;

See Also

Gorilla.Controller.Input.Consts Unit Reference

Input code constants for keyboard, mouse, and gamepad.

Unit: Gorilla.Controller.Input.Consts

Action Constants

Predefined action codes for quick HotKey integration.

System Actions

const
  GORILLA_INPUT_ACTION_NONE = $00000000;
  GORILLA_INPUT_ACTION_HOME = $00000001;
  GORILLA_INPUT_ACTION_SETTINGS = $00000002;

Menu Navigation

const
  GORILLA_INPUT_ACTION_BACK = $00000003;
  GORILLA_INPUT_ACTION_CONTINUE = $00000004;
  GORILLA_INPUT_ACTION_NEXT = $00000005;
  GORILLA_INPUT_ACTION_PREV = $00000006;

Movement Actions

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;

Character Interaction

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;

Climbing Actions

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;

Collecting Actions

const
  GORILLA_INPUT_ACTION_COLLECT_LOW = $0000021B;
  GORILLA_INPUT_ACTION_COLLECT_MID = $0000021C;
  GORILLA_INPUT_ACTION_COLLECT_HIGH = $0000021D;

Combat Actions

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;

Keyboard Input Codes

Letters

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

Numbers

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

Arrow Keys

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

Common Keys

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;

Modifier Keys

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

Symbol Keys

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);

Mouse Input Codes

Mouse Buttons

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

Mouse Events

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;

GamePad Input Codes

Connection Events

const
  GORILLA_INPUT_GAMEPAD_CONNECTED = $200001;
  GORILLA_INPUT_GAMEPAD_DISCONNECTED = $200002;

D-Pad

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;

System Buttons

const
  GORILLA_INPUT_GAMEPAD_STARTBUTTON = $200007;  // Start/Menu
  GORILLA_INPUT_GAMEPAD_MODEBUTTON = $200008;   // Xbox/Guide/Home
  GORILLA_INPUT_GAMEPAD_BACKBUTTON = $200009;   // Back/View/Select

Thumbsticks (Press)

const
  GORILLA_INPUT_GAMEPAD_THUMBSTICK_LEFT = $20000A;   // L3
  GORILLA_INPUT_GAMEPAD_THUMBSTICK_RIGHT = $20000B;  // R3

Shoulder Buttons

const
  GORILLA_INPUT_GAMEPAD_SHOULDER_LEFT = $20000C;   // LB
  GORILLA_INPUT_GAMEPAD_SHOULDER_RIGHT = $20000D;  // RB

Face Buttons

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

Triggers (Persistent)

const
  GORILLA_INPUT_GAMEPAD_TRIGGER_LEFT = $200020;   // LT (0-255)
  GORILLA_INPUT_GAMEPAD_TRIGGER_RIGHT = $200021;  // RT (0-255)

Thumbstick Positions (Persistent)

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;

System Constants

GamePad Limits

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.

HotKey Limits

const
  // Maximum inputs per device in a HotKey
  GORILLA_HOTKEY_INPUTS_MAX = 4;

  // Maximum HotKeys in a Sequence
  GORILLA_INPUT_SEQUENCE_HOTKEY_MAX = 16;

Timing Constants

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;

Button Mapping Reference

Xbox Controller Layout

                    [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

PlayStation Controller Layout

                   [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

See Also

Gorilla.Controller.Input.Types Unit Reference

Type definitions for input handling system.

Unit: Gorilla.Controller.Input.Types

Type Definitions

TGorillaInputDeviceType

type
  TGorillaInputDeviceType = (Keyboard, Mouse, GamePad);

Enumeration of supported input device types.

Values:

TGorillaInputDeviceTypes

type
  TGorillaInputDeviceTypes = set of TGorillaInputDeviceType;

Set of input device types for enabling multiple devices.

Usage:

GorillaInputController1.Supported := [Keyboard, Mouse];

TGorillaInputMode

type
  TGorillaInputMode = (Activated, Deactivated);

Input activation state.

Values:

TGorillaMouseState

type
  TGorillaMouseState = (
    LButtonDown, LButtonUp,
    RButtonDown, RButtonUp,
    MButtonDown, MButtonUp,
    X1ButtonDown, X1ButtonUp,
    X2ButtonDown, X2ButtonUp,
    LButtonDblClick, RButtonDblClick,
    MButtonDblClick, X1ButtonDblClick, X2ButtonDblClick,
    MouseMove, MouseWheel
  );

Mouse event states.

Button States:

Double-Click States:

Movement States:

TGorillaMouseStates

type
  TGorillaMouseStates = set of TGorillaMouseState;

Set of mouse states for event callbacks.

TGorillaInputCode

type
  TGorillaInputCode = NativeInt;

Generic input code type for keyboard keys, mouse buttons, and gamepad buttons.

See: Gorilla.Controller.Input.Consts for available codes.

TGorillaCharacterControllerHotKey

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.

TGorillaCharacterControllerState

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:

Action States:

UI States:

TGorillaCharacterControllerStates

type
  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

TGorillaGamePadDeviceType

type
  TGorillaGamePadDeviceType = (
    Default,
    Wheel,
    ArcadeStick,
    FlightStick,
    DancePad
  );

GamePad device classification.

Values:

TGorillaGamePadButton

type
  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:

System Buttons:

Thumbsticks:

Shoulders:

Face Buttons:

TGorillaGamePadButtons

type
  TGorillaGamePadButtons = set of TGorillaGamePadButton;

Set of gamepad buttons.

Usage:

if TGorillaGamePadButton.ButtonA in AButtons then
  Player.Jump();

TGorillaGamePadButtonsArray

type
  TGorillaGamePadButtonsArray = TArray<TGorillaGamePadButton>;

Dynamic array of gamepad buttons.

Helper Records

TGorillaGamePadButtonHelper

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.

ToInputCode

class function ToInputCode(const ABtn: TGorillaGamePadButton): TGorillaInputCode; static;

Converts gamepad button to input code.

Parameters:

Returns: Input code constant or -1 if None

Example:

var
  LCode: TGorillaInputCode;
begin
  LCode := TGorillaGamePadButtonHelper.ToInputCode(TGorillaGamePadButton.ButtonA);
  // LCode = GORILLA_INPUT_GAMEPAD_BUTTON_A
end;

FromInputCode

class function FromInputCode(const ACode: TGorillaInputCode): TGorillaGamePadButton; static;

Converts input code to gamepad button.

Parameters:

Returns: Gamepad button or None if invalid

Example:

var
  LButton: TGorillaGamePadButton;
begin
  LButton := TGorillaGamePadButtonHelper.FromInputCode(GORILLA_INPUT_GAMEPAD_BUTTON_A);
  // LButton = TGorillaGamePadButton.ButtonA
end;

TGorillaGamePadVector2

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.

Create

constructor Create(AX, AY: NativeUInt);

Creates vector with specified coordinates.

Zero

class function Zero(): TGorillaGamePadVector2; static;

Returns zero vector (0, 0).

Subtract Operator

class operator Subtract(V1, V2: TGorillaGamePadVector2): TGorillaGamePadVector2;

Subtracts two vectors.

Example:

var
  LDelta: TGorillaGamePadVector2;
begin
  LDelta := LCurrentPos - LPreviousPos;
end;

Multiply Operator

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;

Record Types

TGorillaInputMessage

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;

TGorillaHotKeyInputRaw

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:

Methods:

Sort

procedure Sort();

Sorts input codes from low to high value (for comparison).

Contains

function Contains(const AInput: TGorillaHotKeyInputRaw): Boolean;

Checks if this input contains all codes from AInput.

ToString

function ToString(): String;

Converts to string format for debugging.

TGorillaHotKeyRaw

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:

Create

class function Create(): TGorillaHotKeyRaw; static;

Creates empty raw HotKey.

AddInput

procedure AddInput(const AInput: TGorillaHotKeyInputItem);

Adds input from collection item.

GetWeight

function GetWeight(): Integer;

Returns priority weight (more inputs = higher weight).

Usage: Resolves conflicts when multiple HotKeys match current input.

Contains

function Contains(const AKey: TGorillaHotKeyRaw): Boolean;

Checks if this HotKey contains all inputs from AKey.

See Also

Gorilla.Particle Unit Reference

Core particle structure for the particle system.

TGorillaParticle

The particle record structure containing all properties of a single particle.

Unit: Gorilla.Particle

Type: Record

Record Fields

Id

Id: Integer;

Unique identifier for each particle instance. Automatically assigned on creation.

Position

Position: TPoint3D;

Current 3D world position of the particle.

Usage:

LParticle^.Position := Point3D(0, 10, 0);

Normal

Normal: TPoint3D;

Normal vector, used internally for camera facing direction. Typically set to view direction.

Velocity

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

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

Size: Single;

Current size of the particle in pixels or world units.

Angle

Angle: Single;

Rotation angle in degrees.

Weight

Weight: Single;

Particle weight, affects gravity and other force influencers.

Age

Age: Single;

Current age of the particle in seconds. Automatically updated each frame.

Read-only: Modified internally by emitter.

Life

Life: Single;

Total lifetime of the particle in seconds. Particle is destroyed when Age >= Life.

Growth

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

Data: Pointer;

Custom user data pointer. Used internally by physics influencer to store physics body reference.

Class Methods

Create

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.

Instance Methods

GetDeltaTime

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;

GetEyeDistance

function GetEyeDistance(const APosition: TPoint3D): Single;

Calculates distance from particle to specified position (typically camera).

Parameters:

Returns: Distance in world units

Usage:

var
  LDist: Single;
begin
  LDist := LParticle^.GetEyeDistance(Camera.Position.Point);
end;

Operators

Equal (=)

class operator Equal(A, B: TGorillaParticle): Boolean;

Compares two particles by position.

NotEqual (<>)

class operator NotEqual(A, B: TGorillaParticle): Boolean;

Checks if two particles have different positions.

GreaterThan (>)

class operator GreaterThan(A, B: TGorillaParticle): Boolean;

Compares particles by Z-depth. Used for sorting.

LessThan (<)

class operator LessThan(A, B: TGorillaParticle): Boolean;

Compares particles by Z-depth. Used for sorting.

TGorillaParticleList

TGorillaParticleList = TList<PGorillaParticle>;

List type for managing particle collections.

Examples

Manual Particle Creation

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;

Particle Age Progress

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;

Vertex Attributes

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.

Platform Support

All Gorilla platforms supported.

See Also

Gorilla.Particle.Emitter Unit Reference

Particle emitter class and preset configuration for the particle system.

TParticlePreset

Randomization preset for single-value particle properties.

Inheritance: TPersistent → TParticlePreset

Unit: Gorilla.Particle.Emitter

Constructor

Create

constructor Create(const AMin, AMax: Integer; const ADivisor: Integer;
  const ANegative: Boolean);

Creates a preset with specified range and options.

Parameters:

Properties

Min

property Min: Integer;

Minimum value before division.

Max

property Max: Integer;

Maximum value before division.

Divisor

property Divisor: Integer;

Divisor for float conversion. Result = Value / Divisor.

Negative

property Negative: Boolean;

If True, randomly returns positive or negative values.

Methods

Preset

procedure Preset(const AMin, AMax: Integer; const ADivisor: Integer;
  const ANegative: Boolean);

Reconfigure preset values.

GetRandomValue

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;

GetMinValue / GetMaxValue

function GetMinValue(): Single;
function GetMaxValue(): Single;

Returns minimum/maximum value after division.

TParticleVectorPreset

Randomization preset for 3D vector particle properties.

Inheritance: TPersistent → TParticleVectorPreset

Constructor

Create

constructor Create(const AMin, AMax: Integer; const ADivisor: Integer;
  const ADirection: TPoint3D; const AAxis: TAllowedAxisSet = [axX, axY, axZ]);

Parameters:

Properties

RangeX, RangeY, RangeZ

property RangeX: TParticlePreset;
property RangeY: TParticlePreset;
property RangeZ: TParticlePreset;

Individual axis presets.

Direction

property Direction: TPosition3D;

Direction multiplier applied to randomized vector.

Axis

property Axis: TAllowedAxisSet;

Axes allowed for randomization. Set of [axX, axY, axZ].

Methods

Preset

procedure Preset(const AMin, AMax: Integer; const ADivisor: Integer;
  const ADirection: TPoint3D; const AAxis: TAllowedAxisSet = [axX, axY, axZ]);

Reconfigure all axes with same values.

GetRandomValue

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;

TGorillaParticleEmitter

Base particle emitter class.

Inheritance: TGorillaMesh → TGorillaParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Emitter

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates particle emitter with default settings:

Destroy

destructor Destroy(); override;

Stops emitter, clears particles, and frees resources.

Properties

Active (Read-Only)

property Active: Boolean read GetActive;

Returns True if emitter timer/thread is running.

Time (Read-Only)

property Time: Single read GetTime;

Total time in seconds since Start() was called.

DeltaTime (Read-Only)

property DeltaTime: Single read GetDeltaTime;

Time in seconds since last update tick.

Particles (Read-Only)

property Particles: TGorillaParticleList read FParticles;

List of currently active particles.

MeshData (Read-Only)

property MeshData: TMeshData read GetMeshData;

Internal mesh data for particle vertices.

Thread (Read-Only)

property Thread: TThread read GetThread;

Async computation thread if Async = True, otherwise nil.

Emitted (Read-Only)

property Emitted: Integer read GetEmitted;

Number of currently active particles.

Configuration Properties

Camera

property Camera: TCamera;

Linked camera for particle sorting. Required for correct transparency.

Usage:

LEmitter.Camera := GorillaViewport1.Camera;

Async

property Async: Boolean;

Enable background thread processing. Recommended for > 5000 particles.

Default: False

EmitTime

property EmitTime: Integer;

Update interval in milliseconds.

Default: 16ms (~60 FPS)

Usage:

LEmitter.EmitTime := 33;  // 30 FPS

Reuse

property Reuse: Boolean;

Enable particle caching/reuse for better performance.

Default: True

AutoEmit

property AutoEmit: Boolean;

Automatically emit particles each interval.

Default: True

EmitParticles

property EmitParticles: Integer;

Number of particles to emit per interval (when AutoEmit = True).

Default: 10

MaxParticles

property MaxParticles: Integer;

Maximum number of simultaneously active particles.

Default: 1000

Note: Cannot reduce below current particle count.

MaxAutoEmitTime

property MaxAutoEmitTime: Integer;

Maximum auto-emit duration in milliseconds. 0 = infinite.

Default: 0 (infinite)

Usage:

// Emit for 5 seconds then stop
LEmitter.MaxAutoEmitTime := 5000;

AutoRotation

property AutoRotation: Single;

Automatic particle rotation per frame in shader.

Default: 0 (no rotation)

Usage:

LEmitter.AutoRotation := 0.5;  // Gentle rotation

ParticleFade

property ParticleFade: Single;

Fade particle edges to prevent clipping artifacts.

Default: 0 (no fading)

Usage:

LEmitter.ParticleFade := 2.5;

ShowBounds

property ShowBounds: Boolean;

Show/hide emitter bounding box (debug).

Default: False

Particle Property Presets

ParticlePosition

property ParticlePosition: TParticleVectorPreset;

Randomization preset for initial particle position.

ParticleVelocity

property ParticleVelocity: TParticleVectorPreset;

Randomization preset for particle velocity.

ParticleSize

property ParticleSize: TParticlePreset;

Randomization preset for particle size.

ParticleAngle

property ParticleAngle: TParticlePreset;

Randomization preset for particle rotation angle.

ParticleWeight

property ParticleWeight: TParticlePreset;

Randomization preset for particle weight.

ParticleGrowth

property ParticleGrowth: TParticlePreset;

Randomization preset for particle growth/shrinkage.

ParticleLifeTime

property ParticleLifeTime: TParticlePreset;

Randomization preset for particle lifetime.

Blending Properties

BlendFunc

property BlendFunc: TBlendEquationFunc;

Blending equation function.

Usage:

LEmitter.BlendFunc := TBlendEquationFunc.befAdd;

BlendSource

property BlendSource: TBlendFactor;

Source blending factor.

BlendDest

property BlendDest: TBlendFactor;

Destination blending factor.

AlphaBlendSource

property AlphaBlendSource: TBlendFactor;

Alpha channel source blending factor.

AlphaBlendDest

property AlphaBlendDest: TBlendFactor;

Alpha channel destination blending factor.

Influencers

Influencers

property Influencers: TGorillaParticleInfluencerList;

List of active influencers affecting particles.

Methods

Start

procedure Start(); virtual;

Start particle emitter timer/thread.

Triggers: OnStart event

Stop

procedure Stop(); virtual;

Stop particle emitter (particles remain visible).

Triggers: OnStop event

Clear

procedure Clear(); virtual;

Destroy all particles (active and cached).

ClearUnused

procedure ClearUnused(); virtual;

Free cached particles only.

EmitParticle

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;

SortByEyeDistance

procedure SortByEyeDistance(const APosition: TPoint3D); virtual;

Sort particles by distance to camera for correct transparency.

Called automatically when Camera is assigned.

ForceUpdate

procedure ForceUpdate();

Force immediate particle update independent of timer.

AddInfluencer / RemoveInfluencer

procedure AddInfluencer(AInfl: TGorillaParticleInfluencer);
procedure RemoveInfluencer(AInfl: TGorillaParticleInfluencer);

Manage influencers.

ClearInfluencers

procedure ClearInfluencers();

Remove all influencers.

LoadTexture

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:

Usage:

LEmitter.LoadTexture('explosion.png', 64, True, 4, 4, 256, 256);

Events

OnStart

property OnStart: TNotifyEvent;

Fired when emitter starts.

OnStop

property OnStop: TNotifyEvent;

Fired when emitter stops.

OnProcess

property OnProcess: TOnAutoEmitProcess;

Fired during each auto-emit update.

TOnAutoEmitProcess = procedure(ASender: TObject;
  const AElapsedTime: Int64; const ADeltaTime: Double) of object;

OnEmitted

property OnEmitted: TOnParticleEmittedEvent;

Fired when particle is emitted (including reused particles).

TOnParticleEmittedEvent = procedure(ASender: TObject;
  const AParticle: PGorillaParticle) of object;

OnDispose

property OnDispose: TOnParticleNotifyEvent;

Fired before particle destruction.

TOnParticleNotifyEvent = procedure(ASender: TObject;
  const AParticle: PGorillaParticle) of object;

Examples

Basic Emitter

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;

One-Shot Effect

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;

Interactive Emission

procedure TForm1.ViewportMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Single);
var
  LPos: TPoint3D;
begin
  LPos := ScreenToWorld(X, Y);
  LEmitter.EmitParticle(LPos);
end;

See Also

Gorilla.Particle.Eruption Unit Reference

Pre-configured volcanic eruption particle emitter with lava projectiles.

TGorillaEruptionParticleEmitter

Realistic volcanic eruption effect with upward-launching lava particles.

Inheritance: TGorillaParticleEmitter → TGorillaEruptionParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Eruption

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates eruption emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up eruption emitter resources.

Properties

Gravity (Read-Only)

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;

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for lava textures.

Default Configuration

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:

Integrated Influencers

Examples

Basic Eruption

var
  LEruption: TGorillaEruptionParticleEmitter;
begin
  LEruption := TGorillaEruptionParticleEmitter.Create(Self);
  LEruption.Parent := GorillaViewport1;
  LEruption.Camera := Camera1;
  LEruption.Position.Point := Point3D(0, 0, 0);

  LEruption.Start();
end;

Violent Eruption

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;

Gentle Eruption

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;

Geyser Effect

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;

Intermittent Eruption

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;

Lava Fountain

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;

Controlled Burst

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;

Tips

Performance

Visual Quality

Realism

Configuration Tips

Velocity vs Gravity:

Spread Pattern:

Common Combinations

Eruption with Lava Flow

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;

Eruption with Smoke

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;

Eruption with Impact Particles

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;

Physics Considerations

Trajectory Calculation

The default settings approximate realistic lava trajectories:

Performance Notes

See Also

Gorilla.Particle.Explosion Unit Reference

Pre-configured explosion particle emitter with outward burst effect.

TGorillaExplosionParticleEmitter

Dynamic explosion effect with configurable burst direction and intensity.

Inheritance: TGorillaParticleEmitter → TGorillaExplosionParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Explosion

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates explosion emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up explosion emitter resources.

Properties

SpawnSize

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;

Speed

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;

Axis

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);

Gravity (Read-Only)

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;

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for explosion textures.

Default Configuration

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

Integrated Influencers

Examples

Basic Explosion

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;

Large Explosion

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;

Spherical Explosion

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;

Ground Explosion

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;

Directional Blast

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;

Firework

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;

Repeating Explosions

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;

Colored Explosion

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;

Tips

Performance

Visual Quality

Timing

Direction Control

Axis Examples:

Common Combinations

Explosion with Flash

var
  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;

Explosion with Smoke

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;

See Also

Gorilla.Particle.Fire Unit Reference

Pre-configured fire particle emitter with multiple visual styles.

TGorillaFireParticleEmitter

Realistic fire effect with integrated smoke and optional sparks.

Inheritance: TGorillaParticleEmitter → TGorillaFireParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Fire

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates fire emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up fire emitter and integrated smoke/spark emitters.

Properties

Kind

property Kind: TGorillaFireParticleKind;

Fire visual style.

Type: TGorillaFireParticleKind

Default: Default

Usage:

LFire.Kind := TGorillaFireParticleKind.Torch;

Note: On non-Windows platforms, only one fire texture is available due to compiler limitations.

Smoke (Read-Only)

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;

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for fire textures.

Methods

Start

procedure Start(); override;

Starts fire and smoke emitters.

Stop

procedure Stop(); override;

Stops fire and smoke emitters.

ClearUnused

procedure ClearUnused(); override;

Clears unused particles from fire and smoke caches.

Clear

procedure Clear(); override;

Destroys all particles in fire and smoke emitters.

Default Configuration

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

Integrated Influencers

Integrated Sub-Emitters

Examples

Basic Fire

var
  LFire: TGorillaFireParticleEmitter;
begin
  LFire := TGorillaFireParticleEmitter.Create(Self);
  LFire.Parent := GorillaViewport1;
  LFire.Camera := Camera1;
  LFire.Start();
end;

Fire with Smoke

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;

Torch Fire

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;

Campfire

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;

Adjusting Fire Intensity

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;

Tips

Performance

Visual Quality

Positioning

See Also

Gorilla.Particle.Influencer Unit Reference

Particle influencers for manipulating particle behavior at runtime.

TGorillaParticleInfluencer

Base influencer class for all particle manipulators.

Inheritance: TFmxObject → TGorillaParticleInfluencer

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Influencer

Properties

Enabled

property Enabled: Boolean;

Enable/disable influencer. Disabled influencers don't affect particles.

Default: True

Emitter

property Emitter: TComponent;

Linked particle emitter. Must be set for influencer to work.

Usage:

LInfluencer.Emitter := MyParticleEmitter;

Methods

Interpolate

procedure Interpolate(const ADeltaTime: Single; const AParticle: PGorillaParticle);

Called each frame for each particle. Override DoOnInterpolate in derived classes.

EmitParticleCallback

procedure EmitParticleCallback(const AParticle: PGorillaParticle);

Called when particle is emitted. Override DoOnEmitParticle in derived classes.

DestroyParticleCallback

procedure DestroyParticleCallback(const AParticle: PGorillaParticle);

Called before particle destruction. Override DoOnDestroyParticle in derived classes.

Movement Influencers

TGorillaLinearParticleInfluencer

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;

TGorillaSpiralParticleInfluencer

Creates spiral/helical motion perfect for snowflakes.

Inheritance: TGorillaParticleInfluencer → TGorillaSpiralParticleInfluencer

Properties

Spirals
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;

TGorillaGravityParticleInfluencer

Simulates gravity force on particles.

Inheritance: TGorillaForceParticleInfluencer → TGorillaGravityParticleInfluencer

Properties

Force
property Force: TPosition3D;

Gravity vector in meters/second².

Default: Point3D(0, 9.81, 0) (Earth gravity)

Ratio
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;

TGorillaWindParticleInfluencer

Creates wind zones affecting particles.

Inheritance: TGorillaForceParticleInfluencer → TGorillaWindParticleInfluencer

Properties

Origin
property Origin: TPosition3D;

Wind origin point (strongest wind location).

Default: Point3D(0, 0, 0)

Size
property Size: TPosition3D;

Wind zone dimensions.

Default: Point3D(50, 20, 20)

Force
property Force: TPosition3D;

Wind vector in meters/second (Beaufort scale). Direction defines wind direction.

Default: Point3D(-8.0, 0, 0)

Methods

GetBoundingBox
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

TGorillaTraktorInfluencer

Creates gravitational attraction point (black hole effect).

Inheritance: TGorillaParticleInfluencer → TGorillaTraktorInfluencer

Properties

Center
property Center: TPoint3D;

Attraction center point.

Default: Point3D(0, 0, 0)

Radius
property Radius: Single;

Attraction radius. Force is zero at radius edge, maximum at center.

Default: 1.0

Acceleration
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;

TGorillaTrailedParticleInfluencer

Particles follow a predefined 3D path.

Inheritance: TGorillaParticleInfluencer → TGorillaTrailedParticleInfluencer

Properties

Path
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;

Visual Influencers

TGorillaColoredParticleInfluencer

Interpolates particle color from start to end over lifetime.

Inheritance: TGorillaParticleInfluencer → TGorillaColoredParticleInfluencer

Properties

StartColor / StartColorF
property StartColor: TAlphaColor;
property StartColorF: TAlphaColorF;

Initial particle color (at birth).

Default: Blue

EndColor / EndColorF
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;

TGorillaRandomColorParticleInfluencer

Randomizes particle color each frame.

Inheritance: TGorillaParticleInfluencer → TGorillaRandomColorParticleInfluencer

Usage:

var
  LRandColor: TGorillaRandomColorParticleInfluencer;
begin
  LRandColor := TGorillaRandomColorParticleInfluencer.Create(LEmitter);
  LRandColor.Emitter := LEmitter;
  LRandColor.Enabled := True;
end;

Physics Influencers

TGorillaObstacleInfluencer

Simple collision with obstacles (sphere, cube, or mesh).

Inheritance: TGorillaParticleInfluencer → TGorillaObstacleInfluencer

Properties

Center
property Center: TPoint3D;

Obstacle center position.

Default: Point3D(0, 0, 0)

Radius
property Radius: Single;

Obstacle radius (for sphere kind).

Default: 1.0

Size
property Size: TPoint3D;

Obstacle dimensions (for cube kind).

Kind
property Kind: TParticleObstacleKind;

Obstacle type: Sphere, Cube, or Mesh.

Default: Sphere

EmitInside
property EmitInside: Boolean;

Allow particles to spawn inside obstacle.

Default: False

Surface
property Surface: TParticleObstacleSurface;

Surface interaction mode:

Default: Flow

Acceleration
property Acceleration: Single;

Collision acceleration force.

Default: 9.81

Elasticity
property Elasticity: Single;

Surface elasticity (collision threshold).

Default: 0.1

Methods

SetMesh
procedure SetMesh(const AValue: TMeshData; const ATransf: TMatrix3D);

Set obstacle mesh for Kind = Mesh.

Parameters:

Intersects
function 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;

TGorillaPhysicsInfluencer

Full physics engine integration for realistic particle collisions.

Inheritance: TGorillaParticleInfluencer → TGorillaPhysicsInfluencer

Requires: Q3 Physics package

Properties

Physics
property Physics: TComponent;

Linked TGorillaPhysicsSystem component.

Restitution
property Restitution: Single;

Particle bounciness.

Default: 0.1

Density
property Density: Single;

Particle mass density.

Default: 0.00001

Events

OnPhysicsBody
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;

TGorillaParticleInfluencerList

List container for influencers.

Inheritance: TObjectList<TGorillaParticleInfluencer> → TGorillaParticleInfluencerList

Methods

Notification

procedure Notification(AComponent: TComponent; Operation: TOperation);

Handles component notifications for cleanup.

Examples

Falling Rain with Wind

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;

Fire with Color Transition

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;

Bouncing Particles

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;

See Also

Gorilla.Particle.Rain Unit Reference

Pre-configured rain particle emitter with falling droplets and splash effects.

TGorillaRainParticleEmitter

Realistic rain effect with integrated wind and splash emitters.

Inheritance: TGorillaParticleEmitter → TGorillaRainParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Rain

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates rain emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up rain emitter and integrated splash emitter.

Properties

SpawnSize

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.

Wind (Read-Only)

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);

Colored (Read-Only)

property Colored: TGorillaColoredParticleInfluencer read FColored;

Integrated color influencer for raindrop fading.

Default: Light blue to transparent

Splashes (Read-Only)

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

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for raindrop textures.

Methods

Start

procedure Start(); override;

Starts rain and splash emitters.

Stop

procedure Stop(); override;

Stops rain and splash emitters.

Splash

procedure Splash(const APosition: TPoint3D); virtual;

Manually emit a splash particle at specified position.

Parameters:

Usage:

// Create splash on raindrop collision
if RaindropHitsGround(LParticle) then
  LRain.Splash(LParticle^.Position);

Default Configuration

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

Integrated Influencers

Integrated Sub-Emitters

Examples

Basic Rain

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;

Rain with Wind

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;

Rain with Splashes

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;

Heavy Rain

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;

Light Drizzle

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;

Tips

Performance

Visual Quality

Realism

See Also

Gorilla.Particle.Smoke Unit Reference

Pre-configured smoke particle emitter with multiple visual styles.

TGorillaSmokeParticleEmitter

Realistic smoke effect with various texture styles.

Inheritance: TGorillaParticleEmitter → TGorillaSmokeParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Smoke

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates smoke emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up smoke emitter resources.

Properties

Kind

property Kind: TGorillaSmokeParticleKind;

Smoke visual style.

Type: TGorillaSmokeParticleKind

Default: Default

Usage:

LSmoke.Kind := TGorillaSmokeParticleKind.Style2;

Note: Each style uses a different sprite sheet texture.

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for smoke textures.

Default Configuration

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

Examples

Basic Smoke

var
  LSmoke: TGorillaSmokeParticleEmitter;
begin
  LSmoke := TGorillaSmokeParticleEmitter.Create(Self);
  LSmoke.Parent := GorillaViewport1;
  LSmoke.Camera := Camera1;
  LSmoke.Start();
end;

Chimney Smoke

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;

Thick Smoke

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;

Fog Effect

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;

Explosion Smoke

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;

Tips

Performance

Visual Quality

Realistic Effects

Common Combinations

Fire + Smoke

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;

Steam

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;

See Also

Gorilla.Particle.Snow Unit Reference

Pre-configured snow particle emitter with spiral falling motion.

TGorillaSnowParticleEmitter

Realistic snowfall effect with integrated spiral and wind influencers.

Inheritance: TGorillaParticleEmitter → TGorillaSnowParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Snow

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates snow emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up snow emitter resources.

Properties

SpawnSize

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.

Spiral (Read-Only)

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;

Wind (Read-Only)

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);

Colored (Read-Only)

property Colored: TGorillaColoredParticleInfluencer read FColored;

Integrated color influencer for snowflake fading.

Default: Light gray/white to transparent

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for snowflake textures.

Default Configuration

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

Integrated Influencers

Examples

Basic Snowfall

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;

Snow with Wind

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;

Heavy Snowfall

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;

Light Flurries

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;

Blizzard

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;

Gentle Snow

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;

Tips

Performance

Visual Quality

Realism

Optimization

See Also

Gorilla.Particle.Spot Unit Reference

Pre-configured spot/splash particle emitter for small area effects.

TGorillaSpotParticleEmitter

Simple spot effect perfect for splashes, impacts, and small localized particle bursts.

Inheritance: TGorillaParticleEmitter → TGorillaSpotParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Spot

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates spot emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up spot emitter resources.

Properties

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for spot textures.

Default Configuration

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:

Examples

Basic Splash

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;

Rain Splashes

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;

Impact Effect

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;

Footstep Dust

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;

Magic Sparkle

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;

Continuous Drip

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;

Common Use Cases

Collision Effects

Environmental Effects

Character Actions

Magical Effects

Tips

Performance

Visual Quality

Integration

Timing

See Also

Gorilla.Particle.Waterfall Unit Reference

Pre-configured waterfall particle emitter with cascading water effect.

TGorillaWaterfallParticleEmitter

Realistic waterfall effect with forward projection and gravity.

Inheritance: TGorillaParticleEmitter → TGorillaWaterfallParticleEmitter

Platforms: All Gorilla platforms

Unit: Gorilla.Particle.Waterfall

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates waterfall emitter with preconfigured settings:

Destroy

destructor Destroy(); override;

Cleans up waterfall emitter resources.

Properties

SpawnSize

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;

Power

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.

Spread

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;

Speed

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;

Colored (Read-Only)

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

ParticleMaterial (Read-Only)

property ParticleMaterial: TGorillaParticleMaterialSource read GetParticleMaterial;

Attached particle material source for water textures.

Default Configuration

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

Integrated Influencers

Examples

Basic Waterfall

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;

Large Waterfall

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;

Small Stream

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;

Fountain

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;

Rapid Cascade

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;

Gentle Trickle

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;

Tips

Performance

Visual Quality

Realism

Configuration

Power vs Spread:

Speed vs Gravity:

Common Combinations

Waterfall with Mist

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;

See Also

Gorilla.Physics Unit Reference

Overview

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.

Class Hierarchy

TComponent
  └── TControl3D
        └── TGorillaControl
              └── TGorillaPhysicsSystem

TGorillaPhysicsSystem

Published Properties

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

Published Events

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

Public Properties

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

Collider Methods

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

Transform Methods

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

Force / Impulse Methods

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

Lifecycle Methods

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()

Class Methods

Method Description
RegisterDriverClass(AEngineName, AClass) Register a custom physics driver
UnregisterDriverClass(AEngineName/AClass) Unregister a physics driver
GetDriverClass(AEngineName/AType) Get registered driver class

See Also

Gorilla.Physics.Types Unit Reference

Overview

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.

Enumerations

TGorillaPhysicsDriverType

Value Description
Q3Physics Q3 Physics Engine (default)
JOLTPhysics JOLT Physics Engine
CustomPhysics Custom physics driver

TGorillaPhysicsColliderKind

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)

TGorillaPhysicsBodyType

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

TGorillaPhysicsBodyState

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

TGorillaPhysicsJointType

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, RackAndPinion and Pulley were originally JOLT-only; they now have native Q3 solvers as well. Buoyancy is also implemented for JOLT (native ApplyBuoyancyImpulse).

TGorillaPhysicsMotorType

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)

Records

TGorillaPhysicsColliderData

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

TGorillaColliderSettings

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 Methods

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;

TGorillaPhysicsJointPrefab

Design-time joint configuration (collection item).

Published Properties

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

Callback Types

TOnGorillaPhysicsCollisionEvent = procedure(ASender: TObject;
  const AOffset, ANormal: TPoint3D;
  ABody1, ABody2: TGorillaPhysicsBody) of object;

See Also

Gorilla.Terrain Unit Reference

Main terrain component for rendering planar terrain from heightmaps or procedural algorithms.

TGorillaTerrain

Simple terrain component for rendering from heightmaps or procedural algorithms.

Inheritance: TGorillaSingletonMesh → TGorillaTerrain

Platforms: All Gorilla platforms

Unit: Gorilla.Terrain

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates a new terrain instance with default settings:

Destroy

destructor Destroy; override;

Frees all resources including heightmap and material objects.

Properties

TwoFace

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.

ResolutionX

property ResolutionX: Integer read GetResolutionX write SetResolutionX;

Columns of the terrain grid. Larger values create more vertices.

See also: ResolutionY, Resolution, SetXYResolution

ResolutionY

property ResolutionY: Integer read GetResolutionY write SetResolutionY;

Rows of the terrain grid. Larger values create more vertices.

See also: ResolutionX, Resolution, SetXYResolution

Resolution

property Resolution: TPoint read GetResolution write SetResolution;

Gets/sets both X and Y resolution simultaneously.

Storage: Not stored (use ResolutionX/ResolutionY in IDE)

HeightMap

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

Smoothing

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

ShowVertices

property ShowVertices: Boolean read FShowVertices write FShowVertices;

Displays vertices as dots after rendering (debug only).

Warning: Only works when StaticBuffering = False. Significantly reduces performance.

ShowGrid

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.

VerticeColor

property VerticeColor: TAlphaColor read GetVerticeColor write SetVerticeColor;

Color for vertices and grid lines when debug visualization is enabled.

Default: Yellow (TAlphaColorRec.Yellow)

StaticBuffering

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

AutoDecimate

property AutoDecimate: Boolean read FAutoDecimate write SetAutoDecimate;

Automatically reduce vertex data during terrain rebuild.

Default: False

HeightScale (Deprecated)

property HeightScale: Single read GetHeightScale write SetHeightScale; deprecated;

Deprecated: Use the Height property instead for Y-axis scaling.

Methods

SetXYResolution

procedure SetXYResolution(const X, Y: Integer); virtual;

Sets resolution for both axes in one call.

Parameters:

Recommended values: 16, 32, 64, 128, 256, 512, 1024, 2048

Example:

LTerrain.SetXYResolution(256, 256);

RebuildTerrain

procedure RebuildTerrain(const AStaticBuffering: Boolean = true;
  const ADecimate: Boolean = false); virtual;

Clears previous terrain and rebuilds from current heightmap and settings.

Parameters:

Example:

// 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);

RandomTerrain (by Type)

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:

Example:

LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.PerlinNoise);

See also: Gorilla.Terrain.Algorithm

RandomTerrain (by Instance)

procedure RandomTerrain(const AAlgorithm: TRandomTerrainAlgorithm;
  const AStaticBuffering: Boolean = true;
  const ADecimate: Boolean = false); overload;

Builds heightmap using configured algorithm instance.

Parameters:

Example:

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

Decimate

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:

Remarks: 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

BeginUpdate / EndUpdate

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;

GetMeshMatrix

function GetMeshMatrix: TMatrix3D; override;

Returns the mesh transformation matrix for the terrain vertices.

Returns: 4×4 transformation matrix

GetBodySize

function GetBodySize: TPoint3D; override;

Returns terrain dimensions.

Returns: TPoint3D with Width, Height, Depth

LoadFromDefinition / StoreToDefinition

procedure LoadFromDefinition(const ADef: TCustomDef); override;
procedure StoreToDefinition(const ADef: TCustomDef); override;

Load/save terrain configuration from/to definition objects.

Resize3D

procedure Resize3D; override;

Called when terrain is resized. Triggers terrain rebuild.

Examples

Basic Terrain from Heightmap

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;

Optimized High-Resolution Terrain

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;

Debug Visualization

// Enable for debugging (disable StaticBuffering first)
LTerrain.StaticBuffering := False;
LTerrain.RebuildTerrain(False);
LTerrain.ShowGrid := True;
LTerrain.ShowVertices := True;
LTerrain.VerticeColor := TAlphaColorRec.Yellow;

See Also

Gorilla.Terrain.Algorithm Unit Reference

Procedural terrain generation algorithms for creating realistic landscapes without heightmap images.

Unit: Gorilla.Terrain.Algorithm

Constants

const
  GORILLA_TERRAIN_SMOOTHING_MIN = 0;
  GORILLA_TERRAIN_SMOOTHING_MAX = 20;

Valid range for terrain smoothing iterations.

Types

TRandomTerrainAlgorithmType

type
  TRandomTerrainAlgorithmType = (Hill, DiamondSquare, Mandelbrot,
    PerlinNoise, Plateau, Brownian, Planar);

Enumeration of built-in procedural terrain algorithms.

Values:

TPerlinNoiseInterpolation

type
  TPerlinNoiseInterpolation = (Linear, Cosine, Cubic);

Interpolation methods for Perlin noise terrain.

Values:

Classes

TRandomTerrainAlgorithm

Base class for procedural terrain algorithms.

Inheritance: TObject → TRandomTerrainAlgorithm

Properties

Size
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

Methods

GetHeightMap
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()

Creating Custom Algorithms

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;

THillRandomTerrain

Generates smooth procedural hills using radius-based height calculations.

Inheritance: TRandomTerrainAlgorithm → THillRandomTerrain

Properties

Hills
property Hills: Integer read FHills write FHills;

Number of hills to generate.

Default: 20

MinRadius
property MinRadius: Integer read FMinRadius write FMinRadius;

Minimum radius for generated hills.

Default: 10

MaxRadius
property MaxRadius: Integer read FMaxRadius write FMaxRadius;

Maximum radius for generated hills. Algorithm interpolates between min and max.

Default: 100

Example

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;

TDiamondSquareTerrain

Popular algorithm for realistic random terrain with peaks and valleys.

Inheritance: TRandomTerrainAlgorithm → TDiamondSquareTerrain

Properties

MSeed
property MSeed: Integer read FMSeed write FMSeed;

Seed value for random number generation.

Default: 1000

Range: Affects randomness range (0 to MSeed)

Example

var
  LAlg: TDiamondSquareTerrain;
begin
  LAlg := TDiamondSquareTerrain.Create;
  try
    LAlg.Size := 9;
    LAlg.MSeed := 2000;  // More variation
    LTerrain.RandomTerrain(LAlg);
  finally
    LAlg.Free;
  end;
end;

TMandelbrotTerrain

Generates the Mandelbrot fractal set as terrain.

Inheritance: TRandomTerrainAlgorithm → TMandelbrotTerrain

Remarks: Produces fixed pattern (no randomness), useful as base for further processing.

Example

LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Mandelbrot);

TDiamondSquareBasedTerrain

Base class for algorithms combining diamond-square with other techniques.

Inheritance: TRandomTerrainAlgorithm → TDiamondSquareBasedTerrain

Properties

MSeed
property MSeed: Integer read FMSeed write FMSeed;

Random seed value.

Default: 1000

DiamondSquareFactor
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

DiamondSquareEnabled
property DiamondSquareEnabled: Boolean read FDiamondSquareEnabled write FDiamondSquareEnabled;

Enable/disable diamond-square processing.

Default: True


TPerlinNoiseTerrain

Generates smooth terrain using Perlin noise with configurable interpolation.

Inheritance: TDiamondSquareBasedTerrain → TPerlinNoiseTerrain

Properties

Intensity
property Intensity: Single read FIntensity write FIntensity;

Controls height intensity of noise. Higher = taller peaks.

Default: 0.25

Interpolation
property Interpolation: TPerlinNoiseInterpolation read FInterpolation write FInterpolation;

Interpolation method for smoothing.

Values:

Default: Cosine

Example

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;

TPlateauTerrain

Creates high flat plateaus surrounded by lower terrain.

Inheritance: TDiamondSquareTerrain → TPlateauTerrain

Properties

Plateaus
property Plateaus: Integer read FPlateaus write FPlateaus;

Number of plateaus to generate. May overlap due to random placement.

Default: 3

MinSize
property MinSize: Integer read FMinSize write FMinSize;

Minimum plateau radius in pixels.

Default: 50

MaxSize
property MaxSize: Integer read FMaxSize write FMaxSize;

Maximum plateau radius in pixels.

Default: 250

MinHeight
property MinHeight: Single read FMinHeight write FMinHeight;

Minimum height factor for plateaus.

Default: 0.25

Range: 0.0 to 1.0

MaxHeight
property MaxHeight: Single read FMaxHeight write FMaxHeight;

Maximum height factor for plateaus.

Default: 1.0

Range: 0.0 to 1.0

Inverted
property Inverted: Boolean read FInverted write FInverted;

When True, creates flat lowlands instead of plateaus.

Default: False

Example

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;

TBrownianTerrain

Generates terrain using Brownian motion particle simulation.

Inheritance: TDiamondSquareBasedTerrain → TBrownianTerrain

Properties

Particles
property Particles: Integer read FParticles write FParticles;

Number of particles for simulation. More = more detail but slower.

Default: 3000

MinHeight
property MinHeight: Single read FMinHeight write FMinHeight;

Minimum height factor for computed peaks.

Default: 0.01

MaxHeight
property MaxHeight: Single read FMaxHeight write FMaxHeight;

Maximum height factor for computed peaks.

Default: 0.05

Example

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;

TPlanarTerrain

Generates completely flat terrain.

Inheritance: TRandomTerrainAlgorithm → TPlanarTerrain

Remarks: Useful as starting point for custom terrain modification. Generates 32×32 grid by default.

Example

LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Planar);

Algorithm Comparison

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

See Also

Gorilla.Terrain.CVLOD Unit Reference

Level-of-detail terrain with dynamic mesh optimization.

Unit: Gorilla.Terrain.CVLOD

Status: Experimental - clustering system not fully implemented

Overview

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:

Types

TTerrainCluster

type
  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:

Classes

TTerrainUpdateTask

Manages asynchronous mesh updates for the LOD terrain.

Status: Not fully implemented. Async updates currently disabled.

TGorillaCVLODTerrain

Level-of-detail terrain with dynamic mesh optimization.

Inheritance: TGorillaTerrain → TGorillaCVLODTerrain

Properties

Camera
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

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;
LODLevels
property LODLevels: Integer read FLODLevels write SetLODLevels default 4;

Number of detail levels.

Range: 1 to 8

Default: 4

ClusterSize
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

AsyncUpdate
property AsyncUpdate: Boolean read FAsyncUpdate write SetAsyncUpdate default false;

Enable asynchronous mesh updates on background thread.

Status: Not fully implemented, keep disabled

Default: False

CameraMovementThreshold
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

UpdateInterval
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

Methods

RebuildTerrain
procedure RebuildTerrain(const AStaticBuffering: Boolean = true;
  const ADecimate: Boolean = false); override;

Overridden to generate terrain at specified CurrentLOD level.

Behavior:

Example:

LLODTerrain.CurrentLOD := 1;  // Half resolution
LLODTerrain.RebuildTerrain;
ForceUpdateLOD
procedure ForceUpdateLOD;

Immediately updates all clusters based on current camera position (clustering mode).

Note: Only useful in clustering mode (experimental)

SetCustomLODDistances
procedure SetCustomLODDistances(const ADistances: array of Single);

Sets custom distance thresholds for each LOD level (clustering mode).

Parameters:

Example:

LLODTerrain.SetCustomLODDistances([10.0, 30.0, 100.0, 300.0]);

Note: Only used in clustering mode (experimental)

GetLODStatistics
procedure GetLODStatistics(out ATotalVertices, ATotalIndices: Integer;
  out ALODDistribution: TArray<Integer>);

Returns current LOD statistics.

Parameters:

Example:

var
  LVerts, LIndices: Integer;
  LDist: TArray<Integer>;
begin
  LLODTerrain.GetLODStatistics(LVerts, LIndices, LDist);
  ShowMessage(Format('Vertices: %d, Indices: %d', [LVerts, LIndices]));
end;

Usage Modes

Simple LOD Mode (Recommended)

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:

Dynamic LOD Based on Distance

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;

Multiple Terrain Tiles with LOD

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;

Performance Analysis

Vertex Reduction by LOD Level

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%

Performance Impact

Benefits:

Costs:

Optimization Tips

  1. Minimize LOD changes - Only rebuild when distance threshold crossed
  2. Add hysteresis - Use different thresholds for increasing/decreasing LOD
  3. Smooth transitions - Fade between LOD levels or use distance fog
  4. Cache LOD versions - Pre-generate and store multiple LOD levels
  5. Batch updates - Update multiple terrains in one frame

Visual Quality

Preventing Popping

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).

Clustering Mode (Experimental)

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;

Best Practices

  1. Use simple LOD mode - CurrentLOD property is stable and effective
  2. Update on distance thresholds - Not every frame
  3. Add hysteresis - Prevent rapid switching
  4. Combine with culling - Don't render distant terrains at all
  5. Profile performance - Measure actual impact
  6. Consider alternatives - Paging, tiling, or streaming for huge worlds

See Also

Gorilla.Terrain.Sphere Unit Reference

Spherical terrain component for planetary surfaces.

Unit: Gorilla.Terrain.Sphere

TGorillaSphereTerrain

Spherical terrain component that deforms a sphere surface using heightmaps or procedural algorithms.

Inheritance: TGorillaMesh → TGorillaSphereTerrain

Platforms: All Gorilla platforms

Overview

TGorillaSphereTerrain creates planetary terrain by:

  1. Generating a UV-sphere with configurable resolution
  2. Sampling heightmap values at each vertex's UV coordinates
  3. Deforming vertices along their normals based on heightmap values

This is ideal for creating planets, moons, asteroids, and other spherical celestial bodies.

Constructor/Destructor

Create

constructor Create(AOwner: TComponent); override;

Creates a sphere terrain instance with default settings.

Destroy

destructor Destroy; override;

Frees resources.

AfterConstruction

procedure AfterConstruction; override;

Initializes default values:

Properties

All properties from TGorillaTerrain are available with these differences:

HeightScale

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:

ResolutionX / ResolutionY

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

Methods

Same methods as TGorillaTerrain:

Internally uses TGorillaTerrainHelper.BuildSphereTerrainFromHeightMap() instead of planar method.

Examples

Basic Planetary Terrain

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;

Procedural Planet

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;

Asteroid with Craters

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;

Multi-Layer Planet Surface

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;

Optimized High-Resolution Planet

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;

Heightmap Considerations

Equirectangular Projection

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:

UV Coordinate Mapping

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 Guidelines

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

Performance

Resolution Impact

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

Optimization Tips

  1. Use LOD for distant planets - Lower resolution when far from camera
  2. Enable static buffering - Default is True
  3. Apply decimation - Can reduce vertices by 50-70% with minimal visual impact
  4. Match heightmap resolution - Avoid upscaling
  5. Consider culling - Use frustum culling for multiple planets
  6. Texture optimization - Use compressed textures for heightmaps

Mobile Performance

For mobile devices:

Common Issues

Seam at Edges

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.

Polar Distortion

Vertices bunch up at poles (90°N and 90°S). This is normal for UV-spheres.

Solutions:

Heightmap Stretching

Heightmap pixels stretch more at poles than equator.

Solutions:

See Also

Gorilla.Terrain.Utils Unit Reference

Helper classes for terrain mesh generation.

Unit: Gorilla.Terrain.Utils

TGorillaTerrainHelper

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.

Methods

BuildTerrainFromHeightMap

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:

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;

BuildSphereTerrainFromHeightMap

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:

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;

Implementation Details

Heightmap Sampling

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;

Smoothing Algorithm

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.

Vertex Generation

Planar Terrain:

Spherical Terrain:

Triangle Winding

Both methods generate triangles with counter-clockwise winding:

v0---v1
|  \ |
|   \|
v2---v3

Triangle 1: v0, v2, v1
Triangle 2: v1, v2, v3

Advanced Usage

Custom Terrain Generation

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;

Multi-Layer Terrain

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;

Performance Considerations

Memory Usage

The helper methods allocate vertex and index buffers based on resolution:

Planar Terrain:

Spherical Terrain:

Optimization Tips

  1. Match heightmap to resolution - Avoid upscaling/downscaling
  2. Use smoothing judiciously - Each iteration adds processing time
  3. Disable TwoFace - Halves index count
  4. Static buffering - Upload to GPU, clear local data
  5. Decimation - Reduce vertices after generation

See Also

Gorilla.Material.Water Unit Reference

Overview

The 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.

Architecture

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)

Core Classes

TGorillaWaterMaterialSource

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+

Published Properties

Wave Animation
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.

Color Properties
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.

Foam Configuration
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).

Shore Foam Configuration
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.

Depth and Transparency
Property Type Range Description
DepthIntensity Single 0.001-10.0 Depth map influence on water transparency and blending.

Displacement Mapping
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).

Texture Maps
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).

Reflection Configuration
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.

Refraction Configuration
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.

Ripples System (v0.8.3.2265+)
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).

Debug and Advanced
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.

Public Methods

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:


procedure StoreToDefinition(const ADef: TCustomDef); override;

Stores material configuration to definition file.

Parameters:


Ripple Management Methods

procedure 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:

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:

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:

Example:

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:

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();

TGorillaWaterMaterial

Internal material class that performs shader compilation and rendering. Not directly instantiated by user code.

Inheritance: TGorillaDefaultMaterial → TGorillaWaterMaterial

Public Properties

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).

Public Methods

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).


Data Structures

TWaterParams (Uniform Buffer - OpenGL ES 3.0+)

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.


Enumerations

TWaterOutputLayer

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

Constants

Texture Unit Assignments

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)

Ripple Limits

MAX_RIPPLES = 32;  // Maximum simultaneous ripples (platform-dependent)

Platform Notes:


Extension Identifier

GORILLA_WATER_EXTENSION_DEF = 'Water';  // Material extension name

Shader Implementation Details

GLSL Shader Structure

The water shader implements a multi-stage rendering pipeline:

  1. Vertex Shader:

  2. Fragment Shader:

Key GLSL Functions

// 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
);

Usage Examples

Basic Water Material

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;

Water with Reflection and Refraction

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;

Water with Foam and Shore Effects

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;

Interactive Ripples

// 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;

Displacement Mapping

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);

Debug Output Layers

// 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

Important Notes

  1. Render Pass Requirements: Water material REQUIRES both reflection and refraction passes. Water will appear black or incorrect without properly configured passes.

  2. Plane Exclusion: The water mesh MUST be excluded from reflection and refraction passes using IgnoreControl() to prevent self-rendering artifacts.

  3. Displacement Offset: When using displacement mapping, adjust reflection/refraction plane positions to compensate for vertex offset.

  4. Ripple Limits: Maximum 32 simultaneous ripples on most platforms. Older platforms may have lower limits or no ripple support.

  5. Uniform Buffers: On OpenGL ES 3.0+, water parameters use uniform buffer objects for efficiency.

  6. Texture Requirements: Minimum required textures are DUDV and Normal maps. Other textures (specular, foam, shore, displacement) are optional.

  7. Performance: Water rendering is shader-intensive. Use lower resolution render passes on mobile platforms.

  8. Platform Differences: Some features (uniform buffers, ripple count) vary by platform and OpenGL version.

See Also