Debian Codegraph @

src/transform/castletransform_transform.inc

raw
1 {%MainUnit castletransform.pas}
2 {
3 Copyright 2017-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18
19 //type
20 { Group and transform (move, rotate, scale) children objects.
21
22 Add and remove children using the @link(Add), @link(Remove) and similar methods.
23 A child can be any @link(TCastleTransform) instance,
24 in particular it can be a @link(TCastleScene) instance
25 (which allows to load and render any 3D or 2D model).
26
27 Control the transformation using these properties:
28
29 @orderedList(
30 @item(Move using @link(Translation).)
31
32 @item(Rotate using @link(Rotation).
33 The rotation is performed around the @link(Center) point.
34 The rotation may be alternatively controlled using the
35 @link(Direction) and @link(Up) vectors.)
36
37 @item(Change size using @link(Scale).
38 Scale is done around @link(Center) and with orientation given by
39 @link(ScaleOrientation).)
40 )
41
42 This class is the base object that is managed by the @link(TCastleViewport).
43 You insert instances of this class into @link(TCastleViewport.Items),
44 which is actually an instance of @link(TCastleTransform) too.
45
46 This class implements also optional gravity and physics.
47 See the @link(Gravity) property for a simple unrealistic gravity model.
48 See the @link(RigidBody) for a proper rigid-bidy simulation,
49 with correct gravity model and collisions with other rigid bodies. }
50 TCastleTransform = class(TCastleComponent)
51 strict private
52 type
53 TEnumerator = record
54 strict private
55 FList: TCastleTransformList;
56 FPosition: Integer;
57 function GetCurrent: TCastleTransform; inline;
58 public
59 constructor Create(const AList: TCastleTransformList);
60 function MoveNext: Boolean; inline;
61 property Current: TCastleTransform read GetCurrent;
62 end;
63
64 { Used by @link(TCastleTransform.BehaviorsEnumerate).
65 Do not use this type explicitly, it should only be used by for..in
66 construction like "for B in MyTranform.BehaviorsEnumerate do ...".
67 @exclude }
68 TCastleBehaviorEnumerator = record
69 strict private
70 FParent: TCastleTransform;
71 FPosition: Integer;
72 function GetCurrent: TCastleBehavior; inline;
73 public
74 constructor Create(const AParent: TCastleTransform);
75 function MoveNext: Boolean; inline;
76 property Current: TCastleBehavior read GetCurrent;
77 function GetEnumerator: TCastleBehaviorEnumerator;
78 end;
79
80 class var
81 NextTransformId: Cardinal;
82 var
83 FCastShadows: Boolean;
84 FExists: Boolean;
85 FParentExistsInRoot: Boolean;
86 FExistsInRoot: Boolean;
87 FLastExistsChangeFrameId: TFrameId;
88 FCollides: Boolean;
89 FPickable: Boolean;
90 FVisible: Boolean;
91 FCollidesWithMoving: Boolean;
92 FWorld: TCastleAbstractRootTransform;
93 { How many times this is a child in the FWorld, counting all possible paths in transformation tree. }
94 FWorldReferences: Cardinal;
95 FList: TCastleTransformList;
96 FParent: TCastleTransform;
97 FCollisionSphereRadius: Single;
98 FListenPressRelease: Boolean;
99 RegisteredGLContextCloseListener: Boolean;
100 FPendingToRemove: TComponentList;
101 FPendingToRemoveAndFree: TComponentList;
102 FRenderLayer: TRenderLayer;
103
104 // transformation
105 FCenter: TVector3;
106 FRotation: TVector4;
107 FScale: TVector3;
108 FScaleOrientation: TVector4;
109 FTranslation: TVector3;
110
111 // transformation extras
112 FGravity: Boolean;
113 FFallingStartMiddle: TVector3;
114 FFalling: Boolean;
115 FFallSpeed: Single;
116 FGrowSpeed: Single;
117 FMiddleHeight: Single;
118 FOrientation: TOrientationType;
119 FOnlyTranslation: Boolean;
120
121 FTransformation: TTransformation;
122 FTransformationValid: Boolean;
123
124 FWorldTransformation: TTransformation;
125 FWorldTransformationId: Cardinal;
126 FWorldTransformationValid: Boolean;
127
128 FLastParentWorldTransformation: TTransformation;
129 FLastParentWorldTransformationId: Cardinal;
130
131 FOnAddedBehaviorNotification: TCastleComponentNotification;
132 FBeforeRemoveBehaviorNotification: TCastleComponentNotification;
133 FAfterUpdate: TNotifyEventList;
134
135 // Always equal to FindBehaviors(TCastleRigidBody)
136 FCachedRigidBody: TCastleRigidBody;
137 // Always equal to FindBehaviors(TCastleCollider)
138 FCachedCollider: TCastleCollider;
139
140 procedure SerializeChildrenAdd(const C: TComponent);
141 procedure SerializeChildrenClear;
142 procedure SerializeChildrenEnumerate(const Proc: TGetChildProc);
143 procedure SerializeBehaviorsAdd(const C: TComponent);
144 procedure SerializeBehaviorsClear;
145 procedure SerializeBehaviorsEnumerate(const Proc: TGetChildProc);
146 procedure SetCenter(const Value: TVector3);
147 procedure SetRotation(const Value: TVector4);
148 procedure SetScale(const Value: TVector3);
149 procedure SetScaleOrientation(const Value: TVector4);
150 procedure SetTranslation(const Value: TVector3);
151 function GetTranslationXY: TVector2;
152 procedure SetTranslationXY(const Value: TVector2);
153 function GetDirection: TVector3;
154 function GetUp: TVector3;
155 procedure SetDirection(const Value: TVector3);
156 procedure SetUp(const Value: TVector3);
157 function RotationFromDirectionUp(const D, U: TVector3): TVector4;
158 function RotationToDirection(const ARotation: TVector4): TVector3;
159 function RotationToUp(const ARotation: TVector4): TVector3;
160 procedure UpdateSimpleGravity(const SecondsPassed: Single);
161 function GetItem(const I: Integer): TCastleTransform;
162 procedure SetItem(const I: Integer; const Item: TCastleTransform);
163 procedure InternalTransformationMult(var T: TTransformation);
164 procedure InternalTransformation(out T: TTransformation);
165 { Update our FWorldTransformation, FWorldTransformationId. }
166 procedure UpdateWorldTransformation;
167 procedure WarningMatrixNan(const NewParamsInverseTransformValue: TMatrix4);
168 procedure RemoveBehaviorIndex(const BehaviorIndex: Integer);
169 procedure SetListenPressRelease(const Value: Boolean);
170 function GetBehaviors(const Index: Integer): TCastleBehavior;
171 procedure GLContextCloseEvent(Sender: TObject);
172 procedure PendingRemovals;
173 procedure SetExists(const Value: Boolean);
174 procedure SetParentExistsInRoot(const Value: Boolean);
175 { Value of FParent.ParentExistsInRoot, if FParent is non-nil.
176 Always true, if FParent = nil.
177 Intuitively this means "all our parents exist" -- Parent, Parent.Parent etc.,
178 as far as our parent hierarchy goes. }
179 property ParentExistsInRoot: Boolean read FParentExistsInRoot write SetParentExistsInRoot default true;
180 { Call when ParentExistsInRoot or Exists changed. }
181 procedure UpdateExistsInRoot;
182 { Never call ChangedTransform directly, always call this. }
183 procedure ChangedTransformCore(const UpdatePhysicsTransform: Boolean = true);
184 function GetWorldViewRec: TViewVectors;
185 procedure SetWorldViewRec(const Value: TViewVectors);
186 procedure UpdateCachedBehaviors;
187 { Convert distance from the local coordinate system
188 to parent coordinate system
189 (in short: Result := Distance * AverageScale). }
190 function DistanceToParent(const Distance: Single): Single;
191 private
192 { "Meaningful" parent is a parent that competes to be a value of Parent.
193 This allows to avoid TCastleTransformReference from being considered
194 a meaningful parent, so that transforms under TCastleTransformReference
195 can still have useful Parent, WorldTransform and more
196 (so that they work e.g. in editor nicely, with physics nicely etc.)
197
198 This can change only after construction, before any children are actually added to this. }
199 MeaningfulParent: Boolean;
200
201 FBehaviors: TComponentList;
202
203 { Some behaviors need know when castle transform is in world or not or
204 when it changes. They can register to those notifications. When list
205 is not created that means no behaviors need those notifications. }
206 FBehaviorsWorldChangeNotificationList: TCastleBehaviorList;
207
208 { Does any behavior on FBehaviors possibly override BeforeRender. }
209 FBehaviorsNeedBeforeRender: Boolean;
210
211 { Update FWorld, FWorldReferences.
212 This is recursively called on all children as well.
213 Value must not be @nil. }
214 procedure AddToWorld(const Value: TCastleAbstractRootTransform);
215 { Update FWorld, FWorldReferences.
216 This is recursively called on all children as well.
217 Value must not be @nil. }
218 procedure RemoveFromWorld(const Value: TCastleAbstractRootTransform);
219
220 { Add a new parent.
221 Updates FParent, FWorld, FWorldReferences.
222 This is not recursively called on all children -- only the AddToWorld, a subset of this, is recursive.
223 NewParent must not be @nil. }
224 procedure AddParent(const NewParent: TCastleTransform);
225 { Remove parent, previously added by AddParent.
226 Updates FParent, FWorld, FWorldReferences.
227 This is not recursively called on all children -- only the RemoveFromWorld, a subset of this, is recursive.
228 OldParent must not be @nil. }
229 procedure RemoveParent(const OldParent: TCastleTransform);
230
231 { Return non-nil parent, making sure it's valid.
232 It's equivalent to @link(Parent), except it makes exception instead of returning @nil. }
233 function CheckParent: TCastleTransform;
234
235 procedure NotifyWorldAfterAttach;
236 procedure NotifyWorldBeforeDetach;
237
238 // TODO: Do we need so much new API?
239
240 { Ability to add a callback (object of procedure have to be TComponent)
241 to be informed when a behavior is added to this CastleTransform. }
242 procedure AddNotificationOnBehaviorAdded(const AEvent: TComponentEvent); overload;
243 { Ability to add a callback (object of procedure have to be TComponent)
244 to be informed when a behavior is added to this CastleTransform with
245 object class filtering. }
246 procedure AddNotificationOnBehaviorAdded(const AEvent: TComponentEvent;
247 const ClassFilter: TComponentClass); overload;
248 { Calls all behavior add callbacks with ABehavior as parameter value. }
249 procedure NotifyBehaviorAdded(const ABehavior: TCastleBehavior);
250 { Remove all occurrences of callback (object of procedure have to be TComponent)
251 from "OnBehaviorAdded" list. }
252 procedure RemoveNotificationOnBehaviorAdded(const AEvent: TComponentEvent); overload;
253 { Remove a callback (object of procedure have to be TComponent)
254 from "OnBehaviorAdded" calbacks list with object class filtering. }
255 procedure RemoveNotificationOnBehaviorAdded(const AEvent: TComponentEvent;
256 const ClassFilter: TComponentClass); overload;
257
258 { Ability to add a callback (object of procedure have to be TComponent)
259 to be informed when a behavior is added to this CastleTransform }
260 procedure AddNotificationBeforeBehaviorRemove(const AEvent: TComponentEvent); overload;
261 { Ability to add a callback (object of procedure have to be TComponent)
262 to be informed when a behevior is added to this CastleTransform with
263 object class filtering. }
264 procedure AddNotificationBeforeBehaviorRemove(const AEvent: TComponentEvent;
265 const ClassFilter: TComponentClass); overload;
266 { Calls all behavior remove callbacks with ABehavior as parameter value. }
267 procedure NotifyBeforeBehaviorRemove(const ABehavior: TCastleBehavior);
268 { Remove all occurrences of callback (object of procedure have to be TComponent)
269 from "BeforeBehaviorRemove" list. }
270 procedure RemoveNotificationBeforeBehaviorRemove(const AEvent: TComponentEvent); overload;
271 { Remove a callback (object of procedure have to be TComponent)
272 from "BeforeBehaviorRemove" calbacks list with object class filtering. }
273 procedure RemoveNotificationBeforeBehaviorRemove(const AEvent: TComponentEvent;
274 const ClassFilter: TComponentClass); overload;
275
276 { Call ParentBeforeDetach and WorldBeforeDetach on a behavior that will soon be freed. }
277 procedure BeforeBehaviorDestroy(const Behavior: TCastleBehavior);
278
279 { Call UpdateWorldScale on all colliders here and in children. }
280 procedure UpdateCollidersWorldScale;
281
282 procedure SetParent(const Value: TCastleTransform);
283 procedure UpdateBehaviorsNeedBeforeRender;
284 protected
285 { Returns list of TCastleTransform to render. By default, it just returns @link(List). }
286 function GetRenderList(const Params: TRenderParams): TCastleTransformList; virtual;
287
288 { Call this when doing anything that allocates GL resources.
289 This will make sure GLContextClose will get called. }
290 procedure RegisterGLContextClose;
291
292 { Called when the current @link(World) that contains this object changes.
293 In the usual case, @link(World) corresponds to a @link(TCastleViewport.Items)
294 instance, and when this method is called it means that object
295 is added/removed from a viewport.
296
297 You can ignore this when called with Value equal to current @link(World).
298
299 Note that each TCastleTransform instance can only be part of one world
300 (TCastleAbstractRootTransform) at a time.
301 Although we may be present many times within the same world.
302 Always remove the TCastleTransform from previous world
303 before adding it to a new one. }
304 procedure ChangeWorld(const Value: TCastleAbstractRootTransform); virtual;
305
306 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
307
308 { Height of a point above the 3D model.
309 This checks ray collision, from APosition along the negated GravityUp vector.
310 Measures distance to the nearest scene item (called "ground" here).
311
312 @returns(If the 3D scene is hit.
313 @false means that APosition floats above an empty space.
314 That is, if you turn gravity on, it will fall down forever,
315 as far as this 3D scene is concerned.)
316
317 @param(AboveHeight Height above the ground.
318 @italic(One height unit equals one GravityUp vector).
319 Always use normalized GravityUp vector if you expect
320 to receive here a normal distance.
321
322 AboveHeight is always set to MaxSingle when returned result is @false
323 (this guarantee simplifies some code).)
324
325 @param(AboveGround Pointer to PTriangle representing the ground.
326 Must be @nil if returned result is @false.
327 @bold(May) be @nil even if we returned @true (not all 3D
328 objects may be able to generate PTriangle information about collision).
329
330 This may be useful for example to make a footsteps sound dependent
331 on texture of the ground.
332 Or to decrease player life points for walking on hot lava.
333 See "The Castle" game for examples.)
334 }
335 function HeightCollision(const APosition, GravityUp: TVector3;
336 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
337 out AboveHeight: Single; out AboveGround: PTriangle): boolean;
338
339 { Can other 3D object (maybe a player) move without colliding with this object.
340
341 If IsRadius, then you should prefer to perform exact collision with sphere
342 of given radius (must be > 0).
343 At the very least, this checks that the line segment
344 between OldPos and NewPos doesn't collide,
345 @bold(and) that sphere with given Radius centered around NewPos
346 doesn't collide.
347
348 If not IsRadius, or if checking for collisions with sphere is not possible
349 for some reasons, then you can check for collisions with boxes.
350 OldBox should usually be ignored (it can be useful when collision-checking
351 has to be approximate in some corner cases, see TCreature.MoveCollision).
352 NewBox plays the same role as "sphere centered around NewPos" in paragraph
353 above.
354
355 Overloaded version with separate ProposedNewPos and NewPos parameters
356 allows you to accept the move, but for NewPos (that should be some slightly
357 modified version of ProposedNewPos). This allows to implement wall-sliding:
358 when camera tries to walk into the wall, we will change movement
359 to move alongside the wall (instead of just completely blocking the move).
360 When this version returns @false, it's undefined what is the NewPos.
361
362 @groupBegin }
363 function MoveCollision(
364 const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3;
365 const IsRadius: boolean; const Radius: Single;
366 const OldBox, NewBox: TBox3D;
367 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;
368 function MoveCollision(
369 const OldPos, NewPos: TVector3;
370 const IsRadius: boolean; const Radius: Single;
371 const OldBox, NewBox: TBox3D;
372 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload;
373 { @groupEnd }
374
375 { Check collision with a line segment, that is: a line between 2 points in 3D. }
376 function SegmentCollision(const Pos1, Pos2: TVector3;
377 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
378 const ALineOfSight: boolean): boolean;
379
380 { Check collision with a 3D sphere.
381
382 This works precisely when transformation hierarchy has uniform scaling,
383 i.e. scale is the same in all X, Y, Z axes.
384 In case of non-uniform scaling, this is an approximation. }
385 function SphereCollision(const Pos: TVector3; const Radius: Single;
386 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
387
388 { Check collision with a sphere in 2D (a circle, extruded to infinity along the Z axis).
389
390 Note that PointCollision2D and SphereCollision2D @italic(do not work
391 reliably on objects that have 3D rotations). See @link(PointCollision2D)
392 for details.
393
394 This works precisely when transformation hierarchy has uniform scaling,
395 i.e. scale is the same in all X, Y, Z axes.
396 In case of non-uniform scaling, this is an approximation.
397
398 @param(Details If non-nil, these are automatically filled with the details
399 about the collision.
400 If the result is @false, the Details contents are untouched.
401 If the result is @true, the Details contents are set to describe
402 the 3D objects hierarchy that caused this collision.) }
403 function SphereCollision2D(const Pos: TVector2; const Radius: Single;
404 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
405 const Details: TCollisionDetails = nil): boolean;
406
407 { Check collision with a point in 2D (which is an infinite line along the Z axis
408 in 3D).
409
410 Note that PointCollision2D and SphereCollision2D @italic(do not work
411 reliably on objects that have 3D rotations), that is: rotations that change
412 the direction of Z axis! This applies to all ways of rotating --
413 using the @link(TCastleTransform)
414 or using the X3D node @link(TTransformNode) (within a TCastleSce).
415
416 @orderedList(
417 @item(@italic(The reason): we transform the point (or sphere center)
418 to the local coordinates, and we should also transform the Z axis to
419 the local coordinates, to be always correct. Right now, we don't do
420 the latter.)
421
422 @item(And we don't want to do it (at least not in all cases)!
423 The simple 2D point collision check would then actually perform
424 a 3D line collision check, thus PointCollision2D would lose all the speed
425 benefits over LineCollision. PointCollision2D would become
426 a simple shortcut to perform @italic(LineCollision with
427 a line parallel to Z axis).
428
429 And in case of 2D games, or mostly 2D games, this speed loss
430 would not be justified. Often you @italic(know) that your objects
431 have no 3D rotations, for example if your animations are done in Spine.)
432
433 @item(In the future, we may overcome this limitation.
434 To do this, we will detect whether the transformation is "only 2D"
435 (actually this part is easy, you can detect it by looking at the matrix
436 even, so check whether appropriate numbers are zero).
437 And then PointCollision2D will change to LineCollision,
438 and SphereCollision2D will change to something like ExtrudedCircleCollision,
439 @italic(only when necessary).)
440 )
441 }
442 function PointCollision2D(const Point: TVector2;
443 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
444
445 { Check collision with axis-aligned box in 3D. }
446 function BoxCollision(const Box: TBox3D;
447 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean;
448
449 { First object hit by the ray, as a TRayCollision.
450 Returns a collision as TRayCollision instance, or @nil if no collision.
451 Caller is responsible for freeing the returned TRayCollision instance.
452
453 Contrary to other collision routines, this should @italic(ignore
454 the @link(Collides) property). The @link(Collides) property
455 specifies whether item collides with camera. And this method is used
456 for picking (pointing) 3D stuff --- everything visible can be picked,
457 collidable or not. Instead, this looks at @link(Pickable) and @link(Exists) properties.
458
459 This always returns the first collision with the world, that is
460 the one with smallest TRayCollision.Distance. For example, when
461 implemented in TCastleTransform, this checks collisions for all list items,
462 and chooses the closest one. }
463 function RayCollision(const RayOrigin, RayDirection: TVector3;
464 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision;
465
466 function LocalHeightCollision(const APosition, GravityUp: TVector3;
467 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
468 out AboveHeight: Single; out AboveGround: PTriangle): boolean; virtual;
469 function LocalMoveCollision(
470 const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3;
471 const IsRadius: boolean; const Radius: Single;
472 const OldBox, NewBox: TBox3D;
473 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload; virtual;
474 function LocalMoveCollision(
475 const OldPos, NewPos: TVector3;
476 const IsRadius: boolean; const Radius: Single;
477 const OldBox, NewBox: TBox3D;
478 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; overload; virtual;
479 function LocalSegmentCollision(const Pos1, Pos2: TVector3;
480 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
481 const ALineOfSight: boolean): boolean; virtual;
482 function LocalSphereCollision(const Pos: TVector3; const Radius: Single;
483 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
484 function LocalSphereCollision2D(const Pos: TVector2; const Radius: Single;
485 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
486 const Details: TCollisionDetails = nil): boolean; virtual;
487 function LocalPointCollision2D(const Point: TVector2;
488 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
489 function LocalBoxCollision(const Box: TBox3D;
490 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; virtual;
491 function LocalRayCollision(const RayOrigin, RayDirection: TVector3;
492 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision; virtual;
493
494 { Render with given Params (includes a full transformation of this scene).
495
496 This is @bold(mostly an internal method). You should not need to override
497 it during normal engine usage. Instead, you should render everything using
498 TCastleScene, which allows to load or build (by code) nodes to display
499 meshes, light and everything else.
500 But overriding this may be useful for special customized rendering. }
501 procedure LocalRender(const Params: TRenderParams); virtual;
502
503 { Render shadow volumes (with a full transformation of this scene).
504
505 This is @bold(mostly an internal method). You should not need to override
506 it during normal engine usage. If you render everything using TCastleScene,
507 then rendering shadow volumes is also automatically handled by TCastleScene. }
508 procedure LocalRenderShadowVolume(const Params: TRenderParams;
509 const ShadowVolumeRenderer: TBaseShadowVolumeRenderer); virtual;
510
511 { Can we use simple @link(Translation) to express our whole transformation
512 (IOW, we have no scaling, no rotation).
513 Returning @true allows optimization in some cases.
514 @bold(Internal. Protected instead of private only for testing.)
515 @exclude }
516 function OnlyTranslation: boolean;
517
518 { Get translation in 2D (uses @link(Translation), ignores Z coord). }
519 function Translation2D: TVector2; deprecated 'use TranslationXY';
520
521 { Transformation matrices, like @link(Transform) and @link(InverseTransform). }
522 procedure TransformMatricesMult(var M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';
523 procedure TransformMatrices(out M, MInverse: TMatrix4); deprecated 'do not use this directly, instead use Transform and InverseTransform methods';
524
525 { Average value of 3D scale in @link(Scale).
526 It is not calculated as a simple average, it's a little smarter
527 to prevent from weird results sometimes, see @link(Approximate3DScale). }
528 function AverageScale: Single;
529
530 { Average value of 2D scale, from XY components of @link(Scale).
531 It is not calculated as a simple average, it's a little smarter
532 to prevent from weird results sometimes, see @link(Approximate2DScale). }
533 function AverageScale2D: Single;
534
535 { Called when fall ended. You can use FallHeight to decrease creature
536 life or such. }
537 procedure Fall(const FallHeight: Single); virtual;
538
539 { Override to be notified about every transformation change.
540 By default, this calls VisibleChangeHere, which causes the window to redraw. }
541 procedure ChangedTransform; virtual;
542
543 { Override to be notified after ExistsInRoot value changed. }
544 procedure ExistsInRootChanged; virtual;
545 public
546 const
547 DefaultMiddleHeight = 0.5;
548 DefaultDirection: array [TOrientationType] of TVector3 = (
549 (X: 0; Y: 0; Z: -1),
550 (X: 0; Y: 0; Z: +1),
551 (X: 0; Y: -1; Z: 0),
552 (X: 1; Y: 0; Z: 0)
553 );
554 DefaultUp: array [TOrientationType] of TVector3 = (
555 (X: 0; Y: 1; Z: 0),
556 (X: 0; Y: 1; Z: 0),
557 (X: 0; Y: 0; Z: 1),
558 (X: 0; Y: 0; Z: 1)
559 );
560
561 { Default TCastleCamera.Orientation. }
562 DefaultCameraOrientation = otUpYDirectionMinusZ;
563
564 class var
565 { Default value of @link(TCastleTransform.Orientation) for new TCastleTransform instances,
566 except for cameras (cameras use special DefaultCameraOrientation).
567
568 This is @link(otUpYDirectionZ) by default.
569 This matches glTF orientation (as exported from Blender and other software). }
570 DefaultOrientation: TOrientationType;
571
572 var
573 { Workaround for descendants where BoundingBox may suddenly change
574 but their logic depends on stable (not suddenly changing) Middle.
575 If InternalMiddleForceBox then we will use given InternalMiddleForceBoxValue
576 instead of LocalBoundingBox for Middle and PreferredHeight
577 calculation. Descendants that deal with this should usually have
578 some timeout when they restore InternalMiddleForceBox to false.
579
580 This is quite internal hack and you should not use this in your own programs.
581 This is used only by TWalkAttackCreature.
582 @exclude }
583 InternalMiddleForceBox: boolean;
584 { @exclude }
585 InternalMiddleForceBoxValue: TBox3D;
586
587 { Make the transform rendered and (TODO) processed only within parents
588 that are MeaningfulParent, which means: do not enter TCastleTransformReference.Reference.
589 This is useful for debug transforms to visualize selection/gizmos to transform
590 in CGE editor.
591 It is not a complete implementation (right now it only really blocks rendering)
592 and it's generally a hack, in the future visualizing selection/gizmos
593 in CGE editor should probably not be put as parents of non-debug transforms.
594
595 This is quite internal hack for CGE editor and you should not use this
596 in your own programs.
597 It may (and probably will) disappear at some point.
598 @exclude }
599 InternalExistsOnlyInMeaningfulParents: Boolean;
600
601 { Scale of Parent and other higher TCastleTransform does not affect this.
602 Useful for various debug visualizations.
603 This is internal, and implementation is a bit hacky -- we avoid parent scale
604 where needed, not in all relevant places.
605 Also resulting rendering frustum is not correct.
606 @exclude }
607 InternalIgnoreParentScale: Boolean;
608
609 { Exclude this object's bounding volume
610 from parent bounding volume.
611
612 This should be always @false for non-debug scenes.
613 Changing this may cause rendering artifacts, things could
614 disappear when they should not.
615 Using this is reasonable only if you attach a debug geometry
616 to your scene, and you don't want to enlarge your bounding volume
617 (e.g. because this debug geometry visualizes something determined
618 by the bounding volume, and it would create a "feedback loop"
619 if the visualization itself would enlarge the bounding box). }
620 InternalExcludeFromParentBoundingVolume: Boolean;
621
622 { Results in more correct, but often unnecessary and time wasting operation:
623 changing this transformation also updates all children's rigid bodies
624 transformation in the physics engine.
625
626 This is important if you change transformation of some parent,
627 without directly changing the transformation of children,
628 but the children have rigid bodies attached. }
629 InternalMovesPhysicsBodies: Boolean;
630
631 { How many times this is a child in the FWorld,
632 counting all possible paths in transformation tree.
633 @exclude }
634 property InternalWorldReferences: Cardinal read FWorldReferences;
635
636 constructor Create(AOwner: TComponent); override;
637 destructor Destroy; override;
638
639 procedure BeforeDestruction; override;
640
641 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
642 function PropertySections(const PropertyName: String): TPropertySections; override;
643 procedure DesignerWarnings(const SList: TStrings); override;
644 function GetEnumerator: TEnumerator;
645
646 {$ifdef FPC}
647 property GetExists: Boolean read FExists; deprecated 'use Exists';
648 {$endif}
649
650 { Does this transform have a collision mesh that TCastleMeshCollider can use.
651 Default implementation returns @false. }
652 function HasColliderMesh: Boolean; virtual;
653
654 { Enumerate triangles for a collision mesh that TCastleMeshCollider can use. }
655 procedure ColliderMesh(const TriangleEvent: TTriangleEvent); virtual;
656
657 { Does the item really collide. Trivial shortcut for checking @link(Collides) and @link(Exists). }
658 function CheckCollides: Boolean;
659 function GetCollides: boolean; virtual; deprecated 'use CheckCollides';
660
661 { Is the item really pickable. Trivial shortcut for checking @link(Pickable) and @link(Exists). }
662 function CheckPickable: boolean;
663 function GetPickable: boolean; virtual; deprecated 'use CheckPickable';
664
665 { Is the item really visible. Trivial shortcut for checking @link(Visible) and @link(Exists). }
666 function CheckVisible: boolean;
667 function GetVisible: boolean; virtual; deprecated 'use CheckVisible';
668
669 { Add a child.
670
671 Note that adding the same child multiple times is allowed,
672 in general you can use the same TCastleTransform instance multiple times in one hierarchy
673 of TCastleRootTransform. }
674 procedure Add(const Item: TCastleTransform);
675
676 { Insert a child at a specific position on the children list.
677
678 Note: Usually the order of children doesn't matter, so you can as well
679 add children at the end, using @link(Add).
680
681 In particular, when rendering opaque (3D or 2D) objects, the front/back
682 is decided by the actual translation of the object,
683 i.e. what is closer to the camera.
684 (In a typical 2D setup, larger Z values mean "closer to the camera".)
685 The position on the children list doesn't matter in this case.
686
687 When rendering with blending, we recommend to use
688 @link(TCastleViewport.BlendingSort) to automatically use
689 proper order when rendering partially-transparent objects.
690 This will mean that the order of children really doesn't matter.
691
692 However, the position matters in case of blending,
693 if you set @link(TCastleViewport.BlendingSort) to sortNone.
694 See https://castle-engine.io/blending .
695 For correct blending, when you have multiple partially-transparent scenes,
696 the partially-transparent objects must be sorted from back to front on the list.
697 So you should add them in the proper order, or insert on proper positions,
698 or use @link(SortBackToFront2D) on parent transformation. }
699 procedure Insert(const Index: Integer; const Item: TCastleTransform);
700
701 { Remove a child.
702
703 Adding and removing from the TCastleTransform hierarchy is guaranteed
704 to be fast, so you can do it even in the middle of the game.
705 In particular calling @link(Remove) doesn't free rendering reasources
706 of the removed scene,
707 So e.g. removing scene only to add it later to another
708 TCastleViewport.Items is fast.
709
710 Note that removing the child Item @italic(does not free the Item).
711 It merely makes the Item no longer be a child of this TCastleTransform,
712 so it will no longer be shown in the viewport.
713 If you want to free the item instance, you have to do it explicitly,
714 by @code(Item.Free) or @code(FreeAndNil(Item)).
715 Freed items are automatically removed from parent.
716 See also @url(https://castle-engine.io/castle_game_engine_for_unity_developers#_what_is_the_difference_between_owner_and_parent_in_cge
717 What is the difference between Owner and Parent in CGE?). }
718 procedure Remove(const Item: TCastleTransform);
719
720 { Use this to remove (and possibly free) the child, but not immediately.
721
722 The actual removal (and freeing, if FreeItem) will be done at some crucial points:
723
724 @unorderedList(
725 @itemSpacing Compact
726 @item Right before we render children.
727 @item Right before we loop over children in the @link(Update) method.
728 @item Right after we loop over children in the @link(Update) method.
729 @item From our destructor.
730 )
731
732 This allows to use this method safely even in the middle of iteration
733 over TCastleTransform children. For example you can use it from @link(Update) method,
734 from any TCastleTransform.Update or TCastleUserInterface.Update (including TCastleView.Update).
735
736 Note: It is not a problem if the child scheduled to be removed
737 will also be removed (or even freed) directly e.g. by just calling @code(Free) on it.
738 We ignore removal of items that are no longer
739 our children, and we automatically remove the child from "pending to remove" list
740 if it is freed. You only need to be careful in case you add the same TCastleTransform
741 instance multiple times to the same parent
742 (see https://castle-engine.io/viewport_and_scenes_from_code#_multiple_instances_of_the_same_scene )
743 as then each removal removes one instance (not all) of the child from parent.
744
745 Note: When you want to free the Item (that is, FreeItem parameter is @true)
746 then it actually doesn't matter on what parent will you call this.
747 Freeing the Item will always remove it from all parents. }
748 procedure RemoveDelayed(const Item: TCastleTransform; const FreeItem: Boolean = false);
749
750 { Remove a child, by index on the @link(Items) list. }
751 procedure Delete(const Index: Integer);
752
753 { List of current children. }
754 property Items[const I: Integer]: TCastleTransform read GetItem write SetItem; default;
755
756 { Count of current children, to iterate over @link(Items) from 0 to Count-1. }
757 function Count: Integer;
758
759 { Remove all children TCastleTransform instances.
760
761 Note that removing the children using this method,
762 just like using @link(Remove), @italic(does not free the children).
763 It merely makes the children no longer be inside this TCastleTransform,
764 so they will no longer be shown in the viewport.
765 If you want to free the children,
766 you have to do it explicitly, calling
767 @code(Item.Free) or @code(FreeAndNil(Item)) for each child.
768 Freed items are automatically removed from parent.
769 See also @url(https://castle-engine.io/castle_game_engine_for_unity_developers#_what_is_the_difference_between_owner_and_parent_in_cge
770 What is the difference between Owner and Parent in CGE?). }
771 procedure Clear;
772
773 { Exchange position of 2 children TCastleTransform instances. }
774 procedure Exchange(const Index1, Index2: Integer);
775
776 { Parent TCastleTransform.
777
778 In most cases, a TCastleTransform is just a child of one other
779 TCastleTransform, and then this property returns this natural parent.
780
781 Returns @nil if TCastleTransform is not a child of any other TCastleTransform.
782
783 Setting this property removes us from old parent,
784 and adds to the new one. The local transformation (translation, rotation, scale)
785 doesn't change, so changing parent may change the effective (world)
786 transformation of the object.
787
788 In rare cases the child can have multiple parents. The behavior is then:
789
790 @unorderedList(
791 @item(
792 It ignores (never returns) parents caused by referencing transform in
793 TCastleTransformReference.)
794
795 @item(
796 If there is (or was, at some point) more than 1 parent (not counting parents
797 caused by TCastleTransformReference) then it may return nil, or any of
798 the existing parents -- it is undefined which exactly.
799
800 In general, one TCastleTransform instance may be used
801 multiple times as a child of other TCastleTransform instances
802 (as long as they are all within the same TCastleViewport).
803 The parent TCastleTransform instances may include TCastleTransformReference
804 (this allows to create multiple references to one TCastleTransform from editor)
805 but in general any parents are allowed
806 (when you use code, you can just insert TCastleTransform as a child of other TCastleTransform,
807 without the need for TCastleTransformReference).
808
809 This property indicates the one parent that is @italic(not) TCastleTransformReference.
810 If there are multiple such parents (this is impossible at design-time in editor,
811 but it is possible at runtime if you add/remove TCastleTransform children by code)
812 then this returns @nil or any of existing parents.
813 )
814
815 @item(
816 Setting is not allowed if child has (or ever had) multiple parents.
817 The behavior is undefined.
818 )
819 ) }
820 property Parent: TCastleTransform read FParent write SetParent;
821
822 {$ifdef FPC}property UniqueParent: TCastleTransform read FParent; deprecated 'use Parent';{$endif}
823
824 { Sort objects back-to-front @italic(right now)
825 following the blending 2D sorting algorithm.
826 Only the immediate list items are reordered.
827
828 Calling this method makes sense if you use
829 @url(https://castle-engine.io/blending blending)
830 and set @link(TCastleViewport.BlendingSort) to sortNone,
831 and multiple partially-transparent objects may
832 be visible at the same place on the screen.
833 Sorting avoids artifacts when rendering.
834
835 @unorderedList(
836 @item(
837 In general, you should call this method whenever the correct back-to-front order
838 of objects (with respect to the current camera) changes.
839 )
840 @item(
841 In 2D, you typically need to call this only when some objects' Z value changed
842 (making this object move behind / in front of some other object),
843 or when new object is added.
844 You don't need to call this method when camera changes or when object's XY position
845 changes, as they don't affect the order.
846 )
847 )
848
849 Note that this doesn't take care of sorting the shapes
850 within the scenes. For this, you should set
851 @link(TCastleViewport.BlendingSort). }
852 procedure SortBackToFront2D;
853 deprecated 'use TCastleViewport.BlendingSort to sort objects for blending';
854
855 { Bounding box of this object, in the coordinate system of the parent transformation.
856 This method takes into account current transformation
857 (like @link(Translation), @link(Rotation))
858 but not parent TCastleTransform transformations.
859 Use @link(WorldBoundingBox) instead to know bounding box that accounts for all
860 TCastleTransform transformations.
861 Use @link(LocalBoundingBox) instead to know bounding box that does not account for
862 any parent or this TCastleTransform transformations.
863
864 Takes into account both collidable and visible objects.
865 For example, invisible walls (not visible) and fake walls
866 (not collidable) should all be accounted here.
867
868 It's a @italic(bounding) volume, it should be as large as necessary
869 to include the object inside. At the same time, it should be
870 as "tight" as it can, to make various optimizations work best.
871
872 @seealso WorldBoundingBox
873 @seealso LocalBoundingBox }
874 function BoundingBox: TBox3D;
875
876 { Bounding box of this object, ignoring the transformations of this scene and parents.
877
878 @seealso BoundingBox
879 @seealso WorldBoundingBox }
880 function LocalBoundingBox: TBox3D; virtual;
881
882 { Bounding box of this object, taking into account
883 all transformations of this and parents.
884
885 @seealso BoundingBox
886 @seealso LocalBoundingBox }
887 function WorldBoundingBox: TBox3D;
888
889 { Render given object.
890 Should check and immediately exit when @link(CheckVisible) is @false.
891
892 The rendering transformation, frustum, and filtering
893 is specified inside TRenderParams class.
894 This method should only update @code(TRenderParams.Statistics). }
895 procedure Render(const Params: TRenderParams); overload; virtual;
896
897 procedure Render(const Frustum: TFrustum; const Params: TRenderParams); overload;
898 deprecated 'use Render method without an explicit Frustum parameter, it is in Params.Frustum now';
899
900 { Does the 3D object cast shadows by shadow volumes.
901 See also TCastleScene.ReceiveShadowVolumes. }
902 property CastShadowVolumes: boolean
903 read FCastShadows write FCastShadows default true;
904 {$ifdef FPC}deprecated 'use CastShadows';{$endif}
905
906 { Render shadow quads for all the things rendered by @link(Render).
907 This is done only if @link(Exists) and @link(CastShadows).
908
909 It does shadow volumes culling inside (so ShadowVolumeRenderer should
910 have FrustumCullingInit already initialized).
911
912 Params.Transformation describe the transformation,
913 just like for @link(Render). }
914 procedure RenderShadowVolume(const Params: TRenderParams;
915 const ShadowVolumeRenderer: TBaseShadowVolumeRenderer);
916
917 { Prepare resources, making various methods (like rendering and such)
918 to execute fast.
919
920 It is usually simpler to call @link(TCastleViewport.PrepareResources)
921 then this method. Calling @code(Viewport.PrepareResources(MyScene))
922 will automatically call @code(MyScene.PrepareResources(...)) underneath,
923 with proper parameters.
924
925 It is best to call this when the rendering context is initailized,
926 e.g. at Application.OnInitialize or later.
927 Calling this method before the rendering context is initialized
928 (e.g. from initializaton section of some unit)
929 will have to skip some preparations, thus reducing the effectiveness
930 of this method. But it is allowed to call this at any time,
931 regardless of the context being initialized, just like e.g.
932 @link(TCastleContainer.LoadSettings) (which may call this, to warmup cache).
933
934 This makes sure that appropriate methods execute as fast as possible.
935 It's never required to call this method
936 --- everything will be prepared "as needed" anyway.
937 But if you allow everything to be prepared "as needed",
938 then e.g. the first @link(Render) call may take a long time because it may
939 have to prepare resources that will be reused in next @link(Render) calls.
940 This may make your program seem slow at the beginning
941 (when rendering resources are being prepared, so at the first frame,
942 or a couple of first animation frames). To avoid this, call this method,
943 showing the user something like "now we're preparing
944 the resources --- please wait".
945
946 @param(Options What features should be prepared to execute fast.
947 See TPrepareResourcesOption.)
948
949 @param(Params
950 Rendering parameters to prepare for.
951 It is used only if Options contains prRenderSelf or prRenderClones.
952 )
953
954 TODO: It is not possible to call this now without TPrepareParams,
955 and to get params you need to access deprecated TCastleViewport.PrepareParams.
956 We advise to call TCastleViewport.PrepareResources instead.
957 We'd like to get rid of TPrepareParams eventually.
958 }
959 procedure PrepareResources(const Options: TPrepareResourcesOptions;
960 const Params: TPrepareParams); virtual;
961
962 { Press and release events of key and mouse, passed only to instances that set ListenPressRelease.
963 Return @true if you handled the event, and it should not be passed to other objects.
964 See also TCastleUserInterface analogous events.
965 @groupBegin }
966 function Press(const Event: TInputPressRelease): boolean; virtual;
967 function Release(const Event: TInputPressRelease): boolean; virtual;
968 { @groupEnd }
969
970 { Are @link(Press) and @link(Release) virtual methods called. }
971 property ListenPressRelease: Boolean
972 read FListenPressRelease write SetListenPressRelease default false;
973
974 { Pointing device (mouse or touch) events, you can override these to handle pointing device events.
975 These methods are automatically called by the TCastleViewport.
976 They are exposed here only to allow overriding them.
977 Return @true if you handled the event.
978
979 @unorderedList(
980 @item(PointingDevicePress signals that the picking button (usually,
981 left mouse button) was pressed.
982
983 Note that the exact key or mouse responsible for this is configurable
984 in our engine by Input_Interact. By default it's the left mouse button,
985 as is usual for VRML/X3D browsers. But it can be configured to be other
986 mouse button or a key, for example most 3D games use "e" key to interact.
987 )
988
989 @item(PointingDeviceRelease signals that the picking button is released.
990
991 An extra parameter CancelAction indicates
992 whether this pointing device "press and release" sequence may be
993 considered a "click". When CancelAction = @true, then you should not make
994 a "click" event (e.g. TouchSensor should not send touchTime event etc.).
995 )
996
997 @item(PointingDeviceMove signals that pointer moves over this object.)
998 )
999
1000 They receive Pick information (TRayCollisionNode) about what exactly is hit
1001 by the 3D ray corresponding to the current pointing device position.
1002 It contains the detailed information about the point, triangle
1003 and ray (all in local coordinate system of this TCastleTransform) that are indicated
1004 by the pointing device.
1005 TRayCollisionNode.Triangle is @nil when it was not possible to determine,
1006 and TRayCollisionNode.Point is undefined in this case.
1007
1008 They also receive Distance to the collision point,
1009 in world coordinates. See TRayCollision.Distance.
1010 The Distance may be MaxSingle when it was not possible to determine.
1011
1012 There is a concept of a TCastleTransform that is currently "capturing"
1013 the pointing device events. Once TCastleTransform
1014 handles TCastleTransform.PointingDevicePress (returns @true for it),
1015 it captures the following PointingDeviceMove and PointingDeviceRelease events,
1016 regardless if ray still hits this TCastleTransform instance.
1017 The "capturing" instance of TCastleTransform is informed first about
1018 pointing device move/release.
1019
1020 After the "capturing" instance,
1021 every pointing device event (press, release or move) is send to the leaf
1022 in TCastleTransform hierarchy (usually a TCastleScene) that is under the mouse/touch
1023 position.
1024 If the event is not handled, it is passed to other objects under the mouse/touch
1025 position.
1026
1027 The PointingDeviceMove event is also always passed to @link(TCastleRootTransform.MainScene)
1028 at the end (if it wasn't already the "capturing" transform,
1029 or under the mouse/touch position).
1030 This way @link(TCastleRootTransform.MainScene) is always informed about pointing device movement.
1031
1032 These methods are called only if the object Exists.
1033 There's no need to check this condition inside the method implementation.
1034
1035 @groupBegin }
1036 function PointingDevicePress(const Pick: TRayCollisionNode;
1037 const Distance: Single): Boolean; virtual;
1038 function PointingDeviceRelease(const Pick: TRayCollisionNode;
1039 const Distance: Single; const CancelAction: Boolean): Boolean; virtual;
1040 function PointingDeviceMove(const Pick: TRayCollisionNode;
1041 const Distance: Single): Boolean; virtual;
1042 { @groupEnd }
1043
1044 { Continuously occuring event, for various tasks.
1045
1046 Executed only on instances that have @link(Exists) (no need to check this
1047 in overridden Update implementation).
1048
1049 @param(RemoveMe Set this to rtRemove or rtRemoveAndFree to remove
1050 this item from parent after this call finished.
1051 rtRemoveAndFree additionally will free this item.
1052 Initially it's rtNone when this method is called.
1053
1054 You can also use RemoveDelayed from parent for similar effect.
1055 ) }
1056 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); virtual;
1057
1058 { Called on update.
1059 Update listeners fire after all behaviors have been processed. }
1060 procedure AddAfterUpdateListener(const UpdateListener: TNotifyEvent);
1061 procedure RemoveAfterUpdateListener(const UpdateListener: TNotifyEvent);
1062
1063 { Something visible changed inside @italic(this) object.
1064 This is usually called by implementation of this object,
1065 to notify others that it changed.
1066
1067 Changes is a set describing what changes occurred.
1068 See TVisibleChange docs for more information.
1069 It must specify all things that possibly changed.
1070
1071 Changes can be [], meaning "something tells us to redraw, but no visible change
1072 happened yet, maybe something will happen during a redraw"
1073 (this is used when e.g. possibly LOD level changed).
1074 We still increase TCastleAbstractRootTransform.InternalVisibleStateId
1075 even when Changes=[].
1076
1077 The information about visibility changed is passed to TCastleAbstractRootTransform
1078 in @link(World).
1079 It increases @link(TCastleAbstractRootTransform.InternalVisibleStateId),
1080 @link(TCastleAbstractRootTransform.InternalVisibleGeometryStateId),
1081 @link(TCastleAbstractRootTransform.InternalVisibleNonGeometryStateId).
1082 If you want to @italic(react) to visibility changes,
1083 you should not override this method, instead watch above "state id" variables
1084 and react when they change. }
1085 procedure VisibleChangeHere(const Changes: TVisibleChanges); virtual;
1086
1087 { Root transformation (TCastleAbstractRootTransform) containing us.
1088 @nil if we are not (yet) part of some hierarchy rooted in TCastleAbstractRootTransform. }
1089 property World: TCastleAbstractRootTransform read FWorld;
1090
1091 { Called when rendering context is destroyed.
1092 This will be also automatically called from destructor.
1093 Object should clear here any resources that are connected to the rendering context. }
1094 procedure GLContextClose; virtual;
1095
1096 { Middle point, usually "eye point", of the 3D model.
1097 This is used for sphere center
1098 (if @link(CollisionSphereRadius) is non-zero or @link(Sphere) returns @true)
1099 and is the central point from which collisions of this object
1100 are checked (Move, MoveAllowed, Height, LineOfSight).
1101 It's useful for dynamic objects like player and moving creatures,
1102 which rely on @link(MoveAllowed) and gravity.
1103
1104 In short, it's usually most comfortable to think about this as
1105 a position of the eye, or the middle of the creature's head.
1106
1107 In an ideal situation, it should not be based on anything dynamic.
1108 For example, when this is based on the current bounding box of the animation,
1109 there is a risk that a large and sudden change in animation
1110 box could make the Middle point to jump to the other side of
1111 the wall (breaking collisions, as it changes Middle without a chance
1112 to check for collisions by MoveAllowed).
1113 Ideally, it should remain constant even when the shape of the object changes,
1114 and be possible to change only when MoveAllowed is checked
1115 (so only when @link(TCastleTransform.Translation) can change).
1116
1117 In this class this returns something sensible above the bottom
1118 of the box. See @link(TCastleTransform.MiddleHeight).
1119
1120 This is expressed in the parent coordinate system
1121 (so it is close to the @link(Translation) value, but moved up, following GravityUp).
1122 It ignores parent transformations (using @code(Transform.Parent.LocalToWorld(Transform.Middle))
1123 to convert this to world coordinates. }
1124 function Middle: TVector3; virtual;
1125
1126 { Can the approximate sphere (around Middle point)
1127 be used for some collision-detection
1128 tasks. If @true then Radius (and Middle point) determine the approximate
1129 sphere surrounding the 3D object (it does not have to be a perfect
1130 bounding sphere around the object), and it may be used for some
1131 collisions instead of BoundingBox.
1132 See @link(CollidesWithMoving) and @link(MoveAllowed) for when it may happen.
1133
1134 Just like @link(Middle) and @link(CollisionSphereRadius), this is expressed in the parent coordinate system.
1135
1136 Must return @false when not Exists (because we can't express
1137 "empty sphere" by @link(Sphere) method for now, but BoundingBox can express
1138 TBox3D.Empty).
1139
1140 By default, in TCastleTransform class, this returns @true if @link(CollisionSphereRadius)
1141 is non-zero.
1142
1143 The advantages of using a sphere, that does not have to be a perfect
1144 bounding sphere (it may be smaller than necessary, and only
1145 account e.g. for upper body part of the creature), are:
1146
1147 @unorderedList(
1148 @item(It can have constant radius, even though the actual
1149 creature animates. This allows us to perfectly, reliably guarantee
1150 that sphere absolutely never collides with level and such.
1151
1152 In case of a tight bounding volume (box or sphere) that animates,
1153 this guarantee is not really possible. Simply increasing time changes
1154 the animation to the next frame, which may be slightly larger
1155 in one dimension because e.g. creature moves a hand in this direction.
1156 This means that simply increasing time may change the non-collidable
1157 creature into a collidable one, if creature stands close to a wall/other
1158 creature and such. And we cannot simply stop/reverse an arbitrary animation
1159 at an arbitrary time (to avoid collision), this would look weird
1160 for some animations and would require some additional work
1161 at preparing animations and designing AI (as then "every action can
1162 be interrupted").
1163
1164 Also using a bounding volume large enough to account for all
1165 possible positions is not doable, as it would be too large.
1166 Consider that for humanoid creatures, walking animation usually
1167 has tall and thin bounding box (creature stands) but dead/lying animation
1168 usually has flat and wide bounding box.
1169
1170 So, only a bounding volume (like a sphere) that
1171 @italic(may be smaller than bounding volume) can remain constant
1172 and easily guarantee the assertion "it never collides".
1173
1174 This means that using such sphere results in simpler collision
1175 detection routines, as they may assume that collision doesn't occur.
1176 In contrast, detection routines looking at our (possibly animated)
1177 BoundingBox must take into account that collision may already be happening,
1178 and they must incorporate code to allow creatures/players to "get unstruck".)
1179
1180 @item(Using smaller sphere also allows to naturally ascend the stairs
1181 and upward slopes. Sphere can move forward slightly, and then creature
1182 may raise up, to reach it's preferred height. Then sphere can move
1183 further forward, and so on. This alllows to allow stair climbing
1184 for creatures without any extra effort in the code.
1185
1186 The downside is that creature legs will temporarily "sink into the floor"
1187 when climbing up the stairs. But it's not noticeable if "growing up"
1188 mechanism works fast enough.)
1189 )
1190
1191 Sphere disadvantage:
1192
1193 @unorderedList(
1194 @item(Sphere is far from perfect as a bounding volume --- it's too small,
1195 sometimes also too large, sometimes both at the same time...
1196
1197 Since the Sphere radius remains always the same, it must be good
1198 for many creature animation frames. In cases where the sphere
1199 isn't suitable, and you don't need advantages above --- you can
1200 make @name return @false.
1201 E.g. a dead creature may be stuck in a wall,
1202 and it doesn't have to climb stairs. So you don't really need
1203 sphere advantages listed above, and @name may return @false
1204 when creature is in dying state.
1205
1206 But still it may be a problem sometimes, if some creature states
1207 have entirely different animations and bounding boxes. Then you
1208 will be forced to choose one universal Radius for all creature
1209 states. And you need constant radius to keep the advantage above
1210 of "guarantee".
1211
1212 1. Obviously you can't set radius too small, because if it's much smaller
1213 than actual creature's geometry then the creature will noticeably collide
1214 with level geometry and other creatures.
1215
1216 2. On the other hand, you can't set radius too large
1217 (or move sphere center, Middle, much lower).
1218 This would block stair climbing.
1219 )
1220 ) }
1221 function Sphere(out Radius: Single): boolean; virtual;
1222
1223 { Can this object be pushed by (or block movement of) doors, elevators
1224 and other moving level parts (TCastleMoving instances).
1225
1226 Some 3D moving objects may try to avoid crushing this item.
1227 Like an automatic door that stops it's closing animation
1228 to not crush things standing in the doorway.
1229
1230 Some other 3D moving objects may push this object.
1231 Like elevators (vertical, or horizontal moving platforms).
1232 We may use sphere (see @link(CollisionSphereRadius) and @link(Sphere)) for checking
1233 collisions, or bounding box (@link(TCastleTransform.BoundingBox)), depending on need. }
1234 property CollidesWithMoving: boolean read FCollidesWithMoving write FCollidesWithMoving default false;
1235
1236 { Get height of my point above the rest of the world.
1237
1238 The given MyPosition, and returned AboveHeight, are in the parent
1239 coordinate system of this TCastleTransform.
1240 So for example query like this works naturally:
1241 @code(MyTransform.Height(MyTransform.Translation, ...)).
1242
1243 This ignores the geometry of this 3D object (to not accidentally collide
1244 with your own geometry), and checks collisions with the rest of the world.
1245 @groupBegin }
1246 function Height(const MyPosition: TVector3;
1247 out AboveHeight: Single): boolean; overload;
1248 function Height(const MyPosition: TVector3;
1249 out AboveHeight: Single; out AboveGround: PTriangle): boolean; overload;
1250 { @groupEnd }
1251
1252 { Whether there is line of sight (the line segment does not collide with anything
1253 opaque) between these 2 points.
1254
1255 The given Pos1, Pos2 are in the parent
1256 coordinate system of this TCastleTransform.
1257 So for example query like this works naturally:
1258 @code(MyTransform.LineOfSight(MyTransform.Translation, MyTransform.Translation + MyTransform.Direction * 10)).
1259
1260 This ignores the geometry of this 3D object (to not accidentally collide
1261 with your own geometry), and checks collisions with the rest of the world. }
1262 function LineOfSight(const Pos1, Pos2: TVector3): boolean;
1263
1264 { Is the move from OldPos to ProposedNewPos possible for this object.
1265 Returns true and sets NewPos if some move is allowed.
1266
1267 The NewPos may be different than ProposedNewPos,
1268 which allows to perform wall-sliding.
1269 Wall sliding will only work if collision sphere is defined,
1270 which should be configured by setting CollisionSphereRadius to something non-zero.
1271 Otherwise, the move uses only box collisions, and wall sliding doesn't happen.
1272
1273 When checking collisions, it avoids colliding with itself,
1274 so it only checks collisions with the rest of the world (things outside of this TCastleTransform).
1275
1276 The given OldPos, ProposedNewPos, NewPos are in the parent
1277 coordinate system of this TCastleTransform.
1278 Intuitively, you are asking @italic("Can I change @link(Translation)
1279 from OldPos to NewPos").
1280 So this method is consistent with @link(Move), @link(Translate). }
1281 function MoveAllowed(const OldPos, ProposedNewPos: TVector3;
1282 out NewPos: TVector3;
1283 const BecauseOfGravity: boolean): boolean; overload;
1284
1285 { Is the move from OldPos to NewPos possible for this object.
1286
1287 This overloaded version of MoveAllowed doesn't do wall-sliding
1288 (use the version with ProposedNewPos for wall-sliding).
1289
1290 If this object allows to use sphere for collisions
1291 (see @link(CollisionSphereRadius) and @link(Sphere)) then sphere will be used.
1292 Otherwise, it will collide as a bounding box.
1293
1294 When checking collisions, it avoids colliding with itself,
1295 so it only checks collisions with the rest of the world (things outside of this TCastleTransform).
1296
1297 The given OldPos, NewPos are in the parent
1298 coordinate system of this TCastleTransform.
1299 Intuitively, you are asking @italic("Can I change @link(Translation)
1300 from OldPos to NewPos").
1301 So this method is consistent with @link(Move), @link(Translate). }
1302 function MoveAllowed(const OldPos, NewPos: TVector3;
1303 const BecauseOfGravity: boolean): boolean; overload;
1304
1305 { Check for ray collisions within this TCastleTransform and children.
1306 @exclude }
1307 function InternalRayCollision(const RayOrigin, RayDirection: TVector3): TRayCollision;
1308
1309 { Cast a ray, see what is hit (checks the whole world, not just this TCastleTransform hierarchy).
1310
1311 The given RayOrigin, RayDirection are in the parent
1312 coordinate system of this TCastleTransform.
1313 So for example query like this works naturally:
1314 @code(MyTransform.Ray(MyTransform.Translation, MyTransform.Direction)).
1315
1316 This ignores the geometry of this object (to not accidentally collide
1317 with your own geometry), and checks collisions with the rest of the world. }
1318 function Ray(const RayOrigin, RayDirection: TVector3): TRayCollision;
1319
1320 { Cast a ray, see what is hit (checks the whole world, not just this TCastleTransform hierarchy).
1321
1322 The given RayOrigin, RayDirection are in the parent
1323 coordinate system of this TCastleTransform.
1324 So for example query like this works naturally:
1325 @code(MyTransform.RayCast(MyTransform.Translation, MyTransform.Direction)).
1326 In case of the overloaded version with Distance parameter,
1327 the Distance is consistently in the same, parent coordinate system.
1328
1329 This ignores the geometry of this object (to not accidentally collide
1330 with your own geometry), and checks collisions with the rest of the world.
1331
1332 This returns the TCastleTransform that is hit (this is the "leaf" TCastleTransform
1333 in the TCastleTransform tree that is hit)
1334 and a distance from RayOrigin to the hit point.
1335 Returns @nil (Distance is undefined in this case) if nothing was hit.
1336 Use @link(Ray) for a more advanced version of this, with more complicated result.
1337 @groupBegin }
1338 function RayCast(const RayOrigin,
1339 RayDirection: TVector3): TCastleTransform; overload;
1340 function RayCast(const RayOrigin, RayDirection: TVector3;
1341 out Distance: Single): TCastleTransform; overload;
1342 { @groupEnd }
1343
1344 { Convert position between local and outside coordinate system.
1345 This is called OutsideToLocal, not WorldToLocal, because it only handles transformation
1346 defined in this item --- it does not recursively apply all transform on the way to root.
1347 @groupBegin }
1348 function OutsideToLocal(const Pos: TVector3): TVector3;
1349 function LocalToOutside(const Pos: TVector3): TVector3;
1350 { @groupEnd }
1351
1352 { Convert position between local and world coordinate system.
1353 This applies all the transformations on the way to root,
1354 so it looks at this object as well as all parents' transformations.
1355 @groupBegin }
1356 function WorldToLocal(const Pos: TVector3): TVector3;
1357 function LocalToWorld(const Pos: TVector3): TVector3;
1358 { @groupEnd }
1359
1360 { Convert direction between local and world coordinate system.
1361 This applies all the transformations on the way to root,
1362 so it looks at this object as well as all parents' transformations.
1363 @groupBegin }
1364 function WorldToLocalDirection(const Dir: TVector3): TVector3;
1365 function LocalToWorldDirection(const Dir: TVector3): TVector3;
1366 { @groupEnd }
1367
1368 { Convert distance, like sphere radius, between local and world coordinate system.
1369 This applies all the scaling on the way to root,
1370 so it looks at this object as well as all parents' transformations.
1371 @groupBegin }
1372 function LocalToWorldDistance(const Distance: Single): Single;
1373 function WorldToLocalDistance(const Distance: Single): Single;
1374 { @groupEnd }
1375
1376 { Gravity may make this object fall down (see FallSpeed)
1377 or grow up (see GrowSpeed). See also PreferredHeight.
1378
1379 Special notes for TPlayer: player doesn't use this (TPlayer.Gravity
1380 should remain @false), instead player relies on
1381 TPlayer.Navigation.Gravity = @true, that does a similar thing (with some
1382 extras, to make camera effects). This will change in the future,
1383 to merge these two gravity implementations.
1384 Although the TPlayer.Fall method still works as expected
1385 (it's linked to TCastleWalkNavigation.OnFall in this case). }
1386 property Gravity: boolean read FGravity write FGravity default false;
1387 {$ifdef FPC}deprecated 'use physics (TCastleRigidBody, TCastleCollider) to make things affected by gravity';{$endif}
1388
1389 { Falling speed, in units per second, for @link(Gravity).
1390
1391 This is relevant only if @link(Gravity) and PreferredHeight <> 0.
1392 0 means no falling. }
1393 property FallSpeed: Single read FFallSpeed write FFallSpeed {$ifdef FPC}default 0{$endif};
1394 {$ifdef FPC}deprecated 'use physics (TCastleRigidBody, TCastleCollider) to make things affected by gravity';{$endif}
1395
1396 { Growing (raising from crouching to normal standing position)
1397 speed, in units per second.
1398 This is used by non-flying creatures when climbing up stairs,
1399 in which case @link(Translation) ("legs positon") may be sometimes under
1400 the ground while Middle ("eyes position") will be always above the ground
1401 and will try to grow to be at PreferredHeight above the ground.
1402
1403 This is relevant only if @link(Gravity) and PreferredHeight <> 0.
1404 0 means no growing. }
1405 property GrowSpeed: Single read FGrowSpeed write FGrowSpeed {$ifdef FPC}default 0{$endif};
1406 {$ifdef FPC}deprecated 'use physics (TCastleRigidBody, TCastleCollider) to make things affected by gravity';{$endif}
1407
1408 { The preferred height of the object @link(Middle) above the ground,
1409 when the object is standing on the ground firmly.
1410 This is used by objects affected by gravity (like non-flying creatures
1411 and items) to know how far they should fall down or grow up.
1412
1413 The default implementation in this class looks at MiddleHeight property,
1414 see the algorithm described there.
1415 This may be dynamic (may change during creature lifetime,
1416 so you can make the creature duck or grow if you want). }
1417 function PreferredHeight: Single; virtual;
1418 {$ifdef FPC}deprecated 'use physics (TCastleRigidBody, TCastleCollider) to make things affected by gravity';{$endif}
1419
1420 { How high are creature eyes in the model.
1421 Value 0 means that eyes are at the bottom of the model,
1422 0.5 means the middle, 1 means top.
1423
1424 The @italic(top) is always considered to be at the top of the bounding box.
1425
1426 Definition of @italic(bottom) depends on @link(Gravity):
1427
1428 @unorderedList(
1429 @item(
1430 When Gravity is @true, then the @italic(bottom) is considered to be
1431 the plane where World.GravityCoordinate (like Z or Y axis) is zero.
1432 The actual bottom (lowest point) of the bounding box doesn't matter.
1433 This means that things placed below zero plane (like a creature tentacle
1434 or leg) will sink into the ground, instead of causing whole creature
1435 to move up. It also means that the creature can easily float above
1436 the ground, just model it a little above the zero plane.
1437
1438 In other words, this allows you to model the creature
1439 with respect to the ground (zero plane), which is comfortable.
1440
1441 Note that setting MiddleHeight to exact 0 means that gravity will not work,
1442 as it means that the PreferredHeight above the ground
1443 is to be stuck right at the ground level.
1444
1445 For gravity to work right, the MiddleHeight should be large enough
1446 to cause PreferredHeight to be > @link(Sphere) radius,
1447 for all possible animation states (for all possible bounding box values).
1448 )
1449
1450 @item(
1451 When Gravity is @false, then the @italic(bottom) is considered
1452 at the bottom of the bounding box.
1453
1454 This way it works regardless of where (0,0,0) is in your model
1455 (regardless if (0,0,0) represents legs, or middle of your creature),
1456 since we adjust to the BoundingBox position.
1457 )
1458 )
1459
1460 This property determines how the TCastleTransform
1461 handles the @link(Middle) implementation
1462 (this is the point used for various collision detection routines)
1463 and @link(PreferredHeight) (this is the preferred height of @link(Middle)
1464 above the ground). You can override these two methods to use a different
1465 approach, and then ignore MiddleHeight completely. }
1466 property MiddleHeight: Single read FMiddleHeight write FMiddleHeight
1467 {$ifdef FPC}default DefaultMiddleHeight{$endif};
1468
1469 { Transformation (from local to outside) as a matrix.
1470 This matrix represents a concise version of properties like @link(Translation),
1471 @link(Rotation), @link(Scale). It does not take into account the
1472 transformation of parent TCastleTransform (for this, use @link(WorldTransform)). }
1473 function Transform: TMatrix4;
1474
1475 { Inverse transformation as a matrix, thus transforming from outside to local
1476 coordinate system. This is an inverse of @link(Transform). }
1477 function InverseTransform: TMatrix4;
1478
1479 { All conditions are satisfied to have @link(WorldTransform).
1480 When this returns @true, you know that @link(WorldTransform)
1481 and @link(WorldInverseTransform) will not raise @link(ETransformParentUndefined). }
1482 function HasWorldTransform: boolean;
1483
1484 { Transformation (from local to world) as a matrix.
1485 This accumulates the transformation of this instance
1486 (derived from properties like @link(Translation), @link(Rotation), @link(Scale))
1487 with the transformation of parent @link(TCastleTransform) instances,
1488 all the way up to and including the root transformation
1489 (@link(TCastleAbstractRootTransform)).
1490 Thus, this is a transformation to the world known to the
1491 @link(TCastleViewport) instance.
1492
1493 Two conditions are necessary to make this available:
1494
1495 @unorderedList(
1496 @item(
1497 This instance must be part of some @link(World).
1498 So it must be added to @link(TCastleViewport.Items Viewport.Items),
1499 or to some other @link(TCastleTransform) that is part of @link(World).
1500
1501 Otherwise reading this raises @link(ENotAddedToWorld).
1502 )
1503
1504 @item(
1505 This instance must not be present multiple times inside the @link(World).
1506 Ever (even in the past).
1507
1508 In general, it is allowed to have multiple references to the same TCastleTransform
1509 within the same @link(World). So you can add
1510 the same TCastleTransform or TCastleScene many times to
1511 @link(TCastleViewport.Items Viewport.Items).
1512 This is a useful optimization (sharing), and is explicitly allowed.
1513 But if you do this --- you cannot rely on WorldTransform property.
1514
1515 Otherwise reading this raises @link(EMultipleReferencesInWorld)
1516 or @link(ETransformParentUndefined).
1517 )
1518 )
1519
1520 You can check HasWorldTransform before calling this method,
1521 to avoid catching an exception.
1522
1523 Note that the WorldTransform is not updated in @link(Update),
1524 it is smartly updated on-demand.
1525 So you do not have to wait for @link(Update) or other method to be called
1526 before accessing the @link(WorldTransform).
1527
1528 @raises(ENotAddedToWorld
1529 When this instance is not yet part of @link(World).)
1530 @raises(EMultipleReferencesInWorld
1531 When this instance is added multiple times to @link(World).)
1532 @raises(ETransformParentUndefined
1533 When this instance was once added multiple times to @link(World),
1534 or for some other reason cannot be calculated.
1535 This is an ancestor of ENotAddedToWorld and EMultipleReferencesInWorld
1536 too.)
1537 }
1538 function WorldTransform: TMatrix4;
1539
1540 { Inverse transformation of @link(WorldTransform),
1541 thus transforming from world to local coordinate system.
1542
1543 See @link(WorldTransform) for more details how this works.
1544
1545 @raises(ENotAddedToWorld
1546 When this instance is not yet part of @link(World).)
1547 @raises(EMultipleReferencesInWorld
1548 When this instance is added multiple times to @link(World).)
1549 @raises(EMultipleReferencesInWorld
1550 When this instance was once added multiple times to @link(World),
1551 or for some other reason cannot be calculated.
1552 This is an ancestor of ENotAddedToWorld and EMultipleReferencesInWorld
1553 too.)
1554 }
1555 function WorldInverseTransform: TMatrix4;
1556
1557 { Unconditionally move this object by a given vector.
1558
1559 To move and check collisions, use @link(Move) instead of this method.
1560
1561 The provided TranslationChange should be a direction in the parent
1562 coordinate system of this TCastleTransform.
1563 Using this routine is exactly equivalent to
1564 @code(Translation := Translation + TranslationChange). }
1565 procedure Translate(const TranslationChange: TVector3);
1566
1567 { Move, if possible (checking collisions with other objects in world).
1568 This is the simplest way to move an object,
1569 and a basic building block for artificial intelligence of creatures.
1570
1571 Checks move possibility by MoveAllowed, using @link(Middle) point.
1572 Actual move is done using @link(Translate).
1573
1574 Note that wall sliding will only work if collision sphere is defined,
1575 which should be configured by setting CollisionSphereRadius to something non-zero.
1576 Otherwise, the move uses only box collisions, and wall sliding doesn't happen.
1577
1578 The provided TranslationChange should be a direction in the parent
1579 coordinate system of this TCastleTransform,
1580 so using this routine is consistent with doing
1581 @code(Translation := Translation + TranslationChange)
1582 however this checks collisions. }
1583 function Move(const TranslationChange: TVector3;
1584 const BecauseOfGravity: boolean;
1585 const EnableWallSliding: boolean = true): boolean;
1586
1587 { Translation (move) the children. Zero by default.
1588
1589 Set it like this:
1590 @longCode(#
1591 Scene.Translation := Vector3(1, 2, 3);
1592 Scene.Translation := Scene.Translation + Vector3(4, 5, 6);
1593 #) }
1594 property Translation: TVector3 read FTranslation write SetTranslation;
1595
1596 { Get or set the XY components of the translation.
1597 Useful for 2D games. }
1598 property TranslationXY: TVector2 read GetTranslationXY write SetTranslationXY;
1599
1600 { Center point around which the @link(Rotation) and @link(Scale) is performed. }
1601 property Center: TVector3 read FCenter write SetCenter;
1602
1603 { Rotation in 3D, around a specified axis.
1604 Rotation is expressed as a 4D vector, in which the first 3 components
1605 specify the rotation axis (does not need to be normalized, but must be non-zero)
1606 and the last component is the rotation angle @italic(in radians).
1607
1608 Note: the Rotation axis (first 3 components) must not be a zero vector,
1609 however as a special case the rotation value @code(TVector4.Zero) (so all components,
1610 axis and angle, are zero) is also allowed.
1611
1612 Rotation is done around @link(Center).
1613
1614 Set it like this:
1615
1616 @longCode(#
1617 Scene.Rotation := Vector4(0, 0, 1, Pi / 10);
1618 Scene.Rotation := Scene.Rotation + Vector4(0, 0, 0, Pi / 10);
1619 #)
1620
1621 To combine multiple rotations, you can use @italic(quaternion multiplication).
1622 For example to combine a rotation around Y axis with rotation around Z axis,
1623 you can do this:
1624
1625 @longCode(#
1626 var
1627 Q, Q1, Q2: TQuaternion;
1628 begin
1629 Q1 := QuatFromAxisAngle(Vector3(0, 1, 0), 0.123);
1630 Q2 := QuatFromAxisAngle(Vector3(0, 0, 1), 0.456);
1631 Q := Q1 * Q2;
1632 MyTransform.Rotation := Q.ToAxisAngle;
1633 end;
1634 #)
1635
1636 Combining rotations this way is very flexible. You can combine
1637 as many as you want, and it is clear (you define it yourself)
1638 in which order each rotation is applied.
1639 Note that you can also just nest one TCastleTransform within
1640 another TCastleTransform, and set different rotations on each of them,
1641 to also effectively combine the rotations. }
1642 property Rotation: TVector4 read FRotation write SetRotation;
1643
1644 { Scale in 3D. Scaling is done around @link(Center)
1645 and with orientation given by @link(ScaleOrientation).
1646
1647 We do the best we can to work with @italic(any) scale value,
1648 even negative or zero. But usually, it's best to keep the scale
1649 positive. More information:
1650
1651 @orderedList(
1652 @item(If you can, keep the scale uniform, that is scale equal amount
1653 in X, Y and Z. For example set scale = @code((3.0, 3.0, 3.0))
1654 to scale 3x times, and avoid scale like @code((3.0, 1.0, 1.0))
1655 that scales more in one direction.
1656
1657 Non-uniform scale works, but some collisions are not perfectly
1658 calculated then:
1659
1660 @unorderedList(
1661 @item(Sphere collision routines
1662 @link(TCastleAbstractRootTransform.WorldSphereCollision),
1663 @link(TCastleAbstractRootTransform.WorldSphereCollision2D)
1664 only do an approximation in case of non-uniform scale.)
1665
1666 @item(The physics engine also doesn't support non-uniform scale.
1667 Descendants of @link(TCastleCollider) may assume that scale
1668 is uniform, and use an approximation (average) of the actual 3D
1669 scale when necessary.)
1670 )
1671
1672 Note that @link(ScaleOrientation) matters only in case of non-uniform scale.
1673 )
1674
1675 @item(All scale components should > 0 if you want 3D lighting
1676 to work corrrectly. That is, avoid negative scale, that changes
1677 the normals and orientation of faces (counter-clockwise becomes clockwise,
1678 if all scale components are -1), or standard
1679 lighting may not work Ok.
1680
1681 For unlit stuff, or custom lighting, negative scale may be Ok.
1682 For many 2D games that use no lighting/custom lighting,
1683 negative scale is Ok.
1684
1685 If you really need to use negative scale and lighting,
1686 enable @link(TCastleRenderOptions.RobustNegativeScale).)
1687
1688 @item(At least, keep all scale components non-zero.
1689 Otherwise the scaling operation is not invertible,
1690 and generally collisions will not work correctly.
1691
1692 If you really need to set zero scale, the object should not be collidable then.
1693 Set @link(Collides) = @false and don't add @link(TCastleCollider) as a behavior.)
1694 )
1695
1696 Set it like this:
1697 @longCode(#
1698 Scene.Scale := Vector3(5, 5, 5);
1699 Scene.Scale := Scene.Scale * 1.5;
1700 #) }
1701 property Scale: TVector3 read FScale write SetScale;
1702
1703 { Orientation in which 3D @link(Scale) is performed. }
1704 property ScaleOrientation: TVector4 read FScaleOrientation write SetScaleOrientation;
1705
1706 { Make the transform do nothing --- zero @link(Translation), zero @link(Rotation),
1707 @link(Scale) to one. Also resets @link(ScaleOrientation). }
1708 procedure Identity;
1709
1710 { Current TCastleRigidBody behavior that determines do we
1711 participate in the physics simulation.
1712
1713 This property is always exactly equivalent to using
1714 @code(FindBehavior(TCastleRigidBody) as TCastleRigidBody).
1715 It is just a more convenient (and marginally faster) way to access this
1716 common behavior.
1717
1718 See @url(https://castle-engine.io/physics physics manual)
1719 for an overview of using physics. You need to add both
1720 TCastleRigidBody and TCastleCollider to make physics work.
1721 Then this object is collidable with other rigid bodies,
1722 it can move and rotate because of gravity
1723 or because of collisions with other objects
1724 (if @link(TCastleRigidBody.Dynamic) is @true).
1725
1726 It is not possible to set this property.
1727 Instead use @link(AddBehavior)
1728 to add an instance of TCastleRigidBody to the behaviors list.
1729 If there was a previous TCastleRigidBody instance, you can decide what
1730 to do with it, e.g. you can remove it using @link(RemoveBehavior).
1731
1732 Note that an object can only be present once in the @link(World)
1733 to be a rigid body. Breaking this rule will cause the
1734 @link(EMultipleReferencesInWorld) exception at an undefined time. }
1735 property RigidBody: TCastleRigidBody read FCachedRigidBody;
1736
1737 { Current TCastleCollider behavior that determines what is
1738 the shape of this object when it participates in the physics simulation.
1739
1740 This property is always exactly equivalent to using
1741 @code(FindBehavior(TCastleCollider) as TCastleCollider).
1742 It is just a more convenient (and marginally faster) way to access this
1743 common behavior.
1744
1745 See @url(https://castle-engine.io/physics physics manual)
1746 for an overview of using physics. You need to add both
1747 TCastleRigidBody and TCastleCollider to make physics work.
1748 Then this object is collidable with other rigid bodies,
1749 it can move and rotate because of gravity
1750 or because of collisions with other objects
1751 (if @link(TCastleRigidBody.Dynamic) is @true).
1752
1753 It is not possible to set this property.
1754 Instead use @link(AddBehavior)
1755 to add an instance of TCastleCollider to the behaviors list.
1756 If there was a previous TCastleCollider instance, you can decide what
1757 to do with it, e.g. you can remove it using @link(RemoveBehavior).
1758
1759 Note that an object can only be present once in the @link(World)
1760 to be a rigid body. Breaking this rule will cause the
1761 @link(EMultipleReferencesInWorld) exception at an undefined time. }
1762 property Collider: TCastleCollider read FCachedCollider;
1763
1764 { @deprecated Deprecated name for Translation. }
1765 property Position: TVector3 read FTranslation write SetTranslation;
1766 {$ifdef FPC}deprecated 'use Translation';{$endif}
1767
1768 { Direction that this transformation (like creature, space ship, missile, a camera...) is facing.
1769 The property @link(Up) contains an associated up vector.
1770 Together, the @link(Direction) and @link(Up) properties provide an alternative way
1771 to get and set the @link(Rotation) of the transformation.
1772
1773 Thinking in terms of "direction" and "up" is more natural than thinking
1774 about @link(Rotation) for various game objects.
1775 For example, you can move a missile forward by this simple operation:
1776
1777 @longCode(#
1778 MyMissile.Translation := MyMissile.Translation +
1779 MyMissile.Direction * SecondsPassed * MissileMoveSpeed;
1780 #)
1781
1782 The @link(Orientation) determines what is the direction and up you get
1783 when the @link(Rotation) is zero.
1784 For example @link(Orientation) = otUpYDirectionZ (default now) means that:
1785
1786 @orderedList(
1787 @item(When @link(Rotation) is zero,
1788 then @link(Up) will be +Y axis @code((0,1,0)) and
1789 @link(Direction) will be +Z axis @code((0,0,1)).)
1790
1791 @item(Setting the @link(Direction) and @link(Up) to other values will be properly converted.)
1792
1793 @item(So when @link(Orientation) = otUpYDirectionZ, and you set
1794
1795 @longCode(#
1796 MyMissile.Direction := Vector3(0, 0, 1);
1797 MyMissile.Up := Vector3(0, 1, 0);
1798 #)
1799
1800 then you effectively have set @link(Rotation MyMissile.Rotation) to zero (no rotation).
1801 That is, you could have as well done just this:
1802
1803 @longCode(#
1804 MyMissile.Rotation := TVector4.Zero;
1805 #)
1806
1807 Note that you can also set direction and up more efficiently by one @link(SetView) call.
1808 So this is one more way to do it, also equivalent:
1809
1810 @longCode(#
1811 MyMissile.SetView(Vector3(0, 0, 1), Vector3(0, 1, 0));
1812 #)
1813 )
1814 )
1815
1816 Note that changing @link(Orientation) property does not perform @italic(any) transformation
1817 of the model, it will look the same as it was, no matter what @link(Orientation) you set.
1818 Only changing the @link(Direction) or @link(Up) actually change the @link(Rotation),
1819 which in turn actually change how the model looks. This also implies that
1820 @link(Orientation) value completely doesn't matter if you never get or set
1821 @link(Direction) or @link(Up). All engine rendering and processing just looks at @link(Rotation).
1822
1823 See @link(Orientation) for documentation of its default value.
1824
1825 The @link(Direction) and @link(Up) vectors should always be normalized
1826 (have length 1). But when setting them by these properties, we will normalize
1827 them automatically, so you don't need to worry about that.
1828
1829 The direction and up vectors must always be orthogonal.
1830 When setting @link(Direction), @link(Up) will always be automatically
1831 adjusted to be orthogonal to @link(Direction). And vice versa ---
1832 when setting @link(Up), @link(Direction) will be adjusted.
1833
1834 @groupBegin }
1835 property Direction: TVector3 read GetDirection write SetDirection;
1836 property Up: TVector3 read GetUp write SetUp;
1837 { @groupEnd }
1838
1839 { Get at once vectors: position, direction, up.
1840
1841 Just like @link(Translation) and @link(Rotation),
1842 these vectors reflect the transformation defined locally
1843 in this TCastleTransform, disregarding the parent transformations.
1844 Use GetWorldView to account for parent transformations. }
1845 procedure GetView(out APos, ADir, AUp: TVector3);
1846
1847 { Get position, direction, up. Similar to @link(GetView), but in world coordinates.
1848
1849 Returned ADir and AUp are always orthogonal.
1850 Returned ADir and AUp are always normalized. }
1851 procedure GetWorldView(out APos, ADir, AUp: TVector3);
1852
1853 { Position, direction and up in world coordinates.
1854
1855 Returned TViewVectors.Direction and TViewVectors.Up are always orthogonal.
1856 Returned TViewVectors.Dir and TViewVectors.Up are always normalized.
1857
1858 When setting, TViewVectors.Direction and TViewVectors.Up
1859 do not need to be normalized. We will internally normalize them if necessary.
1860
1861 When setting, we will also automatically fix
1862 TViewVectors.Direction and TViewVectors.Up to be orthogonal, if necessary:
1863 we will adjust the up vector (preserving the given direction value). }
1864 property WorldView: TViewVectors
1865 read GetWorldViewRec write SetWorldViewRec;
1866
1867 { Get position in world coordinates.
1868
1869 The returned position is the same as by @link(GetWorldView).
1870 This method just doesn't calculation anything else, thus it is faster
1871 than @link(GetWorldView) if you don't need direction/up. }
1872 function WorldTranslation: TVector3;
1873
1874 { Set at once vectors: position, direction, up.
1875
1876 ADir and AUp given here do not have to be normalized
1877 (they will be normalized if needed).
1878 They will be automatically fixed to be orthogonal, if necessary:
1879 when AdjustUp = @true (the default) we will adjust the up vector
1880 (preserving the given direction value),
1881 otherwise we will adjust the direction (preserving the given up value).
1882
1883 Just like @link(Translation) and @link(Rotation),
1884 these vectors reflect the transformation defined locally
1885 in this TCastleTransform, disregarding the parent transformations.
1886 Use SetWorldView to account for parent transformations. }
1887 procedure SetView(const APos, ADir, AUp: TVector3;
1888 const AdjustUp: boolean = true); overload;
1889 procedure SetView(const ADir, AUp: TVector3;
1890 const AdjustUp: boolean = true); overload;
1891
1892 { Set position, direction, up. Similar to @link(SetView), but in world coordinates.
1893
1894 Given ADir, AUp do not have to be normalized,
1895 we will normalize them internally if necessary.
1896 But make sure they are non-zero.
1897
1898 We will automatically fix ADir and AUp to be orthogonal, if necessary:
1899 when AdjustUp = @true (the default) we will adjust the up vector
1900 (preserving the given direction value),
1901 otherwise we will adjust the direction (preserving the given up value). }
1902 procedure SetWorldView(const APos, ADir, AUp: TVector3;
1903 const AdjustUp: boolean = true);
1904
1905 { Change up vector, keeping the direction unchanged.
1906 If necessary, the up vector provided here will be fixed to be orthogonal
1907 to direction.
1908
1909 This is similar to assigning @link(Up) vector using it's property setter,
1910 but different behavior happens when we need to fix vectors to have
1911 direction orthogonal to up (which must be always true).
1912 In case of assigning @link(Up) by property setter,
1913 the @link(Direction) vector is changed (if necessary, to be orthogonal to up).
1914 In case of this method, the up vector is changed (if necessary,
1915 to be orthogonal to direction).
1916
1917 It's good to use this if you have a preferred up vector for creatures,
1918 but still preserving the direction vector has the highest priority. }
1919 procedure UpPrefer(const AUp: TVector3);
1920
1921 { How the direction and up vectors determine transformation.
1922 See TOrientationType for values documentation.
1923
1924 The default value of this is:
1925
1926 @unorderedList(
1927 @item(For cameras (TCastleCamera):
1928
1929 DefaultCameraOrientation, which is just constant @link(otUpYDirectionMinusZ).
1930 This means direction is -Z (DefaultCameraDirection), up is +Y (DefaultCameraUp).
1931 )
1932
1933 @item(For all other transformations (not cameras):
1934
1935 DefaultOrientation, static variable, by default @link(otUpYDirectionZ).
1936 This means direction is +Z and up is +Y (DefaultCameraUp).
1937 This matches default orientation of glTF models exported from Blender.
1938
1939 You can adjust the Orientation property of particular models.
1940 Or you can adjust DefaultOrientation to set it for all (non-camera) transforms
1941 throughout your application.
1942 )
1943 )
1944
1945 This value determines how you should model your 3D models,
1946 like the creatures, the items, and the player weapons. }
1947 property Orientation: TOrientationType read FOrientation write FOrientation;
1948
1949 { Transformation objects inside.
1950 Freeing these items automatically removes them from this list. }
1951 property List: TCastleTransformList read FList;
1952
1953 { Add a TCastleBehavior to this TCastleTransform.
1954 In effect, the virtual methods of TCastleBehavior, like @link(TCastleBehavior.Update),
1955 will be automatically called.
1956 Also the @link(TCastleBehavior.Parent) gets assigned.
1957 If the TCastleBehavior was part of another TCastleTransform, it is removed from it.
1958
1959 @seealso FindBehavior
1960 @seealso BehaviorsEnumerate }
1961 procedure AddBehavior(const Behavior: TCastleBehavior);
1962
1963 { Insert a TCastleBehavior to this TCastleTransform at specified index
1964 In effect, the virtual methods of TCastleBehavior, like @link(TCastleBehavior.Update),
1965 will be automatically called.
1966 Also the @link(TCastleBehavior.Parent) gets assigned.
1967 If the TCastleBehavior was part of another TCastleTransform, it is removed from it.
1968
1969 @seealso FindBehavior
1970 @seealso BehaviorsEnumerate }
1971 //procedure InsertBehavior(const Index: Integer; const Behavior: TCastleBehavior);
1972
1973 { Returns behavior index, -1 means not found. }
1974 function BehaviorIndex(const Behavior: TCastleBehavior): Integer;
1975
1976 { Remove TCastleBehavior from this TCastleTransform.
1977 In effect, the virtual methods of TCastleBehavior, like @link(TCastleBehavior.Update),
1978 will no longer be automatically called.
1979 The @link(TCastleBehavior.Parent) is set to @nil. }
1980 procedure RemoveBehavior(const Behavior: TCastleBehavior);
1981
1982 { Find the first behavior of the given class, @nil if none. }
1983 function FindBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
1984
1985 { Find all behaviors of given class, in this transform and children (up to any depth).
1986 The behaviors are added to the list, disregaring the Exists or ExistsInRoot property of parents.
1987 Returned class @italic(does not) own children.
1988 The caller is responsible for freeing the returned list. }
1989 function FindAllBehaviors(const BehaviorClass: TCastleBehaviorClass): TCastleBehaviorList;
1990
1991 { Find the first behavior of the given class, or create and add a new one if necessary.
1992 Never returns @nil. }
1993 function FindRequiredBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
1994
1995 { Count of behaviors.
1996 @seealso AddBehavior
1997 @seealso RemoveBehavior }
1998 function BehaviorsCount: Integer;
1999
2000 { Enumerate current behaviors.
2001 @seealso AddBehavior
2002 @seealso RemoveBehavior }
2003 property Behaviors [const Index: Integer]: TCastleBehavior read GetBehaviors;
2004
2005 { You can enumerate current behaviors using loop like
2006 @code(for B in MyTransform.BehaviorsEnumerate do ...).
2007 Do not call this method in other contexts, it is only useful for "for..in" construction. }
2008 function BehaviorsEnumerate: TCastleBehaviorEnumerator;
2009
2010 { Adds a behavior to the list that needs to be informed about the world
2011 change. Adding multiple times the same behavior is harmless and has no effect. }
2012 procedure AddWorldChangeNotification(const Behavior: TCastleBehavior);
2013
2014 { Removes a behavior from the list that needs to be informed about the world
2015 change. }
2016 procedure RemoveWorldChangeNotification(const Behavior: TCastleBehavior);
2017
2018 { Does this object, and all it's parents up to the root, exist.
2019 This has undefined value in case you place this TCastleTransform instance
2020 (or any parent) many times within the viewport root,
2021 and some parents exist while some not.
2022
2023 This property doesn't check whether this TCastleTransform is actually
2024 part of some @link(World). So it will be @true if this item doesn't have
2025 any parent. It only checks that "all parents, going up the tree, have @link(Exists)
2026 true".
2027
2028 @noAutoLinkHere }
2029 property ExistsInRoot: Boolean read FExistsInRoot;
2030 published
2031 { Is this object (and all children) visible and colliding.
2032 Setting this to @false makes this object non-existing,
2033 just as if removing the object from parent would do.
2034
2035 Non-existing object implies also that all children are non-existing.
2036 Behaviors on non-existing objects should also stop working,
2037 e.g. physics engine should ignore bodies / colliders attached to non-existing
2038 objects, and (TODO) TCastleSoundsource should not play when attached to non-existing
2039 object.
2040
2041 @noAutoLinkHere }
2042 property Exists: Boolean read FExists write SetExists default true;
2043
2044 { Should this collide when
2045 @url(https://castle-engine.io/physics#_old_system_for_collisions_and_gravity simple physics) is used.
2046 This setting is honored e.g. by current collisions done by FPS walk/fly navigation
2047 using TCastleWalkNavigation.
2048 This setting is ignored by the physics engine
2049 (for physics, control if something collides just by adding / removing a TCastleCollider component).
2050
2051 You can turn this off, useful to make e.g. "fake" walls
2052 (to some secret places on level).
2053
2054 This describes collision resolution with almost everything --- camera,
2055 player (in third-person perspective, camera may differ from player),
2056 other creatures. That is because everything
2057 resolves collisions through our methods MoveCollision and HeightCollision
2058 (high-level) or SegmentCollision, SphereCollision, SphereCollision2D,
2059 PointCollision2D, BoxCollision (low-level).
2060
2061 (Note that RayCollision is excluded from this,
2062 it exceptionally ignores Collides value, as it's primarily used for picking.
2063 Same for SegmentCollision with LineOfSight=true.)
2064
2065 The only exception are the collisions with TCastleMoving instances
2066 (movable world parts like elevators and doors) that have their own
2067 detection routines and look at CollidesWithMoving property of other objects.
2068 That is, the TCastleMoving instance itself must still have Collides = @true,
2069 but it interacts with @italic(other) objects if and only if they have
2070 CollidesWithMoving = @true (ignoring their Collides value).
2071 This allows items to be moved by elevators, but still player and creatures
2072 can pass through them.
2073
2074 Note that if not @link(Exists) then this doesn't matter
2075 (non-existing objects never participate in collision detection).
2076
2077 @noAutoLinkHere }
2078 property Collides: boolean read FCollides write FCollides default true;
2079
2080 { Is item pickable by @link(RayCollision) method.
2081 Note that if not @link(Exists) then this doesn't matter
2082 (non-existing objects are never pickable).
2083
2084 This affects ray collisions only for some methods that are part of old
2085 @url(https://castle-engine.io/physics#_old_system_for_collisions_and_gravity simple physics).
2086 This setting is ignored by the physics engine.
2087
2088 This is independent from @link(Collides), as @link(RayCollision)
2089 does not look at @link(Collides), it only looks at @link(Pickable).
2090 @noAutoLinkHere }
2091 property Pickable: boolean read FPickable write FPickable default true;
2092
2093 { Is this object (and all children) visible.
2094 Note that if not @link(Exists) then this doesn't matter
2095 (non-existing objects are never visible).
2096
2097 Just like most TCastleTransform properties, this affects both this
2098 TCastleTransform instance (which may be a TCastleScene instance)
2099 and all children, recursively. In other words, setting this to @false
2100 hides this object and all children.
2101
2102 This is independent from @link(Collides) or @link(Pickable).
2103 @noAutoLinkHere }
2104 property Visible: boolean read FVisible write FVisible default true;
2105
2106 { When non-zero, we can approximate collisions with this object using a sphere
2107 in certain situations (@link(MoveAllowed), @link(Gravity)).
2108 This usually makes dynamic objects, like player and creatures, collide better.
2109
2110 Just like @link(Middle), this is expressed
2111 in the parent coordinate system. }
2112 property CollisionSphereRadius: Single read FCollisionSphereRadius write FCollisionSphereRadius;
2113
2114 { Does this object (and children) cast shadows.
2115
2116 Just like most TCastleTransform properties, this affects both this
2117 TCastleTransform instance (which may be a TCastleScene instance)
2118 and all children, recursively. In other words, setting this to @false
2119 makes this object and all children not cast shadows.
2120
2121 TODO: Right now this only affects casting shadows by shadow volumes.
2122 It will be extended to account for shadow maps. }
2123 property CastShadows: boolean
2124 read FCastShadows write FCastShadows default true;
2125
2126 { Objects on front render layer are rendered in front of objects on back render layer,
2127 regardless of their actual position (depth) relative to camera.
2128
2129 rlParent means that object follows the parent layer, which is by default back.
2130
2131 The typical use-case is to force some object to be in front, by setting rlFront. }
2132 property RenderLayer: TRenderLayer read FRenderLayer write FRenderLayer default rlParent;
2133
2134 {$define read_interface_class}
2135 {$I auto_generated_persistent_vectors/tcastletransform_persistent_vectors.inc}
2136 {$undef read_interface_class}
2137 end;
2138
2139 {$endif read_interface}
2140
2141 {$ifdef read_implementation}
2142
2143 { TCastleTransform.TEnumerator ------------------------------------------------- }
2144
2145 function TCastleTransform.TEnumerator.GetCurrent: TCastleTransform;
2146 begin
2147 Result := FList[FPosition];
2148 end;
2149
2150 constructor TCastleTransform.TEnumerator.Create(const AList: TCastleTransformList);
2151 begin
2152 // inherited Create;
2153 FList := AList;
2154 FPosition := -1;
2155 end;
2156
2157 function TCastleTransform.TEnumerator.MoveNext: Boolean;
2158 begin
2159 Inc(FPosition);
2160 Result := FPosition < FList.Count;
2161 end;
2162
2163 { TCastleTransform ---------------------------------------------------------------- }
2164
2165 constructor TCastleTransform.Create(AOwner: TComponent);
2166 begin
2167 inherited;
2168 FCastShadows := true;
2169 FCollides := true;
2170 FPickable := true;
2171 FVisible := true;
2172 FList := TCastleTransformList.Create(false);
2173 FList.FOwner := Self; // get notified about add/release, assign children World, Parent
2174 FBehaviors := TComponentList.Create(false);
2175 FBehaviorsWorldChangeNotificationList := nil;
2176
2177 FMiddleHeight := DefaultMiddleHeight;
2178 FOnlyTranslation := true;
2179 FScale := NoScale;
2180 FOrientation := DefaultOrientation;
2181 MeaningfulParent := true;
2182 FExists := true;
2183 { at the beginning FParent = nil, which implies "all parents exist" }
2184 FParentExistsInRoot := true;
2185 FExistsInRoot := true; // FParentExistsInRoot and FExists;, UpdateExistsInRoot would also set this
2186
2187 {$define read_implementation_constructor}
2188 {$I auto_generated_persistent_vectors/tcastletransform_persistent_vectors.inc}
2189 {$undef read_implementation_constructor}
2190 end;
2191
2192 destructor TCastleTransform.Destroy;
2193 begin
2194 {$define read_implementation_destructor}
2195 {$I auto_generated_persistent_vectors/tcastletransform_persistent_vectors.inc}
2196 {$undef read_implementation_destructor}
2197
2198 FreeAndNil(FPendingToRemove);
2199 FreeAndNil(FPendingToRemoveAndFree);
2200
2201 if RegisteredGLContextCloseListener then
2202 begin
2203 ApplicationProperties.OnGLContextCloseObject.Remove({$ifdef FPC}@{$endif}GLContextCloseEvent);
2204 RegisteredGLContextCloseListener := false;
2205 end;
2206 GLContextClose;
2207
2208 FreeAndNil(FAfterUpdate);
2209 FreeAndNil(FList);
2210 FreeAndNil(FBehaviors);
2211 FreeAndNil(FBehaviorsWorldChangeNotificationList);
2212 inherited;
2213 end;
2214
2215 procedure TCastleTransform.BeforeDestruction;
2216 var
2217 I: Integer;
2218 PreviousCount: SizeInt;
2219 begin
2220 { Remove Self from children, so that in each child we
2221
2222 - decrease FWorldReferences
2223 - set FParent to nil (if it matched Self)
2224 - set FWorld to nil (if it matched Self.FWorld)
2225
2226 Note that this has to be done before "ChangeWorld(nil)",
2227 as RemoveParent in child compares "World = OldParent.World".
2228 That is also why we don't depend on TCastleTransformList.Notify
2229 to call RemoveParent on all children when parent is freed,
2230 as it would be too late, when our World is already nil. }
2231 while FList.Count <> 0 do
2232 begin
2233 PreviousCount := FList.Count;
2234 Delete(0);
2235 if FList.Count >= PreviousCount then
2236 begin
2237 WritelnWarning('During TCastleTransform.BeforeDestruction, the number of children does not decrease -- this means that some TCastleTransform destructor adds new TCastleTransform instances. ' +
2238 'We break infinite loop by aborting normal destruction, but expect further problems. To avoid this warning, make sure your TCastleTransform destructor does not create new TCastleTransform instances.');
2239 Break;
2240 end;
2241 end;
2242
2243 { set to nil, to detach free notification }
2244 ChangeWorld(nil);
2245
2246 PendingRemovals;
2247
2248 { Before we start destroying the transform we need to remove all behaviors from
2249 it, because destroying behavior calls on it events like BeforeParentDetach,
2250 ParentChanged.
2251
2252 And we want Parent (this TCastleTransform) state to be valid
2253 then, e.g. FBehaviors should still be good.
2254
2255 In case of descendants, like TCastleScene, also their state has to be valid
2256 in case behavior's implementation accesses them, e.g. doing
2257 "(Parent as TCastleScene).StopAnimation" from BeforeParentDetach implementation.
2258 That's why we do this from BeforeDestruction, before e.g. TCastleScene.Destroy starts
2259 destroying the instance. }
2260
2261 for I := FBehaviors.Count - 1 downto 0 do
2262 RemoveBehaviorIndex(I);
2263
2264 inherited BeforeDestruction;
2265 end;
2266
2267 procedure TCastleTransform.VisibleChangeHere(const Changes: TVisibleChanges);
2268 begin
2269 if World <> nil then
2270 begin
2271 Inc(World.InternalVisibleStateId);
2272 if vcVisibleGeometry in Changes then
2273 Inc(World.InternalVisibleGeometryStateId);
2274 if vcVisibleNonGeometry in Changes then
2275 Inc(World.InternalVisibleNonGeometryStateId);
2276 end;
2277 end;
2278
2279 function TCastleTransform.CheckCollides: Boolean;
2280 begin
2281 {$warnings off} // using deprecated to keep it working
2282 Result := GetCollides;
2283 {$warnings on}
2284 end;
2285
2286 function TCastleTransform.GetCollides: boolean;
2287 begin
2288 Result := FCollides and Exists;
2289 end;
2290
2291 function TCastleTransform.CheckPickable: boolean;
2292 begin
2293 {$warnings off} // using deprecated to keep it working
2294 Result := GetPickable;
2295 {$warnings on}
2296 end;
2297
2298 function TCastleTransform.GetPickable: boolean;
2299 begin
2300 Result := FPickable and Exists;
2301 end;
2302
2303 function TCastleTransform.CheckVisible: boolean;
2304 begin
2305 {$warnings off} // using deprecated to keep it working
2306 Result := GetVisible;
2307 {$warnings on}
2308 end;
2309
2310 function TCastleTransform.GetVisible: boolean;
2311 begin
2312 Result := FVisible and Exists;
2313 end;
2314
2315 function TCastleTransform.Sphere(out Radius: Single): boolean;
2316 begin
2317 Radius := CollisionSphereRadius;
2318 Result := Radius <> 0;
2319 end;
2320
2321 procedure TCastleTransform.AddToWorld(const Value: TCastleAbstractRootTransform);
2322 var
2323 I: Integer;
2324 begin
2325 Assert(Value <> nil);
2326 if FWorld <> Value then
2327 begin
2328 if FWorld <> nil then
2329 raise ECannotAddToAnotherWorld.Create('Cannot add object existing in one TCastleRootTransform to another. ' + 'This usually means that your object is part of "Viewport1.Items", and you are adding it to "Viewport2.Items". You have to remove it from "Viewport1.Items" first, or set both "Viewport1.Items" and "Viewport2.Items" to be equal.');
2330 ChangeWorld(Value);
2331 end else
2332 Inc(FWorldReferences);
2333
2334 // list stuff
2335 if FList <> nil then // when one list is within another, this may be called during own destruction by TCastleTransformList.Notify
2336 for I := 0 to List.Count - 1 do
2337 List[I].AddToWorld(Value);
2338 end;
2339
2340 procedure TCastleTransform.RemoveFromWorld(const Value: TCastleAbstractRootTransform);
2341 var
2342 I: Integer;
2343 begin
2344 Assert(Value <> nil);
2345 Assert(FWorldReferences > 0);
2346 if FWorld <> Value then
2347 WritelnWarning('TCastleTransform.RemoveFromWorld: Removing from World you were not part of. ' + 'This probably means that you added one TCastleTransform instance to multiple TCastleRootTransform trees, which is not allowed. Always remove TCastleTransform from previous viewport (e.g. by "Viewport1.Items.Remove(xxx)") before adding to the new viewport.');
2348
2349 Dec(FWorldReferences);
2350 if FWorldReferences = 0 then
2351 ChangeWorld(nil);
2352
2353 // list stuff
2354 if FList <> nil then // when one list is within another, this may be called during own destruction by TCastleTransformList.Notify
2355 for I := 0 to List.Count - 1 do
2356 List[I].RemoveFromWorld(Value);
2357 end;
2358
2359 procedure TCastleTransform.AddParent(const NewParent: TCastleTransform);
2360 begin
2361 { Assign FParent before calling AddToWorld
2362 (that may cause PhysicsChangeWorldAttach that may use Parent).
2363 We check MeaningfulParent, so that adding children to TCastleTransformReference
2364 will not change parent. }
2365 if NewParent.MeaningfulParent then
2366 begin
2367 FParent := NewParent;
2368 { Keep our ParentExistsInRoot synchronized with FParent, and thus keep our ExistsInRoot correct }
2369 ParentExistsInRoot := FParent.ExistsInRoot;
2370 end;
2371
2372 if NewParent.World <> nil then
2373 AddToWorld(NewParent.World);
2374
2375 FreeNotification(NewParent);
2376 end;
2377
2378 procedure TCastleTransform.RemoveParent(const OldParent: TCastleTransform);
2379 begin
2380 if (OldParent.World <> nil) and
2381 { It is possible that "World <> OldParent.World" when Self is getting
2382 freed and has World set to nil in constructor already. }
2383 (World = OldParent.World) then
2384 RemoveFromWorld(OldParent.World);
2385
2386 { Clear FParent only if previous parent matched OldParent.
2387 This way removing from TCastleTransformReference will not change FParent. }
2388 if FParent = OldParent then
2389 begin
2390 FParent := nil;
2391 { non-existing parent means "all parents exist" }
2392 ParentExistsInRoot := true;
2393 end;
2394
2395 { Do not call RemoveFreeNotification when OldParent is equal to World,
2396 this would prevent getting notification when FWorld is set to nil in
2397 TCastleTransform.Notification. }
2398 if World <> OldParent then
2399 RemoveFreeNotification(OldParent);
2400 end;
2401
2402 procedure TCastleTransform.ChangeWorld(const Value: TCastleAbstractRootTransform);
2403 begin
2404 if FWorld <> Value then
2405 begin
2406 if FWorld <> nil then
2407 begin
2408 if ListenPressRelease then
2409 FWorld.UnregisterPressRelease(Self);
2410
2411 NotifyWorldBeforeDetach;
2412
2413 { Do not call RemoveFreeNotification when FWorld is also our list owner,
2414 this would prevent getting notification in TCastleTransform.Notification. }
2415 if (FWorld.List = nil) or (FWorld.List.IndexOf(Self) = -1) then
2416 FWorld.RemoveFreeNotification(Self);
2417 end;
2418
2419 FWorld := Value;
2420 FWorldReferences := Iff(Value <> nil, 1, 0);
2421
2422 if FWorld <> nil then
2423 begin
2424 // Ignore FWorld = Self case, when this is done by TCastleAbstractRootTransform.Create? No need to.
2425 //if FWorld <> Self then
2426 FWorld.FreeNotification(Self);
2427
2428 NotifyWorldAfterAttach;
2429
2430 if ListenPressRelease then
2431 FWorld.RegisterPressRelease(Self);
2432 end;
2433 end;
2434 end;
2435
2436 procedure TCastleTransform.Notification(AComponent: TComponent; Operation: TOperation);
2437 begin
2438 inherited;
2439
2440 { make sure to nil FWorld reference }
2441 if (Operation = opRemove) and (AComponent = FWorld) then
2442 ChangeWorld(nil);
2443
2444 { We have to remove a reference to the object from the List.
2445 This is crucial: TCastleTransformList.Notify,
2446 and e.g. GLContextClose call, assume that all objects on
2447 the List are always valid objects (no invalid references,
2448 even for a short time). }
2449
2450 { About List <> nil check:
2451
2452 How situation with List = nil may happen? When our List is destroyed,
2453 it calls B.FreeNotification on all it's items, so it (falsely) seems we will
2454 not get any more notifications.
2455
2456 It turns out that we may get notifications,
2457 and they are notifications about our own destruction (AComponent = Self).
2458 That is because TComponent.Notification passes down the notification to
2459 all it's FComponents, that is rtl/objpas/classes/compon.inc
2460 (in FPC sources) contains code
2461
2462 Procedure TComponent.Notification(AComponent: TComponent; Operation: TOperation);
2463 begin
2464 ...
2465 For Runner:=0 To FComponents.Count-1 do
2466 TComponent(FComponents.Items[Runner]).Notification(AComponent,Operation);
2467 end;
2468
2469 And FComponents contain all components that are owned.
2470 So we are informed when something is removed from the owner,
2471 including about our own removal. (And in this case, we are a TCastleTransform descendant
2472 ourselves, just like our children; so check "AComponent is TCastleTransform" doesn't
2473 protect us.)
2474 Practical situation when it happens is in testcases
2475 TTestCastleTransform.TestNotifications and TTestCastleTransform.TestNotificationsSceneManager. }
2476
2477 if (Operation = opRemove) and (AComponent is TCastleTransform) and (List <> nil) then
2478 List.RemoveAll(AComponent);
2479 end;
2480
2481 function TCastleTransform.Height(const MyPosition: TVector3;
2482 out AboveHeight: Single): boolean;
2483 var
2484 AboveGroundIgnored: PTriangle;
2485 begin
2486 Result := Height(MyPosition, AboveHeight, AboveGroundIgnored);
2487 end;
2488
2489 function TCastleTransform.Height(const MyPosition: TVector3;
2490 out AboveHeight: Single; out AboveGround: PTriangle): boolean;
2491 var
2492 MyPositionWorld: TVector3;
2493 SavedExists: Boolean;
2494 begin
2495 MyPositionWorld := Parent.LocalToWorld(MyPosition);
2496 SavedExists := Exists;
2497 Exists := false;
2498 try
2499 Result := World.WorldHeight(MyPositionWorld, AboveHeight, AboveGround);
2500 if Result then
2501 AboveHeight := Parent.WorldToLocalDistance(AboveHeight);
2502 finally Exists := SavedExists end;
2503 end;
2504
2505 function TCastleTransform.LineOfSight(const Pos1, Pos2: TVector3): boolean;
2506 var
2507 Pos1World, Pos2World: TVector3;
2508 SavedExists: Boolean;
2509 begin
2510 Pos1World := Parent.LocalToWorld(Pos1);
2511 Pos2World := Parent.LocalToWorld(Pos2);
2512 SavedExists := Exists;
2513 Exists := false;
2514 try
2515 Result := World.WorldLineOfSight(Pos1World, Pos2World);
2516 finally Exists := SavedExists end;
2517 end;
2518
2519 function TCastleTransform.MoveAllowed(const OldPos, ProposedNewPos: TVector3;
2520 out NewPos: TVector3;
2521 const BecauseOfGravity: boolean): boolean;
2522 var
2523 Sp: boolean;
2524 SpRadius, SpRadiusWorld: Single;
2525 OldBox, NewBox: TBox3D;
2526 OldPosWorld, ProposedNewPosWorld, NewPosWorld: TVector3;
2527 SavedExists: Boolean;
2528 begin
2529 Assert(Parent <> nil, 'Need to know world transformation before MoveAllowed');
2530
2531 OldPosWorld := Parent.LocalToWorld(OldPos);
2532 ProposedNewPosWorld := Parent.LocalToWorld(ProposedNewPos);
2533
2534 { Save bounding volume information before calling Disable, as Disable makes
2535 bounding volume empty }
2536 Sp := Sphere(SpRadius);
2537 if not Sp then
2538 SpRadius := 0; { something predictable, for safety }
2539 OldBox := WorldBoundingBox;
2540 NewBox := OldBox.Translate(ProposedNewPosWorld - OldPosWorld);
2541
2542 SpRadiusWorld := Parent.LocalToWorldDistance(SpRadius);
2543
2544 SavedExists := Exists;
2545 Exists := false;
2546 try
2547 Result := World.WorldMoveAllowed(OldPosWorld, ProposedNewPosWorld, NewPosWorld,
2548 Sp, SpRadiusWorld, OldBox, NewBox, BecauseOfGravity);
2549 finally Exists := SavedExists end;
2550
2551 if Result then
2552 NewPos := Parent.WorldToLocal(NewPosWorld);
2553 end;
2554
2555 function TCastleTransform.MoveAllowed(const OldPos, NewPos: TVector3;
2556 const BecauseOfGravity: boolean): boolean;
2557 var
2558 Sp: boolean;
2559 SpRadius: Single;
2560 OldBox, NewBox: TBox3D;
2561 SavedExists: Boolean;
2562 begin
2563 { save bounding volume information before calling Disable, as Disable makes
2564 bounding volume empty }
2565 Sp := Sphere(SpRadius);
2566 if not Sp then
2567 SpRadius := 0; { something predictable, for safety }
2568 OldBox := WorldBoundingBox;
2569 NewBox := OldBox.Translate(NewPos - OldPos);
2570
2571 SavedExists := Exists;
2572 Exists := false;
2573 try
2574 Result := World.WorldMoveAllowed(OldPos, NewPos,
2575 Sp, SpRadius, OldBox, NewBox, BecauseOfGravity);
2576 finally Exists := SavedExists end;
2577 end;
2578
2579 function TCastleTransform.Ray(
2580 const RayOrigin, RayDirection: TVector3): TRayCollision;
2581 var
2582 RayOriginWorld, RayDirectionWorld: TVector3;
2583 SavedExists: Boolean;
2584 begin
2585 RayOriginWorld := Parent.LocalToWorld(RayOrigin);
2586 RayDirectionWorld := Parent.LocalToWorldDirection(RayDirection);
2587 SavedExists := Exists;
2588 Exists := false;
2589 try
2590 Result := World.WorldRay(RayOriginWorld, RayDirectionWorld);
2591 finally Exists := SavedExists end;
2592 end;
2593
2594 function TCastleTransform.RayCast(const RayOrigin, RayDirection: TVector3): TCastleTransform;
2595 var
2596 RayOriginWorld, RayDirectionWorld: TVector3;
2597 SavedExists: Boolean;
2598 begin
2599 RayOriginWorld := Parent.LocalToWorld(RayOrigin);
2600 RayDirectionWorld := Parent.LocalToWorldDirection(RayDirection);
2601 SavedExists := Exists;
2602 Exists := false;
2603 try
2604 Result := World.WorldRayCast(RayOriginWorld, RayDirectionWorld);
2605 finally Exists := SavedExists end;
2606 end;
2607
2608 function TCastleTransform.RayCast(const RayOrigin, RayDirection: TVector3; out Distance: Single): TCastleTransform;
2609 var
2610 RayOriginWorld, RayDirectionWorld: TVector3;
2611 SavedExists: Boolean;
2612 begin
2613 RayOriginWorld := Parent.LocalToWorld(RayOrigin);
2614 RayDirectionWorld := Parent.LocalToWorldDirection(RayDirection);
2615 SavedExists := Exists;
2616 Exists := false;
2617 try
2618 Result := World.WorldRayCast(RayOriginWorld, RayDirectionWorld, Distance);
2619 if Result <> nil then
2620 Distance := Parent.WorldToLocalDistance(Distance);
2621 finally Exists := SavedExists end;
2622 end;
2623
2624 { list stuff ---------------------------------------------------------------- }
2625
2626 procedure TCastleTransform.Add(const Item: TCastleTransform);
2627 begin
2628 List.Add(Item);
2629 end;
2630
2631 procedure TCastleTransform.Insert(const Index: Integer; const Item: TCastleTransform);
2632 begin
2633 List.Insert(Index, Item);
2634 end;
2635
2636 function TCastleTransform.GetItem(const I: Integer): TCastleTransform;
2637 begin
2638 Result := List[I];
2639 end;
2640
2641 procedure TCastleTransform.SetItem(const I: Integer; const Item: TCastleTransform);
2642 begin
2643 List[I] := Item;
2644 end;
2645
2646 function TCastleTransform.Count: Integer;
2647 begin
2648 { Free notifications may want to iterate over some children from a TCastleTransform
2649 that is being freed, and has List = nil now.
2650 This happens for lights in designs, when we remove the light or close the design.
2651 Behave as if we don't have children then. }
2652 if List <> nil then
2653 Result := List.Count
2654 else
2655 Result := 0;
2656 end;
2657
2658 procedure TCastleTransform.Remove(const Item: TCastleTransform);
2659 begin
2660 { Free notifications of various components (like TVisualizeTransform)
2661 may want to remove some children from a TCastleTransform that is being
2662 freed, and has List = nil now.
2663 Ignore it -- removing from a nil list doesn't require doing anything. }
2664 if List <> nil then
2665 List.Remove(Item);
2666 end;
2667
2668 procedure TCastleTransform.Delete(const Index: Integer);
2669 begin
2670 { As in Remove, check "List <> nil" }
2671 if List <> nil then
2672 List.Delete(Index);
2673 end;
2674
2675 procedure TCastleTransform.Clear;
2676 begin
2677 List.Clear;
2678 end;
2679
2680 procedure TCastleTransform.Exchange(const Index1, Index2: Integer);
2681 begin
2682 List.Exchange(Index1, Index2);
2683 end;
2684
2685 procedure TCastleTransform.SortBackToFront2D;
2686 begin
2687 {$warnings off} // using deprecated in deprecated
2688 List.SortBackToFront2D;
2689 {$warnings on}
2690 end;
2691
2692 function TCastleTransform.LocalBoundingBox: TBox3D;
2693 var
2694 I: Integer;
2695 begin
2696 Result := TBox3D.Empty;
2697 if Exists then
2698 begin
2699 for I := 0 to List.Count - 1 do
2700 { Ignoring InternalExcludeFromParentBoundingVolume when
2701 InternalGizmoBoundingBox <> 0 is a hack,
2702 so that when TCastleViewport.ItemsWithGizmosBoundingBox is called,
2703 then all gizmos are taken into account. }
2704 if not (List[I].InternalExcludeFromParentBoundingVolume and
2705 (InternalGizmoBoundingBox = 0)) then
2706 Result.Include(List[I].BoundingBox);
2707 end;
2708 end;
2709
2710 function TCastleTransform.GetRenderList(const Params: TRenderParams): TCastleTransformList;
2711 begin
2712 Result := List;
2713 end;
2714
2715 procedure TCastleTransform.LocalRender(const Params: TRenderParams);
2716 var
2717 I: Integer;
2718 RenderList: TCastleTransformList;
2719 begin
2720 if CheckVisible then
2721 begin
2722 PendingRemovals;
2723 RenderList := GetRenderList(Params);
2724 for I := 0 to RenderList.Count - 1 do
2725 RenderList[I].Render(Params);
2726 end;
2727 end;
2728
2729 procedure TCastleTransform.LocalRenderShadowVolume(const Params: TRenderParams;
2730 const ShadowVolumeRenderer: TBaseShadowVolumeRenderer);
2731 var
2732 I: Integer;
2733 begin
2734 if CheckVisible and CastShadows then
2735 begin
2736 for I := 0 to List.Count - 1 do
2737 List[I].RenderShadowVolume(Params, ShadowVolumeRenderer);
2738 end;
2739 end;
2740
2741 procedure TCastleTransform.GLContextCloseEvent(Sender: TObject);
2742 begin
2743 GLContextClose;
2744 end;
2745
2746 procedure TCastleTransform.RegisterGLContextClose;
2747 begin
2748 if not RegisteredGLContextCloseListener then
2749 begin
2750 RegisteredGLContextCloseListener := true;
2751 ApplicationProperties.OnGLContextCloseObject.Add({$ifdef FPC}@{$endif}GLContextCloseEvent);
2752 end;
2753 end;
2754
2755 procedure TCastleTransform.PrepareResources(const Options: TPrepareResourcesOptions;
2756 const Params: TPrepareParams);
2757 var
2758 I: Integer;
2759 begin
2760 for I := 0 to List.Count - 1 do
2761 List[I].PrepareResources(Options, Params);
2762 RegisterGLContextClose;
2763 end;
2764
2765 function TCastleTransform.Press(const Event: TInputPressRelease): boolean;
2766 var
2767 I: Integer;
2768 begin
2769 Result := false;
2770 if not Exists then Exit;
2771
2772 for I := 0 to List.Count - 1 do
2773 if List[I].Press(Event) then Exit(true);
2774 end;
2775
2776 function TCastleTransform.Release(const Event: TInputPressRelease): boolean;
2777 var
2778 I: Integer;
2779 begin
2780 Result := false;
2781 if not Exists then Exit;
2782
2783 for I := 0 to List.Count - 1 do
2784 if List[I].Release(Event) then Exit(true);
2785 end;
2786
2787 function TCastleTransform.PointingDevicePress(const Pick: TRayCollisionNode;
2788 const Distance: Single): Boolean;
2789 begin
2790 { This event is not automatically passed to all children on List,
2791 instead the TCastleViewport has special logic which
2792 TCastleTransform instances receive the PointingDevicePress call. }
2793 Result := false;
2794 end;
2795
2796 function TCastleTransform.PointingDeviceRelease(const Pick: TRayCollisionNode;
2797 const Distance: Single; const CancelAction: Boolean): Boolean;
2798 begin
2799 { This event is not automatically passed to all children on List,
2800 instead the TCastleViewport has special logic which
2801 TCastleTransform instances receive the PointingDeviceRelease call. }
2802 Result := false;
2803 end;
2804
2805 function TCastleTransform.PointingDeviceMove(const Pick: TRayCollisionNode;
2806 const Distance: Single): Boolean;
2807 begin
2808 { This event is not automatically passed to all children on List,
2809 instead the TCastleViewport has special logic which
2810 TCastleTransform instances receive the PointingDeviceMove call. }
2811 Result := false;
2812 end;
2813
2814 procedure TCastleTransform.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
2815
2816 procedure UpdateBehaviors;
2817 var
2818 I: Integer;
2819 Beh: TCastleBehavior;
2820 RemoveItem: TRemoveType;
2821 begin
2822 I := 0;
2823 while I < FBehaviors.Count do
2824 begin
2825 Beh := FBehaviors[I] as TCastleBehavior;
2826 RemoveItem := rtNone;
2827 Beh.Update(SecondsPassed, RemoveItem);
2828 if RemoveItem in [rtRemove, rtRemoveAndFree] then
2829 begin
2830 RemoveBehaviorIndex(I);
2831 if RemoveItem = rtRemoveAndFree then
2832 FreeAndNil(Beh);
2833 end else
2834 Inc(I);
2835 end;
2836 end;
2837
2838 procedure UpdateChildren;
2839 var
2840 I: Integer;
2841 Item: TCastleTransform;
2842 RemoveItem: TRemoveType;
2843 begin
2844 PendingRemovals;
2845
2846 I := 0;
2847 while I < List.Count do
2848 begin
2849 Item := List[I];
2850 if Item.Exists then
2851 begin
2852 RemoveItem := rtNone;
2853 Item.Update(SecondsPassed, RemoveItem);
2854 if RemoveItem in [rtRemove, rtRemoveAndFree] then
2855 begin
2856 List.Delete(I);
2857 if RemoveItem = rtRemoveAndFree then
2858 FreeAndNil(Item);
2859 end else
2860 Inc(I);
2861 end else
2862 Inc(I);
2863 end;
2864
2865 PendingRemovals;
2866 end;
2867
2868 begin
2869 Assert(Exists); // this should never be called on TCastleTransform that does not exist
2870
2871 UpdateBehaviors;
2872 UpdateChildren;
2873
2874 if FAfterUpdate <> nil then
2875 FAfterUpdate.ExecuteAll(Self);
2876
2877 { Disable physics and gravity in design mode (in the future we may add optional way to enable them) }
2878 if not CastleDesignMode then
2879 begin
2880 UpdateSimpleGravity(SecondsPassed);
2881 end;
2882 end;
2883
2884 procedure TCastleTransform.AddAfterUpdateListener(
2885 const UpdateListener: TNotifyEvent);
2886 begin
2887 if FAfterUpdate = nil then
2888 FAfterUpdate := TNotifyEventList.Create;
2889
2890 FAfterUpdate.Add(UpdateListener);
2891 end;
2892
2893 procedure TCastleTransform.RemoveAfterUpdateListener(
2894 const UpdateListener: TNotifyEvent);
2895 begin
2896 if FAfterUpdate = nil then
2897 Exit;
2898
2899 FAfterUpdate.Remove(UpdateListener);
2900 end;
2901
2902 procedure TCastleTransform.GLContextClose;
2903 begin
2904 { Does nothing now.
2905 In particular, this does not call GLContextClose on children.
2906 This way it keeps their OpenGL resources prepared,
2907 to be able to quickly readd them to another transform (without time-consuming
2908 initial PrepareResources). }
2909 end;
2910 (*
2911 var
2912 I: Integer;
2913 begin
2914 { this is called from inherited destructor, so check <> nil carefully }
2915 if FList <> nil then
2916 begin
2917 for I := 0 to List.Count - 1 do
2918 List[I].GLContextClose;
2919 end;
2920 end;
2921 *)
2922
2923 { transform stuff -------------------------------------------------------- }
2924
2925 function TCastleTransform.Translation2D: TVector2;
2926 begin
2927 Result := Translation.XY;
2928 end;
2929
2930 function TCastleTransform.Transform: TMatrix4;
2931 begin
2932 if not FTransformationValid then
2933 begin
2934 InternalTransformation(FTransformation);
2935 FTransformationValid := true;
2936 end;
2937 Result := FTransformation.Transform;
2938 end;
2939
2940 function TCastleTransform.InverseTransform: TMatrix4;
2941 begin
2942 if not FTransformationValid then
2943 begin
2944 InternalTransformation(FTransformation);
2945 FTransformationValid := true;
2946 end;
2947 Result := FTransformation.InverseTransform;
2948 end;
2949
2950 function TCastleTransform.WorldTransform: TMatrix4;
2951 begin
2952 UpdateWorldTransformation;
2953 Result := FWorldTransformation.Transform;
2954 end;
2955
2956 function TCastleTransform.WorldInverseTransform: TMatrix4;
2957 begin
2958 UpdateWorldTransformation;
2959 Result := FWorldTransformation.InverseTransform;
2960 end;
2961
2962 function TCastleTransform.CheckParent: TCastleTransform;
2963 begin
2964 { We no longer check here FWorldReferences = 1.
2965 As FWorldReferences > 1 even when we're child of 1 normal transform
2966 and multiple TCastleTransformReference.
2967
2968 Also, this makes Parent a simple property that just returns FParent
2969 without checking for nil.
2970 Otherwise, Parent would have to be a function that returns FParent or nil,
2971 depending on FWorldReferences, making things more complicated. }
2972
2973 if FParent = nil then
2974 begin
2975 if Self = World then
2976 raise ETransformParentUndefined.CreateFmt('Parent not available: This is the root node (%s %s).', [
2977 Name,
2978 ClassName
2979 ])
2980 else
2981 raise ETransformParentUndefined.CreateFmt('Parent (and WorldTransform) not available for %s %s.' + NL +
2982 NL +
2983 'This instance is not part of TCastleRootTransform (Viewport.Items).' + NL +
2984 'Or it was (at some point in time) added multiple times to TCastleRootTransform (Viewport.Items). References through TCastleTransformReference are not counted here.' + NL +
2985 NL +
2986 'To have a Parent (and WorldTransform), add it exactly once to TCastleRootTransform (Viewport.Items). You can still use TCastleTransformReference to have more instances.',
2987 [
2988 Name,
2989 ClassName
2990 ]);
2991 end;
2992 Result := FParent;
2993 end;
2994
2995 procedure TCastleTransform.NotifyWorldAfterAttach;
2996 var
2997 I: Integer;
2998 begin
2999 if FBehaviorsWorldChangeNotificationList = nil then
3000 Exit;
3001
3002 for I := 0 to FBehaviorsWorldChangeNotificationList.Count - 1 do
3003 begin
3004 FBehaviorsWorldChangeNotificationList[I].WorldAfterAttach;
3005 end;
3006 end;
3007
3008 procedure TCastleTransform.NotifyWorldBeforeDetach;
3009 var
3010 I: Integer;
3011 begin
3012 if FBehaviorsWorldChangeNotificationList = nil then
3013 Exit;
3014
3015 for I := 0 to FBehaviorsWorldChangeNotificationList.Count - 1 do
3016 begin
3017 FBehaviorsWorldChangeNotificationList[I].WorldBeforeDetach;
3018 end;
3019 end;
3020
3021 procedure TCastleTransform.AddNotificationOnBehaviorAdded(const AEvent: TComponentEvent);
3022 begin
3023 AddNotificationOnBehaviorAdded(AEvent, TCastleComponent);
3024 end;
3025
3026 procedure TCastleTransform.AddNotificationOnBehaviorAdded(
3027 const AEvent: TComponentEvent; const ClassFilter: TComponentClass);
3028 begin
3029 if FOnAddedBehaviorNotification = nil then
3030 FOnAddedBehaviorNotification := TCastleComponentNotification.Create(Self);
3031
3032 FOnAddedBehaviorNotification.AddNotification(AEvent, ClassFilter);
3033 end;
3034
3035 procedure TCastleTransform.NotifyBehaviorAdded(const ABehavior: TCastleBehavior);
3036 begin
3037 if FOnAddedBehaviorNotification = nil then
3038 Exit;
3039
3040 FOnAddedBehaviorNotification.Notify(ABehavior);
3041 end;
3042
3043 procedure TCastleTransform.RemoveNotificationOnBehaviorAdded(
3044 const AEvent: TComponentEvent);
3045 begin
3046 if FOnAddedBehaviorNotification = nil then
3047 Exit;
3048
3049 FOnAddedBehaviorNotification.RemoveNotification(AEvent);
3050 end;
3051
3052 procedure TCastleTransform.RemoveNotificationOnBehaviorAdded(
3053 const AEvent: TComponentEvent; const ClassFilter: TComponentClass);
3054 begin
3055 if FOnAddedBehaviorNotification = nil then
3056 Exit;
3057
3058 FOnAddedBehaviorNotification.RemoveNotification(AEvent, ClassFilter);
3059 end;
3060
3061 procedure TCastleTransform.AddNotificationBeforeBehaviorRemove(
3062 const AEvent: TComponentEvent);
3063 begin
3064 AddNotificationBeforeBehaviorRemove(AEvent, TCastleComponent);
3065 end;
3066
3067 procedure TCastleTransform.AddNotificationBeforeBehaviorRemove(
3068 const AEvent: TComponentEvent; const ClassFilter: TComponentClass);
3069 begin
3070 if FBeforeRemoveBehaviorNotification = nil then
3071 FBeforeRemoveBehaviorNotification := TCastleComponentNotification.Create(Self);
3072
3073 FBeforeRemoveBehaviorNotification.AddNotification(AEvent, ClassFilter);
3074 end;
3075
3076 procedure TCastleTransform.NotifyBeforeBehaviorRemove(
3077 const ABehavior: TCastleBehavior);
3078 begin
3079 if FBeforeRemoveBehaviorNotification = nil then
3080 Exit;
3081
3082 FBeforeRemoveBehaviorNotification.Notify(ABehavior);
3083 end;
3084
3085 procedure TCastleTransform.RemoveNotificationBeforeBehaviorRemove(
3086 const AEvent: TComponentEvent);
3087 begin
3088 if FBeforeRemoveBehaviorNotification = nil then
3089 Exit;
3090
3091 FBeforeRemoveBehaviorNotification.RemoveNotification(AEvent);
3092 end;
3093
3094 procedure TCastleTransform.RemoveNotificationBeforeBehaviorRemove(
3095 const AEvent: TComponentEvent; const ClassFilter: TComponentClass);
3096 begin
3097 if FBeforeRemoveBehaviorNotification = nil then
3098 Exit;
3099
3100 FBeforeRemoveBehaviorNotification.RemoveNotification(AEvent, ClassFilter);
3101 end;
3102
3103 procedure TCastleTransform.BeforeBehaviorDestroy(const Behavior: TCastleBehavior);
3104 begin
3105 if Behavior.Parent <> nil then
3106 begin
3107 NotifyBeforeBehaviorRemove(Behavior);
3108
3109 if Behavior.ListenWorldChange and (FWorld <> nil) then
3110 Behavior.WorldBeforeDetach;
3111
3112 Behavior.ParentBeforeDetach;
3113
3114 Behavior.FParent := nil;
3115
3116 { Could be called but a lot of exsiting code doesn't check Parent = nil.
3117 For backward compatibility of this deprecated method, don't call it. }
3118 // Behavior.ParentChanged;
3119
3120 RemoveWorldChangeNotification(Behavior);
3121
3122 { In case TCastleBehavior is freed, clear the associated FCachedXxx
3123 value.
3124
3125 This is important in case the TCastleBehavior is freed
3126 but the RemoveBehavior was not called explicitly (because RemoveBehavior
3127 already does UpdateCachedBehaviors).
3128 E.g. when you free the whole design, testcase TestPhysicsMeshResolving. }
3129 if FCachedCollider = Behavior then
3130 FCachedCollider := nil;
3131 if FCachedRigidBody = Behavior then
3132 FCachedRigidBody := nil;
3133 end;
3134 end;
3135
3136 procedure TCastleTransform.UpdateCollidersWorldScale;
3137 var
3138 T: TCastleTransform;
3139 begin
3140 if Collider <> nil then
3141 Collider.UpdateWorldScale;
3142
3143 for T in Self do
3144 T.UpdateCollidersWorldScale;
3145 end;
3146
3147 function TCastleTransform.HasWorldTransform: boolean;
3148 begin
3149 { Check for "FWorld <> nil" is still necessary, otherwise a TCastleTransform
3150 could satisfy this without having World assigned:
3151 when it has a FParent, but FParent is not yet part of any World.
3152
3153 This matters, e.g. we activate FScene.ProcessEvents:=true
3154 in TCastleAbstractLight.Create, at which point FScene has a parent
3155 but the parent (TCastleAbstractLight instance) is not yet part of world.
3156 SetProcessEvents calls GetCameraLocal that checks HasWorldTransform,
3157 assuming that HasWorldTransform => implies World <> nil.
3158
3159 TODO: maybe just "FWorld <> nil" should be enough? }
3160 Result := (FWorld <> nil) and ((Self = World) or (FParent <> nil));
3161 end;
3162
3163 procedure TCastleTransform.UpdateWorldTransformation;
3164 var
3165 Par: TCastleTransform;
3166 IsWorld: boolean;
3167 begin
3168 { The main feature that enables to optimize this (usually reuse previously
3169 calculated FWorldTransformation) is that we keep
3170 FWorldTransformationId.
3171 This id changes every time the FWorldTransform or FWorldInverseTransform changes.
3172 So a child can save this id, and know that as long as FWorldTransformationId
3173 didn't change, so also FWorldTransformation didn't change.
3174
3175 The FWorldTransformationId is never zero after UpdateWorldTransformation.
3176 So you can safely use FLastParentWorldTransformationId = 0
3177 as a value that "will never be considered equal". }
3178
3179 IsWorld := Self = World;
3180
3181 if not IsWorld then
3182 begin
3183 // first, update FLastParentWorldTransform*
3184 Par := CheckParent;
3185 Par.UpdateWorldTransformation;
3186 if FLastParentWorldTransformationId <> Par.FWorldTransformationId then
3187 begin
3188 FLastParentWorldTransformationId := Par.FWorldTransformationId;
3189 FLastParentWorldTransformation := Par.FWorldTransformation;
3190 // need to recalculate our FWorldTransformation
3191 FWorldTransformationValid := false;
3192 end;
3193 end;
3194
3195 { Note that FWorldTransformationValid is set to false
3196 - when Par.WorldTransform changes or
3197 - when our Transform changes
3198 Both situations imply that our WorldTransform should change.
3199 }
3200
3201 if not FWorldTransformationValid then
3202 begin
3203 // update NextTransformId
3204 if NextTransformId = High(NextTransformId) then
3205 begin
3206 WritelnLog('Watch out, UpdateWorldTransformation overflows the NextTransformId');
3207 NextTransformId := 1; // skip over 0
3208 end else
3209 Inc(NextTransformId);
3210
3211 FWorldTransformationId := NextTransformId;
3212
3213 // actually calculate World[Inverse]Transform here
3214 if IsWorld then
3215 begin
3216 FWorldTransformation.Transform := Transform;
3217 FWorldTransformation.InverseTransform := InverseTransform;
3218 end else
3219 begin
3220 FWorldTransformation.Transform := FLastParentWorldTransformation.Transform * Transform;
3221 FWorldTransformation.InverseTransform := InverseTransform * FLastParentWorldTransformation.InverseTransform;
3222 end;
3223 FWorldTransformationValid := true;
3224 end;
3225 end;
3226
3227 procedure TCastleTransform.TransformMatricesMult(var M, MInverse: TMatrix4);
3228 var
3229 T: TTransformation;
3230 begin
3231 // call InternalTransformationMult (non-deprecated)
3232 T.Transform := M;
3233 T.InverseTransform := MInverse;
3234 // T.Scale := 1; // doesn't matter
3235 InternalTransformationMult(T);
3236 M := T.Transform;
3237 MInverse := T.InverseTransform;
3238 end;
3239
3240 procedure TCastleTransform.TransformMatrices(out M, MInverse: TMatrix4);
3241 var
3242 T: TTransformation;
3243 begin
3244 // call InternalTransformation (non-deprecated)
3245 InternalTransformation(T);
3246 M := T.Transform;
3247 MInverse := T.InverseTransform;
3248 end;
3249
3250 procedure TCastleTransform.InternalTransformationMult(var T: TTransformation);
3251
3252 {$ifdef COMPILER_BUGGY_PARAMETERS}
3253 type
3254 TTransformData = record
3255 Transform, InverseTransform: TMatrix4;
3256 Center: TVector3;
3257 Rotation: TVector4;
3258 Scale: TVector3;
3259 ScaleOrientation: TVector4;
3260 Translation: TVector3;
3261 end;
3262
3263 procedure MultiplyWorkaround(var T: TTransformation; const TransformData: TTransformData);
3264 begin
3265 T.Multiply(
3266 TransformData.Center,
3267 TransformData.Rotation,
3268 TransformData.Scale,
3269 TransformData.ScaleOrientation,
3270 TransformData.Translation);
3271 end;
3272
3273 var
3274 TransformData: TTransformData;
3275 begin
3276 TransformData.Center := FCenter;
3277 TransformData.Rotation := FRotation;
3278 TransformData.Scale := FScale;
3279 TransformData.ScaleOrientation := FScaleOrientation;
3280 TransformData.Translation := FTranslation;
3281 MultiplyWorkaround(T, TransformData);
3282 {$else}
3283 begin
3284 T.Multiply(
3285 FCenter,
3286 FRotation,
3287 FScale,
3288 FScaleOrientation,
3289 FTranslation);
3290 {$endif}
3291 end;
3292
3293 procedure TCastleTransform.InternalTransformation(out T: TTransformation);
3294 begin
3295 T.Init;
3296 InternalTransformationMult(T);
3297 end;
3298
3299 function TCastleTransform.AverageScale: Single;
3300 begin
3301 Result := Approximate3DScale(Scale);
3302 end;
3303
3304 function TCastleTransform.AverageScale2D: Single;
3305 begin
3306 Result := Approximate2DScale(Scale.XY);
3307 end;
3308
3309 { We assume in all methods below that FOnlyTranslation is the most common case,
3310 and then that Translation = 0,0,0 is the most common case.
3311 This is true for many 3D objects. And for only translation,
3312 we can calculate result much faster (and for translation = zero,
3313 we don't have to do anything besides calling inherited).
3314
3315 For some simplest operations, we do not check for Translation = 0,0,0
3316 case --- if applying Translation is very fast, then checking for
3317 zero translation would be a waste of time. }
3318
3319 function TCastleTransform.BoundingBox: TBox3D;
3320 begin
3321 if FOnlyTranslation then
3322 Result := LocalBoundingBox.Translate(Translation)
3323 else
3324 Result := LocalBoundingBox.Transform(Transform);
3325 end;
3326
3327 function TCastleTransform.WorldBoundingBox: TBox3D;
3328 begin
3329 Result := LocalBoundingBox.Transform(WorldTransform);
3330 end;
3331
3332 procedure TCastleTransform.Render(const Frustum: TFrustum; const Params: TRenderParams);
3333 var
3334 SavedFrustumPtr: PFrustum;
3335 begin
3336 SavedFrustumPtr := Params.Frustum;
3337 Params.Frustum := @Frustum;
3338 try
3339 Render(Params);
3340 finally Params.Frustum := SavedFrustumPtr end;
3341 end;
3342
3343 procedure TCastleTransform.WarningMatrixNan(const NewParamsInverseTransformValue: TMatrix4);
3344 begin
3345 WritelnWarning('Transform', Format(
3346 'Inverse transform of "%s" (%s) matrix has NaN value inside:' + NL +
3347 '%s' + NL +
3348 ' Matrix source: Center %s, Rotation %s, Scale %s, ScaleOrientation %s, Translation %s', [
3349 Name,
3350 ClassName,
3351 NewParamsInverseTransformValue.ToString(' '),
3352 FCenter.ToString,
3353 FRotation.ToString,
3354 FScale.ToString,
3355 FScaleOrientation.ToString,
3356 FTranslation.ToString
3357 ]));
3358 end;
3359
3360 procedure TCastleTransform.Render(const Params: TRenderParams);
3361
3362 procedure BehaviorsBeforeRender(
3363 const CameraView: TViewVectors;
3364 const ParentWorldTransformation, WorldTransformation: TTransformation);
3365 var
3366 I: Integer;
3367 Beh: TCastleBehavior;
3368 begin
3369 for I := 0 to FBehaviors.Count - 1 do
3370 begin
3371 Beh := FBehaviors[I] as TCastleBehavior;
3372 Beh.BeforeRender(CameraView, ParentWorldTransformation, WorldTransformation);
3373 end;
3374 end;
3375
3376 var
3377 T: TVector3;
3378 // Saved Params.Xxx before applying our transformation
3379 SavedTransformationPtr: PTransformation;
3380 SavedFrustumPtr: PFrustum;
3381 SavedInMeaningfulParent: Boolean;
3382 HasSavedDepthRange: Boolean;
3383 SavedDepthRange: TDepthRange;
3384 // Values after applying our transformation
3385 NewTransformation: TTransformation;
3386 NewFrustum: TFrustum;
3387 begin
3388 SavedInMeaningfulParent := Params.InMeaningfulParent;
3389 Params.InMeaningfulParent := Params.InMeaningfulParent and
3390 { We look at Parent.MeaningfulParent, not Self.MeaningfulParent,
3391 because CGE editor visualizations on TCastleTransformReference.Reference
3392 should still be rendered. }
3393 //((Parent = nil) or Parent.MeaningfulParent);
3394 MeaningfulParent;
3395
3396 HasSavedDepthRange := RenderLayer <> rlParent;
3397 if HasSavedDepthRange then
3398 begin
3399 { The idea of using DepthRange for render layers is nice:
3400 you don't have to split rendering layers in passes,
3401 you can render all objects in one pass,
3402 just switching DepthRange as necessary. }
3403 SavedDepthRange := Params.DepthRange;
3404 case RenderLayer of
3405 rlFront: Params.DepthRange := drNear;
3406 rlBack : Params.DepthRange := drFar;
3407 else ;
3408 end;
3409 end else
3410 SavedDepthRange := Low(SavedDepthRange); // avoid Delphi warnings about SavedDepthRange uninitialized
3411
3412 if (not InternalExistsOnlyInMeaningfulParents) or Params.InMeaningfulParent then
3413 begin
3414 T := Translation;
3415 if FOnlyTranslation and T.IsZero and (not InternalIgnoreParentScale) then
3416 begin
3417 if FBehaviorsNeedBeforeRender then
3418 BehaviorsBeforeRender(
3419 Params.RenderingCamera.View,
3420 Params.Transformation^,
3421 Params.Transformation^);
3422 LocalRender(Params);
3423 end else
3424 begin
3425 //FrameProfiler.Start(fmRenderTransform);
3426
3427 SavedTransformationPtr := Params.Transformation;
3428 SavedFrustumPtr := Params.Frustum;
3429 Assert(SavedFrustumPtr <> nil);
3430
3431 NewTransformation := SavedTransformationPtr^;
3432 NewFrustum := SavedFrustumPtr^;
3433
3434 Params.Transformation := @NewTransformation;
3435 Params.Frustum := @NewFrustum;
3436
3437 if InternalIgnoreParentScale then
3438 NewTransformation.ScaleToIdentity;
3439
3440 { Update NewXxx to apply the transformation defined by this TCastleTransform.
3441 LocalRender expects Frustum in local coordinates (without transformation),
3442 so we subtract transformation below. }
3443 if FOnlyTranslation then
3444 begin
3445 NewTransformation.Translate(T);
3446 NewFrustum.MoveVar(-T);
3447 end else
3448 begin
3449 InternalTransformationMult(NewTransformation);
3450 if IsNan(NewTransformation.Transform.Data[0, 0]) then
3451 WarningMatrixNan(NewTransformation.Transform);
3452 NewFrustum := NewFrustum.TransformByInverse(Transform);
3453 { Equivalent version but slower (more than 2x),
3454 see speed tests near TTestCastleFrustum.TestTransformFrustum: }
3455 //NewFrustum := NewFrustum.Transform(InverseTransform);
3456 end;
3457
3458 //FrameProfiler.Stop(fmRenderTransform);
3459 if FBehaviorsNeedBeforeRender then
3460 BehaviorsBeforeRender(
3461 Params.RenderingCamera.View,
3462 SavedTransformationPtr^,
3463 Params.Transformation^);
3464 LocalRender(Params);
3465 //FrameProfiler.Start(fmRenderTransform);
3466
3467 { Restore SavedXxxPtr values.
3468 They can be restored fast, thanks to restoring pointers, not content. }
3469 Params.Transformation := SavedTransformationPtr;
3470 Params.Frustum := SavedFrustumPtr;
3471 //FrameProfiler.Stop(fmRenderTransform);
3472 end;
3473 end;
3474
3475 Params.InMeaningfulParent := SavedInMeaningfulParent;
3476
3477 if HasSavedDepthRange then
3478 Params.DepthRange := SavedDepthRange;
3479 end;
3480
3481 procedure TCastleTransform.RenderShadowVolume(const Params: TRenderParams;
3482 const ShadowVolumeRenderer: TBaseShadowVolumeRenderer);
3483 var
3484 T: TVector3;
3485 // Saved Params.Transformation, Params.Frustum before applying our transformation
3486 SavedTransformationPtr: PTransformation;
3487 SavedFrustumPtr: PFrustum;
3488 // Values after applying our transformation
3489 NewTransformation: TTransformation;
3490 NewFrustum: TFrustum;
3491 begin
3492 T := Translation;
3493 if FOnlyTranslation and T.IsZero then
3494 begin
3495 LocalRenderShadowVolume(Params, ShadowVolumeRenderer);
3496 end else
3497 begin
3498 { TODO: This is a copy-paste of transformation algorithm from TCastleTransform.Render. }
3499
3500 SavedTransformationPtr := Params.Transformation;
3501 SavedFrustumPtr := Params.Frustum;
3502 Assert(SavedFrustumPtr <> nil);
3503
3504 NewTransformation := SavedTransformationPtr^;
3505 NewFrustum := SavedFrustumPtr^;
3506
3507 Params.Transformation := @NewTransformation;
3508 Params.Frustum := @NewFrustum;
3509
3510 if InternalIgnoreParentScale then
3511 NewTransformation.ScaleToIdentity;
3512
3513 { Update NewXxx to apply the transformation defined by this TCastleTransform.
3514 LocalRender expects Frustum in local coordinates (without transformation),
3515 so we subtract transformation below. }
3516 if FOnlyTranslation then
3517 begin
3518 NewTransformation.Translate(T);
3519 NewFrustum.MoveVar(-T);
3520 end else
3521 begin
3522 InternalTransformationMult(NewTransformation);
3523 if IsNan(NewTransformation.Transform.Data[0, 0]) then
3524 WarningMatrixNan(NewTransformation.Transform);
3525 NewFrustum := NewFrustum.TransformByInverse(Transform);
3526 // 2x slower: NewFrustum := NewFrustum.Transform(InverseTransform);
3527 end;
3528
3529 LocalRenderShadowVolume(Params, ShadowVolumeRenderer);
3530
3531 { Restore SavedXxxPtr values.
3532 They can be restored fast, thanks to restoring pointers, not content. }
3533 Params.Transformation := SavedTransformationPtr;
3534 Params.Frustum := SavedFrustumPtr;
3535 end;
3536 end;
3537
3538 { Bottom value (0 or box bottom).
3539 In the same coordinate system as given ModelBox. }
3540 function Bottom(const Gravity: boolean; const GravityCoordinate: Integer;
3541 const ModelBox: TBox3D): Single;
3542 begin
3543 if Gravity then
3544 Result := 0 else
3545 Result := ModelBox.Data[0][GravityCoordinate];
3546 end;
3547
3548 function TCastleTransform.DistanceToParent(const Distance: Single): Single;
3549 begin
3550 Result := Distance * Abs(AverageScale);
3551 end;
3552
3553 function TCastleTransform.Middle: TVector3;
3554 var
3555 GC: Integer;
3556 B: TBox3D;
3557 begin
3558 GC := World.GravityCoordinate;
3559 if InternalMiddleForceBox then
3560 B := InternalMiddleForceBoxValue
3561 else
3562 B := LocalBoundingBox;
3563
3564 { More correct version would be to take B bottom point, add PreferredHeight,
3565 and transform this point just like TCastleTransform transforms everything
3566 else. Optimized implementation below assumes that instead
3567 of transforming we can add Translation, so we assume that
3568 transformations do not change this middle point
3569 (which is Ok if you think e.g. about a non-flying creature that,
3570 besides moving, only rotates around it's own up axis). }
3571
3572 Result := Translation;
3573 { Using deprecated in deprecated.
3574 This should be simpler at some point:
3575 Result.Data[GC] := Lerp(MiddleHeight, B.Data[0][GC], B.Data[1][GC]);
3576 }
3577 {$warnings off}
3578 Result.Data[GC] := Result.Data[GC] +
3579 DistanceToParent(Bottom(Gravity, GC, B)) +
3580 PreferredHeight;
3581 {$warnings on}
3582 end;
3583
3584 function TCastleTransform.PreferredHeight: Single;
3585 var
3586 GC: Integer;
3587 B: TBox3D;
3588 { $define CHECK_HEIGHT_VS_RADIUS}
3589 {$ifdef CHECK_HEIGHT_VS_RADIUS} R: Single; {$endif}
3590 begin
3591 GC := World.GravityCoordinate;
3592 if InternalMiddleForceBox then
3593 B := InternalMiddleForceBoxValue
3594 else
3595 B := LocalBoundingBox;
3596 if B.IsEmpty then
3597 Result := 0
3598 else
3599 {$warnings off} // using deprecated in deprecated
3600 Result := MiddleHeight *
3601 DistanceToParent(
3602 B.Data[1][GC] - Bottom(Gravity, GC, B)
3603 );
3604 {$warnings on}
3605
3606 {$ifdef CHECK_HEIGHT_VS_RADIUS}
3607 if Sphere(R) and (R > Result) then
3608 begin
3609 WritelnWarning('3D Radius',
3610 Format('PreferredHeight %f is smaller than radius %f. Gravity may work weird for this 3D object.',
3611 [Result, R]));
3612 end;
3613 {$endif}
3614 end;
3615
3616 {$warnings off} // keep deprecated working
3617 procedure TCastleTransform.UpdateSimpleGravity(const SecondsPassed: Single);
3618
3619 procedure DoGravity(const PreferredHeight: Single);
3620 var
3621 GravityUp: TVector3;
3622
3623 { TODO: this is a duplicate of similar TCastleWalkNavigation method }
3624 procedure DoFall;
3625 var
3626 BeginPos, EndPos, FallVector: TVector3;
3627 begin
3628 { Project Middle and FFallingStartMiddle
3629 onto GravityUp vector to calculate fall height. }
3630 BeginPos := PointOnLineClosestToPoint(TVector3.Zero, GravityUp, FFallingStartMiddle);
3631 EndPos := PointOnLineClosestToPoint(TVector3.Zero, GravityUp, Middle);
3632 FallVector := BeginPos - EndPos;
3633
3634 { Because of various growing and jumping effects (imagine you jump up
3635 onto a taller pillar) it may turn out that we're higher at the end
3636 at the end of fall. Do not report it to Fall event in this case. }
3637 if TVector3.DotProduct(GravityUp, FallVector.Normalize) <= 0 then
3638 Exit;
3639
3640 Fall(FallVector.Length);
3641 end;
3642
3643 const
3644 { HeightMargin is used to safeguard against floating point inaccuracy.
3645 Without this, creature would too often be considered "falling down"
3646 or "growing up". }
3647 HeightMargin = 1.01;
3648 var
3649 IsAbove: boolean;
3650 AboveHeight, RadiusIgnored: Single;
3651 OldFalling: boolean;
3652 FallingDistance, MaximumFallingDistance: Single;
3653 begin
3654 if (World = nil) or
3655 (World.MainCamera = nil) then
3656 Exit;
3657
3658 { calculate and save GravityUp once, it's used quite often in this procedure }
3659 GravityUp := World.GravityUp;
3660
3661 OldFalling := FFalling;
3662
3663 IsAbove := Height(Middle, AboveHeight);
3664
3665 if (FallSpeed <> 0) and
3666 (AboveHeight > PreferredHeight * HeightMargin) then
3667 begin
3668 { Fall down }
3669 if not FFalling then
3670 FFallingStartMiddle := Middle;
3671
3672 FFalling := true;
3673
3674 FallingDistance := FallSpeed * SecondsPassed;
3675 if IsAbove then
3676 begin
3677 MaximumFallingDistance := AboveHeight - PreferredHeight;
3678
3679 { If you will fall down by exactly
3680 AboveHeight - PreferredHeight,
3681 then you will get exatly into collision with the ground.
3682 So actually this is too large MaximumFallingDistance.
3683
3684 But actually it's OK when Sphere is used, because then wall-sliding
3685 in MoveCollision can correct new position,
3686 so actually it will be slightly above the ground. So falling
3687 down will work.
3688
3689 But when Sphere is not used, the situation is worse,
3690 because then MoveCollision doesn't do wall-sliding.
3691 And it will always simply reject such move
3692 with MaximumFallingDistance.
3693 If FPS is low (so we would like to fall down at once
3694 by large distance), this is noticeable: in such case, instead
3695 of falling down, creature hangs over the ground,
3696 because MoveCollision simply doesn't allow it fall
3697 exactly by AboveHeight - PreferredHeight.
3698 So MaximumFallingDistance has to be a little smaller in this case.
3699 In particular, this was noticeable for the initially dead alien
3700 creature on "Doom" level, when shadows were on (when shadows were on,
3701 FPS is low, that's why the bug was noticeable only with shadows = on).
3702
3703 TODO: the better version would be to improve
3704 MoveCollision for Sphere=false case, instead of
3705 workarounding it here with this epsilon.
3706 See TBaseTrianglesOctree.MoveCollision. }
3707 if not Sphere(RadiusIgnored) then
3708 MaximumFallingDistance := MaximumFallingDistance - 0.01;
3709 MinVar(FallingDistance, MaximumFallingDistance);
3710 end;
3711
3712 if not Move(GravityUp * -FallingDistance, true) then
3713 FFalling := false;
3714 end else
3715 begin
3716 FFalling := false;
3717
3718 if (GrowSpeed <> 0) and
3719 (AboveHeight < PreferredHeight / HeightMargin) then
3720 begin
3721 { Growing up }
3722 Move(GravityUp * Min(GrowSpeed * SecondsPassed,
3723 PreferredHeight - AboveHeight), false);
3724 end;
3725 end;
3726
3727 if OldFalling and (not FFalling) then
3728 DoFall;
3729 end;
3730
3731 var
3732 PH: Single;
3733 begin
3734 if Gravity then
3735 begin
3736 PH := PreferredHeight;
3737 if (PH <> 0) and
3738 ((FallSpeed <> 0) or (GrowSpeed <> 0)) then
3739 { calculate and save PreferredHeight once,
3740 as it's used quite often in the DoGravity procedure }
3741 DoGravity(PH);
3742 end;
3743 end;
3744 {$warnings on}
3745
3746 procedure TCastleTransform.Fall(const FallHeight: Single);
3747 begin
3748 { Nothing to do in this class }
3749 end;
3750
3751 function TCastleTransform.Move(const TranslationChange: TVector3;
3752 const BecauseOfGravity: boolean; const EnableWallSliding: boolean): boolean;
3753 var
3754 OldMiddle, ProposedNewMiddle, NewMiddle: TVector3;
3755 begin
3756 OldMiddle := Middle;
3757
3758 if EnableWallSliding then
3759 begin
3760 ProposedNewMiddle := OldMiddle + TranslationChange;
3761 Result := MoveAllowed(OldMiddle, ProposedNewMiddle, NewMiddle, BecauseOfGravity);
3762 end else
3763 begin
3764 NewMiddle := OldMiddle + TranslationChange;
3765 Result := MoveAllowed(OldMiddle, NewMiddle, BecauseOfGravity);
3766 end;
3767
3768 if Result then
3769 Translate(NewMiddle - OldMiddle);
3770 end;
3771
3772 procedure TCastleTransform.ChangedTransformCore(const UpdatePhysicsTransform: Boolean);
3773
3774 procedure RecursiveRigidBodySetWorldTransformation(const Transform: TCastleTransform);
3775 var
3776 I: Integer;
3777 RBody: TCastleRigidBody;
3778 begin
3779 RBody := Transform.RigidBody;
3780 if (RBody <> nil) and
3781 (not RBody.DuringSettingTransformationFromPhysicsEngine) then
3782 RBody.SetWorldTransformation(Transform.WorldTransform);
3783
3784 { TODO: This is time-consuming for changing larger hierarchies.
3785 We should avoid it somehow. }
3786 if InternalMovesPhysicsBodies then
3787 for I := 0 to Transform.List.Count - 1 do
3788 RecursiveRigidBodySetWorldTransformation(Transform.List[I]);
3789 end;
3790
3791 begin
3792 FTransformationValid := false;
3793 FWorldTransformationValid := false;
3794 VisibleChangeHere([vcVisibleGeometry]);
3795
3796 if (FWorld <> nil) and (FWorld.EnablePhysics) and UpdatePhysicsTransform then
3797 begin
3798 RecursiveRigidBodySetWorldTransformation(Self);
3799 end;
3800
3801 ChangedTransform;
3802 end;
3803
3804 procedure TCastleTransform.ChangedTransform;
3805 begin
3806 end;
3807
3808 procedure TCastleTransform.CustomSerialization(const SerializationProcess: TSerializationProcess);
3809 begin
3810 inherited;
3811 SerializationProcess.ReadWriteList('Children',
3812 {$ifdef FPC}@{$endif}SerializeChildrenEnumerate,
3813 {$ifdef FPC}@{$endif}SerializeChildrenAdd,
3814 {$ifdef FPC}@{$endif}SerializeChildrenClear);
3815 SerializationProcess.ReadWriteList('Behaviors',
3816 {$ifdef FPC}@{$endif}SerializeBehaviorsEnumerate,
3817 {$ifdef FPC}@{$endif}SerializeBehaviorsAdd,
3818 {$ifdef FPC}@{$endif}SerializeBehaviorsClear);
3819 end;
3820
3821 procedure TCastleTransform.SerializeChildrenEnumerate(const Proc: TGetChildProc);
3822 var
3823 I: Integer;
3824 begin
3825 for I := 0 to List.Count - 1 do
3826 if List[I].ComponentStyle * [csSubComponent, csTransient] = [] then
3827 Proc(List[I]);
3828 end;
3829
3830 procedure TCastleTransform.SerializeChildrenAdd(const C: TComponent);
3831 begin
3832 Add(C as TCastleTransform);
3833 end;
3834
3835 procedure TCastleTransform.SerializeChildrenClear;
3836 var
3837 I: Integer;
3838 begin
3839 for I := List.Count - 1 downto 0 do // downto, as list may shrink during loop
3840 if List[I].ComponentStyle * [csSubComponent, csTransient] = [] then
3841 List[I].Free; // will remove itself from children list
3842 end;
3843
3844 procedure TCastleTransform.SerializeBehaviorsEnumerate(const Proc: TGetChildProc);
3845 var
3846 I: Integer;
3847 begin
3848 for I := 0 to BehaviorsCount - 1 do
3849 if Behaviors[I].ComponentStyle * [csSubComponent, csTransient] = [] then
3850 Proc(Behaviors[I]);
3851 end;
3852
3853 procedure TCastleTransform.SerializeBehaviorsAdd(const C: TComponent);
3854 begin
3855 AddBehavior(C as TCastleBehavior);
3856 end;
3857
3858 procedure TCastleTransform.SerializeBehaviorsClear;
3859 var
3860 I: Integer;
3861 begin
3862 for I := BehaviorsCount - 1 downto 0 do // downto, as list may shrink during loop
3863 if Behaviors[I].ComponentStyle * [csSubComponent, csTransient] = [] then
3864 Behaviors[I].Free; // will remove itself from Behaviors list
3865 end;
3866
3867 function TCastleTransform.PropertySections(const PropertyName: String): TPropertySections;
3868 begin
3869 if ArrayContainsString(PropertyName, [
3870 'Exists', 'CastShadows', 'RenderLayer'
3871 ]) then
3872 Result := [psBasic]
3873 else
3874 if ArrayContainsString(PropertyName, [
3875 'CenterPersistent', 'ScaleOrientationPersistent'
3876 ]) then
3877 Result := [psLayout]
3878 else
3879 if ArrayContainsString(PropertyName, [
3880 'RotationPersistent', 'ScalePersistent', 'TranslationPersistent',
3881 // Direction and Up expose also Rotation but in alternative way
3882 'DirectionPersistent', 'UpPersistent'
3883 ]) then
3884 Result := [psBasic, psLayout]
3885 else
3886 Result := inherited PropertySections(PropertyName);
3887 end;
3888
3889 { We try hard to keep FOnlyTranslation return fast, and return with true.
3890 This allows TCastleTransform to be optimized and accurate
3891 for the (often) case of pure translation. }
3892
3893 function TCastleTransform.OnlyTranslation: boolean;
3894 begin
3895 Result := FOnlyTranslation;
3896 end;
3897
3898 procedure TCastleTransform.SetCenter(const Value: TVector3);
3899 begin
3900 if not TVector3.PerfectlyEquals(FCenter, Value) then
3901 begin
3902 FCenter := Value;
3903 FOnlyTranslation := FOnlyTranslation and Value.IsPerfectlyZero;
3904 ChangedTransformCore;
3905 end;
3906 end;
3907
3908 procedure TCastleTransform.SetRotation(const Value: TVector4);
3909 begin
3910 if not TVector4.PerfectlyEquals(FRotation, Value) then
3911 begin
3912 FRotation := Value;
3913 FOnlyTranslation := FOnlyTranslation and (Value[3] = 0);
3914 ChangedTransformCore;
3915 end;
3916 end;
3917
3918 procedure TCastleTransform.SetScale(const Value: TVector3);
3919 var
3920 UpdatePhysicsTransform: Boolean;
3921 begin
3922 if not TVector3.PerfectlyEquals(FScale, Value) then
3923 begin
3924 { No point in doing RBody.SetWorldTransformation when scale only changed
3925 e.g. from (-1,1,1) to (1,1,1).
3926 This avoids causing noticeable delays when moving in platformer,
3927 that updates scale often. }
3928 UpdatePhysicsTransform := not TVector3.Equals(FScale.Abs, Value.Abs);
3929
3930 FScale := Value;
3931 FOnlyTranslation := FOnlyTranslation and
3932 (Value[0] = 1) and (Value[1] = 1) and (Value[2] = 1);
3933 ChangedTransformCore(UpdatePhysicsTransform);
3934
3935 if (FWorld <> nil) and
3936 FWorld.EnablePhysics then
3937 UpdateCollidersWorldScale;
3938 end;
3939 end;
3940
3941 procedure TCastleTransform.SetScaleOrientation(const Value: TVector4);
3942 begin
3943 if not TVector4.PerfectlyEquals(FScaleOrientation, Value) then
3944 begin
3945 FScaleOrientation := Value;
3946 FOnlyTranslation := FOnlyTranslation and (Value[3] = 0);
3947 ChangedTransformCore;
3948 end;
3949 end;
3950
3951 procedure TCastleTransform.SetTranslation(const Value: TVector3);
3952 begin
3953 if not TVector3.PerfectlyEquals(FTranslation, Value) then
3954 begin
3955 FTranslation := Value;
3956 ChangedTransformCore;
3957 end;
3958 end;
3959
3960 function TCastleTransform.GetTranslationXY: TVector2;
3961 begin
3962 Result := Translation.XY;
3963 end;
3964
3965 procedure TCastleTransform.SetTranslationXY(const Value: TVector2);
3966 begin
3967 Translation := Vector3(Value, Translation.Z);
3968 end;
3969
3970 procedure TCastleTransform.Translate(const TranslationChange: TVector3);
3971 begin
3972 Translation := Translation + TranslationChange;
3973 end;
3974
3975 procedure TCastleTransform.Identity;
3976 begin
3977 Center := TVector3.Zero;
3978 Rotation := TVector4.Zero;
3979 Scale := NoScale;
3980 ScaleOrientation := TVector4.Zero;
3981 Translation := TVector3.Zero;
3982 end;
3983
3984 function TCastleTransform.RotationFromDirectionUp(const D, U: TVector3): TVector4;
3985 begin
3986 Result := OrientationFromDirectionUp(D, U,
3987 DefaultDirection[Orientation],
3988 DefaultUp[Orientation]
3989 );
3990 end;
3991
3992 function TCastleTransform.RotationToDirection(const ARotation: TVector4): TVector3;
3993 begin
3994 Result := RotatePointAroundAxis(ARotation, DefaultDirection[Orientation]);
3995 end;
3996
3997 function TCastleTransform.RotationToUp(const ARotation: TVector4): TVector3;
3998 begin
3999 Result := RotatePointAroundAxis(ARotation, DefaultUp[Orientation]);
4000 end;
4001
4002 function TCastleTransform.GetDirection: TVector3;
4003 begin
4004 Result := RotationToDirection(Rotation);
4005 end;
4006
4007 function TCastleTransform.GetUp: TVector3;
4008 begin
4009 Result := RotationToUp(Rotation);
4010 end;
4011
4012 procedure TCastleTransform.SetDirection(const Value: TVector3);
4013 var
4014 D, U: TVector3;
4015 begin
4016 D := Value; // no need to normalize here
4017 U := GetUp;
4018 MakeVectorsOrthoOnTheirPlane(U, D);
4019 Rotation := RotationFromDirectionUp(D, U);
4020 end;
4021
4022 procedure TCastleTransform.SetUp(const Value: TVector3);
4023 var
4024 D, U: TVector3;
4025 begin
4026 U := Value; // no need to normalize here
4027 D := GetDirection;
4028 MakeVectorsOrthoOnTheirPlane(D, U);
4029 Rotation := RotationFromDirectionUp(D, U);
4030 end;
4031
4032 procedure TCastleTransform.UpPrefer(const AUp: TVector3);
4033 var
4034 D, U: TVector3;
4035 begin
4036 U := AUp; // no need to normalize here
4037 D := GetDirection;
4038 MakeVectorsOrthoOnTheirPlane(U, D);
4039 Rotation := RotationFromDirectionUp(D, U);
4040 end;
4041
4042 procedure TCastleTransform.GetView(out APos, ADir, AUp: TVector3);
4043 begin
4044 APos := Translation;
4045 ADir := Direction;
4046 AUp := Up;
4047 end;
4048
4049 procedure TCastleTransform.GetWorldView(out APos, ADir, AUp: TVector3);
4050 var
4051 T, S: TVector3;
4052 R: TVector4;
4053 begin
4054 MatrixDecompose(WorldTransform, T, R, S);
4055 APos := T;
4056 ADir := RotationToDirection(R);
4057 AUp := RotationToUp(R);
4058 end;
4059
4060 function TCastleTransform.GetWorldViewRec: TViewVectors;
4061 begin
4062 GetWorldView(Result.Translation, Result.Direction, Result.Up);
4063 end;
4064
4065 procedure TCastleTransform.SetWorldViewRec(const Value: TViewVectors);
4066 begin
4067 SetWorldView(Value.Translation, Value.Direction, Value.Up);
4068 end;
4069
4070 function TCastleTransform.WorldTranslation: TVector3;
4071 begin
4072 Result := TranslationFromMatrix(WorldTransform);
4073 end;
4074
4075 procedure TCastleTransform.SetView(const APos, ADir, AUp: TVector3;
4076 const AdjustUp: boolean);
4077 begin
4078 Translation := APos;
4079 SetView(ADir, AUp, AdjustUp);
4080 end;
4081
4082 procedure TCastleTransform.SetView(const ADir, AUp: TVector3;
4083 const AdjustUp: boolean);
4084 var
4085 D, U: TVector3;
4086 begin
4087 D := ADir; // no need to normalize here
4088 U := AUp; // no need to normalize here
4089 if AdjustUp then
4090 MakeVectorsOrthoOnTheirPlane(U, D)
4091 else
4092 MakeVectorsOrthoOnTheirPlane(D, U);
4093 Rotation := RotationFromDirectionUp(D, U);
4094 end;
4095
4096 procedure TCastleTransform.SetWorldView(const APos, ADir, AUp: TVector3;
4097 const AdjustUp: boolean = true);
4098 var
4099 D, U, T, S: TVector3;
4100 R: TVector4;
4101 DesiredWorldTransform, ParentWorldTransform, LocalTransform: TMatrix4;
4102 ParentWorldTransformDeterminant: Single;
4103 begin
4104 if Parent = nil then
4105 begin
4106 SetView(APos, ADir, AUp, AdjustUp);
4107 Exit;
4108 end;
4109
4110 D := ADir; // no need to normalize here
4111 U := AUp; // no need to normalize here
4112 if AdjustUp then
4113 MakeVectorsOrthoOnTheirPlane(U, D)
4114 else
4115 MakeVectorsOrthoOnTheirPlane(D, U);
4116 DesiredWorldTransform := TranslationMatrix(APos) * RotationMatrix(RotationFromDirectionUp(D, U));
4117
4118 { Note: This would be wrong:
4119 DesiredWorldTransform := LookDirMatrix(APos, D, U);
4120 as LookDirMatrix already assumes some things about camera, e.g. that it looks along -Z.
4121 But SetWorldView and GetWorldView are independent from cameras,
4122 so think only in terms of "rotations" (just like GetWorldView does),
4123 and only convert from/to direction/up using RotationFromDirectionUp/RotationTo...
4124 }
4125
4126 ParentWorldTransform := Parent.WorldTransform;
4127 ParentWorldTransformDeterminant := ParentWorldTransform.Determinant;
4128 if IsZero(ParentWorldTransformDeterminant) then
4129 begin
4130 WritelnWarning('Camera under non-reversible world transformation, cannot apply camera vectors reliably.');
4131 SetView(APos, ADir, AUp, AdjustUp);
4132 Exit;
4133 end;
4134
4135 { We want LocalTransform such that
4136 ParentWorldTransform * LocalTransform = DesiredWorldTransform }
4137 LocalTransform := ParentWorldTransform.Inverse(ParentWorldTransformDeterminant) * DesiredWorldTransform;
4138 MatrixDecompose(LocalTransform, T, R, S);
4139 Translation := T;
4140 Rotation := R;
4141 Scale := S;
4142 end;
4143
4144 function TCastleTransform.GetEnumerator: TEnumerator;
4145 begin
4146 Result := TEnumerator.Create(FList);
4147 end;
4148
4149 function TCastleTransform.HasColliderMesh: Boolean;
4150 begin
4151 Result := false;
4152 end;
4153
4154 procedure TCastleTransform.ColliderMesh(const TriangleEvent: TTriangleEvent);
4155 begin
4156 // No triangles returned by this
4157 end;
4158
4159 function TCastleTransform.BehaviorsEnumerate: TCastleBehaviorEnumerator;
4160 begin
4161 Result := TCastleBehaviorEnumerator.Create(Self);
4162 end;
4163
4164 procedure TCastleTransform.AddWorldChangeNotification(
4165 const Behavior: TCastleBehavior);
4166 begin
4167 if FBehaviorsWorldChangeNotificationList = nil then
4168 FBehaviorsWorldChangeNotificationList := TCastleBehaviorList.Create(false);
4169
4170 if FBehaviorsWorldChangeNotificationList.IndexOf(Behavior) = -1 then
4171 FBehaviorsWorldChangeNotificationList.Add(Behavior);
4172 end;
4173
4174 procedure TCastleTransform.RemoveWorldChangeNotification(
4175 const Behavior: TCastleBehavior);
4176 begin
4177 if FBehaviorsWorldChangeNotificationList = nil then
4178 Exit;
4179
4180 FBehaviorsWorldChangeNotificationList.Remove(Behavior);
4181 end;
4182
4183 procedure TCastleTransform.SetListenPressRelease(const Value: Boolean);
4184 begin
4185 if FListenPressRelease <> Value then
4186 begin
4187 FListenPressRelease := Value;
4188 if World <> nil then
4189 begin
4190 if Value then
4191 FWorld.RegisterPressRelease(Self)
4192 else
4193 FWorld.UnregisterPressRelease(Self);
4194 end;
4195 end;
4196 end;
4197
4198 function TCastleTransform.BehaviorsCount: Integer;
4199 begin
4200 { This can be called when TCastleTransform is in the middle of being
4201 destroyed, and TDesignFrame.SetTransformForGizmos tries to iterate
4202 over behaviors. So prepare to handle FBehaviors = nil case,
4203 which should not be possible during normal lifetime. }
4204 if FBehaviors = nil then
4205 Exit(0);
4206
4207 Result := FBehaviors.Count;
4208 end;
4209
4210 function TCastleTransform.GetBehaviors(const Index: Integer): TCastleBehavior;
4211 begin
4212 Result := TCastleBehavior(FBehaviors[Index]);
4213 end;
4214
4215 procedure TCastleTransform.UpdateCachedBehaviors;
4216 begin
4217 FCachedRigidBody := FindBehavior(TCastleRigidBody) as TCastleRigidBody;
4218 FCachedCollider := FindBehavior(TCastleCollider) as TCastleCollider;
4219 end;
4220
4221 procedure TCastleTransform.AddBehavior(const Behavior: TCastleBehavior);
4222 var
4223 ReasonWhyCannot: String;
4224 begin
4225 if Behavior.FParent <> Self then
4226 begin
4227 if not Behavior.CanAttachToParent(Self, ReasonWhyCannot) then
4228 raise Exception.CreateFmt('Cannot add behavior %s (%s) to %s (%s) because: %s', [
4229 Behavior.Name,
4230 Behavior.ClassName,
4231 Name,
4232 ClassName,
4233 ReasonWhyCannot
4234 ]);
4235
4236 { As a first action (after the check CanAttachToParent has passed) remove
4237 from previous parent. This will also cause necessary virtual method calls,
4238 like ParentBeforeDetach, WorldBeforeDetach. }
4239 if Behavior.FParent <> nil then
4240 Behavior.FParent.RemoveBehavior(Behavior);
4241 Assert(Behavior.FParent = nil);
4242
4243 { Add to new parent }
4244
4245 FBehaviors.Add(Behavior);
4246 Behavior.FParent := Self;
4247 Behavior.ParentAfterAttach;
4248 {$warnings off}
4249 Behavior.ParentChanged; // call at end, when state is consistent
4250 {$warnings on}
4251
4252 { Call WorldAfterAttach }
4253 if Behavior.ListenWorldChange then
4254 begin
4255 AddWorldChangeNotification(Behavior);
4256 if FWorld <> nil then
4257 Behavior.WorldAfterAttach;
4258 end;
4259 NotifyBehaviorAdded(Behavior);
4260
4261 UpdateBehaviorsNeedBeforeRender;
4262 UpdateCachedBehaviors;
4263 end;
4264 end;
4265
4266 (*
4267 This is only for unused MoveBehaviorBeforeAfterAnotherBehavior now.
4268 TODO: Cannot be implemented like this, as copy-paste of AddBehavior -- to easy
4269 to introduce mistakes when maintaining (it already happened at merge).
4270 Should be implemented by adjusting AddBehavior, and then
4271 AddBehavior should jus call InsertBehavior.
4272
4273 procedure TCastleTransform.InsertBehavior(const Index: Integer;
4274 const Behavior: TCastleBehavior);
4275 var
4276 ReasonWhyCannot: String;
4277 begin
4278 // TODO: A lot of code copied form AddBehavior()
4279 // TODO: What to do when Behavior.FParent = Self only move on list or? remove and insert?
4280 // TODO: maybe should be Internal
4281 if Behavior.FParent <> Self then
4282 begin
4283 if not Behavior.CanAttachToParent(Self, ReasonWhyCannot) then
4284 raise Exception.CreateFmt('Cannot add behavior %s (%s) to %s (%s) because: %s', [
4285 Behavior.Name,
4286 Behavior.ClassName,
4287 Name,
4288 ClassName,
4289 ReasonWhyCannot
4290 ]);
4291
4292 { As a first action (after the check CanAttachToParent has passed) remove
4293 from previous parent. This will also cause necessary virtual method calls,
4294 like ParentBeforeDetach, WorldBeforeDetach. }
4295 if Behavior.FParent <> nil then
4296 Behavior.FParent.RemoveBehavior(Behavior);
4297 Assert(Behavior.FParent = nil);
4298
4299 { Inseert to new parent }
4300 FBehaviors.Insert(Index, Behavior);
4301 Behavior.FParent := Self;
4302 Behavior.ParentAfterAttach;
4303 {$warnings off}
4304 Behavior.ParentChanged; // call at end, when state is consistent
4305 {$warnings on}
4306
4307 { Call WorldAfterAttach }
4308 if Behavior.ListenWorldChange then
4309 begin
4310 AddWorldChangeNotification(Behavior);
4311 if FWorld <> nil then
4312 Behavior.WorldAfterAttach;
4313 end;
4314 NotifyBehaviorAdded(Behavior);
4315
4316 UpdateBehaviorsNeedBeforeRender;
4317 UpdateCachedBehaviors;
4318 end;
4319 end;
4320 *)
4321
4322 function TCastleTransform.BehaviorIndex(const Behavior: TCastleBehavior
4323 ): Integer;
4324 begin
4325 Result := FBehaviors.IndexOf(Behavior);
4326 end;
4327
4328 procedure TCastleTransform.RemoveBehaviorIndex(const BehaviorIndex: Integer);
4329 var
4330 Beh: TCastleBehavior;
4331 begin
4332 Beh := FBehaviors[BehaviorIndex] as TCastleBehavior;
4333
4334 NotifyBeforeBehaviorRemove(Beh);
4335
4336 { Call WorldBeforeDetach }
4337 if Beh.ListenWorldChange and (FWorld <> nil) then
4338 Beh.WorldBeforeDetach;
4339
4340 Beh.ParentBeforeDetach;
4341
4342 Beh.FParent := nil;
4343 FBehaviors.Delete(BehaviorIndex);
4344 {$warnings off}
4345 Beh.ParentChanged; // call at end, when state is consistent
4346 {$warnings on}
4347 RemoveWorldChangeNotification(Beh);
4348
4349 UpdateBehaviorsNeedBeforeRender;
4350 UpdateCachedBehaviors;
4351 end;
4352
4353 procedure TCastleTransform.RemoveBehavior(const Behavior: TCastleBehavior);
4354 var
4355 I: Integer;
4356 begin
4357 if Behavior.FParent = Self then
4358 begin
4359 I := FBehaviors.IndexOf(Behavior);
4360 if I = -1 then
4361 begin
4362 WritelnWarning('Internal Error: Behavior %s %s has our parent, but is not present on FBehaviors list', [
4363 Behavior.Name,
4364 Behavior.ClassType
4365 ]);
4366 Exit;
4367 end;
4368 RemoveBehaviorIndex(I);
4369 end;
4370 end;
4371
4372 function TCastleTransform.FindBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
4373 var
4374 I: Integer;
4375 begin
4376 for I := 0 to FBehaviors.Count - 1 do
4377 if FBehaviors[I] is BehaviorClass then
4378 Exit(TCastleBehavior(FBehaviors[I])); // since it's BehaviorClass, casting to TCastleBehavior must be safe
4379 Result := nil;
4380 end;
4381
4382 function TCastleTransform.FindAllBehaviors(const BehaviorClass: TCastleBehaviorClass): TCastleBehaviorList;
4383
4384 procedure AddTransform(const T: TCastleTransform);
4385 var
4386 I: Integer;
4387 TChild: TCastleTransform;
4388 begin
4389 for I := 0 to T.FBehaviors.Count - 1 do
4390 if T.FBehaviors[I] is BehaviorClass then
4391 Result.Add(TCastleBehavior(T.FBehaviors[I]));
4392 for TChild in T do
4393 AddTransform(TChild);
4394 end;
4395
4396 begin
4397 Result := TCastleBehaviorList.Create(false);
4398 AddTransform(Self);
4399 end;
4400
4401 function TCastleTransform.FindRequiredBehavior(const BehaviorClass: TCastleBehaviorClass): TCastleBehavior;
4402 begin
4403 Result := FindBehavior(BehaviorClass);
4404 if Result = nil then
4405 begin
4406 Result := BehaviorClass.Create(Self);
4407 AddBehavior(Result);
4408 end;
4409 end;
4410
4411 var
4412 { Must be an instance of exactly TCastleBehavior, not any descedant.
4413 Used by CustomizedBeforeRender. }
4414 InternalBehavior: TCastleBehavior;
4415
4416 procedure TCastleTransform.UpdateBehaviorsNeedBeforeRender;
4417
4418 { Beh overriddes TCastleBehavior.BeforeRender.
4419
4420 Note: In general checking for such "is this method overridden" is dirty,
4421 as not expected by developers. But in this case it's used only for optimization,
4422 no functional change occurs: when FBehaviorsNeedBeforeRender is false
4423 (which is often), we can avoid calling BehaviorBeforeRender at all. }
4424 function CustomizedBeforeRender(const Beh: TCastleBehavior): Boolean;
4425 type
4426 TBeforeRenderEvent = procedure (
4427 const CameraView: TViewVectors;
4428 const ParentParentWorldTransformation, ParentWorldTransformation: TTransformation) of object;
4429 var
4430 CurMethod, NotOverriddedMethod: TBeforeRenderEvent;
4431 begin
4432 CurMethod := {$ifdef FPC}@{$endif} Beh.BeforeRender;
4433 NotOverriddedMethod := {$ifdef FPC}@{$endif} InternalBehavior.BeforeRender;
4434 Result := TMethod(CurMethod).Code <> TMethod(NotOverriddedMethod).Code;
4435 end;
4436
4437 var
4438 I: Integer;
4439 Beh: TCastleBehavior;
4440 begin
4441 FBehaviorsNeedBeforeRender := false;
4442 for I := 0 to FBehaviors.Count - 1 do
4443 begin
4444 Beh := FBehaviors[I] as TCastleBehavior;
4445 if CustomizedBeforeRender(Beh) then
4446 begin
4447 FBehaviorsNeedBeforeRender := true;
4448 Exit; // no point in checking the rest
4449 end;
4450 end;
4451 end;
4452
4453 procedure TCastleTransform.PendingRemovals;
4454 var
4455 I: Integer;
4456 Item: TCastleTransform;
4457 begin
4458 { We iterate downto, and still check that index is valid.
4459 That is because removing/freeing may call some virtual methods,
4460 and may in turn cause removal/free of other items,
4461 even items on the pending list.
4462 They may also add new items to this list. }
4463
4464 if FPendingToRemove <> nil then
4465 for I := FPendingToRemove.Count - 1 downto 0 do
4466 if I < FPendingToRemove.Count then
4467 begin
4468 Item := FPendingToRemove[I] as TCastleTransform;
4469 Remove(Item);
4470 FPendingToRemove.Remove(Item);
4471 end;
4472
4473 if FPendingToRemoveAndFree <> nil then
4474 for I := FPendingToRemoveAndFree.Count - 1 downto 0 do
4475 if I < FPendingToRemoveAndFree.Count then
4476 FPendingToRemoveAndFree[I].Free; // this will remove it from children, and from FPendingToRemoveAndFree
4477 end;
4478
4479 procedure TCastleTransform.RemoveDelayed(const Item: TCastleTransform; const FreeItem: Boolean = false);
4480 begin
4481 { Avoid crash in certain cases,
4482 see https://forum.castle-engine.io/t/sigsegv-when-i-try-to-remove/859/8 }
4483 if Item = Self then
4484 raise Exception.Create('Cannot remove the object from itself using RemoveDelayed');
4485
4486 if FreeItem then
4487 begin
4488 if FPendingToRemoveAndFree = nil then
4489 FPendingToRemoveAndFree := TComponentList.Create(false);
4490 { Just like TCastleApplicationProperties.FreeDelayed, avoid duplicates. }
4491 if FPendingToRemoveAndFree.IndexOf(Item) = -1 then
4492 FPendingToRemoveAndFree.Add(Item);
4493 end else
4494 begin
4495 if FPendingToRemove = nil then
4496 FPendingToRemove := TComponentList.Create(false);
4497 { Just like TCastleApplicationProperties.FreeDelayed, avoid duplicates. }
4498 if FPendingToRemove.IndexOf(Item) = -1 then
4499 FPendingToRemove.Add(Item);
4500 end;
4501 end;
4502
4503 procedure TCastleTransform.SetExists(const Value: Boolean);
4504 var
4505 RBody: TCastleRigidBody;
4506 begin
4507 if FExists <> Value then
4508 begin
4509 FExists := Value;
4510 UpdateExistsInRoot;
4511
4512 RBody := RigidBody; // FindBehavior(TCastleRigidBody) as TCastleRigidBody; // use cached value
4513 if (RBody <> nil) and RBody.Exists then
4514 begin
4515 if FLastExistsChangeFrameId = TFramesPerSecond.FrameId then
4516 WritelnWarning('%s:%s: The existence of this TCastleTransform changed multiple times in a single frame and it uses physics (has TCastleRigidBody and TCastleCollider behaviors). ' +
4517 'This is not good for performance and right now can even cause physics simulation crashes, esp. when TCastleCollider.AutoSize=true and animation may change LocalBoundingBox. ' +
4518 'Avoid changing the Exists of physical objects multiple times in a single Update.', [
4519 Name,
4520 ClassName
4521 ]);
4522 FLastExistsChangeFrameId := TFramesPerSecond.FrameId;
4523 end;
4524 end;
4525 end;
4526
4527 procedure TCastleTransform.SetParentExistsInRoot(const Value: Boolean);
4528 begin
4529 if FParentExistsInRoot <> Value then
4530 begin
4531 FParentExistsInRoot := Value;
4532 UpdateExistsInRoot;
4533 end;
4534 end;
4535
4536 procedure TCastleTransform.UpdateExistsInRoot;
4537 var
4538 NewExistsInRoot: Boolean;
4539 I: Integer;
4540 begin
4541 NewExistsInRoot := ParentExistsInRoot and Exists;
4542 if FExistsInRoot <> NewExistsInRoot then
4543 begin
4544 FExistsInRoot := NewExistsInRoot;
4545 for I := Count - 1 downto 0 do
4546 Items[I].ParentExistsInRoot := FExistsInRoot; // use child SetParentExistsInRoot, so it can update it's ExistsInRoot
4547 ExistsInRootChanged; // virtual, called at end to be called when all children are valid too
4548 end;
4549 end;
4550
4551 procedure TCastleTransform.ExistsInRootChanged;
4552 var
4553 RBody: TCastleRigidBody;
4554 begin
4555 { Update rigid body existence when ExistsInRoot changes }
4556 if (FWorld <> nil) and (FWorld.FKraftEngine <> nil) then
4557 begin
4558 RBody := RigidBody; // FindBehavior(TCastleRigidBody) as TCastleRigidBody; // use cached value
4559 if RBody <> nil then
4560 RBody.UpdateExist;
4561 end;
4562 end;
4563
4564 procedure TCastleTransform.SetParent(const Value: TCastleTransform);
4565 begin
4566 if Parent <> Value then
4567 begin
4568 if Parent <> nil then
4569 Parent.Remove(Self);
4570 if Value <> nil then
4571 Value.Add(Self);
4572 end;
4573 end;
4574
4575 procedure TCastleTransform.DesignerWarnings(const SList: TStrings);
4576
4577 { Scale is uniform (all 3 components are ~equal) and all components are > 0. }
4578 function ScalePhysicsFriendly(const S: TVector3): Boolean;
4579 begin
4580 Result :=
4581 (S.X > 0) and
4582 (S.Y > 0) and
4583 (S.Z > 0) and
4584 SameValue(S.X, S.Y) and
4585 SameValue(S.X, S.Z);
4586 end;
4587
4588 var
4589 R, C: TCastleBehavior;
4590 begin
4591 inherited;
4592 R := RigidBody; // FindBehavior(TCastleRigidBody) as TCastleRigidBody; // use cached value
4593 C := FindBehavior(TCastleCollider);
4594
4595 if (R <> nil) <> (C <> nil) then
4596 begin
4597
4598 SList.Add('Both TCastleRigidBody and TCastleCollider behaviors are required for physics to affect this component.');
4599 end;
4600
4601 if (R <> nil) and
4602 (C <> nil) then
4603 begin
4604 { physics behaviors set up }
4605 if not ScalePhysicsFriendly(Scale) then
4606 begin
4607 SList.Add('Physics engine only supports a uniform scale: all 3 scale components must be equal and posititive.');
4608 end;
4609 end else
4610 begin
4611 { physics behaviors not set up }
4612 if FindBehavior(TCastleAbstractJoint) <> nil then
4613 begin
4614 SList.Add('Physics joint only works if also TCastleRigidBody and TCastleCollider behaviors are present.');
4615 end;
4616 end;
4617 end;
4618
4619 {$define read_implementation_methods}
4620 {$I auto_generated_persistent_vectors/tcastletransform_persistent_vectors.inc}
4621 {$undef read_implementation_methods}
4622
4623 {$endif read_implementation}