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
TGorillaDefaultMaterialSourceand derived Gorilla3D materials. They do not work with FireMonkey's embedded materials likeTLightMaterialSourceorTColorMaterialSource.
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
- Shader Injection: Behaviours add custom shader code to materials during shader compilation
- Uniform Buffers: Each behaviour manages its own GPU uniform buffer (std140 layout)
- Per-Material State: Each material maintains separate uniform buffer instances
- 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:
- WindSource (TPosition3D): Wind origin point
- WindDir (TPosition3D): Wind direction vector
- WindColor (TAlphaColor): Optional wind coloring (set to transparent to disable)
- WindWidth (Single): Width of wind channel (stronger in middle, weaker outside)
- WindHeight (Single): Height of wind channel
- WindDistance (Single): Maximum wind distance from source
- WindPower (Single): Overall wind strength
- WindWaving (Single): Waving intensity influenced by channel dimensions
- WindSpeed (Single): Speed of waving animation
- WindDecay (Single): Distance/dimension influence on intensity
- ShowVisualizer (Boolean): Show debug arrow (requires Viewport property)
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:
- WobbleIntensity (Single): Strength of wobble effect
- WobbleSpeed (Single): Animation speed
- WobbleScale (Single): Noise scale/frequency
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:
- RimColor (TAlphaColor): Rim light color (default: Cornflower blue)
- RimIntensity (Single): Rim effect intensity (0-1)
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:
- CausticsIntensity (Single): Caustics brightness
- CausticsSpeed (Single): Animation speed
- CausticsScale (Single): Pattern scale/frequency
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:
- AdjustedColor (TAlphaColor): Base color adjustment (default: white = no change)
- Brightness (Single): Brightness adjustment
- Contrast (Single): Contrast multiplier (default: 1.0)
- Gamma (Single): Gamma correction (default: 1.0)
- Hue (Single): Hue shift (0-1, default: 0.5 = no shift)
- Saturation (Single): Saturation adjustment (default: 0.0 = no change)
- Luminosity (Single): Luminosity adjustment
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:
- Design-time parameter collection (
TDesignTimeUBO) - Automatic std140 uniform buffer generation
- No manual memory management required
- Property-based parameter configuration
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
- Add material behaviour component to form (e.g.,
TGorillaMaterialWindBehaviour) - Configure behaviour properties in Object Inspector
- Select material source component
- Expand
Behaviourscollection in Object Inspector - Add new behaviour item
- Set
Behaviourproperty 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:
- vec4: 16-byte alignment
- vec3: 16-byte alignment (padded to vec4)
- float: 4-byte alignment
- Structs: Align to largest member (usually 16 bytes)
- Arrays: Each element 16-byte aligned
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
-
Uniform Buffer Updates: Behaviours update GPU buffers every frame. Minimize parameter changes.
-
Shader Compilation: Adding/removing behaviours triggers shader recompilation. Attach behaviours once at initialization.
-
Multiple Behaviours: Each behaviour adds shader code. Too many behaviours increase shader complexity.
-
Shared Behaviours: One behaviour instance for multiple materials is more efficient than multiple instances.
-
Memory Layout: Incorrect std140 alignment causes GPU errors. Always pad structs properly.
Limitations
-
Gorilla Materials Only: Behaviours don't work with FireMonkey materials (
TLightMaterialSource,TColorMaterialSource, etc.) -
Shader Complexity: Too many behaviours may exceed shader complexity limits on older hardware
-
Platform Differences: Some GLSL features may behave differently across platforms (OpenGL vs OpenGL ES vs Metal)
-
Design-Time: Behaviour changes at design-time may not update immediately; recompile project
Best Practices
-
Share Behaviours: Create one behaviour instance per effect type, attach to multiple materials
-
Initialize Early: Attach behaviours during form creation, not runtime loops
-
Use Events: Handle
OnAttached/OnDetachedevents for cleanup -
Batch Updates: Use
Material.BeginChange()/EndChange()when modifying multiple properties -
Debug Visualization: Enable visualizers during development, disable for production
-
Test on Target: Verify behaviour effects on target platform before deployment
-
Monitor Shader Size: Check generated shader code size; excessive complexity impacts performance
-
Profile Performance: Measure GPU performance impact, especially with multiple behaviours
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;