Class TCastleTransform

Unit

Declaration

type TCastleTransform = class(TCastleComponent)

Description

Group and transform (move, rotate, scale) children objects.

Add and remove children using the Add, Remove and similar methods. A child can be any TCastleTransform instance, in particular it can be a TCastleScene instance (which allows to load and render any 3D or 2D model).

Control the transformation using these properties:

  1. Move using Translation.

  2. Rotate using Rotation. The rotation is performed around the Center point. The rotation may be alternatively controlled using the Direction and Up vectors.

  3. Change size using Scale. Scale is done around Center and with orientation given by ScaleOrientation.

This class is the base object that is managed by the TCastleViewport. You insert instances of this class into TCastleViewport.Items, which is actually an instance of TCastleTransform too.

This class implements also optional gravity and physics. See the Gravity property for a simple unrealistic gravity model. See the RigidBody for a proper rigid-bidy simulation, with correct gravity model and collisions with other rigid bodies.

Hierarchy

Overview

Fields

Public nested const DefaultMiddleHeight = 0.5;
Public nested const DefaultDirection: array [TOrientationType] of TVector3 = ( (Data: (0, 0, -1)), (Data: (0, 0, +1)), (Data: (0, -1, 0)), (Data: (1, 0, 0)) );
Public nested const DefaultUp: array [TOrientationType] of TVector3 = ( (Data: (0, 1, 0)), (Data: (0, 1, 0)), (Data: (0, 0, 1)), (Data: (0, 0, 1)) );
Public var DefaultOrientation: TOrientationType; static;

Methods

Protected procedure RegisterGLContextClose;
Protected procedure ChangeWorld(const Value: TCastleAbstractRootTransform); virtual;
Protected procedure Notification(AComponent: TComponent; Operation: TOperation); override;
Protected function HeightCollision(const APosition, GravityUp: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; out AboveHeight: Single; out AboveGround: PTriangle): boolean;
Protected function MoveCollision( const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;
Protected function MoveCollision( const OldPos, NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;
Protected function SegmentCollision(const Pos1, Pos2: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const ALineOfSight: boolean): boolean;
Protected function SphereCollision(const Pos: TVector3; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
Protected function SphereCollision2D(const Pos: TVector2; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const Details: TCollisionDetails = nil): boolean;
Protected function PointCollision2D(const Point: TVector2; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
Protected function BoxCollision(const Box: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
Protected function RayCollision(const RayOrigin, RayDirection: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision;
Protected function LocalHeightCollision(const APosition, GravityUp: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; out AboveHeight: Single; out AboveGround: PTriangle): boolean; virtual;
Protected function LocalMoveCollision( const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
Protected function LocalMoveCollision( const OldPos, NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
Protected function LocalSegmentCollision(const Pos1, Pos2: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const ALineOfSight: boolean): boolean; virtual;
Protected function LocalSphereCollision(const Pos: TVector3; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
Protected function LocalSphereCollision2D(const Pos: TVector2; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const Details: TCollisionDetails = nil): boolean; virtual;
Protected function LocalPointCollision2D(const Point: TVector2; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
Protected function LocalBoxCollision(const Box: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
Protected function LocalRayCollision(const RayOrigin, RayDirection: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision; virtual;
Protected procedure LocalRender(const Params: TRenderParams); virtual;
Protected procedure LocalRenderShadowVolume( ShadowVolumeRenderer: TBaseShadowVolumeRenderer; const ParentTransformIsIdentity: boolean; const ParentTransform: TMatrix4); virtual;
Protected function Translation2D: TVector2; deprecated 'use TranslationXY';
Protected procedure TransformMatricesMult(var M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';
Protected procedure TransformMatrices(out M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';
Protected function AverageScale: Single;
Protected function AverageScale2D: Single;
Protected procedure Fall(const FallHeight: Single); virtual;
Protected procedure ChangedTransform; virtual;
Public constructor Create(AOwner: TComponent); override;
Public destructor Destroy; override;
Public procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
Public function PropertySections(const PropertyName: String): TPropertySections; override;
Public function GetEnumerator: TEnumerator;
Public function GetExists: boolean; virtual;
Public function GetCollides: boolean; virtual;
Public function GetPickable: boolean; virtual;
Public function GetVisible: boolean; virtual;
Public procedure Disable;
Public procedure Enable;
Public procedure Add(const Item: TCastleTransform);
Public procedure Insert(const Index: Integer; const Item: TCastleTransform);
Public procedure Remove(const Item: TCastleTransform);
Public function Count: Integer;
Public procedure Clear;
Public procedure Exchange(const Index1, Index2: Integer);
Public procedure SortBackToFront(const BlendingSort: TBlendingSort; const CameraPosition: TVector3);
Public procedure SortBackToFront2D;
Public function BoundingBox: TBox3D;
Public function LocalBoundingBox: TBox3D; virtual;
Public function WorldBoundingBox: TBox3D;
Public procedure Render(const Params: TRenderParams); virtual; overload;
Public procedure Render(const Frustum: TFrustum; const Params: TRenderParams); overload; deprecated 'use Render method without an explicit Frustum parameter, it is in Params.Frustum now';
Public procedure RenderShadowVolume( ShadowVolumeRenderer: TBaseShadowVolumeRenderer; const ParentTransformIsIdentity: boolean; const ParentTransform: TMatrix4);
Public procedure PrepareResources(const Options: TPrepareResourcesOptions; const ProgressStep: boolean; const Params: TPrepareParams); virtual;
Public function PrepareResourcesSteps: Cardinal; virtual;
Public function Press(const Event: TInputPressRelease): boolean; virtual;
Public function Release(const Event: TInputPressRelease): boolean; virtual;
Public function PointingDevicePress(const Pick: TRayCollisionNode; const Distance: Single): Boolean; virtual;
Public function PointingDeviceRelease(const Pick: TRayCollisionNode; const Distance: Single; const CancelAction: Boolean): Boolean; virtual;
Public function PointingDeviceMove(const Pick: TRayCollisionNode; const Distance: Single): Boolean; virtual;
Public procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); virtual;
Public procedure VisibleChangeHere(const Changes: TVisibleChanges);
Public procedure GLContextClose; virtual;
Public function Middle: TVector3; virtual;
Public function Sphere(out Radius: Single): boolean; virtual;
Public function Height(const MyPosition: TVector3; out AboveHeight: Single): boolean; overload;
Public function Height(const MyPosition: TVector3; out AboveHeight: Single; out AboveGround: PTriangle): boolean; overload;
Public function LineOfSight(const Pos1, Pos2: TVector3): boolean;
Public function MoveAllowed(const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const BecauseOfGravity: boolean): boolean; overload;
Public function MoveAllowed(const OldPos, NewPos: TVector3; const BecauseOfGravity: boolean): boolean; overload;
Public function Ray(const RayOrigin, RayDirection: TVector3): TRayCollision;
Public function RayCast(const RayOrigin, RayDirection: TVector3): TCastleTransform;
Public function RayCast(const RayOrigin, RayDirection: TVector3; out Distance: Single): TCastleTransform;
Public function OutsideToLocal(const Pos: TVector3): TVector3;
Public function LocalToOutside(const Pos: TVector3): TVector3;
Public function WorldToLocal(const Pos: TVector3): TVector3;
Public function LocalToWorld(const Pos: TVector3): TVector3;
Public function WorldToLocalDirection(const Dir: TVector3): TVector3;
Public function LocalToWorldDirection(const Dir: TVector3): TVector3;
Public function LocalToWorldDistance(const Distance: Single): Single;
Public function WorldToLocalDistance(const Distance: Single): Single;
Public function PreferredHeight: Single; virtual;
Public function Transform: TMatrix4;
Public function InverseTransform: TMatrix4;
Public function HasWorldTransform: boolean;
Public function WorldTransform: TMatrix4;
Public function WorldInverseTransform: TMatrix4;
Public procedure Translate(const TranslationChange: TVector3);
Public function Move(const TranslationChange: TVector3; const BecauseOfGravity: boolean; const EnableWallSliding: boolean = true): boolean;
Public function GetTranslation: TVector3; deprecated 'use Translation';
Public procedure Identity;
Public procedure GetView(out APos, ADir, AUp: TVector3);
Public procedure SetView(const APos, ADir, AUp: TVector3; const AdjustUp: boolean = true); overload;
Public procedure SetView(const ADir, AUp: TVector3; const AdjustUp: boolean = true); overload;
Public procedure UpPrefer(const AUp: TVector3);
Public procedure AddBehavior(const Behavior: TCastleBehavior);
Public procedure RemoveBehavior(const Behavior: TCastleBehavior);
Public function FindBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
Public function FindRequiredBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
Public function BehaviorsCount: Integer;
Public function BehaviorsEnumerate: TCastleBehaviorEnumerator;

Properties

Public property Items[I: Integer]: TCastleTransform read GetItem write SetItem;
Public property UniqueParent: TCastleTransform read FParent;
Public property CastShadowVolumes: boolean read FCastShadowVolumes write FCastShadowVolumes default true;
Public property ListenPressRelease: Boolean read FListenPressRelease write SetListenPressRelease default false;
Public property World: TCastleAbstractRootTransform read FWorld;
Public property Cursor: TMouseCursor read FCursor write SetCursor default mcDefault;
Public property CollidesWithMoving: boolean read FCollidesWithMoving write FCollidesWithMoving default false;
Public property InternalExcludeFromParentBoundingVolume: boolean read FInternalExcludeFromParentBoundingVolume write FInternalExcludeFromParentBoundingVolume;
Public property Gravity: boolean read FGravity write FGravity default false;
Public property FallSpeed: Single read FFallSpeed write FFallSpeed default 0;
Public property GrowSpeed: Single read FGrowSpeed write FGrowSpeed default 0;
Public property MiddleHeight: Single read FMiddleHeight write FMiddleHeight default DefaultMiddleHeight;
Public property Translation: TVector3 read FTranslation write SetTranslation;
Public property TranslationXY: TVector2 read GetTranslationXY write SetTranslationXY;
Public property Center: TVector3 read FCenter write SetCenter;
Public property Rotation: TVector4 read FRotation write SetRotation;
Public property Scale: TVector3 read FScale write SetScale;
Public property ScaleOrientation: TVector4 read FScaleOrientation write SetScaleOrientation;
Public property RigidBody: TRigidBody read FRigidBody write SetRigidBody;
Public property Position: TVector3 read FTranslation write SetTranslation; deprecated 'use Translation';
Public property Direction: TVector3 read GetDirection write SetDirection;
Public property Up: TVector3 read GetUp write SetUp;
Public property Orientation: TOrientationType read FOrientation write FOrientation;
Public property List: TCastleTransformList read FList;
Public property Behaviors [const Index: Integer]: TCastleBehavior read GetBehaviors;
Published property Exists: boolean read FExists write FExists default true;
Published property Collides: boolean read FCollides write FCollides default true;
Published property Pickable: boolean read FPickable write FPickable default true;
Published property Visible: boolean read FVisible write FVisible default true;
Published property ExcludeFromGlobalLights: boolean read FExcludeFromGlobalLights write FExcludeFromGlobalLights default false;
Published property ExcludeFromStatistics: boolean read FExcludeFromStatistics write FExcludeFromStatistics default false;
Published property CollisionSphereRadius: Single read FCollisionSphereRadius write FCollisionSphereRadius;
Published property CenterPersistent: TCastleVector3Persistent read FCenterPersistent ;
Published property RotationPersistent: TCastleVector4Persistent read FRotationPersistent ;
Published property ScalePersistent: TCastleVector3Persistent read FScalePersistent ;
Published property ScaleOrientationPersistent: TCastleVector4Persistent read FScaleOrientationPersistent ;
Published property TranslationPersistent: TCastleVector3Persistent read FTranslationPersistent ;

Description

Fields

Public nested const DefaultMiddleHeight = 0.5;
 
Public nested const DefaultDirection: array [TOrientationType] of TVector3 = ( (Data: (0, 0, -1)), (Data: (0, 0, +1)), (Data: (0, -1, 0)), (Data: (1, 0, 0)) );
 
Public nested const DefaultUp: array [TOrientationType] of TVector3 = ( (Data: (0, 1, 0)), (Data: (0, 1, 0)), (Data: (0, 0, 1)), (Data: (0, 0, 1)) );
 
Public var DefaultOrientation: TOrientationType; static;

Default value of TCastleTransform.Orientation for new instances. By default otUpYDirectionZ, matching glTF orientation (as exported from Blender and other software).

Methods

Protected procedure RegisterGLContextClose;

Call this when doing anything that allocates GL resources. This will make sure GLContextClose will get called.

Protected procedure ChangeWorld(const Value: TCastleAbstractRootTransform); virtual;

Called when the current World that contains this object changes. In the usual case, World corresponds to a TCastleViewport.Items instance, and when this method is called it means that object is added/removed from a viewport.

You can ignore this when called with Value equal to current World.

Note that each TCastleTransform instance can only be part of one world (TCastleAbstractRootTransform) at a time. Although we may be present many times within the same world. Always remove the TCastleTransform from previous world before adding it to a new one.

Protected procedure Notification(AComponent: TComponent; Operation: TOperation); override;
 
Protected function HeightCollision(const APosition, GravityUp: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; out AboveHeight: Single; out AboveGround: PTriangle): boolean;

Height of a point above the 3D model. This checks ray collision, from APosition along the negated GravityUp vector. Measures distance to the nearest scene item (called "ground" here).

Parameters
AboveHeight
Height above the ground. One height unit equals one GravityUp vector. Always use normalized GravityUp vector if you expect to receive here a normal distance.

AboveHeight is always set to MaxSingle when returned result is False (this guarantee simplifies some code).

AboveGround
Pointer to PTriangle representing the ground. Must be Nil if returned result is False. May be Nil even if we returned True (not all 3D objects may be able to generate PTriangle information about collision).

This may be useful for example to make a footsteps sound dependent on texture of the ground. Or to decrease player life points for walking on hot lava. See "The Castle" game for examples.

Returns

If the 3D scene is hit. False means that APosition floats above an empty space. That is, if you turn gravity on, it will fall down forever, as far as this 3D scene is concerned.

Protected function MoveCollision( const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;

Can other 3D object (maybe a player) move without colliding with this object.

If IsRadius, then you should prefer to perform exact collision with sphere of given radius (must be > 0). At the very least, this checks that the line segment between OldPos and NewPos doesn't collide, and that sphere with given Radius centered around NewPos doesn't collide.

If not IsRadius, or if checking for collisions with sphere is not possible for some reasons, then you can check for collisions with boxes. OldBox should usually be ignored (it can be useful when collision-checking has to be approximate in some corner cases, see TCreature.MoveCollision). NewBox plays the same role as "sphere centered around NewPos" in paragraph above.

Overloaded version with separate ProposedNewPos and NewPos parameters allows you to accept the move, but for NewPos (that should be some slightly modified version of ProposedNewPos). This allows to implement wall-sliding: when camera tries to walk into the wall, we will change movement to move alongside the wall (instead of just completely blocking the move). When this version returns False, it's undefined what is the NewPos.

Protected function MoveCollision( const OldPos, NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;
 
Protected function SegmentCollision(const Pos1, Pos2: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const ALineOfSight: boolean): boolean;

Check collision with a line segment, that is: a line between 2 points in 3D.

Protected function SphereCollision(const Pos: TVector3; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;

Check collision with a 3D sphere.

This works precisely when transformation hierarchy has uniform scaling, i.e. scale is the same in all X, Y, Z axes. In case of non-uniform scaling, this is an approximation.

Protected function SphereCollision2D(const Pos: TVector2; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const Details: TCollisionDetails = nil): boolean;

Check collision with a sphere in 2D (a circle, extruded to infinity along the Z axis).

Note that PointCollision2D and SphereCollision2D do not work reliably on objects that have 3D rotations. See PointCollision2D for details.

This works precisely when transformation hierarchy has uniform scaling, i.e. scale is the same in all X, Y, Z axes. In case of non-uniform scaling, this is an approximation.

Parameters
Details
If non-nil, these are automatically filled with the details about the collision. If the result is False, the Details contents are untouched. If the result is True, the Details contents are set to describe the 3D objects hierarchy that caused this collision.
Protected function PointCollision2D(const Point: TVector2; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;

Check collision with a point in 2D (which is an infinite line along the Z axis in 3D).

Note that PointCollision2D and SphereCollision2D do not work reliably on objects that have 3D rotations, that is: rotations that change the direction of Z axis! This applies to all ways of rotating – using the TCastleTransform or using the X3D node TTransformNode (within a TCastleSce).

  1. The reason: we transform the point (or sphere center) to the local coordinates, and we should also transform the Z axis to the local coordinates, to be always correct. Right now, we don't do the latter.

  2. And we don't want to do it (at least not in all cases)! The simple 2D point collision check would then actually perform a 3D line collision check, thus PointCollision2D would lose all the speed benefits over LineCollision. PointCollision2D would become a simple shortcut to perform LineCollision with a line parallel to Z axis.

    And in case of 2D games, or mostly 2D games, this speed loss would not be justified. Often you know that your objects have no 3D rotations, for example if your animations are done in Spine.

  3. In the future, we may overcome this limitation. To do this, we will detect whether the transformation is "only 2D" (actually this part is easy, you can detect it by looking at the matrix even, so check whether appropriate numbers are zero). And then PointCollision2D will change to LineCollision, and SphereCollision2D will change to something like ExtrudedCircleCollision, only when necessary.

Protected function BoxCollision(const Box: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;

Check collision with axis-aligned box in 3D.

Protected function RayCollision(const RayOrigin, RayDirection: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision;

Check collision with a ray, building a TRayCollision result. Returns a collision as TRayCollision instance, or Nil if no collision. Caller is responsible for freeing the returned TRayCollision instance.

Contrary to other collision routines, this should ignore the Collides property. The Collides property specifies whether item collides with camera. And this method is used for picking (pointing) 3D stuff — everything visible can be picked, collidable or not. Instead, this looks at Pickable property (actually, at GetPickable method result).

This always returns the first collision with the world, that is the one with smallest TRayCollision.Distance. For example, when implemented in TCastleTransform, this checks collisions for all list items, and chooses the closest one.

Protected function LocalHeightCollision(const APosition, GravityUp: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; out AboveHeight: Single; out AboveGround: PTriangle): boolean; virtual;
 
Protected function LocalMoveCollision( const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
 
Protected function LocalMoveCollision( const OldPos, NewPos: TVector3; const IsRadius: boolean; const Radius: Single; const OldBox, NewBox: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
 
Protected function LocalSegmentCollision(const Pos1, Pos2: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const ALineOfSight: boolean): boolean; virtual;
 
Protected function LocalSphereCollision(const Pos: TVector3; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
 
Protected function LocalSphereCollision2D(const Pos: TVector2; const Radius: Single; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc; const Details: TCollisionDetails = nil): boolean; virtual;
 
Protected function LocalPointCollision2D(const Point: TVector2; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
 
Protected function LocalBoxCollision(const Box: TBox3D; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
 
Protected function LocalRayCollision(const RayOrigin, RayDirection: TVector3; const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision; virtual;
 
Protected procedure LocalRender(const Params: TRenderParams); virtual;

Render with given Params (includes a full transformation of this scene).

This is mostly an internal method. You should not need to override it during normal engine usage. Instead, you should render everything using TCastleScene, which allows to load or build (by code) nodes to display meshes, light and everything else. But overriding this may be useful for special customized rendering.

Protected procedure LocalRenderShadowVolume( ShadowVolumeRenderer: TBaseShadowVolumeRenderer; const ParentTransformIsIdentity: boolean; const ParentTransform: TMatrix4); virtual;

Render shadow volumes (with a full transformation of this scene).

This is mostly an internal method. You should not need to override it during normal engine usage. If you render everything using TCastleScene, then rendering shadow volumes is also automatically handled by TCastleScene.

Protected function Translation2D: TVector2; deprecated 'use TranslationXY';

Warning: this symbol is deprecated: use TranslationXY

Get translation in 2D (uses Translation, ignores Z coord).

Protected procedure TransformMatricesMult(var M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';

Warning: this symbol is deprecated: do not use this directly, instead use Transform and InverseTransform methods

Transformation matrices, like Transform and InverseTransform.

Protected procedure TransformMatrices(out M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';

Warning: this symbol is deprecated: do not use this directly, instead use Transform and InverseTransform methods

 
Protected function AverageScale: Single;

Average value of 3D scale in Scale. It is not calculated as a simple average, it's a little smarter to prevent from weird results sometimes, see Approximate3DScale.

Protected function AverageScale2D: Single;

Average value of 2D scale, from XY components of Scale. It is not calculated as a simple average, it's a little smarter to prevent from weird results sometimes, see Approximate2DScale.

Protected procedure Fall(const FallHeight: Single); virtual;

Called when fall ended. You can use FallHeight to decrease creature life or such.

Protected procedure ChangedTransform; virtual;

Override this to be notified about every transformation change. By default, this calls VisibleChangeHere, which causes the window to redraw.

Public constructor Create(AOwner: TComponent); override;
 
Public destructor Destroy; override;
 
Public procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
 
Public function PropertySections(const PropertyName: String): TPropertySections; override;
 
Public function GetEnumerator: TEnumerator;
 
Public function GetExists: boolean; virtual;

Does item really exist, see Exists and Enable, Disable. It TCastleTransform class, returns True if Exists and not disabled. May be modified in subclasses, to return something more complicated.

Public function GetCollides: boolean; virtual;

Does item really collide, see Collides. It TCastleTransform class, returns Collides and GetExists. May be modified in subclasses, to return something more complicated.

Public function GetPickable: boolean; virtual;

Is item really pickable, see Pickable. It TCastleTransform class, returns Pickable and GetExists. May be modified in subclasses, to return something more complicated.

Public function GetVisible: boolean; virtual;

Is item really visible, see Visible. It v class, returns Visible and GetExists. May be modified in subclasses, to return something more complicated.

Public procedure Disable;

Items that are at least once disabled are treated like not existing. Every Disable call should always be paired with Enable call (usually using try ... finally .... end block). Internally, we keep a counter of how many times the object is disabled, and if this counter is <> 0 then GetExists returns False. Using this is useful for taming collisions, especially to avoid self-collisions (when a creature moves, it checks for collision with other creatures, but it doesn't want to check for collisions with it's own bounding volume).

Public procedure Enable;
 
Public procedure Add(const Item: TCastleTransform);

Operate on 3D objects contained in the list. You can also operate directly on List instance.

Note that adding and removing from this hierarchy is guaranteed to be fast, so you can do it even in the middle of the game. In particular calling Remove doesn't free rendering reasources of the removed scene, so removing scene only to add it later to another TCastleViewport.Items is blazingly fast.

Public procedure Insert(const Index: Integer; const Item: TCastleTransform);
 
Public procedure Remove(const Item: TCastleTransform);
 
Public function Count: Integer;
 
Public procedure Clear;
 
Public procedure Exchange(const Index1, Index2: Integer);
 
Public procedure SortBackToFront(const BlendingSort: TBlendingSort; const CameraPosition: TVector3);

Sort objects back-to-front right now following one of the blending sorting algorithms. Only the immediate list items are reordered, looking at their bounding boxes (the sorting is not recursive).

Calling this method makes sense if you use blending and multiple partially-transparent objects may be visible at the same place on the screen. Sorting avoids artifacts when rendering.

  • In general, you should call this method whenever the correct back-to-front order of objects (with respect to the current camera) changes.

  • In 3D, it may make sense to call this method even every frame (like in every TCastleWindowBase.OnUpdate). Call it if you move or otherwise change the objects (changing their bounding boxes), or if the CameraPosition may change (note that CameraPosition is only relevant if BlendingSort = bs3D).

  • In 2D, it is a bit simpler. You typically need to call this only when some objects' Z value changed (making this object move behind / in front of some other object), or when new object is added. You don't need to call this method when camera changes or when object's XY position changes, as they don't affect the order.

Note that this doesn't take care of sorting the shapes within the scenes. For this, you should set Scene.RenderOptions.BlendingSort to a value like bs3D, to keep it sorted. It is the default now, so you typically don't need to worry about it.

See the TBlendingSort documentation for the exact specification of sorting algorithms. Using BlendingSort = bsNone does nothing.

See also
SortBackToFront2D
Sort objects back-to-front right now following the 2D blending sorting algorithm.
Public procedure SortBackToFront2D;

Sort objects back-to-front right now following the 2D blending sorting algorithm. See SortBackToFront for documentation, this method is only a shortcut for SortBackToFront(bs2D, TVector3.Zero).

See also
SortBackToFront
Sort objects back-to-front right now following one of the blending sorting algorithms.
Public function BoundingBox: TBox3D;

Bounding box of this object, in the coordinate system of the parent transformation. This method takes into account current transformation (like Translation, Rotation) but not parent TCastleTransform transformations. Use WorldBoundingBox instead to know bounding box that accounts for all TCastleTransform transformations. Use LocalBoundingBox instead to know bounding box that does not account for any parent or this TCastleTransform transformations.

Takes into account both collidable and visible objects. For example, invisible walls (not visible) and fake walls (not collidable) should all be accounted here.

It's a bounding volume, it should be as large as necessary to include the object inside. At the same time, it should be as "tight" as it can, to make various optimizations work best.

See also
WorldBoundingBox
Bounding box of this object, taking into account all transformations of this and parents.
LocalBoundingBox
Bounding box of this object, ignoring the transformations of this scene and parents.
Public function LocalBoundingBox: TBox3D; virtual;

Bounding box of this object, ignoring the transformations of this scene and parents.

See also
BoundingBox
Bounding box of this object, in the coordinate system of the parent transformation.
WorldBoundingBox
Bounding box of this object, taking into account all transformations of this and parents.
Public function WorldBoundingBox: TBox3D;

Bounding box of this object, taking into account all transformations of this and parents.

See also
BoundingBox
Bounding box of this object, in the coordinate system of the parent transformation.
LocalBoundingBox
Bounding box of this object, ignoring the transformations of this scene and parents.
Public procedure Render(const Params: TRenderParams); virtual; overload;

Render given object. Should check and immediately exit when GetVisible is False.

The rendering transformation, frustum, and filtering is specified inside TRenderParams class. This method should only update TRenderParams.Statistics.

Public procedure Render(const Frustum: TFrustum; const Params: TRenderParams); overload; deprecated 'use Render method without an explicit Frustum parameter, it is in Params.Frustum now';

Warning: this symbol is deprecated: use Render method without an explicit Frustum parameter, it is in Params.Frustum now

 
Public procedure RenderShadowVolume( ShadowVolumeRenderer: TBaseShadowVolumeRenderer; const ParentTransformIsIdentity: boolean; const ParentTransform: TMatrix4);

Render shadow quads for all the things rendered by Render. This is done only if Exists and CastShadowVolumes.

It does shadow volumes culling inside (so ShadowVolumeRenderer should have FrustumCullingInit already initialized).

ParentTransform and ParentTransformIsIdentity describe the transformation of this object in the world. TCastleTransform objects may be organized in a hierarchy when parent transforms it's children. When ParentTransformIsIdentity, ParentTransform must be TMatrix4.Identity (it's not guaranteed that when ParentTransformIsIdentity = True, Transform value will be ignored !).

Public procedure PrepareResources(const Options: TPrepareResourcesOptions; const ProgressStep: boolean; const Params: TPrepareParams); virtual;

Prepare resources, making various methods (like rendering and such) to execute fast.

It is usually simpler to call TCastleViewport.PrepareResources then this method. Calling Viewport.PrepareResources(MyScene) will automatically call MyScene.PrepareResources(...) underneath, with proper parameters.

It is best to call this when the rendering context is initailized, e.g. at Application.OnInitialize or later. Calling this method before the rendering context is initialized (e.g. from initializaton section of some unit) will have to skip some preparations, thus reducing the effectiveness of this method.

This makes sure that appropriate methods execute as fast as possible. It's never required to call this method — everything will be prepared "as needed" anyway. But if you allow everything to be prepared "as needed", then e.g. the first Render call may take a long time because it may have to prepare resources that will be reused in next Render calls. This may make your program seem slow at the beginning (when rendering resources are being prepared, so at the first frame, or a couple of first animation frames). To avoid this, call this method, showing the user something like "now we're preparing the resources — please wait".

Parameters
Options
What features should be prepared to execute fast. See TPrepareResourcesOption.
ProgressStep
Says that we should call Progress.Step. It will be called PrepareResourcesSteps times. Useful to show progress bar to the user during long preparation.
Params
Rendering parameters to prepare for. It is used only if Options contains prRenderSelf or prRenderClones.
Public function PrepareResourcesSteps: Cardinal; virtual;

How many times PrepareResources will call Progress.Step. Useful only if you want to pass ProgressStep = True to PrepareResources. In the base class TCastleTransform this just returns 0.

Public function Press(const Event: TInputPressRelease): boolean; virtual;

Press and release events of key and mouse, passed only to instances that set ListenPressRelease. Return True if you handled the event, and it should not be passed to other objects. See also TCastleUserInterface analogous events.

Public function Release(const Event: TInputPressRelease): boolean; virtual;
 
Public function PointingDevicePress(const Pick: TRayCollisionNode; const Distance: Single): Boolean; virtual;

Pointing device (mouse or touch) events, you can override these to handle pointing device events. These methods are automatically called by the TCastleViewport. They are exposed here only to allow overriding them. Return True if you handled the event.

  • PointingDevicePress signals that the picking button (usually, left mouse button) was pressed.

    Note that the exact key or mouse responsible for this is configurable in our engine by Input_Interact. By default it's the left mouse button, as is usual for VRML/X3D browsers. But it can be configured to be other mouse button or a key, for example most 3D games use "e" key to interact.

  • PointingDeviceRelease signals that the picking button is released.

    An extra parameter CancelAction indicates whether this pointing device "press and release" sequence may be considered a "click". When CancelAction = True, then you should not make a "click" event (e.g. TouchSensor should not send touchTime event etc.).

  • PointingDeviceMove signals that pointer moves over this object.

They receive Pick information (TRayCollisionNode) about what exactly is hit by the 3D ray corresponding to the current pointing device position. It contains the detailed information about the point, triangle and ray (all in local coordinate system of this TCastleTransform) that are indicated by the pointing device. TRayCollisionNode.Triangle is Nil when it was not possible to determine, and TRayCollisionNode.Point is undefined in this case.

They also receive Distance to the collision point, in world coordinates. See TRayCollision.Distance. The Distance may be MaxSingle when it was not possible to determine.

There is a concept of a TCastleTransform that is currently "capturing" the pointing device events. Once TCastleTransform handles TCastleTransform.PointingDevicePress (returns True for it), it captures the following PointingDeviceMove and PointingDeviceRelease events, regardless if ray still hits this TCastleTransform instance. The "capturing" instance of TCastleTransform is informed first about pointing device move/release.

After the "capturing" instance, every pointing device event (press, release or move) is send to the leaf in TCastleTransform hierarchy (usually a TCastleScene) that is under the mouse/touch position. If the event is not handled, it is passed to other objects under the mouse/touch position.

The PointingDeviceMove event is also always passed to TCastleRootTransform.MainScene at the end (if it wasn't already the "capturing" transform, or under the mouse/touch position). This way TCastleRootTransform.MainScene is always informed about pointing device movement.

These methods are called only if the object GetExists. There's no need to check this condition inside the method implementation.

Public function PointingDeviceRelease(const Pick: TRayCollisionNode; const Distance: Single; const CancelAction: Boolean): Boolean; virtual;
 
Public function PointingDeviceMove(const Pick: TRayCollisionNode; const Distance: Single): Boolean; virtual;
 
Public procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); virtual;

Continuously occuring event, for various tasks.

Parameters
RemoveMe
Set this to rtRemove or rtRemoveAndFree to remove this item from parent after this call finished. rtRemoveAndFree additionally will free this item. Initially it's rtNone when this method is called.
Public procedure VisibleChangeHere(const Changes: TVisibleChanges);

Something visible changed inside this object. This is usually called by implementation of this object, to notify others that it changed.

Changes is a set describing what changes occurred. See TVisibleChange docs for more information. It must specify all things that possibly changed.

Changes can be [], meaning "something tells us to redraw, but no visible change happened yet, maybe something will happen during a redraw" (this is used when e.g. possibly LOD level changed). We still increase TCastleAbstractRootTransform.InternalVisibleStateId even when Changes=[].

The information about visibility changed is passed to TCastleAbstractRootTransform in World. It increases TCastleAbstractRootTransform.InternalVisibleStateId, TCastleAbstractRootTransform.InternalVisibleGeometryStateId, TCastleAbstractRootTransform.InternalVisibleNonGeometryStateId. If you want to react to visibility changes, you should not override this method, instead watch above "state id" variables and react when they change.

Public procedure GLContextClose; virtual;

Called when rendering context is destroyed. This will be also automatically called from destructor. Object should clear here any resources that are connected to the rendering context.

Public function Middle: TVector3; virtual;

Middle point, usually "eye point", of the 3D model. This is used for sphere center (if CollisionSphereRadius is non-zero or Sphere returns True) and is the central point from which collisions of this object are checked (Move, MoveAllowed, Height, LineOfSight). It's useful for dynamic objects like player and moving creatures, which rely on MoveAllowed and gravity.

In short, it's usually most comfortable to think about this as a position of the eye, or the middle of the creature's head.

In an ideal situation, it should not be based on anything dynamic. For example, when this is based on the current bounding box of the animation, there is a risk that a large and sudden change in animation box could make the Middle point to jump to the other side of the wall (breaking collisions, as it changes Middle without a chance to check for collisions by MoveAllowed). Ideally, it should remain constant even when the shape of the object changes, and be possible to change only when MoveAllowed is checked (so only when TCastleTransform.Translation can change).

In this class this returns something sensible above the bottom of the box. See TCastleTransform.MiddleHeight.

This is expressed in the parent coordinate system (so it is close to the Translation value, but moved up, following GravityUp). It ignores parent transformations (using Transform.UniqueParent.LocalToWorld(Transform.Middle) to convert this to world coordinates.

Public function Sphere(out Radius: Single): boolean; virtual;

Can the approximate sphere (around Middle point) be used for some collision-detection tasks. If True then Radius (and Middle point) determine the approximate sphere surrounding the 3D object (it does not have to be a perfect bounding sphere around the object), and it may be used for some collisions instead of BoundingBox. See CollidesWithMoving and MoveAllowed for when it may happen.

Must return False when not GetExists (because we can't express "empty sphere" by Sphere method for now, but BoundingBox can express TBox3D.Empty).

By default, in TCastleTransform class, this returns True if CollisionSphereRadius is non-zero.

The advantages of using a sphere, that does not have to be a perfect bounding sphere (it may be smaller than necessary, and only account e.g. for upper body part of the creature), are:

  • It can have constant radius, even though the actual creature animates. This allows us to perfectly, reliably guarantee that sphere absolutely never collides with level and such.

    In case of a tight bounding volume (box or sphere) that animates, this guarantee is not really possible. Simply increasing time changes the animation to the next frame, which may be slightly larger in one dimension because e.g. creature moves a hand in this direction. This means that simply increasing time may change the non-collidable creature into a collidable one, if creature stands close to a wall/other creature and such. And we cannot simply stop/reverse an arbitrary animation at an arbitrary time (to avoid collision), this would look weird for some animations and would require some additional work at preparing animations and designing AI (as then "every action can be interrupted").

    Also using a bounding volume large enough to account for all possible positions is not doable, as it would be too large. Consider that for humanoid creatures, walking animation usually has tall and thin bounding box (creature stands) but dead/lying animation usually has flat and wide bounding box.

    So, only a bounding volume (like a sphere) that may be smaller than bounding volume can remain constant and easily guarantee the assertion "it never collides".

    This means that using such sphere results in simpler collision detection routines, as they may assume that collision doesn't occur. In contrast, detection routines looking at our (possibly animated) BoundingBox must take into account that collision may already be happening, and they must incorporate code to allow creatures/players to "get unstruck".

  • Using smaller sphere also allows to naturally ascend the stairs and upward slopes. Sphere can move forward slightly, and then creature may raise up, to reach it's preferred height. Then sphere can move further forward, and so on. This alllows to allow stair climbing for creatures without any extra effort in the code.

    The downside is that creature legs will temporarily "sink into the floor" when climbing up the stairs. But it's not noticeable if "growing up" mechanism works fast enough.

Sphere disadvantage:

  • Sphere is far from perfect as a bounding volume — it's too small, sometimes also too large, sometimes both at the same time...

    Since the Sphere radius remains always the same, it must be good for many creature animation frames. In cases where the sphere isn't suitable, and you don't need advantages above — you can make Sphere return False. E.g. a dead creature may be stuck in a wall, and it doesn't have to climb stairs. So you don't really need sphere advantages listed above, and Sphere may return False when creature is in dying state.

    But still it may be a problem sometimes, if some creature states have entirely different animations and bounding boxes. Then you will be forced to choose one universal Radius for all creature states. And you need constant radius to keep the advantage above of "guarantee".

    1. Obviously you can't set radius too small, because if it's much smaller than actual creature's geometry then the creature will noticeably collide with level geometry and other creatures.

    2. On the other hand, you can't set radius too large (or move sphere center, Middle, much lower). This would block stair climbing.

Public function Height(const MyPosition: TVector3; out AboveHeight: Single): boolean; overload;

Get height of my point above the rest of the world.

The given MyPosition, and returned AboveHeight, are in the parent coordinate system of this TCastleTransform. So for example query like this works naturally: MyTransform.Height(MyTransform.Translation, ...).

This ignores the geometry of this 3D object (to not accidentally collide with your own geometry), and checks collisions with the rest of the world.

Public function Height(const MyPosition: TVector3; out AboveHeight: Single; out AboveGround: PTriangle): boolean; overload;
 
Public function LineOfSight(const Pos1, Pos2: TVector3): boolean;

Whether there is line of sight (the line segment does not collide with anything opaque) between these 2 points.

The given Pos1, Pos2 are in the parent coordinate system of this TCastleTransform. So for example query like this works naturally: MyTransform.LineOfSight(MyTransform.Translation, MyTransform.Translation + MyTransform.Direction * 10).

This ignores the geometry of this 3D object (to not accidentally collide with your own geometry), and checks collisions with the rest of the world.

Public function MoveAllowed(const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3; const BecauseOfGravity: boolean): boolean; overload;

Is the move from OldPos to ProposedNewPos possible for this object. Returns true and sets NewPos if some move is allowed.

The NewPos may be different than ProposedNewPos, which allows to perform wall-sliding. Wall sliding will only work if collision sphere is defined, which should be configured by setting CollisionSphereRadius to something non-zero. Otherwise, the move uses only box collisions, and wall sliding doesn't happen.

When checking collisions, it avoids colliding with itself, so it only checks collisions with the rest of the world (things outside of this TCastleTransform).

The given OldPos, ProposedNewPos, NewPos are in the parent coordinate system of this TCastleTransform. Intuitively, you are asking "Can I change Translation from OldPos to NewPos". So this method is consistent with Move, Translate.

Public function MoveAllowed(const OldPos, NewPos: TVector3; const BecauseOfGravity: boolean): boolean; overload;

Is the move from OldPos to NewPos possible for this object.

This overloaded version of MoveAllowed doesn't do wall-sliding (use the version with ProposedNewPos for wall-sliding).

If this object allows to use sphere for collisions (see CollisionSphereRadius and Sphere) then sphere will be used. Otherwise, it will collide as a bounding box.

When checking collisions, it avoids colliding with itself, so it only checks collisions with the rest of the world (things outside of this TCastleTransform).

The given OldPos, NewPos are in the parent coordinate system of this TCastleTransform. Intuitively, you are asking "Can I change Translation from OldPos to NewPos". So this method is consistent with Move, Translate.

Public function Ray(const RayOrigin, RayDirection: TVector3): TRayCollision;

Cast a ray, see what is hit.

The given RayOrigin, RayDirection are in the parent coordinate system of this TCastleTransform. So for example query like this works naturally: MyTransform.Ray(MyTransform.Translation, MyTransform.Direction).

This ignores the geometry of this object (to not accidentally collide with your own geometry), and checks collisions with the rest of the world.

Public function RayCast(const RayOrigin, RayDirection: TVector3): TCastleTransform;

Cast a ray, see what is hit.

The given RayOrigin, RayDirection are in the parent coordinate system of this TCastleTransform. So for example query like this works naturally: MyTransform.RayCast(MyTransform.Translation, MyTransform.Direction). In case of the overloaded version with Distance parameter, the Distance is consistently in the same, parent coordinate system.

This ignores the geometry of this object (to not accidentally collide with your own geometry), and checks collisions with the rest of the world.

This returns the TCastleTransform that is hit (this is the "leaf" TCastleTransform in the TCastleTransform tree that is hit) and a distance from RayOrigin to the hit point. Returns Nil (Distance is undefined in this case) if nothing was hit. Use Ray for a more advanced version of this, with more complicated result.

Public function RayCast(const RayOrigin, RayDirection: TVector3; out Distance: Single): TCastleTransform;
 
Public function OutsideToLocal(const Pos: TVector3): TVector3;

Convert position between local and outside coordinate system. This is called OutsideToLocal, not WorldToLocal, because it only handles transformation defined in this item — it does not recursively apply all transform on the way to root.

Public function LocalToOutside(const Pos: TVector3): TVector3;
 
Public function WorldToLocal(const Pos: TVector3): TVector3;

Convert position between local and world coordinate system. This applies all the transformations on the way to root, so it looks at this object as well as all parents' transformations.

Public function LocalToWorld(const Pos: TVector3): TVector3;
 
Public function WorldToLocalDirection(const Dir: TVector3): TVector3;

Convert direction between local and world coordinate system. This applies all the transformations on the way to root, so it looks at this object as well as all parents' transformations.

Public function LocalToWorldDirection(const Dir: TVector3): TVector3;
 
Public function LocalToWorldDistance(const Distance: Single): Single;

Convert distance, like sphere radius, between local and world coordinate system. This applies all the scaling on the way to root, so it looks at this object as well as all parents' transformations.

Public function WorldToLocalDistance(const Distance: Single): Single;
 
Public function PreferredHeight: Single; virtual;

The preferred height of the object Middle above the ground, when the object is standing on the ground firmly. This is used by objects affected by gravity (like non-flying creatures and items) to know how far they should fall down or grow up.

The default implementation in this class looks at MiddleHeight property, see the algorithm described there. This may be dynamic (may change during creature lifetime, so you can make the creature duck or grow if you want).

Public function Transform: TMatrix4;

Transformation (from local to outside) as a matrix. This matrix represents a concise version of properties like Translation, Rotation, Scale. It does not take into account the transformation of parent TCastleTransform (for this, use WorldTransform).

Public function InverseTransform: TMatrix4;

Inverse transformation as a matrix, thus transforming from outside to local coordinate system. This is an inverse of Transform.

Public function HasWorldTransform: boolean;

All conditions are satisfied to have WorldTransform. When this returns True, you know that WorldTransform and WorldInverseTransform will not raise ETransformParentUndefined.

Public function WorldTransform: TMatrix4;

Transformation (from local to world) as a matrix. This accumulates the transformation of this instance (derived from properties like Translation, Rotation, Scale) with the transformation of parent TCastleTransform instances, all the way up to and including the root transformation (TCastleAbstractRootTransform). Thus, this is a transformation to the world known to the TCastleViewport instance.

Two conditions are necessary to make this available:

You can check HasWorldTransform before calling this method, to avoid catching an exception.

Note that the WorldTransform is not updated in Update, it is smartly updated on-demand. So you do not have to wait for Update or other method to be called before accessing the WorldTransform.

Exceptions raised
ENotAddedToWorld
When this instance is not yet part of World.
EMultipleReferencesInWorld
When this instance is added multiple times to World.
ETransformParentUndefined
When this instance was once added multiple times to World, or for some other reason cannot be calculated. This is an ancestor of ENotAddedToWorld and EMultipleReferencesInWorld too.
Public function WorldInverseTransform: TMatrix4;

Inverse transformation of WorldTransform, thus transforming from world to local coordinate system.

See WorldTransform for more details how this works.

Exceptions raised
ENotAddedToWorld
When this instance is not yet part of World.
EMultipleReferencesInWorld
When this instance is added multiple times to World.
EMultipleReferencesInWorld
When this instance was once added multiple times to World, or for some other reason cannot be calculated. This is an ancestor of ENotAddedToWorld and EMultipleReferencesInWorld too.
Public procedure Translate(const TranslationChange: TVector3);

Unconditionally move this object by a given vector.

To move and check collisions, use Move instead of this method.

The provided TranslationChange should be a direction in the parent coordinate system of this TCastleTransform. Using this routine is exactly equivalent to Translation := Translation + TranslationChange.

Public function Move(const TranslationChange: TVector3; const BecauseOfGravity: boolean; const EnableWallSliding: boolean = true): boolean;

Move, if possible (checking collisions with other objects in world). This is the simplest way to move an object, and a basic building block for artificial intelligence of creatures.

Checks move possibility by MoveAllowed, using Middle point. Actual move is done using Translate.

Note that wall sliding will only work if collision sphere is defined, which should be configured by setting CollisionSphereRadius to something non-zero. Otherwise, the move uses only box collisions, and wall sliding doesn't happen.

The provided TranslationChange should be a direction in the parent coordinate system of this TCastleTransform, so using this routine is consistent with doing Translation := Translation + TranslationChange however this checks collisions.

Public function GetTranslation: TVector3; deprecated 'use Translation';

Warning: this symbol is deprecated: use Translation

 
Public procedure Identity;

Make the transform do nothing — zero Translation, zero Rotation, Scale to one. Also resets ScaleOrientation.

Public procedure GetView(out APos, ADir, AUp: TVector3);

Get at once vectors: position, direction, up.

Public procedure SetView(const APos, ADir, AUp: TVector3; const AdjustUp: boolean = true); overload;

Set at once vectors: position, direction, up.

ADir and AUp given here do not have to be normalized (they will be normalized if needed). They will be automatically fixed to be orthogonal, if necessary: when AdjustUp = True (the default) we will adjust the up vector (preserving the given direction value), otherwise we will adjust the direction (preserving the given up value).

Public procedure SetView(const ADir, AUp: TVector3; const AdjustUp: boolean = true); overload;
 
Public procedure UpPrefer(const AUp: TVector3);

Change up vector, keeping the direction unchanged. If necessary, the up vector provided here will be fixed to be orthogonal to direction.

This is similar to assigning Up vector using it's property setter, but different behavior happens when we need to fix vectors to have direction orthogonal to up (which must be always true). In case of assigning Up by property setter, the Direction vector is changed (if necessary, to be orthogonal to up). In case of this method, the up vector is changed (if necessary, to be orthogonal to direction).

It's good to use this if you have a preferred up vector for creatures, but still preserving the direction vector has the highest priority.

Public procedure AddBehavior(const Behavior: TCastleBehavior);

Add a TCastleBehavior to this TCastleTransform. In effect, the virtual methods of TCastleBehavior, like TCastleBehavior.Update, will be automatically called. Also the TCastleBehavior.Parent gets assigned. If the TCastleBehavior was part of another TCastleTransform, it is removed from it.

See also
FindBehavior
Find the first behavior of the given class, Nil if none.
BehaviorsEnumerate
You can enumerate current behaviors using loop like for B in MyTransform.BehaviorsEnumerate do ....
Public procedure RemoveBehavior(const Behavior: TCastleBehavior);

Remove TCastleBehavior from this TCastleTransform. In effect, the virtual methods of TCastleBehavior, like TCastleBehavior.Update, will no longer be automatically called. The TCastleBehavior.Parent is set to Nil.

Public function FindBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;

Find the first behavior of the given class, Nil if none.

Public function FindRequiredBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;

Find the first behavior of the given class, or create and add a new one if necessary. Never returns Nil.

Public function BehaviorsCount: Integer;

Count of behaviors.

See also
AddBehavior
Add a TCastleBehavior to this TCastleTransform.
RemoveBehavior
Remove TCastleBehavior from this TCastleTransform.
Public function BehaviorsEnumerate: TCastleBehaviorEnumerator;

You can enumerate current behaviors using loop like for B in MyTransform.BehaviorsEnumerate do .... Do not call this method in other contexts, it is only useful for "for..in" construction.

Properties

Public property Items[I: Integer]: TCastleTransform read GetItem write SetItem;
 
Public property UniqueParent: TCastleTransform read FParent;

Return parent TCastleTransform, but only if this TCastleTransform is a child of exactly one other TCastleTransform.

In general, the same TCastleTransform instance may be used multiple times as a child of other TCastleTransform instances (as long as they are all within the same TCastleViewport), in which case this property is Nil.

It is also Nil if this is the root transform, not added to any parent.

Public property CastShadowVolumes: boolean read FCastShadowVolumes write FCastShadowVolumes default true;

Does the 3D object cast shadows by shadow volumes. See also TCastleScene.ReceiveShadowVolumes.

Public property ListenPressRelease: Boolean read FListenPressRelease write SetListenPressRelease default false;

Are Press and Release virtual methods called.

Public property World: TCastleAbstractRootTransform read FWorld;

Root transformation (TCastleAbstractRootTransform) containing us. Nil if we are not (yet) part of some hierarchy rooted in TCastleAbstractRootTransform.

Public property Cursor: TMouseCursor read FCursor write SetCursor default mcDefault;

Mouse cursor over this object.

Public property CollidesWithMoving: boolean read FCollidesWithMoving write FCollidesWithMoving default false;

Can this object be pushed by (or block movement of) doors, elevators and other moving level parts (TCastleMoving instances).

Some 3D moving objects may try to avoid crushing this item. Like an automatic door that stops it's closing animation to not crush things standing in the doorway.

Some other 3D moving objects may push this object. Like elevators (vertical, or horizontal moving platforms). We may use sphere (see CollisionSphereRadius and Sphere) for checking collisions, or bounding box (TCastleTransform.BoundingBox), depending on need.

Public property InternalExcludeFromParentBoundingVolume: boolean read FInternalExcludeFromParentBoundingVolume write FInternalExcludeFromParentBoundingVolume;

Is this object's bounding volume (BoundingBox) included in parent bounding volume. This should be always True for non-debug scenes. Violating this may cause rendering artifacts, things could disappear when they should not. Using this is reasonable only if you attach a debug geometry to your scene, and you don't want to enlarge your bounding volume (e.g. because this debug geometry visualizes something determined by the bounding volume, and it would create a "feedback loop" if the visualization itself would enlarge the bounding box).

Public property Gravity: boolean read FGravity write FGravity default false;

Gravity may make this object fall down (see FallSpeed) or grow up (see GrowSpeed). See also PreferredHeight.

Special notes for TPlayer: player doesn't use this (TPlayer.Gravity should remain False), instead player relies on TPlayer.Navigation.Gravity = True, that does a similar thing (with some extras, to make camera effects). This will change in the future, to merge these two gravity implementations. Although the TPlayer.Fall method still works as expected (it's linked to TCastleWalkNavigation.OnFall in this case).

TODO: This will be deprecated at some point, and you will be adviced to always use physics, through TCastleTransform.RigidBody, to have realistic gravity.

Public property FallSpeed: Single read FFallSpeed write FFallSpeed default 0;

Falling speed, in units per second, for Gravity.

This is relevant only if Gravity and PreferredHeight <> 0. 0 means no falling.

TODO: In CGE 7.x this will be deprecated, and you will be adviced to always use physics, through TCastleTransform.RigidBody, to have realistic gravity.

Public property GrowSpeed: Single read FGrowSpeed write FGrowSpeed default 0;

Growing (raising from crouching to normal standing position) speed, in units per second. This is used by non-flying creatures when climbing up stairs, in which case Translation ("legs positon") may be sometimes under the ground while Middle ("eyes position") will be always above the ground and will try to grow to be at PreferredHeight above the ground.

This is relevant only if Gravity and PreferredHeight <> 0. 0 means no growing.

Public property MiddleHeight: Single read FMiddleHeight write FMiddleHeight default DefaultMiddleHeight;

How high are creature eyes in the model. Value 0 means that eyes are at the bottom of the model, 0.5 means the middle, 1 means top.

The top is always considered to be at the top of the bounding box.

Definition of bottom depends on Gravity:

  • When Gravity is True, then the bottom is considered to be the plane where World.GravityCoordinate (like Z or Y axis) is zero. The actual bottom (lowest point) of the bounding box doesn't matter. This means that things placed below zero plane (like a creature tentacle or leg) will sink into the ground, instead of causing whole creature to move up. It also means that the creature can easily float above the ground, just model it a little above the zero plane.

    In other words, this allows you to model the creature with respect to the ground (zero plane), which is comfortable.

    Note that setting MiddleHeight to exact 0 means that gravity will not work, as it means that the PreferredHeight above the ground is to be stuck right at the ground level.

    For gravity to work right, the MiddleHeight should be large enough to cause PreferredHeight to be > Sphere radius, for all possible animation states (for all possible bounding box values).

  • When Gravity is False, then the bottom is considered at the bottom of the bounding box.

    This way it works regardless of where (0,0,0) is in your model (regardless if (0,0,0) represents legs, or middle of your creature), since we adjust to the BoundingBox position.

This property determines how the TCastleTransform handles the Middle implementation (this is the point used for various collision detection routines) and PreferredHeight (this is the preferred height of Middle above the ground). You can override these two methods to use a different approach, and then ignore MiddleHeight completely.

Public property Translation: TVector3 read FTranslation write SetTranslation;

Translation (move) the children. Zero by default.

Public property TranslationXY: TVector2 read GetTranslationXY write SetTranslationXY;

Get or set the XY components of the translation. Useful for 2D games.

Public property Center: TVector3 read FCenter write SetCenter;

Center point around which the Rotation and Scale is performed.

Public property Rotation: TVector4 read FRotation write SetRotation;

Rotation in 3D, around a specified axis. Rotation is expressed as a 4D vector, in which the first 3 components specify the rotation axis (does not need to be normalized, but must be non-zero), and the last component is the rotation angle in radians.

Note: the Rotation axis (first 3 components) must be non-zero, however as a special case the rotation value TVector4.Zero (so all components, axis and angle, are zero) is also allowed.

Rotation is done around Center.

Public property Scale: TVector3 read FScale write SetScale;

Scale in 3D. Scaling is done around Center and with orientation given by ScaleOrientation.

We do the best we can to work with any scale value, even negative or zero. But usually, it's best to keep the scale positive. More information:

  1. If you can, keep the scale uniform, that is scale equal amount in X, Y and Z. For example set scale = (3.0, 3.0, 3.0) to scale 3x times, and avoid scale like (3.0, 1.0, 1.0) that scales more in one direction.

    Non-uniform scale works, but some collisions are not perfectly calculated then. In particular sphere collision routines (TCastleAbstractRootTransform.WorldSphereCollision, TCastleAbstractRootTransform.WorldSphereCollision2D) only do an approximation in case of non-uniform scale.

    Note that ScaleOrientation matters only in case of non-uniform scale.

  2. All scale components should > 0 if you want 3D lighting to work corrrectly. That is, avoid negative scale, that changes the normals and orientation of faces (counter-clockwise becomes clockwise, if all scale components are -1), or standard lighting may not work Ok.

    For unlit stuff, or custom lighting, negative scale may be Ok. For many 2D games that use no lighting/custom lighting, negative scale is Ok.

  3. At least, keep all scale components non-zero. Otherwise the scaling operation is not invertible, and generally collisions will not work correctly.

    If you really need to set zero scale, at least consider using Collides = False.

Public property ScaleOrientation: TVector4 read FScaleOrientation write SetScaleOrientation;

Orientation in which 3D Scale is performed.

Public property RigidBody: TRigidBody read FRigidBody write SetRigidBody;

Participate in rigid body physics simulation. This makes this object collidable with other rigid bodies (if Collides) and it allows to move and rotate because of gravity or because of collisions with other objects (if TRigidBody.Dynamic is True).

Setting this property makes this 3D object a single rigid body for the physics engine.

If this property is assigned and the TRigidBody.Dynamic is True (and TRigidBody.Dynamic is True by default) then this object is moved and rotated using the physics engine. It will move because of gravity (if TRigidBody.Gravity, also True by default), and because of collisions with other objects.

The TRigidBody.Collider property must be initialized before assigning the TRigidBody instance here. So you must create a TCollider descendant, specyfying the given TRigidBody as a parent. A rigid body without a collider would in theory not collide with anything, and (if TRigidBody.Dynamic) would simply fall down because of gravity. In practice, a rigid body without a collider is simply not allowed. If you really need this, assign anything to TRigidBody.Collider and just set Collides to False.

Our engine (for now) also has an internal, simple physics simulation, used to perform collisions with player, creatures, and optional (unrealistic) gravity. So we have two independent physics systems, but they try to not get into each others way (they each perform a different task). In the future there will be an option to use the full-featured physics engine for all simulations, also for player and creatures, at which point our "internal physics simulation" will become deprecated. For now, be aware of these:

Note that an object can only be present once in the World to be a rigid body. Breaking this rule will cause the EMultipleReferencesInWorld exception at an undefined time.

Public property Position: TVector3 read FTranslation write SetTranslation; deprecated 'use Translation';

Warning: this symbol is deprecated: use Translation

 
Public property Direction: TVector3 read GetDirection write SetDirection;

Direction the creature is facing, and up vector. These properties provide an alternative way to get and set the Rotation of the transformation. Thinking in terms of "direction" and "up" is often more natural when transforming creatures and player.

The Orientation determines what is your default direction and up (when the Rotation is zero). By default we follow X3D standard vectors suitable for gravity along the Y axis. So direction is -Z (DefaultCameraDirection), up is +Y (DefaultCameraUp).

The Direction and Up vectors should always be normalized (have length 1). When setting them by these properties, we will normalize them automatically.

They must also always be orthogonal. When setting Direction, Up will always be automatically adjusted to be orthogonal to Direction. And vice versa — when setting Up, Direction will be adjusted.

Public property Up: TVector3 read GetUp write SetUp;
 
Public property Orientation: TOrientationType read FOrientation write FOrientation;

How the direction and up vectors determine transformation. See TOrientationType for values documentation.

The default value of this is determined by static variable DefaultOrientation, this is usually comfortable (because almost always you use the same Orientation throughout your game). By default it's otUpYDirectionMinusZ (matching default cameras of OpenGL and VRML/X3D).

This value determines how you should model your 3D models, like the creatures, the items, and the player weapons. Generally, it applies to every 3D model that is used as a child of this TCastleTransform instance.

Public property List: TCastleTransformList read FList;

Transformation objects inside. Freeing these items automatically removes them from this list.

Public property Behaviors [const Index: Integer]: TCastleBehavior read GetBehaviors;

Enumerate current behaviors.

See also
AddBehavior
Add a TCastleBehavior to this TCastleTransform.
RemoveBehavior
Remove TCastleBehavior from this TCastleTransform.
Published property Exists: boolean read FExists write FExists default true;

Is this object visible and colliding.

Setting this to False pretty much turns everything of this 3D object to "off". This is useful for objects that disappear completely from the level when something happens. You could just as well remove this object from TCastleViewport.Items tree, but sometimes it's more comfortable to simply turn this property to False.

Descendants may also override GetExists method.

Published property Collides: boolean read FCollides write FCollides default true;

Should this 3D object participate in collision detection. You can turn this off, useful to make e.g. "fake" walls (to some secret places on level).

This describes collision resolution with almost everything — camera, player (in third-person perspective, camera may differ from player), other creatures. That is because everything resolves collisions through our methods MoveCollision and HeightCollision (high-level) or SegmentCollision, SphereCollision, SphereCollision2D, PointCollision2D, BoxCollision (low-level).

(Note that RayCollision is excluded from this, it exceptionally ignores Collides value, as it's primarily used for picking. Same for SegmentCollision with LineOfSight=true.)

The only exception are the collisions with TCastleMoving instances (movable world parts like elevators and doors) that have their own detection routines and look at CollidesWithMoving property of other objects. That is, the TCastleMoving instance itself must still have Collides = True, but it interacts with other objects if and only if they have CollidesWithMoving = True (ignoring their Collides value). This allows items to be moved by elevators, but still player and creatures can pass through them.

Note that if not Exists then this doesn't matter (not existing objects never participate in collision detection).

Descendants may also override GetCollides method. Sometimes it's more comfortable than changing the property value.

Published property Pickable: boolean read FPickable write FPickable default true;

Is item pickable by RayCollision method. Note that if not Exists then this doesn't matter (not existing objects are never pickable). This is independent from Collides, as RayCollision does not look at Collides, it only looks at Pickable.

Descendants may also override GetPickable method. Sometimes it's more comfortable than changing the property value.

Published property Visible: boolean read FVisible write FVisible default true;

Is item visible. Note that if not Exists then this doesn't matter (not existing objects are never visible). This is independent from Collides or Pickable.

Descendants may also override GetVisible method. Sometimes it's more comfortable than changing the property value.

Published property ExcludeFromGlobalLights: boolean read FExcludeFromGlobalLights write FExcludeFromGlobalLights default false;

If this 3D object is rendered as part of TCastleViewport, and TCastleViewport.UseGlobalLights is True, then this property allows to make an exception for this 3D object: even though TCastleViewport.UseGlobalLights is True, do not use global lights for this 3D object.

Note that this is not applied recursively. Instead, it is checked at each TCastleTransform instance that checks TRenderParams.BaseLights. In practice, it is only checked at TCastleScene, unless you do custom rendering on your own.

Published property ExcludeFromStatistics: boolean read FExcludeFromStatistics write FExcludeFromStatistics default false;

Exclude from rendering statistics in TCastleViewport.Statistics.

Published property CollisionSphereRadius: Single read FCollisionSphereRadius write FCollisionSphereRadius;

When non-zero, we can approximate collisions with this object using a sphere in certain situations (MoveAllowed, Gravity). This usually makes dynamic objects, like player and creatures, collide better.

Published property CenterPersistent: TCastleVector3Persistent read FCenterPersistent ;

Center that can be visually edited in Castle Game Engine Editor, Lazarus and Delphi. Normal user code does not need to deal with this, instead read or write Center directly.

See also
Center
Center point around which the Rotation and Scale is performed.
Published property RotationPersistent: TCastleVector4Persistent read FRotationPersistent ;

Rotation that can be visually edited in Castle Game Engine Editor, Lazarus and Delphi. Normal user code does not need to deal with this, instead read or write Rotation directly.

See also
Rotation
Rotation in 3D, around a specified axis.
Published property ScalePersistent: TCastleVector3Persistent read FScalePersistent ;

Scale that can be visually edited in Castle Game Engine Editor, Lazarus and Delphi. Normal user code does not need to deal with this, instead read or write Scale directly.

See also
Scale
Scale in 3D.
Published property ScaleOrientationPersistent: TCastleVector4Persistent read FScaleOrientationPersistent ;

ScaleOrientation that can be visually edited in Castle Game Engine Editor, Lazarus and Delphi. Normal user code does not need to deal with this, instead read or write ScaleOrientation directly.

See also
ScaleOrientation
Orientation in which 3D Scale is performed.
Published property TranslationPersistent: TCastleVector3Persistent read FTranslationPersistent ;

Translation that can be visually edited in Castle Game Engine Editor, Lazarus and Delphi. Normal user code does not need to deal with this, instead read or write Translation directly.

See also
Translation
Translation (move) the children.

Generated by PasDoc 0.16.0.