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
TGorillaViewportinstance 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:
- Add a
TGorillaModelcomponent to your form - Set the
Sourceproperty to your model file path - 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
.fmxfile storing process, which is performed on making changes at design time.
Asset Packages
Link external ZIP archives for better development workflow:
- Add a
TGorillaAssetsManagercomponent - Create or link an asset package
- Set the model's
AssetsManagerandPackageNameproperties - Set the
Sourceproperty 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_DEFAULTis 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
- IDE Limit: 3GB maximum; large embedded models slow performance
- Recommendation: Use asset packages for development
- Binary Storage: Models are stored as compressed G3D format in
.fmxfiles
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
- G3D: Best for Gorilla3D, supports all features
- DAE: Excellent for animations, lights, cameras
- FBX: Good animation support but binary only
- glTF: Modern format, good web asset pipeline integration
- OBJ: Simple static models, widely supported
- STL: CAD/3D printing, no materials or animations
Best Practices
- Use asset packages during development for better IDE performance
- Cache animations with
VertexPositionflag for balanced performance/memory - Limit texture sizes for mobile platforms
- Use GPU instancing for rendering many identical objects
- Enable frustum culling for large scenes
- Prefer G3D format for final deployment
- Test on target platform before deploying
- Use LoadFromStream for loading from resources or compressed archives