Debian Codegraph @

src/scene/castlescenecore.pas

raw
1 {
2 Copyright 2003-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Loading and processing of scenes (TCastleSceneCore). }
17 unit CastleSceneCore;
18
19 {$I castleconf.inc}
20 {$I octreeconf.inc}
21
22 interface
23
24 uses SysUtils, Classes, Generics.Collections, Contnrs, Kraft,
25 CastleVectors, CastleBoxes, CastleTriangles, X3DFields, X3DNodes,
26 CastleClassUtils, CastleUtils, CastleShapes, CastleInternalTriangleOctree,
27 CastleInternalOctree, CastleInternalShapeOctree,
28 CastleKeysMouse, X3DTime, CastleCameras, CastleInternalBaseTriangleOctree,
29 CastleTimeUtils, CastleTransform, CastleInternalShadowMaps, CastleProjection,
30 CastleComponentSerialize, CastleInternalFileMonitor;
31
32 type
33 { These are various features that may be freed by
34 TCastleSceneCore.FreeResources.
35
36 @italic(Warning): This is for experienced usage of TCastleSceneCore.
37 Everything is explained in detail below, but still --- if you have some
38 doubts, or you just don't observe any memory shortage in your program,
39 it's probably best to not use TCastleSceneCore.FreeResources.
40
41 @unorderedList(
42 @item(For frTextureDataInNodes, frBackgroundImageInNodes and TrianglesList,
43 if you will free them unnecessarily
44 (i.e. you will use it after you freed it), it will be automatically
45 recreated on next use. So everything will work correctly, but you
46 will experience unnecessary slowdown if we will need to recreate
47 exactly the same resource over and over again.)
48
49 @item(For frTextureDataInNodes and frBackgroundImageInNodes note that
50 freeing these resources too eagerly may make texture cache
51 (see TextureImages) less effective. In normal circumstances,
52 if you will use the same cache instance throughout the program,
53 loaded images are reused. If you free frTextureDataInNodes
54 too early, you may remove them from the cache too early, and lose
55 a chance to reuse them. So you may cause unnecessary slowdown
56 of preparing models, e.g. inside PrepareResources.)
57 )
58 }
59 TSceneFreeResource = (
60 { Unloads the texture images/videos allocated in texture nodes.
61
62 It's useful if you know that you already prepared everything
63 that needed the texture images, and you will not need texture images
64 later. For TCastleScene this means that you use Optimization
65 method other than roNone,
66 and you already did PrepareResources (so textures are already loaded to OpenGL),
67 and your code will not access TextureImage / TextureVideo anymore.
68 This is commonly @true for various games.
69
70 Then you can call this to free some resources.
71
72 Note that if you made an accident and you will use some TextureImage or
73 TextureVideo after FreeResources, then you will get no crash,
74 but texture image will be simply reloaded. So you may experience
75 slowdown if you inappropriately use this feature. }
76 frTextureDataInNodes,
77
78 { Unloads the background images allocated in VRML/X3D Background nodes.
79 The same comments as for frTextureDataInNodes apply. }
80 frBackgroundImageInNodes,
81
82 { Free data created for shadow volumes processing.
83 This frees some memory, but trying to render shadow volumes will
84 need to recreate this data again (at least for all active shapes).
85 So freeing this is useful only if you have used shadow volumes,
86 but you will not need to render with shadow volumes anymore
87 (for some time). }
88 frShadowVolume
89 );
90
91 TSceneFreeResources = set of TSceneFreeResource;
92
93 TCastleSceneCore = class;
94
95 { Callback for TCastleSceneCore.OnGeometryChanged.
96
97 SomeLocalGeometryChanged means that octree, triangles, bounding volumes
98 local to some shape changed (not just e.g. shape transformation).
99
100 OnlyShapeChanged is meaningful when SomeLocalGeometryChanged = @true.
101 If nil, it indicates that only the given shape geometry changed.
102 If not nil, assume that every shape's geometry potentially changed. }
103 TSceneGeometryChanged = procedure (Scene: TCastleSceneCore;
104 const SomeLocalGeometryChanged: boolean;
105 OnlyShapeChanged: TShape) of object;
106
107 { Stack of bindable nodes (only the top, bound, node is used for rendering/navigation).
108 This keeps a stack of TAbstractBindableNode, with comfortable routines
109 to examine top and push/pop from top. The stack is actually stored
110 as a list, with the last item being the top one. }
111 TX3DBindableStack = class(TX3DBindableStackBasic)
112 private
113 FParentScene: TCastleSceneCore;
114 FOnBoundChanged: TNotifyEvent;
115 BoundChangedSchedule: Cardinal;
116 BoundChangedScheduled: boolean;
117
118 { A useful utility: if the Node is not @nil, send isBound = Value and
119 bindTime events to it. }
120 procedure SendIsBound(Node: TAbstractBindableNode; const Value: boolean);
121
122 { Add new node to the top.
123
124 This is internal, note that it doesn't send any events
125 and doesn't produce DoBoundChanged / DoScheduleBoundChanged. }
126 procedure Push(Node: TAbstractBindableNode);
127
128 { Remove current top node. Returns removed node, or @nil if no current
129 node was present (that is, stack was empty).
130
131 This is internal, note that it doesn't send any events
132 and doesn't produce DoBoundChanged / DoScheduleBoundChanged. }
133 function Pop: TAbstractBindableNode;
134
135 { When we're inside BeginChangesSchedule / EndChangesSchedule,
136 then DoScheduleBoundChanged will not immediately call DoBoundChanged.
137 Effectively, you can wrap a part of code inside
138 BeginChangesSchedule / EndChangesSchedule, to delay calling
139 DoBoundChanged (and so OnBoundChanged callback). }
140 procedure BeginChangesSchedule;
141 procedure EndChangesSchedule;
142 protected
143 { Notification when the currently bound node, that is
144 @link(Top), changed.
145 In this class, just calls OnBoundChanged if assigned. }
146 procedure DoBoundChanged; virtual;
147
148 { Call DoBoundChanged at the nearest comfortable time.
149 Either now (when not inside BeginChangesSchedule / EndChangesSchedule)
150 or at a closing EndChangesSchedule. }
151 procedure DoScheduleBoundChanged;
152 public
153 constructor Create(AParentScene: TCastleSceneCore);
154
155 property ParentScene: TCastleSceneCore read FParentScene;
156
157 { Returns top item on this stack, or @nil if not present. }
158 function Top: TAbstractBindableNode;
159
160 { Add new node to the top, but only if stack is currently empty.
161 If SendEvents, then isBound = true and bindTime events will be
162 send to newly bound node. }
163 procedure PushIfEmpty(Node: TAbstractBindableNode; SendEvents: boolean);
164
165 { Use when you suspect that some nodes on the stack
166 are no longer present in VRML/X3D graph RootNode (they were deleted).
167 In this case, they have to be removed from stack.
168
169 If this will change the currently bound node, then the new bound
170 node will receive isBound = true and bindTime events (the old node
171 will not receive any set_bind = false or isBound = false events, since it
172 may be destroyed by now). }
173 procedure CheckForDeletedNodes(const RootNode: TX3DRootNode;
174 const SendEvents: boolean);
175
176 { Handle set_bind event send to given Node.
177 This always generates appropriate events. }
178 procedure Set_Bind(Node: TAbstractBindableNode; const Value: boolean); override;
179
180 { Notification when the currently bound node, that is
181 @link(Top), changed. This also includes notification
182 when @link(Top) changed to (or from) @nil, that is
183 when no node becomes bound or when some node is initially bound. }
184 property OnBoundChanged: TNotifyEvent read FOnBoundChanged write FOnBoundChanged;
185 end;
186
187 TBackgroundStack = class(TX3DBindableStack)
188 public
189 function Top: TAbstractBackgroundNode;
190 procedure PushIfEmpty(Node: TAbstractBackgroundNode; SendEvents: boolean);
191 end;
192
193 TFogStack = class(TX3DBindableStack)
194 public
195 function Top: TFogNode;
196 procedure PushIfEmpty(Node: TFogNode; SendEvents: boolean);
197 end;
198
199 TNavigationInfoStack = class(TX3DBindableStack)
200 protected
201 procedure DoBoundChanged; override;
202 public
203 function Top: TNavigationInfoNode;
204 procedure PushIfEmpty(Node: TNavigationInfoNode; SendEvents: boolean);
205 end;
206
207 TViewpointStack = class(TX3DBindableStack)
208 public
209 function Top: TAbstractViewpointNode;
210 procedure PushIfEmpty(Node: TAbstractViewpointNode; SendEvents: boolean);
211 end;
212
213 { Possible spatial structures that may be managed by TCastleSceneCore,
214 see @link(TCastleSceneCore.Spatial). }
215 TSceneSpatialStructure = (
216 { Create @italic(and keep up-to-date) a spatial structure
217 containing all visible shapes.
218 It's useful for "frustum culling", it will be automatically
219 used by TCastleScene rendering to speed it up.
220
221 This octree will be automatically updated on dynamic scenes
222 (when e.g. animation moves some shape by changing it's transformation). }
223 ssRendering,
224
225 { Create @italic(and keep up-to-date) a spatial structure
226 containing all collidable shapes (and then reaching
227 into collidable triangles for a specifc shape).
228 It is automatically used by the XxxCollision methods in this class.
229
230 This is actually a hierarchy of octrees: scene is partitioned
231 first into Shapes (each instance of VRML/X3D geometry node),
232 and then each Shape has an octree of triangles inside.
233
234 This octree is useful for all kinds of collision detection.
235 Compared to ssStaticCollisions, it is (very slightly on typical scenes)
236 less efficient, but it can also be updated very fast.
237 For example, merely transforming some Shape means that only
238 one item needs to be moved in the top-level shape tree.
239 So this is the most important structure for collision detection on
240 dynamic scenes. }
241 ssDynamicCollisions,
242
243 { Create a spatial structure containing all visible triangles, suitable only
244 for scenes that stay static.
245
246 It's primarily use is for ray-tracers, that make a lot of collision queries
247 to the same scene in the same time. When rendering using OpenGL,
248 this has no use currently.
249
250 This structure is not updated on scene changes. In fact, the scene
251 contents cannot change when this octree is created --- as this octree
252 keeps pointers to some states that may become invalid in dynamic scenes. }
253 ssVisibleTriangles,
254
255 { Create a spatial structure containing all collidable triangles,
256 @bold(only for scenes that never change).
257
258 It may be useful if you're absolutely sure that you have a static scene
259 (nothing changes, i.e. ProcessEvents = @false and you never
260 make any change to X3D nodes from code) and
261 you want to have collision detection with the scene.
262
263 For dynamic scenes, using this is a bad idea as
264 this octree is not updated on scene changes. In fact, the scene
265 contents cannot change when this octree is created --- as this octree
266 keeps pointers to some states that may become invalid in dynamic scenes.
267 Use ssDynamicCollisions for dynamic scenes. }
268 ssStaticCollisions);
269 TSceneSpatialStructures = set of TSceneSpatialStructure;
270
271 TGeometryChange =
272 ( { Everything changed. All octrees must be rebuild, old State pointers
273 may be invalid.
274
275 Every ChangedAll call does this.
276 ChangedAll must take into account that everything could change.
277 Note that ChangedAll traverses the VRML/X3D graph again,
278 recalculating State values... so the old States are not
279 correct anymore. You have to rebuild the octree or your pointers
280 will be bad.
281
282 When DoGeometryChanged with gcAll is called, we know that ChangedAll
283 called this, and every TShape will be (or already is) destroyed
284 and created new. }
285 gcAll,
286
287 { Transformation of some shape changed.
288 @groupBegin }
289 gcCollidableTransformChanged,
290 gcVisibleTransformChanged,
291 { @groupEnd }
292
293 { Local geometry change
294 happened (actual octree free is already done by
295 TShape.LocalGeometryChanged, octree create will be done at next demand).
296 We should update stuff at higher (TCastleSceneCore) level accordingly.
297
298 gcLocalGeometryChangedCoord means that coordinates changed.
299 Compared to gcLocalGeometryChanged, this means that model edges
300 structure remains the same (this is helpful e.g. to avoid
301 recalculating Manifold/BorderEdges).
302
303 In this case, DoGeometryChanged parameter LocalGeometryShape is non-nil
304 and indicated the (only) shape that changed.
305
306 @groupBegin }
307 gcLocalGeometryChanged,
308 gcLocalGeometryChangedCoord,
309 { @groupEnd }
310
311 { What is considered "active" shapes changed. Like after Switch.whichChoice
312 change. }
313 gcActiveShapesChanged);
314
315 TStopAnimationEvent = procedure (const Scene: TCastleSceneCore;
316 const Animation: TTimeSensorNode) of object;
317
318 { Parameters to use when playing animation,
319 see @link(TCastleSceneCore.PlayAnimation).
320
321 Design note: This is a class, not e.g. an advanced record.
322 This way is has always sensible defaults.
323 You will usually create and quickly destroy it around
324 the @link(TCastleSceneCore.PlayAnimation) call.
325 Don't worry, time of creation/destruction of it really doesn't matter
326 in practice, thanks to fast FPC memory allocator. }
327 TPlayAnimationParameters = class
328 { Animation name.
329 You have to set at least this field, otherwise calling
330 @link(TCastleSceneCore.PlayAnimation) with this is useless. }
331 Name: String;
332
333 { Should we play in a loop, default @false which means to play just once. }
334 Loop: boolean;
335
336 { Does animation play forward, default @true. }
337 Forward: boolean;
338
339 { Notification when the animation finished playing,
340 which happens if the animation was non-looping and it reached the end,
341 or another animation was started by @link(TCastleSceneCore.PlayAnimation).
342
343 This will never fire if the animation did not exist
344 (@link(TCastleSceneCore.PlayAnimation) returned @false).
345 It also may never fire if the scene was destroyed or rebuilt
346 (@link(TCastleSceneCore.ChangedAll)) during the animation playing.
347
348 Listening on this notification is usually simpler
349 and more reliable then explicitly adding a notification
350 to TTimeSensorNode.EventIsActive, e.g. by
351 @code(CurrentAnimation.EventIsActive.AddNotification).
352 It avoids corner cases when PlayAnimation restarts playing the current
353 animation. This notification will happen when the animation that you
354 caused (by the call to @link(TCastleSceneCore.PlayAnimation)) stops,
355 not at other times.
356
357 Example usage:
358 @includeCode(../../examples/short_api_samples/animation_stop_notification/animation_stop_notification.dpr) }
359 StopNotification: TStopAnimationEvent;
360
361 { Time, in seconds, when this animation fades-in (and the previous
362 animation, if any, fades-out).
363 See https://castle-engine.io/wp/2018/03/21/animation-blending/ }
364 TransitionDuration: TFloatTime;
365
366 { Start new animation at given moment in animation.
367 Allows to start animation from the middle, not necessarily from the start.
368
369 Note that animation blending (TransitionDuration) starts
370 from the moment you called the PlayAnimation, i.e. from InitialTime,
371 not from 0. In other words, animation will enter smoothly (cross-fade),
372 regardless of InitialTime. }
373 InitialTime: TFloatTime;
374
375 constructor Create;
376 end;
377
378 { Possible options for @link(TCastleSceneCore.Load). }
379 TSceneLoadOption = (
380 slDisableResetTime
381 );
382 TSceneLoadOptions = set of TSceneLoadOption;
383
384 { Loading and processing of a scene.
385 Almost everything visible in your game will be an instance of
386 @link(TCastleScene), which is a descendant of this class that adds rendering
387 capabilities.
388
389 This class provides a lot of functionality, like loading of the scene
390 (@link(Load) method), animating it, performing collisions with the scene,
391 and calculating things (like @link(LocalBoundingBox)).
392
393 The actual scene information (visible and collidable things) is inside
394 X3D nodes graph contained within the @link(RootNode).
395 During the lifetime of the scene, this X3D graph can change
396 (e.g. because of animations), and you can always change it by code
397 too. E.g. you can freely change @link(TTransformNode.Translation)
398 or add children by @link(TAbstractGroupingNode.AddChildren RootNode.AddChildren).
399 The X3D nodes graph works like a DOM tree for rendering HTML documents:
400 it's typically initialized from a file (3D model), but during
401 the game execution it is dynamic, always changing.
402
403 This class takes care of performing the X3D events
404 and routes mechanism (if @link(ProcessEvents) is @true).
405 This is what allows X3D graph to be animated, or even be interactive
406 (respond to user actions).
407 For a simple way to play animations, use the @link(PlayAnimation) method.
408
409 This class maintains a @link(Shapes) tree is
410 always synchronized with the X3D nodes tree in @link(RootNode).
411 The @link(Shapes) tree provides a little simple view at the scene,
412 sometimes easier (or faster) to iterate over.
413
414 Many results are cached, so querying them multiple times is fast,
415 if the scene does not change (in a significant way) between each query.
416 So you can query information like @link(LocalBoundingBox),
417 @link(BoundingBox), @link(VerticesCount)... as often as you want to. }
418 TCastleSceneCore = class(TX3DEventsEngine)
419 private
420 type
421 TSceneValidity = (fvLocalBoundingBox,
422 fvVerticesCount,
423 fvTrianglesCount,
424 fvMainLightForShadows,
425 fvShapesActiveCount,
426 fvShapesActiveVisibleCount);
427
428 TSceneValidities = set of TSceneValidity;
429
430 TGeneratedTexture = record
431 { May be only TGeneratedCubeMapTextureNode or TRenderedTextureNode
432 or TGeneratedShadowMapNode. }
433 TextureNode: TAbstractTextureNode;
434 Functionality: TGeneratedTextureFunctionality;
435 Shape: TShape;
436 end;
437 PGeneratedTexture = ^TGeneratedTexture;
438
439 { @exclude
440 Internal for TCastleSceneCore: list of generated textures
441 (GeneratedCubeMapTexture, RenderedTexture and similar nodes)
442 along with their shape. }
443 TGeneratedTextureList = class({$ifdef FPC}specialize{$endif} TStructList<TGeneratedTexture>)
444 public
445 function IndexOfTextureNode(TextureNode: TX3DNode): Integer;
446 function FindTextureNode(TextureNode: TX3DNode): PGeneratedTexture;
447 function AddShapeTexture(Shape: TShape; Tex: TAbstractTextureNode): Pointer;
448 procedure UpdateShadowMaps(LightNode: TAbstractLightNode);
449 end;
450
451 TProximitySensorInstanceList = {$ifdef FPC}specialize{$endif} TObjectList<TProximitySensorInstance>;
452 TTimeDependentList = class({$ifdef FPC}specialize{$endif} TObjectList<TTimeDependentFunctionality>)
453 procedure AddIfNotExists(const Item: TTimeDependentFunctionality);
454 end;
455
456 TCompiledScriptHandler = procedure (
457 Value: TX3DField; const Time: TX3DTime) of object;
458
459 TCompiledScriptHandlerInfo = record
460 Handler: TCompiledScriptHandler;
461 Name: String;
462 end;
463 PCompiledScriptHandlerInfo = ^TCompiledScriptHandlerInfo;
464 TCompiledScriptHandlerInfoList = {$ifdef FPC}specialize{$endif} TStructList<TCompiledScriptHandlerInfo>;
465
466 TExposedTransform = class
467 strict private
468 ChildObserver: TFreeNotificationObserver;
469 WarningDone: Boolean;
470 FNode: TTransformNode;
471 FTransformFunctionality: TTransformFunctionality;
472 FChild: TCastleTransform;
473 FParentScene: TCastleSceneCore;
474 procedure ChildFreeNotification(const Sender: TFreeNotificationObserver);
475 public
476 constructor Create(const AParentScene: TCastleSceneCore;
477 const ANode: TTransformNode; const AChild: TCastleTransform);
478 destructor Destroy; override;
479 property Node: TTransformNode read FNode;
480 property Child: TCastleTransform read FChild;
481 property ParentScene: TCastleSceneCore read FParentScene;
482 procedure Synchronize;
483 class function X3dNameToPascal(const Prefix, S: String): String; static;
484 end;
485 TExposedTransformList = {$ifdef FPC}specialize{$endif} TObjectList<TExposedTransform>;
486
487 protected
488 type
489 TVisibilitySensorInstanceList = {$ifdef FPC}specialize{$endif} TObjectList<TVisibilitySensorInstance>;
490 TVisibilitySensors = class({$ifdef FPC}specialize{$endif} TDictionary<TVisibilitySensorNode, TVisibilitySensorInstanceList>)
491 public
492 destructor Destroy; override;
493 { Remove everything are released owned stuff.
494 We own TVisibilitySensorInstanceList instances on our Data list.
495 We do not own TVisibilitySensorNode (our Keys list). }
496 procedure Clear; reintroduce;
497 end;
498
499 private
500 FShapes: TShapeTree;
501 FRootNode, FRootNodeCacheOrigin: TX3DRootNode;
502 FOwnsRootNode: Boolean;
503 FPendingSetUrl: String;
504 FOnPointingDeviceSensorsChange: TNotifyEvent;
505 FTimePlaying: boolean;
506 FTimePlayingSpeed: Single;
507 { Change only using FUrlMonitoring.ChangeUrl. }
508 FUrl: String;
509 FUrlMonitoring: TUrlMonitoring;
510 FShadowMaps: boolean;
511 FShadowMapsDefaultSize: Cardinal;
512 ScheduleHeadlightOnFromNavigationInfoInChangedAll: boolean;
513 LastUpdateFrameId: TFrameId;
514 LastCameraStateId: TFrameId;
515 FDefaultAnimationTransition: Single;
516 FCache: Boolean;
517
518 { All InternalUpdateCamera calls will disable smooth (animated)
519 transitions when this is true.
520 This is set to true by @link(Load),
521 when ChangedAll is scheduled, so that first camera bindings
522 (in particular after LoadAnchor, when the already existing camera
523 is changed) will have immediate transitions in newly loaded file.
524 ChangedAll sets this back to false at the end. }
525 ForceTeleportTransitions: boolean;
526
527 WatchForTransitionComplete: boolean;
528
529 { Humanoids on which we should call AnimateSkin.
530 We don't do AnimateSkin immediately, as it would force slowdown
531 when many joints are changed at once (e.g. many joints, and each one
532 animated with it's own OrientationInterpolator). }
533 ScheduledHumanoidAnimateSkin: TX3DNodeList;
534
535 { NewPlayingAnimationXxx describe scheduled animation to change.
536 They are set by PlayAnimation, and used by UpdateNewPlayingAnimation.
537 Note that NewPlayingAnimationUse does *not* imply that
538 NewPlayingAnimationNode is <> nil,
539 it can be nil (if we want to change animation to nil). }
540 NewPlayingAnimationUse: boolean;
541 NewPlayingAnimationNode: TTimeSensorNode;
542 NewPlayingAnimationLoop: boolean;
543 NewPlayingAnimationForward: boolean;
544 NewPlayingAnimationStopNotification: TStopAnimationEvent;
545 NewPlayingAnimationTransitionDuration: TFloatTime;
546 NewPlayingAnimationInitialTime: TFloatTime;
547
548 { PlayingAnimationXxx are changed in UpdateNewPlayingAnimation,
549 when the new animation actually starts
550 (the X3D TimeSensor gets event to start). }
551 PlayingAnimationNode: TTimeSensorNode;
552 PlayingAnimationStartTime: TFloatTime;
553 PlayingAnimationStopNotification: TStopAnimationEvent;
554 PlayingAnimationTransitionDuration: TFloatTime;
555
556 PreviousPlayingAnimation: TTimeSensorNode;
557 PreviousPlayingAnimationLoop: boolean;
558 PreviousPlayingAnimationForward: boolean;
559 PreviousPlayingAnimationTimeInAnimation: TFloatTime;
560
561 PreviousPartialAffectedFields: TX3DFieldList;
562
563 FCurrentAnimation: TTimeSensorNode;
564 FAnimationPrefix: String;
565 FAnimationsList: TStrings;
566 FTimeAtLoad: TFloatTime;
567
568 { Some TimeSensor with DetectAffectedFields exists on TimeDependentList . }
569 NeedsDetectAffectedFields: Boolean;
570 AnimationAffectedFields: TX3DFieldList;
571
572 { The transformation change happened,
573 and should be processed (for the whole X3D graph inside RootNode).
574 Used only when OptimizeExtensiveTransformations. }
575 TransformationDirty: Boolean;
576
577 { This always holds pointers to all TShapeTreeLOD instances in Shapes
578 tree. }
579 ShapeLODs: TObjectList;
580
581 { Increased when something changed that could affect the results
582 of Shapes tree traversal, i.e. different TShape instances returned
583 by Shapes.Traverse.
584 Never zero. }
585 FShapesHash: TShapesHash;
586
587 FExposeTransforms: TStrings;
588 FExposedTransforms: TExposedTransformList;
589 FExposeTransformsPrefix: String;
590
591 { Perform animation fade-in and fade-out by initializing
592 TTimeDependentFunctionality.PartialSend before
593 TTimeDependentFunctionality.SetTime. }
594 procedure PartialSendBegin(const TimeFunctionality: TTimeDependentFunctionality);
595
596 { Finalize what PartialSendBegin started,
597 after TTimeDependentFunctionality.SetTime was called. }
598 procedure PartialSendEnd(const TimeFunctionality: TTimeDependentFunctionality);
599
600 { Call this if during this frame, TTimeDependentFunctionality.PartialSend always remained @nil. }
601 procedure NoPartialSend;
602
603 { Recalculate and update LODTree.Level.
604 Also sends level_changed when needed.
605 Call only when ProcessEvents. }
606 procedure UpdateLODLevel(const LODTree: TShapeTreeLOD;
607 const CameraLocalPosition: TVector3);
608
609 procedure SetUrl(const AValue: String);
610 procedure SetShadowMaps(const Value: boolean);
611 procedure SetShadowMapsDefaultSize(const Value: Cardinal);
612
613 { Handle change of transformation of a node with TTransformFunctionality.
614 TransformFunctionality.Parent must be associated only with TShapeTreeTransform,
615 which must be true for all nodes implementing TTransformFunctionality.
616 Changes must include chTransform, may also include other changes
617 (this will be passed to shapes affected).
618
619 Do not ever call this when OptimizeExtensiveTransformations.
620 It would be buggy when both OptimizeExtensiveTransformations
621 and InternalFastTransformUpdate are set, because in this case,
622 TShapeTreeTransform.FastTransformUpdateCore leaves
623 TShapeTreeTransform.Transform invalid,
624 which will cause TransformationChanged result invalid.
625 }
626 procedure TransformationChanged(const TransformFunctionality: TTransformFunctionality);
627 { Like TransformationChanged, but specialized for TransformNode = RootNode. }
628 procedure RootTransformationChanged;
629
630 function LocalBoundingVolumeMoveCollision(
631 const OldPos, NewPos: TVector3;
632 const IsRadius: boolean; const Radius: Single;
633 const OldBox, NewBox: TBox3D): boolean;
634
635 procedure SetRootNode(const Value: TX3DRootNode);
636
637 { Always assigned to PlayingAnimationNode.EventIsActive. }
638 procedure PlayingAnimationIsActive(
639 const Event: TX3DEvent; const Value: TX3DField; const ATime: TX3DTime);
640
641 { If we have NewPlayingAnimationUse, apply it
642 (actually start playing it using X3D nodes, calling UpdateNewPlayingAnimation).
643 This may be necessary to call in some circumstances.
644
645 Returns false if we had NewPlayingAnimationUse, applied it,
646 but we still have unapplied NewPlayingAnimationUse (which means that stopping
647 previous animation started yet another animation). }
648 function ApplyNewPlayingAnimation: Boolean;
649
650 { Apply NewPlayingAnimation* stuff.
651
652 Call outside of AnimateOnlyWhenVisible check, to do it even when object
653 is not visible. Otherwise stop/start time would be delayed too until
654 it becomes visible, which is not perfect (although it would be Ok
655 in practice too?) }
656 procedure UpdateNewPlayingAnimation(out NeedsUpdateTimeDependent: Boolean);
657
658 { Call SetTime on all things in TimeDependentList. }
659 procedure UpdateTimeDependentList(const TimeIncrease: TFloatTime; const ResetTime: boolean);
660
661 function SensibleCameraRadius(out RadiusAutoCalculated: Boolean): Single;
662
663 { Apply TransformationDirty effect
664 (necessary to finalize OptimizeExtensiveTransformations,
665 after TTransformNode values changed).
666 Always call this after doing something that could change
667 TTransformNode values. }
668 procedure FinishTransformationChanges;
669
670 procedure SetExposeTransforms(const Value: TStrings);
671 procedure ExposeTransformsChange(Sender: TObject);
672 procedure SetExposeTransformsPrefix(const Value: String);
673 function CreateAnimations: TStringList;
674 private
675 FGlobalLights: TLightInstancesList;
676
677 FLocalBoundingBox: TBox3D;
678 FVerticesCount, FTrianglesCount: Cardinal;
679 Validities: TSceneValidities;
680 function CalculateLocalBoundingBox: TBox3D;
681 function CalculateVerticesCount: Cardinal;
682 function CalculateTrianglesCount: Cardinal;
683 private
684 type
685 TAbstractViewpointNodeList = {$ifdef FPC}specialize{$endif} TObjectList<TAbstractViewpointNode>;
686 var
687 FShapesActiveCount: Cardinal;
688 FShapesActiveVisibleCount: Cardinal;
689 { For easier access to list of viewpoints in the scene }
690 FViewpointsArray: TAbstractViewpointNodeList;
691
692 function GetViewpointCore(
693 const OnlyPerspective: boolean;
694 out ProjectionType: TProjectionType;
695 out CamPos, CamDir, CamUp, GravityUp: TVector3;
696 const ViewpointDescription: String):
697 TAbstractViewpointNode;
698 private
699 procedure FreeResources_UnloadTextureData(Node: TX3DNode);
700 procedure FreeResources_UnloadTexture3DData(Node: TX3DNode);
701 procedure FontChanged_TextNode(Node: TX3DNode);
702 procedure FontChanged_AsciiTextNode_1(Node: TX3DNode);
703 private
704 FOnGeometryChanged: TSceneGeometryChanged;
705 FOnViewpointsChanged: TNotifyEvent;
706 FOnBoundViewpointVectorsChanged: TNotifyEvent;
707 FOnBoundNavigationInfoFieldsChanged: TNotifyEvent;
708
709 FProcessEvents: boolean;
710 procedure SetProcessEvents(const Value: boolean);
711 private
712 KeyDeviceSensorNodes: TX3DNodeList;
713 TimeDependentList: TTimeDependentList;
714 ProximitySensors: TProximitySensorInstanceList;
715 FVisibilitySensors: TVisibilitySensors;
716 BillboardNodes: TX3DNodeList;
717
718 procedure ChangedAllEnumerateCallback(Node: TX3DNode);
719 procedure ScriptsInitializeCallback(Node: TX3DNode);
720 procedure ScriptsFinalizeCallback(Node: TX3DNode);
721
722 procedure ScriptsInitialize;
723 procedure ScriptsFinalize;
724 private
725 FTimeNow: TX3DTime;
726
727 { Internal procedure that handles Time changes. }
728 procedure InternalSetTime(
729 const NewValue: TFloatTime; const TimeIncrease: TFloatTime; const ResetTime: boolean);
730
731 procedure ResetLastEventTime(Node: TX3DNode);
732 private
733 { Bindable nodes helpers }
734 FBackgroundStack: TBackgroundStack;
735 FFogStack: TFogStack;
736 FNavigationInfoStack: TNavigationInfoStack;
737 FViewpointStack: TViewpointStack;
738
739 { If @true, then next ChangedAll call will do ProcessShadowMapsReceivers
740 at the end.
741
742 ProcessShadowMapsReceivers are correctly called at the
743 right moment of ChangedAll, so that they have the necessary
744 information (Shapes) ready and their modifications (new GeneratedTextures
745 items) are accounted for. }
746 ScheduledShadowMapsProcessing: boolean;
747
748 { Mechanism to schedule ChangedAll and GeometryChanged calls. }
749 ChangedAllSchedule: Cardinal;
750 ChangedAllScheduled: Boolean;
751 ChangedAllScheduledOnlyAdditions: Boolean;
752
753 ChangedAllCurrentViewpointIndex: Cardinal;
754 FInitialViewpointIndex: Cardinal;
755 FInitialViewpointName: String;
756
757 FPointingDeviceOverItem: PTriangle;
758 FPointingDeviceOverPoint: TVector3;
759 FPointingDeviceActive: boolean;
760 FPointingDeviceActiveSensors: TX3DNodeList;
761 private
762 { Call this when the ProximitySensor instance changed (either the box or
763 it's transformation) or when camera position changed (by user actions
764 or animating the Viewpoint). }
765 procedure ProximitySensorUpdate(const PSI: TProximitySensorInstance;
766 const CameraVectors: TViewVectors);
767 private
768 FCompiledScriptHandlers: TCompiledScriptHandlerInfoList;
769
770 { Create octree containing all triangles or shapes from our scene.
771 Create octree, inits it with our LocalBoundingBox
772 and adds shapes (or all triangles from our Shapes).
773
774 Triangles are generated using calls like
775 @code(Shape.Triangulate(...)).
776
777 If Collidable, then only the collidable, or at least "pickable",
778 triangles are generated. Which means that children of
779 Collision nodes with collide = FALSE (or proxy <> nil) are not placed here.
780 Otherwise, only the visible (not necessarily collidable)
781 items are placed in the octree.
782
783 Remember that triangle octree has references to Shape nodes
784 inside RootNode VRML/X3D tree and to State objects inside
785 our @link(Shapes) tree.
786 And shape octree has references to our @link(Shapes) tree.
787 So you must rebuild such octree when this object changes.
788
789 Note: remember that this is a function and it returns
790 created octree object. It does *not* set value of any
791 OctreeXxx property, and the returned octree is not managed
792 by this scene.
793
794 Everything in my units is done in the spirit
795 that you can create as many octrees as you want for a given scene
796 (both octrees based on triangles and based on shapes).
797 Also, in some special cases an octree may be constructed in
798 some special way (not only using @link(CreateShapeOctree)
799 or @link(CreateTriangleOctree)) so that it doesn't contain
800 the whole scene from some TCastleSceneCore object, or it contains
801 the scene from many TCastleSceneCore objects, or something else.
802
803 What I want to say is that it's generally wrong to think of
804 an octree as something that maps 1-1 to some TCastleSceneCore object.
805 Octrees, as implemented here, are a lot more flexible.
806
807 @groupBegin }
808 function CreateTriangleOctree(const Limits: TOctreeLimits;
809 const Collidable: boolean): TTriangleOctree;
810 function CreateShapeOctree(const Limits: TOctreeLimits;
811 const Collidable: boolean): TShapeOctree;
812 { @groupEnd }
813 private
814 FTriangleOctreeLimits: TOctreeLimits;
815
816 FShapeOctreeLimits: TOctreeLimits;
817
818 FOctreeRendering: TShapeOctree;
819 FOctreeDynamicCollisions: TShapeOctree;
820 FOctreeVisibleTriangles: TTriangleOctree;
821 FOctreeStaticCollisions: TTriangleOctree;
822 FSpatial: TSceneSpatialStructures;
823
824 { Properties of created triangle octrees.
825 See TriangleOctree unit comments for description.
826
827 Default value comes from DefTriangleOctreeLimits.
828
829 They are used only when the octree is created, so usually you
830 want to set them right before changing @link(Spatial) from []
831 to something else.
832
833 Note that particular models may override this by
834 [https://castle-engine.io/x3d_extensions.php#section_ext_octree_properties].
835
836 @groupBegin }
837 function TriangleOctreeLimits: POctreeLimits;
838
839 { Properties of created shape octrees.
840 See ShapeOctree unit comments for description.
841
842 Default value comes from DefShapeOctreeLimits.
843
844 They are used only when the octree is created, so usually you
845 want to set them right before changing @link(Spatial) from []
846 to something else.
847
848 Note that particular models may override this by
849 [https://castle-engine.io/x3d_extensions.php#section_ext_octree_properties]. }
850 function ShapeOctreeLimits: POctreeLimits;
851
852 procedure SetSpatial(const Value: TSceneSpatialStructures);
853 function GetPreciseCollisions: Boolean;
854 procedure SetPreciseCollisions(const Value: Boolean);
855 private
856 FMainLightForShadowsExists: boolean;
857 FMainLightForShadows: TVector4;
858 FMainLightForShadowsNode: TAbstractPunctualLightNode;
859 FMainLightForShadowsTransform: TMatrix4;
860 function SearchMainLightForShadows(
861 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
862 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
863 { Based on FMainLightForShadowsNode and FMainLightForShadowsTransform,
864 calculate FMainLightForShadows (position). }
865 procedure CalculateMainLightForShadowsPosition;
866 procedure ValidateMainLightForShadows;
867 private
868 FAutoAnimation: String;
869 FAutoAnimationLoop: Boolean;
870 FHeadlightOn: boolean;
871 FOnHeadlightOnChanged: TNotifyEvent;
872 FAnimateOnlyWhenVisible: boolean;
873 FAnimateGatheredTime: TFloatTime;
874 FAnimateSkipTicks: Cardinal;
875 AnimateSkipNextTicks: Cardinal;
876
877 procedure SetAnimateSkipTicks(const Value: Cardinal);
878 procedure SetHeadlightOn(const Value: boolean);
879 procedure SetAutoAnimation(const Value: String);
880 procedure SetAutoAnimationLoop(const Value: Boolean);
881 procedure UpdateAutoAnimation(const StopIfPlaying: Boolean);
882
883 { Get camera position in current scene local coordinates.
884 This is calculated every time now (in the future it may be optimized
885 to recalculate only when WorldTransform changed, e.g. using
886 FWorldTransformAndInverseId). }
887 function GetCameraLocal(out CameraVectors: TViewVectors): boolean; overload;
888 function GetCameraLocal(out CameraLocalPosition: TVector3): boolean; overload;
889
890 function PointingDevicePressRelease(const DoPress: boolean;
891 const Distance: Single; const CancelAction: boolean): boolean;
892
893 { Like Load but with additional ARootNodeCacheOrigin parameter. }
894 procedure LoadCore(const ARootNode: TX3DRootNode;
895 const ARootNodeCacheOrigin: TX3DRootNode;
896 const AOwnsRootNode: boolean;
897 const AOptions: TSceneLoadOptions);
898 { Free FRootNode and FRootNodeCacheOrigin and set it to @nil.
899 Always use this to free FRootNode. }
900 procedure FreeRootNode;
901 protected
902 { List of TScreenEffectNode nodes, collected by ChangedAll. }
903 ScreenEffectNodes: TX3DNodeList;
904
905 { Is the scene visible currently. Descendants may set this to @true
906 during @link(TCastleTransform.LocalRender). }
907 IsVisibleNow: boolean;
908
909 GeneratedTextures: TGeneratedTextureList;
910
911 { Create TShape (or descendant) instance suitable for this
912 TCastleSceneCore descendant. In this class, this simply creates new
913 TShape instance. If you make a descendant of TCastleSceneCore,
914 you may need to store some per-shape information, and then it may
915 be useful to have your own TShape descendant to carry this information.
916 So you can override this to create your own descendant, and then
917 you're sure that all leafs within Shapes tree are created using
918 this.
919
920 Example: TCastleScene uses this to create TGLShape. }
921 function CreateShape(const AGeometry: TAbstractGeometryNode;
922 const AState: TX3DGraphTraverseState;
923 const ParentInfo: PTraversingInfo): TShape; virtual;
924
925 procedure UpdateHeadlightOnFromNavigationInfo;
926
927 { Camera changed.
928 In this class this updates various X3D nodes using the camera position/direction/up,
929 like LOD, Billboard, ProximitySensor.
930 @exclude }
931 procedure InternalCameraChanged; virtual;
932
933 { Background node changed. @exclude }
934 procedure InternalInvalidateBackgroundRenderer; virtual;
935
936 property VisibilitySensors: TVisibilitySensors read FVisibilitySensors;
937
938 procedure ChangedTransform; override;
939 procedure ChangeWorld(const Value: TCastleAbstractRootTransform); override;
940
941 { Called after PointingDeviceSensors or
942 PointingDeviceActiveSensors lists (possibly) changed.
943
944 In this class, DoPointingDeviceSensorsChange updates Cursor and calls
945 OnPointingDeviceSensorsChange. }
946 procedure DoPointingDeviceSensorsChange; virtual;
947
948 procedure ExecuteCompiledScript(const HandlerName: String; ReceivedValue: TX3DField); override;
949
950 function LocalHeightCollision(const APosition, GravityUp: TVector3;
951 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
952 out AboveHeight: Single; out AboveGround: PTriangle): boolean; override;
953 function LocalMoveCollision(
954 const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3;
955 const IsRadius: boolean; const Radius: Single;
956 const OldBox, NewBox: TBox3D;
957 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; override;
958 function LocalMoveCollision(
959 const OldPos, NewPos: TVector3;
960 const IsRadius: boolean; const Radius: Single;
961 const OldBox, NewBox: TBox3D;
962 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; override;
963 function LocalSegmentCollision(const Pos1, Pos2: TVector3;
964 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
965 const ALineOfSight: boolean): boolean; override;
966 function LocalSphereCollision(const Pos: TVector3; const Radius: Single;
967 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; override;
968 function LocalSphereCollision2D(const Pos: TVector2; const Radius: Single;
969 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc;
970 const Details: TCollisionDetails): boolean; override;
971 function LocalPointCollision2D(const Point: TVector2;
972 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; override;
973 function LocalBoxCollision(const Box: TBox3D;
974 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): boolean; override;
975 function LocalRayCollision(const RayOrigin, RayDirection: TVector3;
976 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision; override;
977
978 procedure LocalRender(const Params: TRenderParams); override;
979 procedure Loaded; override;
980
981 { Called before changing one node into another,
982 when old node may have beeen associated with a shape using TShapeTree.AssociateNode.
983
984 Both OldNode and NewNode may be @nil, this method can handle it.
985
986 It is allowed to call this even when OldNode = NewNode, which means that nothing
987 really changes. }
988 procedure InternalMoveShapeAssociations(
989 const OldNode, NewNode: TX3DNode; const ContainingShapes: TObject); override;
990
991 { Local (not affected by our @link(Translation), @link(Rotation), @link(Scale)) bounding box.
992 Takes into account loaded scene (in @link(Url))
993 but not children TCastleTransform bounding volumes. }
994 function LocalBoundingBoxNoChildren: TBox3D;
995 public
996 var
997 { Nonzero value prevents rendering of this scene,
998 and generally means that our state isn't complete.
999 This is useful if we're in the middle of some operation
1000 (like ChangedAll call or octree creation).
1001
1002 Some callbacks *may* be called during such time.
1003 (No good example now; old example was: callbacks caused by progress steps
1004 done during constructing octrees).
1005 As these callbacks may try to e.g. render our scene (which should
1006 not be done on the dirty state), we have to protect ourselves
1007 using this variable (e.g. Render routines will exit immediately
1008 when InternalDirty <> 0).
1009
1010 @exclude }
1011 InternalDirty: Cardinal;
1012
1013 { @exclude
1014 Do not warn when changed node seems to belong to a different TCastleSceneCore. }
1015 InternalNodeSharing: Boolean;
1016
1017 const
1018 DefaultShadowMapsDefaultSize = 256;
1019
1020 public // repeat "public" is necessary for FPC to parse Node<NodeType> method declaration later with FPC 3.2.2
1021
1022 { }
1023 constructor Create(AOwner: TComponent); override;
1024 function PropertySections(const PropertyName: String): TPropertySections; override;
1025
1026 { Load the given model.
1027 This replaces @link(RootNode) with new value.
1028
1029 @param(ARootNode The model to load.
1030 This will become a new value of our @link(RootNode) property.)
1031
1032 @param(AOwnsRootNode Should the scene take care of freeing
1033 this root node when it is no longer used. If @false,
1034 you are expected to free it yourself, but only after the scene
1035 using it was freed.)
1036
1037 @param(AResetTime If @true then we will reset time at loading
1038 (using @link(ResetTimeAtLoad)),
1039 changing the @link(Time). This is usually what you want when you
1040 load a new world.)
1041
1042 Note that you should never load the same @link(TX3DRootNode) instance
1043 into multiple @link(TCastleScene) instances.
1044
1045 @longCode(#
1046 // DON'T DO THIS!
1047 Node := LoadNode(Url);
1048 Scene1 := TCastleScene.Create(Application);
1049 Scene1.Load(Node, false);
1050 Scene2 := TCastleScene.Create(Application);
1051 Scene2.Load(Node, false);
1052 #)
1053
1054 If you need to load the same model into multiple scenes,
1055 it is best to use the @link(Clone) method:
1056
1057 @longCode(#
1058 SceneTemplate := TCastleScene.Create(Application);
1059 SceneTemplate.Load(Url);
1060 Scene1 := SceneTemplate.Clone(Application);
1061 Scene2 := SceneTemplate.Clone(Application);
1062 #)
1063
1064 Using the @link(Clone) makes a copy of the underlying X3D graph,
1065 so it is roughly like doing:
1066
1067 @longCode(#
1068 Node := LoadNode(Url);
1069 Scene1 := TCastleScene.Create(Application);
1070 Scene1.Load(Node.DeepCopy as TX3DRootNode, false);
1071 Scene2 := TCastleScene.Create(Application);
1072 Scene2.Load(Node.DeepCopy as TX3DRootNode, false);
1073 #)
1074
1075 Note that sometimes you don't need to create multiple scenes
1076 to show the same model many times.
1077 You can simply insert the same TCastleScene instance multiple
1078 times to TCastleViewport.Items (TCastleRootTransform).
1079 See the manual:
1080 https://castle-engine.io/manual_scene.php#section_many_instances
1081 }
1082 procedure Load(const ARootNode: TX3DRootNode; const AOwnsRootNode: boolean;
1083 const AOptions: TSceneLoadOptions = []); overload;
1084
1085 { Load the 3D model from given URL.
1086
1087 We load a number of 3D model formats (X3D, VRML, Collada, Wavefront OBJ...)
1088 and some 2D model formats (Spine JSON).
1089 See https://castle-engine.io/creating_data_model_formats.php
1090 for the complete list.
1091
1092 URL is downloaded using the CastleDownload unit,
1093 so it supports files, http resources and more.
1094 See https://castle-engine.io/manual_network.php
1095 about supported URL schemes.
1096 If you all you care about is loading normal files, then just pass
1097 a normal filename (absolute or relative to the current directory)
1098 as the URL parameter. }
1099 procedure Load(const AUrl: String; const AOptions: TSceneLoadOptions = []); overload;
1100 procedure Load(const AUrl: String; const AllowStdIn: boolean;
1101 const AResetTime: boolean = true); overload; deprecated 'use Load with (AUrl: String, AOptions: TSceneLoadOptions) parameters. AllowStdIn is not implemented anymore.';
1102
1103 { Save the current 3D model (X3D nodes graph) to the given file (URL).
1104
1105 The X3D encoding is automatically guessed from the URL extension.
1106 By default it is XML, and we suggest using the @code(.x3d) extension.
1107 If you specify an extension indicating "classic encoding",
1108 we will use such encoding (use @code(.x3dv) for X3D
1109 in classic encoding, or @code(.wrl) for older VRML content).
1110
1111 The file may also be automatically gzip compressed if extension indicates it.
1112 Use @code(.x3d.gz) to indicated XML compressed with gzip,
1113 or use @code(.x3dv.gz) or @code(.wrl.gz) to indicate classic encoding
1114 compressed with gzip.
1115
1116 The @link(Url) property is also changed. }
1117 procedure Save(const AUrl: String);
1118
1119 procedure BeforeDestruction; override;
1120 destructor Destroy; override;
1121
1122 { Tree of shapes in the scene, acting as a simplfied mirror
1123 of the X3D node graph.
1124 Contents of this tree are read-only from outside. }
1125 property Shapes: TShapeTree read FShapes;
1126
1127 // { Bounding box of all occurrences of the given X3D Shape node. }
1128 // function ShapeBoundingBox(const Node: TShapeNode): TBox3D;
1129
1130 { Number of active shapes in the @link(Shapes) tree.
1131 This is equivalent to Shapes.ShapesCount(true), except that this
1132 is faster (it's cached and reused in this instance, and automatically
1133 invalidated only when needed). }
1134 function ShapesActiveCount: Cardinal;
1135
1136 { Number of active and visible (TShape.Visible) shapes in the
1137 @link(Shapes) tree.
1138
1139 @seealso ShapesActiveCount }
1140 function ShapesActiveVisibleCount: Cardinal;
1141
1142 { Calculate the number of triangls and vertexes of all
1143 shapa states. For detailed specification of what these functions
1144 do see appropriate TAbstractGeometryNode methods.
1145 Here, we just sum their results for all shapes.
1146 @groupBegin }
1147 function VerticesCount: Cardinal; overload;
1148 function TrianglesCount: Cardinal; overload;
1149 { @groupEnd }
1150
1151 { Number of viewpoints (named camera position+orientation).
1152 -1 if none. }
1153 function ViewpointsCount: Cardinal;
1154
1155 { Viewpoint node (TAbstractViewpointNode) from an index between 0 and ViewpointsCount. }
1156 function GetViewpointNode(const Idx: integer): TAbstractViewpointNode;
1157
1158 { Good name to show user for a viewpoint, defined by an index between 0 and ViewpointsCount. }
1159 function GetViewpointName(const Idx: integer): String;
1160
1161 { Move current camera of the enclosing TCastleViewport to reflect the given
1162 viewpoint. This changes the camera position and orientation.
1163
1164 In X3D terminology, the new viewpoint node becomes "bound" (current).
1165 Switching the viewpoint that is already bound (current) also has an effect,
1166 it will change the camera position and orientation to reflect the viewpoint
1167 defined position / orientation. }
1168 procedure MoveToViewpoint(const Idx: integer; const Animated: boolean = true);
1169
1170 { Add to scene nodes (graph in @link(RootNode)) new viewpoint node
1171 reflecting current camera and navigation settings.
1172 The new viewpoint increases ViewpointsCount, so it's also immediately
1173 available for switching to it. }
1174 procedure AddViewpointFromNavigation(const Navigation: TCastleNavigation;
1175 const AName: String);
1176
1177 { Methods to notify this class about changes to the underlying RootNode
1178 graph. Since this class caches some things, it has to be notified
1179 when you manually change something within RootNode graph. }
1180
1181 { Release all internal associations with your VRML/X3D nodes.
1182 In particular, this will release OpenGL resources connected to your nodes.
1183 You should always call this @italic(before) you (may) free some nodes in
1184 @link(RootNode).
1185
1186 @italic(You have to call ChangedAll or Load at sometime
1187 after BeforeNodesFree, and before you try actual rendering, events etc.)
1188 Otherwise some stuff may not get recalculated.
1189
1190 The InternalChangedAll parameter is for internal use.
1191 It is set to @true when ChangedAll
1192 calls this method at the beginning of it's work, and means that nothing is freed,
1193 and we only require necessary cleanup at the beginning of ChangedAll.
1194 This way ChangedAll (when it wasn't preceeded by explicit
1195 BeforeNodesFree(false)) produces events from stacks CheckForDeletedNodes. }
1196 procedure BeforeNodesFree(const InternalChangedAll: boolean = false); override;
1197
1198 { Call Node.FreeRemovingFromAllParents, making sure that changes
1199 to our VRML/X3D node graph are allowed. This makes sure we call
1200 BeforeNodesFree befor freeing, and ChangedAll afterwards.
1201
1202 This avoids a common pitfall with relying on TShape or such
1203 existence between BeforeNodesFree and ChangedAll.
1204 BeforeNodesFree may free all our TShape instances, so if you
1205 want to free TX3DNode from our graph --- you typically want to
1206 get this TX3DNode instance *before* calling BeforeNodesFree.
1207 Using this method to free the node ensures this. }
1208 procedure NodeFreeRemovingFromAllParents(Node: TX3DNode);
1209
1210 { Remove the shape node from the scene.
1211 In case of VRML 1.0 / Inventor, when the Shape doesn't have a node,
1212 we remove the geometry node. }
1213 procedure RemoveShape(Shape: TShape);
1214
1215 { Notify scene that potentially everything changed
1216 in the VRML/X3D graph. This includes adding/removal of some nodes within
1217 RootNode graph and changing their fields' values.
1218 (Before freeing the nodes, remember to also call BeforeNodesFree
1219 earlier.)
1220
1221 @bold(You usually never need to call this method explicitly.
1222 It's called by engine when necesssary.)
1223 However, you need to call it yourself if you change the X3D graph directly
1224 through nodes' @code(FdXxx) fields,
1225 and you don't want to call for some reason @link(TX3DField FdXxx.Changed).
1226
1227 ChangedAll causes recalculation of all things dependent on RootNode,
1228 so it's very costly to call this. Avoid calling this.
1229 When you change a simple field, like by @code(FdXxx.Value := ...),
1230 you should rather call @code(FdXxx.Changed), and it may do something
1231 much faster than rebuilding the scene.
1232
1233 @italic(Descendant implementors notes:) ChangedAll is virtual,
1234 when overriding it remember that it's
1235 called by constructor of this class, so you can put a lot of your
1236 initialization there (instead of in the constructor).
1237
1238 ChangedAll calls BeforeNodesFree(true) first, for safety (and TGLShape
1239 actually depends on it, see implementation comments). }
1240 procedure ChangedAll(const OnlyAdditions: Boolean = false); override;
1241
1242 { Notify scene that you changed the value of given field.
1243 @bold(This method is internal, it should be used only by TX3DField
1244 implementation.)
1245
1246 This does relatively intelligent discovery what could be possibly
1247 affected by this field, and updates / invalidates
1248 internal information where needed.
1249
1250 Every change you do directly to the VRML/X3D nodes inside RootNode
1251 (using directly the methods of TX3DNode or TX3DField) must be
1252 reported to scene by calling this method. This includes changes
1253 to the inactive graph part (e.g. in inactive Switch child),
1254 because our shapes have to track it also.
1255 Changes to TShape.State.VRML1State (these nodes may come
1256 from VRML1DefaultState) should also be reported here.
1257 In fact, you can even notify this scene about changes to fields
1258 that don't belong to our RootNode --- nothing bad will happen.
1259 We always try to intelligently
1260 detect what this change implicates for this VRML/X3D scene.
1261
1262 @exclude }
1263 procedure InternalChangedField(const Field: TX3DField; const Change: TX3DChange); override;
1264
1265 { Notification when geometry changed.
1266 "Geometry changed" means that the positions
1267 of triangles changed. This is not send when merely things like
1268 material changed.
1269
1270 It is not guaranteed that octrees are already recalculated
1271 when this is called. (They may be recalculated only on-demand,
1272 that is when you actually access them.)
1273 However, it is guaranteed that shape's transformation
1274 (like TShape.State.Transform) are already updated. }
1275 property OnGeometryChanged: TSceneGeometryChanged
1276 read FOnGeometryChanged write FOnGeometryChanged;
1277
1278 { Notification when the list of viewpoints in the scene possibly
1279 changed.
1280
1281 Note that this doesn't necessarily mean that the current,
1282 bound viewpoint changed (although it could).
1283 If you only want to get notified when currently @italic(bound)
1284 viewpoint changes, then what you seek is rather
1285 @link(TX3DBindableStack.OnBoundChanged ViewpointStack.OnBoundChanged). }
1286 property OnViewpointsChanged: TNotifyEvent
1287 read FOnViewpointsChanged write FOnViewpointsChanged;
1288
1289 { Notification when the currently bound viewpoint's vectors
1290 (position/orientation and such) changed.
1291
1292 More precisely, this is called whenever values generated by
1293 ViewpointStack.Top.GetView changed.
1294
1295 It cannot be called when ViewpointStack.Top = @nil.
1296 Note that this also doesn't notify you about changes to
1297 currently bound viewpoint, for this you rather want to use
1298 @link(TX3DBindableStack.OnBoundChanged ViewpointStack.OnBoundChanged).
1299 This is called only when @italic(currently bound viewpoint stays
1300 the same, only it's vectors change). }
1301 property OnBoundViewpointVectorsChanged: TNotifyEvent
1302 read FOnBoundViewpointVectorsChanged write FOnBoundViewpointVectorsChanged;
1303
1304 { Called when geometry changed.
1305 Does OnGeometryChanged, and does some other stuff necessary
1306 (mark some octrees for regenerating at next access).
1307
1308 This is public only for overloading (and for internal TShape
1309 access). Do not call this yourself --- TShape and TCastleSceneCore
1310 implementations know when and how to call this. }
1311 procedure DoGeometryChanged(const Change: TGeometryChange;
1312 LocalGeometryShape: TShape); virtual;
1313
1314 { Call OnViewpointsChanged, if assigned. }
1315 procedure DoViewpointsChanged;
1316
1317 { Call OnBoundViewpointVectorsChanged, if assigned. }
1318 procedure DoBoundViewpointVectorsChanged;
1319
1320 property OnBoundNavigationInfoFieldsChanged: TNotifyEvent
1321 read FOnBoundNavigationInfoFieldsChanged write FOnBoundNavigationInfoFieldsChanged;
1322 procedure DoBoundNavigationInfoFieldsChanged; virtual;
1323
1324 { Mechanism to schedule ChangedAll calls.
1325
1326 Since these calls may be costly (traversing the hierarchy),
1327 and their results are often
1328 not immediately needed by TCastleSceneCore or TX3DNode hierarchy,
1329 it's sometimes not desirable to call them immediately
1330 when geometry changed / all changed.
1331
1332 So you can use ScheduleChangedAll instead of ChangedAll.
1333 All event handlers within TCastleSceneCore already do this.
1334
1335 When you're within Begin/EndChangesSchedule, then
1336 ScheduleChangedAll just sets an internal flag and actual ChangedAll
1337 will be done only once at EndChangesSchedule. Otherwise
1338 (when not within Begin/EndChangesSchedule), ScheduleChangedAll will
1339 immediately call ChangedAll.
1340
1341 @groupBegin }
1342 procedure ScheduleChangedAll(const OnlyAdditions: Boolean = false);
1343 procedure BeginChangesSchedule;
1344 procedure EndChangesSchedule;
1345 { @groupEnd }
1346
1347 { Returns short information about the scene.
1348 This consists of a few lines, separated by newlines.
1349 Last line also ends with CastleUtils.NL. }
1350 function Info(
1351 ATriangleVerticesCounts,
1352 ABoundingBox: boolean;
1353 AManifoldAndBorderEdges: boolean): String; deprecated 'do not use this, better to construct a summary string yourself';
1354
1355 function InfoTriangleVerticesCounts: String;
1356 deprecated 'better to construct a string yourself, use TrianglesCount, VerticesCount';
1357 function InfoBoundingBox: String;
1358 deprecated 'better to construct a string yourself, use BoundingBox.ToString';
1359 function InfoManifoldAndBorderEdges: String;
1360 deprecated 'better to construct a string yourself, use EdgesCount';
1361
1362 { Edges count in the scene, for information purposes. }
1363 procedure EdgesCount(out ManifoldEdges, BorderEdges: Cardinal);
1364
1365 { Actual VRML/X3D graph defining this scene.
1366
1367 It is allowed to change contents of RootNode. Just make sure
1368 the scene is notified about these changes.
1369 The simplest option is to use simple properties of nodes
1370 (not the ones starting with @code(Fd...) prefix), when possible.
1371 Then everything is notified automatically.
1372 If you must use fields through the @code(FdXxx) properties,
1373 then assign them using @link(TX3DField.Send),
1374 or (if you need to assign field
1375 values directly, like @code(TSFVec3f.Value := ...))
1376 call @link(TX3DField.Changed).
1377
1378 It is also allowed to change the value of RootNode
1379 and even to set RootNode to @nil.
1380 Changing RootNode allows you to load
1381 and unload whole new VRML/X3D graph (for example from some 3D file)
1382 whenever you want, and keep the same TCastleSceneCore instance
1383 (with the same rendering settings and such). }
1384 property RootNode: TX3DRootNode read FRootNode write SetRootNode;
1385
1386 { If @true, RootNode will be freed by destructor of this class. }
1387 property OwnsRootNode: boolean read FOwnsRootNode write FOwnsRootNode default true;
1388 {$ifdef FPC} deprecated 'set OwnsRootNode only at loading, do not depend on this property'; {$endif}
1389
1390 { A spatial structure containing all visible shapes.
1391 Add ssRendering to @link(Spatial) property, otherwise it's @nil.
1392
1393 @bold(You should not use this directly.
1394 Instead use TCastleViewport
1395 and then use @code(Viewport.Items.WorldXxxCollision) methods like
1396 @link(TCastleAbstractRootTransform.WorldRay Viewport.Items.WorldRay) or
1397 @link(TCastleAbstractRootTransform.WorldSphereCollision Viewport.Items.WorldSphereCollision).)
1398
1399 Note that when VRML/X3D scene contains Collision nodes, this octree
1400 contains the @italic(visible (not necessarily collidable)) objects. }
1401 function InternalOctreeRendering: TShapeOctree;
1402
1403 { A spatial structure containing all collidable shapes.
1404 Add ssDynamicCollisions to @link(Spatial) property, otherwise it's @nil.
1405
1406 @bold(You should not usually use this directly.
1407 Instead use TCastleViewport
1408 and then use @code(Viewport.Items.WorldXxxCollision) methods like
1409 @link(TCastleAbstractRootTransform.WorldRay Viewport.Items.WorldRay) or
1410 @link(TCastleAbstractRootTransform.WorldSphereCollision Viewport.Items.WorldSphereCollision).)
1411
1412 You can use @link(InternalOctreeCollisions) to get either
1413 @link(InternalOctreeDynamicCollisions) or
1414 @link(InternalOctreeStaticCollisions), whichever is available.
1415
1416 Note that when VRML/X3D scene contains Collision nodes, this octree
1417 contains the @italic(collidable (not necessarily rendered)) objects.
1418
1419 TODO: Temporarily, this is updated simply by rebuilding. }
1420 function InternalOctreeDynamicCollisions: TShapeOctree;
1421
1422 { A spatial structure containing all visible triangles, suitable only
1423 for scenes that stay static.
1424 Add ssVisibleTriangles to @link(Spatial) property, otherwise it's @nil.
1425
1426 @bold(You should not usually use this directly.
1427 Instead use TCastleViewport
1428 and then use @code(Viewport.Items.WorldXxxCollision) methods like
1429 @link(TCastleAbstractRootTransform.WorldRay Viewport.Items.WorldRay) or
1430 @link(TCastleAbstractRootTransform.WorldSphereCollision Viewport.Items.WorldSphereCollision).)
1431
1432 Note that when VRML/X3D scene contains X3D Collision nodes, this octree
1433 contains the @italic(visible (not necessarily collidable)) objects. }
1434 function InternalOctreeVisibleTriangles: TTriangleOctree;
1435
1436 { A spatial structure containing all collidable triangles.
1437 Add ssStaticCollisions to @link(Spatial) property, otherwise it's @nil.
1438
1439 @bold(You should not usually use this directly.
1440 Instead use TCastleViewport
1441 and then use @code(Viewport.Items.WorldXxxCollision) methods like
1442 @link(TCastleAbstractRootTransform.WorldRay Viewport.Items.WorldRay) or
1443 @link(TCastleAbstractRootTransform.WorldSphereCollision Viewport.Items.WorldSphereCollision).)
1444
1445 It is automatically used by the XxxCollision methods in this class,
1446 if exists, unless OctreeDynamicCollisions exists.
1447
1448 Note that you can use @link(InternalOctreeCollisions) to get either
1449 @link(InternalOctreeDynamicCollisions)
1450 or @link(InternalOctreeStaticCollisions), whichever is available. }
1451 function InternalOctreeStaticCollisions: TTriangleOctree;
1452
1453 { Octree for collisions. This returns either
1454 @link(InternalOctreeStaticCollisions) or
1455 @link(InternalOctreeDynamicCollisions), whichever is available (or @nil if none).
1456 Be sure to add ssDynamicCollisions or ssStaticCollisions to have
1457 this available.
1458
1459 @bold(You should not usually use this directly.
1460 Instead use TCastleViewport
1461 and then use @code(Viewport.Items.WorldXxxCollision) methods like
1462 @link(TCastleAbstractRootTransform.WorldRay Viewport.Items.WorldRay) or
1463 @link(TCastleAbstractRootTransform.WorldSphereCollision Viewport.Items.WorldSphereCollision).) }
1464 function InternalOctreeCollisions: TBaseTrianglesOctree;
1465
1466 function UseInternalOctreeCollisions: boolean;
1467
1468 { Viewpoint defined in the 3D file (or some default camera settings
1469 if no viewpoint is found).
1470
1471 GetViewpoint seeks for VRML/X3D nodes like
1472 Viewpoint, OrthoViewpoint (actually, any X3DViewpointNode)
1473 and VRML 1.0 PerspectiveCamera and OrthographicCamera.
1474 GetPerspectiveViewpoint seeks only for perspective viewpoints.
1475
1476 If ViewpointDescription = '', they return the first found viewpoint node.
1477 Otherwise, they look for X3DViewpointNode with description field mathing
1478 given string.
1479
1480 If camera properties were found in some node,
1481 it returns this node. Otherwise it returns nil.
1482 This way you can optionally extract some additional info from
1483 used viewpoint node, or do something special if default values
1484 were used. Often you will just ignore result of this function
1485 --- after all, the most important feature of this function
1486 is that you don't @italic(have) to care about details of
1487 dealing with camera node.
1488
1489 Returned CamDir and CamUp and GravityUp are always normalized ---
1490 reasons the same as for TAbstractViewpointNode.GetView.
1491
1492 @groupBegin }
1493 function GetViewpoint(
1494 out ProjectionType: TProjectionType;
1495 out CamPos, CamDir, CamUp, GravityUp: TVector3;
1496 const ViewpointDescription: String = ''):
1497 TAbstractViewpointNode;
1498
1499 function GetPerspectiveViewpoint(
1500 out CamPos, CamDir, CamUp, GravityUp: TVector3;
1501 const ViewpointDescription: String = ''):
1502 TAbstractViewpointNode;
1503 { @groupEnd }
1504
1505 { Frees some scene resources, to conserve memory.
1506 See TSceneFreeResources documentation. }
1507 procedure FreeResources(Resources: TSceneFreeResources); virtual;
1508
1509 { Recursively unset node's TX3DNode.Scene. }
1510 procedure UnregisterScene(Node: TX3DNode);
1511 deprecated 'use Node.UnregisterScene';
1512
1513 { Scene processes X3D key sensor nodes here, https://castle-engine.io/x3d_implementation_keydevicesensor.php .
1514 Remember to set ListenPressRelease to process the key sensor nodes. }
1515 function Press(const Event: TInputPressRelease): boolean; override;
1516 function Release(const Event: TInputPressRelease): boolean; override;
1517
1518 function PointingDevicePress(const Pick: TRayCollisionNode;
1519 const Distance: Single): Boolean; override;
1520 function PointingDeviceRelease(const Pick: TRayCollisionNode;
1521 const Distance: Single; const CancelAction: Boolean): Boolean; override;
1522
1523 { Called when pointing device moves.
1524 This may generate the continuously-generated events like
1525 hitPoint_changed, also it updates PointingDeviceOverItem
1526 and PointingDeviceOverPoint,
1527 thus producing isOver and such events.
1528
1529 To make pointing-device sensors work Ok, make sure you have non-nil
1530 OctreeCollisions (e.g. include ssDynamicCollisions in @link(Spatial)). }
1531 function PointingDeviceMove(const Pick: TRayCollisionNode;
1532 const Distance: Single): boolean; override;
1533
1534 { Current item over which the pointing device is. @nil if over none.
1535 For example, you can investigate it's pointing device sensors
1536 (in PointingDeviceOverItem^.State.PointingDeviceSensors),
1537 although there's a shortcut for just this in @link(PointingDeviceSensors).
1538 You can change this by PointingDeviceMove and PointingDeviceClear. }
1539 property PointingDeviceOverItem: PTriangle
1540 read FPointingDeviceOverItem write FPointingDeviceOverItem;
1541
1542 { Current 3D point under the pointing device.
1543 Only meaningful when PointingDeviceOverItem <> nil,
1544 otherwise undefined. }
1545 property PointingDeviceOverPoint: TVector3
1546 read FPointingDeviceOverPoint write FPointingDeviceOverPoint;
1547
1548 { Pointing-device sensors over which the pointing device is.
1549 This is just a shortcut for
1550 PointingDeviceOverItem^.State.PointingDeviceSensors,
1551 returning @nil if PointingDeviceOverItem = @nil. }
1552 function PointingDeviceSensors: TPointingDeviceSensorList;
1553
1554 { Currently active pointing-device sensors.
1555 Only TAbstractPointingDeviceSensorNode instances.
1556 Always empty when PointingDeviceActive = @false.
1557 Read-only from outside of this class.
1558
1559 Note that sensor specified here doesn't have to be one of the sensors of
1560 PointingDeviceOverItem. When some sensor is activated, it grabs
1561 further events until it's deactivated (e.g. when you set
1562 PointingDeviceActive := false, which means that user released mouse
1563 button). This means that when user moves the mouse while given
1564 sensors are active, he can move mouse over other items, even the ones
1565 where the active sensors aren't listed --- but the sensors remain active. }
1566 property PointingDeviceActiveSensors: TX3DNodeList
1567 read FPointingDeviceActiveSensors;
1568
1569 { Clear any references to PTriangle passed previously in TRayCollisionNode argument to
1570 PointingDevicePress, PointingDeviceRelease, PointingDeviceMove.
1571 This is internally used in case some of past seen PTriangle may become invalid,
1572 so any memory about them should be cleared.
1573
1574 This doesn't cause any X3D events
1575 (contrary to e.g. calling PointingDeviceMove with Pick.Triangle = @nil).
1576
1577 This method clears any references to saved PTriangle and
1578 PointingDeviceActiveSensors.
1579 Note that this still calls DoPointingDeviceSensorsChange
1580 (making OnPointingDeviceSensorsChange event), if PointingDeviceActiveSensors /
1581 PointingDeviceSensors possibly changed. }
1582 procedure PointingDeviceClear;
1583
1584 { Is pointing device currently active
1585 (for example, mouse button is pressed down). }
1586 property PointingDeviceActive: boolean
1587 read FPointingDeviceActive default false;
1588
1589 { Event called PointingDeviceSensors or
1590 PointingDeviceActiveSensors lists (possibly) changed. }
1591 property OnPointingDeviceSensorsChange: TNotifyEvent
1592 read FOnPointingDeviceSensorsChange
1593 write FOnPointingDeviceSensorsChange;
1594
1595 function LocalBoundingBox: TBox3D; override;
1596 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
1597
1598 { Change current scene time, setting @link(Time).
1599 It is crucial that you call this continuously to have some VRML/X3D
1600 time-dependent features working, like TimeSensor and MovieTexture.
1601 See @link(Time) for details what is affected by this.
1602
1603 This is automatically taken care of if you added this scene
1604 to TCastleWindow.Controls or TCastleControl.Controls.
1605 Then our @link(Update) takes care of doing the job,
1606 according to TimePlaying and TimePlayingSpeed.
1607
1608 This causes time to be passed to appropriate time-dependent nodes,
1609 events will be called etc.
1610
1611 SetTime and IncreaseTime do exactly the same, the difference is
1612 only that for IncreaseTime you specify increase in the time
1613 (that is, NewTime = @link(Time) + TimeIncrease). Use whichever version
1614 is more handy.
1615
1616 Following X3D specification, time should only grow. So NewValue should
1617 be > @link(Time) (or TimeIncrease > 0).
1618 Otherwise we ignore this call.
1619 For resetting the time (when you don't necessarily want to grow @link(Time))
1620 see ResetTime.
1621
1622 If a change of Time will produce some visible change in the VRML/X3D model
1623 (for example, MovieTexture will change, or TimeSensor change will be
1624 routed by interpolator to coordinates of some visible node) it
1625 will be reported by usual method, that is VisibleChangeHere.
1626
1627 @groupBegin }
1628 procedure SetTime(const NewValue: TFloatTime);
1629 procedure IncreaseTime(const TimeIncrease: TFloatTime);
1630 { @groupEnd }
1631
1632 procedure IncreaseTimeTick;
1633 deprecated 'it should not be necessary to call this, ever; using TX3DEvent.Send(...) or TX3DEvent.Send(..., NextEventTime) will automatically behave Ok.';
1634
1635 { The time within this scene, in seconds.
1636 Increasing this "drives" the animations (by increasing
1637 time of time-dependent nodes like X3D TimeSensor, which in turn
1638 drive the rest of the animation).
1639
1640 You can use @link(SetTime) or @link(IncreaseTime) to move time
1641 forward manually. But usually there's no need for it:
1642 our @link(Update) method takes care of it automatically,
1643 you only need to place the scene inside @link(TCastleViewport.Items).
1644
1645 You can start/stop time progress by @link(TimePlaying)
1646 and scale it by @link(TimePlayingSpeed). These properties
1647 affect how the time is updated by the @link(Update) method
1648 (so if you use @link(SetTime) or @link(IncreaseTime) methods,
1649 you're working around these properties).
1650
1651 Default time value is 0.0 (zero). However it will be reset
1652 at load to a current time (seconds since Unix epoch ---
1653 that's what X3D standard says to use, although you can change
1654 it by KambiNavigationInfo.timeOriginAtLoad,
1655 see https://castle-engine.io/x3d_implementation_navigation_extensions.php#section_ext_time_origin_at_load ).
1656 You can perform this "time reset" yourself by @link(ResetTimeAtLoad)
1657 or @link(ResetTime). }
1658 function Time: TFloatTime; override;
1659
1660 { Time that should be used for next event.
1661 You usually don't need to call this directly, this is automatically
1662 used by TX3DEvent.Send when you don't specify explicit time. }
1663 function NextEventTime: TX3DTime; override;
1664
1665 { Set @link(Time) to arbitrary value.
1666
1667 You should only use this when you loaded new VRML/X3D model.
1668
1669 Unlike SetTime and IncreaseTime, this doesn't require that
1670 @link(Time) grows. It still does some time-dependent events work,
1671 although some time-dependent nodes may be just unconditionally reset
1672 by this to starting value (as they keep local time, and so require
1673 TimeIncrease notion, without it we can only reset them).
1674
1675 @groupBegin }
1676 procedure ResetTime(const NewValue: TFloatTime);
1677 { @groupEnd }
1678
1679 { Set @link(Time) to suitable initial value after loading a world.
1680
1681 This honours VRML/X3D specification about VRML/X3D time origin,
1682 and our extension
1683 [https://castle-engine.io/x3d_extensions.php#section_ext_time_origin_at_load]. }
1684 procedure ResetTimeAtLoad;
1685
1686 { Initial world time, set by the last ResetTimeAtLoad call. }
1687 property TimeAtLoad: TFloatTime read FTimeAtLoad;
1688
1689 { Stack of background nodes. The node at the top is the current background.
1690 All nodes on this stack must descend from TAbstractBackgroundNode class. }
1691 property BackgroundStack: TBackgroundStack read FBackgroundStack;
1692
1693 { Stack of fog nodes. The node at the top is the current fog.
1694 All nodes on this stack must descend from TFogNode class. }
1695 property FogStack: TFogStack read FFogStack;
1696
1697 { Stack of NavigatinInfo nodes. The node at the top is the current NavigatinInfo.
1698 All nodes on this stack must descend from TNavigationInfoNode class. }
1699 property NavigationInfoStack: TNavigationInfoStack read FNavigationInfoStack;
1700
1701 { Stack of viewpoint nodes. The node at the top is the current Viewpoint.
1702 All nodes on this stack must descend from TAbstractViewpointNode.
1703 Note that this includes also VRML 1.0/Inventor nodes. }
1704 property ViewpointStack: TViewpointStack read FViewpointStack;
1705
1706 function GetBackgroundStack: TX3DBindableStackBasic; override;
1707 function GetFogStack: TX3DBindableStackBasic; override;
1708 function GetNavigationInfoStack: TX3DBindableStackBasic; override;
1709 function GetViewpointStack: TX3DBindableStackBasic; override;
1710
1711 { List of handlers for VRML/X3D Script node with "compiled:" protocol.
1712 This is read-only, change this only by RegisterCompiledScript. }
1713 property CompiledScriptHandlers: TCompiledScriptHandlerInfoList
1714 read FCompiledScriptHandlers;
1715
1716 { Register compiled script handler, for VRML/X3D Script node with
1717 "compiled:" protocol.
1718 See [https://castle-engine.io/x3d_extensions.php#section_ext_script_compiled]. }
1719 procedure RegisterCompiledScript(const HandlerName: String;
1720 Handler: TCompiledScriptHandler);
1721
1722 { Update TCastleNavigation properties based on currently bound TNavigationInfoNode.
1723
1724 Bound TNavigationInfoNode is taken from
1725 NavigationInfoStack.Top. If no such node is bound (NavigationInfoStack.Top is @nil)
1726 then we behave as if TNavigationInfoNode with all fields at default was active.
1727
1728 Note that, since some fields are only in some descendants (e.g. MoveSpeed
1729 is only at TCastleWalkNavigation) then some TNavigationInfoNode settings
1730 are just not transferred to all Navigation instances like
1731 TCastleExamineNavigation }
1732 procedure InternalUpdateNavigation(
1733 const Navigation: TCastleNavigation);
1734
1735 { Update TCastleCamera properties based on the current X3D nodes
1736 (currently bound X3D Viewpoint and NavigationInfo nodes).
1737 When no viewpoint is currently bound, we will go to a suitable
1738 viewpoint to see the whole world (based on the WorldBox).
1739
1740 The initial camera vectors position, direction, up, gravity up
1741 are set to the current viewpoint. This is done
1742 regardless of the RelativeCameraTransform value.
1743
1744 TODO: below is no longer valid, RelativeCameraTransform has no meaning now.
1745
1746 How current camera vectors change depends on RelativeCameraTransform:
1747
1748 @unorderedList(
1749 @item(RelativeCameraTransform = @false means that we just
1750 set current vectors to the initial vectors.
1751 In other words, camera jumps to the viewpoint.
1752
1753 In this case, AllowTransitionAnimate determines if we allow
1754 moving camera by a smooth transition. If this is @true,
1755 and also NavigationInfo allows it (see CameraTransition),
1756 then camera will jump smoothy. Otherwise camera will jump
1757 to viewpoint immediately.)
1758
1759 @item(RelativeCameraTransform = @true means that we translate/rotate
1760 the current camera in the same manner as initial camera
1761 changed. This is suitable when you change transformation, position
1762 or orientation of the X3D Viewpoint node: conceptually,
1763 there exists a "user" camera transformation that is the child
1764 of the viewpoint. When viewpoint is moved, then the current
1765 camera moves with it.)
1766 )
1767
1768 @exclude }
1769 procedure InternalUpdateCamera(const ACamera: TCastleCamera;
1770 const WorldBox: TBox3D;
1771 const RelativeCameraTransform: boolean;
1772 const AllowTransitionAnimate: boolean);
1773
1774 { Make Camera go to the view given by (world coordinates) APosition, ADirection, AUp.
1775
1776 Honours current NavigationInfo.transitionType and transitionTime.
1777 If transitionType indicates instanteneous transition, then jumps
1778 by simple @code(Camera.SetWorldView(APosition, ADirection, AUp)).
1779 Otherwise makes a smooth animation into new values by
1780 @code(Camera.AnimateTo(APosition, ADirection, AUp, TransitionTime)).
1781
1782 Will generate NavigationInfo.transitionComplete when transition ends.
1783
1784 @groupBegin }
1785 procedure CameraTransition(const Camera: TCastleCamera; const APosition, ADirection, AUp: TVector3); overload;
1786 deprecated 'use Camera.AnimateTo(APosition, ADirection, AUp)';
1787 procedure CameraTransition(const Camera: TCastleCamera; const APosition, ADirection, AUp, GravityUp: TVector3); overload;
1788 deprecated 'use Camera.AnimateTo(APosition, ADirection, AUp)';
1789 procedure CameraTransition(const Navigation: TCastleNavigation; const APosition, ADirection, AUp: TVector3); overload;
1790 deprecated 'use Camera.AnimateTo(APosition, ADirection, AUp)';
1791 procedure CameraTransition(const Navigation: TCastleNavigation; const APosition, ADirection, AUp, GravityUp: TVector3); overload;
1792 deprecated 'use Camera.AnimateTo(APosition, ADirection, AUp)';
1793 { @groupEnd }
1794
1795 { Detect position/direction of the main light that produces shadow volumes.
1796 This is useful when you want to make shadows on the scene
1797 from only a single light, but your scene has many lights.
1798
1799 The main light is simply one with both @code(shadowVolumes) and
1800 @code(shadowVolumesMain) fields set to @true. See
1801 [https://castle-engine.io/x3d_extensions.php#section_ext_shadows]
1802 for more info.
1803 If no light with shadowVolumes = shadowVolumesMain = TRUE
1804 is present then this function returns @false,
1805 since AMainLightPosition cannot be calculated.
1806
1807 AMainLightPosition[3] is always set to 1
1808 (positional light) or 0 (indicates that this is a directional light).
1809 Returned value is local to this transformation (i.e. it is in this scene's space,
1810 not world space).
1811
1812 @exclude
1813 Should only be used internally by TCastleViewport. }
1814 function InternalMainLightForShadowVolumes(out AMainLightPosition: TVector4): boolean;
1815
1816 { Light node that should be used for headlight, or @nil if default
1817 directional headlight is suitable.
1818
1819 This never returns @nil. It's not concerned whether the headlight
1820 should actually be used --- for this, see HeadlightOn. }
1821 function CustomHeadlight: TAbstractLightNode;
1822
1823 { Should we use headlight for this scene. Controls if containing TCastleViewport
1824 will use a headlight, if this is the main scene.
1825
1826 When you load a new model, this is always updated based on this model's
1827 NavigationInfo.headlight. (If no NavigationInfo node, then default
1828 is to use the headlight.) When you bind a new NavigationInfo node,
1829 this is also updated to follow NavigationInfo.headlight.
1830
1831 You can change the value of this property. If we have a
1832 NavigationInfo node, then NavigationInfo.headlight field will
1833 be always updated to correspond to this value.
1834 (It will be even updated using events mechanism if ProcessEvents,
1835 so scripts inside the VRML/X3D "know" when
1836 you turn on/off the headlight and may react to it,
1837 e.g. spawn a zombie monster when you turn on the flashlight.) }
1838 property HeadlightOn: boolean
1839 read FHeadlightOn write SetHeadlightOn;
1840
1841 property OnHeadlightOnChanged: TNotifyEvent
1842 read FOnHeadlightOnChanged write FOnHeadlightOnChanged;
1843
1844 procedure PrepareResources(const Options: TPrepareResourcesOptions;
1845 const Params: TPrepareParams); override;
1846
1847 { Nice scene caption. Uses the "title" of WorldInfo
1848 node inside the VRML/X3D scene. If there is no WorldInfo node
1849 (or it has empty title) then result is based on loaded URL. }
1850 function Caption: String;
1851
1852 { Global lights of this scene. Read-only.
1853 Useful to shine these lights on other scenes, if TCastleScene.CastGlobalLights. }
1854 property InternalGlobalLights: TLightInstancesList read FGlobalLights;
1855
1856 { Find a named X3D node in the current node graph.
1857
1858 By default it searches both active and inactive graph parts.
1859 Add fnOnlyActive to search only in active parts.
1860
1861 It searches only within nodes of given type (NodeClass).
1862 Specifying NodeClass helps to make search unambiguous
1863 (as name clashes are possible, some authoring tools may write models with duplicate
1864 names for materials, meshes etc. and both glTF and X3D allow it).
1865 This allows to safely write code like:
1866
1867 @longCode(#
1868 MyMaterial := Scene.Node(TNodePhysicalMaterial, 'MyMaterial') as TNodePhysicalMaterial;
1869 #)
1870
1871 TODO: An even better version, "MyMaterial := Scene.Node<TNodePhysicalMaterial>('MyMaterial')",
1872 may be available in the future, if FPC support for generic methods will improve.
1873 Define GENERIC_METHODS to try it out now, but heed the warnings in castleconf.inc .
1874
1875 @raises(EX3DNotFound When node is not found.
1876 Unless fnNilOnMissing in Options, then it returns @nil on missing node,
1877 and EX3DNotFound is never raised.)
1878 }
1879 function Node(const NodeClass: TX3DNodeClass; const NodeName: String;
1880 const Options: TFindNodeOptions = []): TX3DNode; overload;
1881 function Node(const NodeName: String): TX3DNode; overload;
1882 { deprecated 'use Node(NodeClass, NodeName)';
1883
1884 Do not deprecate. It doesn't offer that big benefit over using version
1885 without NodeClass, when you know that node name is unique.
1886 The "as" with perform check in case types differ. }
1887
1888 { Find a named field within an X3D node in the current node graph.
1889
1890 Like @link(Node), this searches all nodes (in active or not) graph parts.
1891
1892 @raises(EX3DNotFound If given node or field could not be found.) }
1893 function Field(const NodeName, FieldName: String): TX3DField; overload;
1894 {$ifdef GENERIC_METHODS} deprecated 'use Field<NodeType>(NodeName, FieldName)'; {$endif}
1895
1896 { Find a named event within an X3D node in the current node graph.
1897
1898 Like @link(Node), this searches all nodes (in active or not) graph parts.
1899
1900 @raises(EX3DNotFound If given node or event could not be found.) }
1901 function Event(const NodeName, EventName: String): TX3DEvent; overload;
1902 {$ifdef GENERIC_METHODS} deprecated 'use Event<NodeType>(NodeName, FieldName)'; {$endif}
1903
1904 {$ifdef GENERIC_METHODS}
1905 (*Find a named X3D node in the current node graph.
1906 See non-generic Node for description of Options.
1907
1908 It searches only within nodes of given type (T) and also
1909 returns the appropriate type. Use it like this:
1910
1911 @longCode(#
1912 var
1913 Material: TPhysicalMaterialNode;
1914 begin
1915 Material := MyScene.{$ifdef FPC}specialize{$endif} Node<TPhysicalMaterialNode>('MyMaterialName');
1916 end;
1917 #)
1918
1919 You can simplify the code if you only care about FPC or Delphi compiler.
1920
1921 TODO: The extra "specialize" looks ugly, it is excessive. It is even uglier when compounded
1922 if "ifdef FPC", if you need to support both FPC and Delphi.
1923
1924 TODO: FPC 3.2.2. unfortunately makes internal error if you forget
1925 "specialize", not a proper error message.
1926 And sometimes it compiles something weird, that always crashes. *)
1927 {$ifdef FPC}generic{$endif} function Node<T: TX3DNode>(const NodeName: String;
1928 const Options: TFindNodeOptions = []): T; overload;
1929 {$ifdef FPC}generic{$endif} function Field<T: TX3DNode>(const NodeName, FieldName: String): TX3DField; overload;
1930 {$ifdef FPC}generic{$endif} function Event<T: TX3DNode>(const NodeName, EventName: String): TX3DEvent; overload;
1931 {$endif}
1932
1933 { List the names of available animations in current scene.
1934 Animations are detected looking for TimeSensor nodes.
1935 See https://castle-engine.io/x3d_implementation_interpolation.php
1936 for an overview how nodes are used to create animations.
1937
1938 Note that if you set @link(AnimationPrefix) property, we additionally
1939 filter TimeSensor nodes to show only the names starting with given prefix.
1940 In this case, not all TTimeSensorNode are reflected in this list.
1941
1942 You can get the corresponding TTimeSensorNode by AnimationTimeSensor.
1943 Note that the same TTimeSensorNode may occur multiple times on this list,
1944 in case X3D IMPORT mechanism was used to rename the imported animation.
1945
1946 The resulting TStringList instance is owned by this object,
1947 do not free it.
1948
1949 Note that the list of animations may change if you rebuild the underlying
1950 X3D nodes graph, for example if you start to delete / add some TimeSensor
1951 nodes. }
1952 property AnimationsList: TStrings read FAnimationsList;
1953
1954 { Does named animation with given name exist.
1955 @seealso AnimationsList
1956 @seealso PlayAnimation }
1957 function HasAnimation(const AnimationName: String): boolean;
1958
1959 { TimeSensor of this animation. @nil if this name not found. }
1960 function AnimationTimeSensor(const AnimationName: String): TTimeSensorNode; overload;
1961
1962 { TimeSensor of this animation, by animation index (index
1963 on AnimationsList). @nil if this index not found. }
1964 function AnimationTimeSensor(const Index: Integer): TTimeSensorNode; overload;
1965
1966 { Forcefully, immediately, set pose from given animation,
1967 with given time in animation.
1968
1969 This avoids the normal passage of time in X3D scenes,
1970 it ignores the @link(ProcessEvents) and @link(AnimateOnlyWhenVisible)
1971 properties, it ignores the current animation set by @link(PlayAnimation),
1972 and forces the current time on TimeSensors by @link(TTimeSensorNode.FakeTime). }
1973 function ForceAnimationPose(const AnimationName: String;
1974 const TimeInAnimation: TFloatTime;
1975 const Loop: boolean;
1976 const Forward: boolean = true): boolean; overload;
1977
1978 { Play an animation specified by name.
1979
1980 You can specify the animation name, whether it should loop,
1981 and whether to play it forward or backward using parameters to this method.
1982
1983 Or you can specify even more parameters using TPlayAnimationParameters instance.
1984 TPlayAnimationParameters can additionally specify a stop notification,
1985 initial time and more.
1986 It is OK to create a short-lived TPlayAnimationParameters instance and destroy
1987 it right after calling this method.
1988 This method doesn't store the TPlayAnimationParameters instance reference.
1989
1990 To get the list of available animations, see @link(AnimationsList).
1991
1992 This is one of the simplest way to play animations using Castle Game Engine.
1993 Alternative (that calls PlayAnimation under the hood) is to set @link(AutoAnimation).
1994 See https://castle-engine.io/viewport_3d#_play_animation .
1995
1996 Playing an already-playing animation is guaranteed to restart it from
1997 the beginning (more precisely: from TPlayAnimationParameters.InitialTime,
1998 if you pass TPlayAnimationParameters).
1999
2000 If the given animation name exists,
2001 then we stop previously playing animation (if any),
2002 calling it's stop notification (see TPlayAnimationParameters.StopNotification),
2003 start playing the new animation, and return @true.
2004 If the animation name does not exist then we return @false,
2005 make a warning and the current animation is unchanged.
2006
2007 The change from previous to new animation can be smooth (using animation
2008 cross-fading) if you use TPlayAnimationParameters with @link(TPlayAnimationParameters.TransitionDuration)
2009 or if you set DefaultAnimationTransition to something non-zero.
2010
2011 This automatically turns on @link(ProcessEvents),
2012 if it wasn't turned on already.
2013 Processing events is necessary for playing animations.
2014
2015 More details about how this works:
2016
2017 @unorderedList(
2018 @item(Calling this method @italic(does not change the scene immediately).
2019 There may be a delay between calling PlayAnimation and actually
2020 changing the scene to reflect the state at the beginning of the indicated
2021 animation. This delay is usually 1 frame (that is, the scene is updated
2022 at the next @link(Update) call), but it may be larger if you use
2023 the optimization @link(AnimateSkipTicks).
2024
2025 This is often a desirable optimization. There's often no "rush" to
2026 visually change the animation @italic(right now), and doing it at
2027 the nearest @link(Update) call is acceptable.
2028 It also means that calling @link(PlayAnimation) multiple times
2029 before a single @link(Update) call is not expensive.
2030
2031 If you really need to change the scene immediately (for example,
2032 because you don't want to show user the initial scene state),
2033 simply call @link(ForceInitialAnimationPose) right after @link(PlayAnimation).
2034 )
2035
2036 @item(@italic(The animation is performed using X3D TTimeSensorNode).
2037
2038 For example, TTimeSensorNode
2039 may instruct a TCoordinateInterpolatorNode to update the TIndexedFaceSetNode coordinates,
2040 and in effect the animation can deform a mesh.
2041 Or TTimeSensorNode may instruct a TPositionInterpolatorNode to update
2042 @link(TTransformNode.Translation),
2043 and in effect the animation can move something.
2044 See https://castle-engine.io/x3d_implementation_interpolation.php
2045 for a thorough description how the animation works in X3D.
2046
2047 This means that during the animation,
2048 the X3D nodes graph (within @link(RootNode)) is being changed.
2049
2050 If you load a model from a castle-anim-frames or MD3 format, note that it
2051 is animated using a special "node interpolator".
2052 This also works using a special (internal) X3D node that
2053 switches which node is visible.)
2054
2055 @item(Starting an animation effectively cancels any effect from
2056 any previous animation. That is, even if the new animation doesn't
2057 modify some transformations, these transformations are @italic(not)
2058 left "as is", instead they are reset to the default model state using
2059 @link(ResetAnimationState). This is usually the desired effect, corresponding
2060 to how the animations should intuitively behave, e.g. if you have "walk"
2061 and "idle" animations.
2062
2063 If you want to simultaneously play multiple animations
2064 or if you want to simultaneously modify scene by code (while playing some animation)
2065 then you can control each time sensor using @link(TTimeSensorNode.Start)
2066 and @link(TTimeSensorNode.Stop). See also the example
2067 in examples/animations/simultaneous_animations_one_scene .
2068 )
2069 )
2070 }
2071 function PlayAnimation(const Parameters: TPlayAnimationParameters): boolean; overload;
2072 function PlayAnimation(const AnimationName: String;
2073 const Loop: boolean; const Forward: boolean = true): boolean; overload;
2074
2075 { Force the model to look like the initial animation frame @italic(now).
2076
2077 Use this after calling @link(PlayAnimation).
2078 Calling this is simply ignored if no @link(PlayAnimation) was called
2079 earlier, of if the model already looks following the
2080 animation requested by @link(PlayAnimation).
2081
2082 If you don't use this method, there may be a 1-frame delay
2083 between calling @link(PlayAnimation) and actually updating the rendered
2084 scene look. If during that time a rendering will happen,
2085 the user will see a scene in previous pose (not in the first
2086 pose of animation you requested by @link(PlayAnimation)).
2087 To avoid this, simply call this method right after @link(PlayAnimation).
2088
2089 This sets first animation frame,
2090 unless you used TPlayAnimationParameters.InitialTime <> 0. }
2091 procedure ForceInitialAnimationPose;
2092
2093 { Duration, in seconds, of the named animation
2094 (named animations are detected by @link(AnimationsList) method).
2095 For a looping animation, this is the duration of a single cycle.
2096 0 if not found. }
2097 function AnimationDuration(const AnimationName: String): TFloatTime;
2098
2099 {$ifdef FPC}
2100 { The prefix of an X3D TimeSensor node name to treat it as a "named animation".
2101 Named animation are used by methods @link(AnimationsList), @link(PlayAnimation),
2102 and @link(AnimationDuration), @link(HasAnimation).
2103 By default this is empty, which means we consider all TimeSensor nodes
2104 a "named animation".
2105
2106 You can set this to something like 'Anim_' or 'Animation_'
2107 or whatever your 3D export software produces. Only the TimeSensor
2108 nodes with names starting with this prefix will be available
2109 on @link(AnimationsList), and this prefix will be stripped from
2110 the names you use with methods like @link(PlayAnimation). }
2111 property AnimationPrefix: String
2112 read FAnimationPrefix write FAnimationPrefix;
2113 deprecated 'this property did not prove to be of much use; report if you need it, otherwise it may be removed one day';
2114 {$endif}
2115
2116 { Currently played animation by @link(PlayAnimation), or @nil.
2117
2118 Note that, in a general case, you can have multiple active animations
2119 (multiple TimeSensor X3D nodes may be active) at the same time.
2120 Calling @link(TTimeSensorNode.Start) directly on multiple nodes is
2121 one way to make it happen.
2122 This property simply describes
2123 the animation controlled by the last @link(PlayAnimation) method.
2124
2125 Note that the animation may be started by PlayAnimation with a 1-frame
2126 delay, but this property hides it from you, it is changed
2127 immediately by the PlayAnimation call. }
2128 property CurrentAnimation: TTimeSensorNode read FCurrentAnimation;
2129
2130 { Stop the @link(CurrentAnimation), started by last @link(PlayAnimation) call.
2131 Note that this leaves the model in a state in the middle of the last animation.
2132
2133 You can use @link(ResetAnimationState) to reset the state afterwards.
2134 Calling @link(ForceInitialAnimationPose) also will do it.
2135
2136 Note that it is not necessary to stop the previous animation
2137 before starting a new one (by @link(PlayAnimation)).
2138 @link(PlayAnimation) will automatically stop the previous animation.
2139 Moreover, @link(PlayAnimation) may do animation blending (cross-fade)
2140 between old and new animation (if you use @link(TPlayAnimationParameters.TransitionDuration)),
2141 which only works if you @italic(did not) call StopAnimation.
2142
2143 When animation is stopped (by this or any other means),
2144 by default it's @link(TPlayAnimationParameters.StopNotification) is called.
2145 You can use DisableStopNotification to avoid it,
2146 which should be used only in exceptional situations. }
2147 procedure StopAnimation(const DisableStopNotification: Boolean = false);
2148
2149 { Reset all the fields affected by animations.
2150 See TimeSensor.detectAffectedFields documentation
2151 (https://castle-engine.io/x3d_implementation_time_extensions.php#section_detect_affected_fields)
2152 for details how these fields are detected, and when this is useful.
2153 By default this is enabled, for all TimeSensor nodes.
2154
2155 If IgnoreAffectedBy <> nil, the fields affected by the given TimeSensor
2156 may not be reset. This is an optimization useful in case this TimeSensor
2157 will modify the scene very soon, so resetting its affected fields
2158 is a waste of time.
2159 Do not depend on 100% that the fields affected by given TimeSensor
2160 are left untouched (in the current implementation, this field is ignored). }
2161 procedure ResetAnimationState(const IgnoreAffectedBy: TTimeSensorNode = nil);
2162
2163 { Force recalculating the text shapes when font changed.
2164 For now, we don't detect font changes (e.g. when TFontStyleNode.CustomFont changed)
2165 automatically.
2166 This calls @link(TTextNode.FontChanged) and @link(TAsciiTextNode_1.FontChanged)
2167 on all appropriate nodes. }
2168 procedure FontChanged;
2169
2170 { Create a scene with the same contents (X3D scene graph) as this one.
2171 The created scene has exactly the same class as this one
2172 (we use ClassType.Create to call a virtual constructor).
2173
2174 Note that this @bold(does not copy other scene attributes),
2175 like @link(ProcessEvents) or @link(Spatial) or rendering attributes
2176 in @link(TCastleScene.RenderOptions).
2177 It only copies the scene graph (RootNode) and also sets
2178 target URL based on source URL (for logging purposes, e.g.
2179 TCastleProfilerTime use this URL to report loading and preparation times). }
2180 function Clone(const AOwner: TComponent): TCastleSceneCore;
2181
2182 {$ifdef FPC}
2183 { @deprecated Deprecated name for @link(Url). }
2184 property FileName: String read FUrl write SetUrl; deprecated;
2185 {$endif}
2186
2187 procedure InternalIncShapesHash;
2188 property InternalShapesHash: TShapesHash read FShapesHash;
2189
2190 { Load again the model from current URL.
2191 This makes sense to be used when underlying file on disk
2192 changed, and you want to reload it.
2193
2194 TODO: If the file is cached using @link(Cache), then it will not reload
2195 the version in cache, so effectively it will not load new version from
2196 disk. This will be fixed at some point. }
2197 procedure ReloadUrl;
2198 published
2199 { When using @link(PlayAnimation) without TPlayAnimationParameters,
2200 this value is used as the duration (in seconds) of animation cross-fade
2201 (blending of animations).
2202 Zero (default value) disables the smooth transition, animations
2203 will change without any transition by default.
2204
2205 This default transition is only used if some previous animation
2206 was playing. Otherwise, it would be applied even when starting
2207 the initial animation. }
2208 property DefaultAnimationTransition: Single
2209 read FDefaultAnimationTransition write FDefaultAnimationTransition {$ifdef FPC}default 0.0{$endif};
2210
2211 { When TimePlaying is @true, the time of our 3D world will keep playing.
2212 More precisely, our @link(Update) will take care of increasing @link(Time).
2213 Our @link(Update) is usually automatically called (if you added this
2214 scene to TCastleWindow.Controls or TCastleControl.Controls)
2215 so you don't have to do anything to make this work. }
2216 property TimePlaying: boolean read FTimePlaying write FTimePlaying default true;
2217
2218 { Controls the time speed (if TimePlaying is @true):
2219 1.0 means that 1 second of real time equals to 1 unit of world time. }
2220 property TimePlayingSpeed: Single read FTimePlayingSpeed write FTimePlayingSpeed {$ifdef FPC}default 1.0{$endif};
2221
2222 { In most cases you should get / set simpler @link(PreciseCollisions) property, not this.
2223 Which spatial structures (octrees) should be created and used.
2224
2225 Using "spatial structures" allows to achieve various things:
2226
2227 @unorderedList(
2228 @item(@bold(ssDynamicCollisions) or @bold(ssStaticCollisions):
2229
2230 Using one of these two flags allows to resolve collisions with
2231 the (collidable) triangles of the model.
2232 By default, every X3D Shape is collidable using it's exact mesh.
2233 You can use the X3D @link(TCollisionNode) to turn collisions
2234 off for some shapes, or replace some shapes with simpler objects
2235 for the collision-detection purposes.
2236
2237 If you use neither @bold(ssDynamicCollisions) nor @bold(ssStaticCollisions),
2238 then the collisions are resolved using the whole scene bounding
2239 box. That is, treating the whole scene as a giant cube.
2240
2241 You can always toggle @link(Collides) to quickly make
2242 the scene not collidable. In summary:
2243
2244 @unorderedList(
2245 @item(@link(Collides) = @false: the scene does not collide.)
2246
2247 @item(@link(Collides) = @true and Spatial is empty:
2248 the scene collides as it's bounding box (LocalBoundingBoxNoChildren to be precise,
2249 so the box of @link(Url) model is taken into account,
2250 but not children).
2251 This is the default situation after constructing TCastleScene.)
2252
2253 @item(@link(Collides) = @true and
2254 Spatial contains @bold(ssDynamicCollisions) or @bold(ssStaticCollisions):
2255 the scene collides as a set of triangles.
2256 The triangles are derived from information in X3D Shape and Collision
2257 nodes.)
2258 )
2259
2260 The ssStaticCollisions can be used instead of ssDynamicCollisions
2261 when the scene is guaranteed to @italic(absolutely never) change,
2262 and @italic(only when the speed is absolutely crucial).
2263 The collision structure created by ssStaticCollisions
2264 is a bit faster (although may use significantly more memory).
2265 The @italic(practical advice is to almost always use ssDynamicCollisions
2266 instead of ssStaticCollisions): the speed gains
2267 from ssStaticCollisions are usually impossible to measure,
2268 and ssStaticCollisions sometimes uses significantly more memory,
2269 and if you by accident modify the model (animate it etc.)
2270 with ssStaticCollisions -> then results are undefined,
2271 even crashes are possible.
2272 )
2273
2274 @item(@bold(ssRendering):
2275
2276 Using this flag adds an additional optimization during rendering.
2277 It allows to use frustum culling with an octree.
2278 Whether the frustum culling is actually used depends
2279 on @link(TCastleScene.ShapeFrustumCulling) value (by default: yes).
2280
2281 Without this flag, we can still use frustum culling,
2282 but it's less effective as it considers each shape separately.
2283 Whether the frustum culling is actually used also depends
2284 on @link(TCastleScene.ShapeFrustumCulling) value.
2285
2286 Using frustum culling (preferably with ssRendering flag)
2287 is highly adviced if your camera usually only sees
2288 only a part of the scene. For example, it a noticeable optimization
2289 if you have a camera walking/flying inside a typical game
2290 level/location.)
2291
2292 @item(@bold(ssVisibleTriangles):
2293
2294 Using this flag allows to resolve collisions with visible
2295 (not only collidable) triangles quickly.
2296
2297 This is in practice useful only for ray-tracers,
2298 normal applications should not use this.
2299 Normal applications should avoid collision detection with the
2300 @italic(visible) version of the model.
2301 Normal applications should instead
2302 perform collision detection with the @italic(collidable)
2303 version of the model, since this is much better optimized
2304 (both by the engine code, and by an artist creating the model,
2305 using X3D Collision nodes etc.)
2306 )
2307 )
2308
2309 See @link(TSceneSpatialStructure) for more details about
2310 the possible values. For usual dynamic scenes rendered in real-time,
2311 you set this to @code([ssRendering, ssDynamicCollisions]).
2312
2313 By default, the value of this property is empty, which means that
2314 no octrees will be created. This has to be the default value,
2315 to:
2316
2317 @orderedList(
2318 @item(Not create octrees by default (e.g. at construction).
2319 Creating them takes time (and memory).)
2320 @item(Allow developer to adjust TriangleOctreeLimits
2321 before creating the octree.)
2322 ) }
2323 property Spatial: TSceneSpatialStructures read FSpatial write SetSpatial
2324 stored false default [];
2325 {$ifdef FPC}deprecated 'use PreciseCollisions';{$endif}
2326
2327 { Resolve collisions precisely with the scene triangles.
2328
2329 When this is @false we will only consider the bounding box of this scene
2330 for collisions. We look at bounding box of model loaded in @link(Url),
2331 not at children (TCastleTransform) bounding boxes.
2332
2333 Internal notes:
2334 When @true, this sets @link(TCastleSceneCore.Spatial) to [ssRendering, ssDynamicCollisions].
2335 This is a good setting for scenes that may be dynamic.
2336 When @false, this sets @link(TCastleSceneCore.Spatial) to [].
2337 When reading, any @link(TCastleSceneCore.Spatial) <> [] means "precise collisions". }
2338 property PreciseCollisions: Boolean read GetPreciseCollisions write SetPreciseCollisions default false;
2339
2340 { Should the event mechanism (a basic of animations and interactions) work.
2341
2342 If @true, then events will be send and received
2343 through X3D routes, time dependent nodes (TTimeDependentFunctionality,
2344 like TTimeSensorNode) will be activated and updated from @link(Time) time
2345 property, @link(Press), @link(Release) and other methods will activate
2346 key/mouse sensor nodes, scripts will be initialized and work, etc.
2347
2348 In other words, this makes the scene fully animated and interacting
2349 with the user.
2350
2351 If @false, this all doesn't work, which makes the scene static. }
2352 property ProcessEvents: boolean
2353 read FProcessEvents write SetProcessEvents default false;
2354
2355 { Currently loaded scene URL. Change this property to load a scene
2356 from the given URL. We support many 3D and 2D scene formats,
2357 like X3D and glTF,
2358 see https://castle-engine.io/creating_data_model_formats.php .
2359
2360 Setting this property works just like using the @link(Load) method with a new URL.
2361 In fact, using directly the @link(Load) method will also change this URL property.
2362
2363 The only difference between @code(Scene.Url := 'blah.x3d') and
2364 @code(Scene.Load('blah.x3d')) is that setting the URL will
2365 @italic(not) reload the scene if you set it to the same value.
2366 That is, @code(Scene.Url := Scene.Url;) will not reload
2367 the scene (you have to use explicit @link(Load) for this.).
2368
2369 Pass Url = '' to load an empty scene, this sets @link(RootNode) to @nil.
2370 }
2371 property Url: String read FUrl write SetUrl;
2372
2373 { At loading, process the scene to support shadow maps.
2374 This happens at the @link(Load) method call,
2375 and it makes "receiveShadows" field automatically handled.
2376
2377 Note that this is not the only way to make shadow maps.
2378 VRML/X3D author can always make shadow maps by using lower-level nodes, see
2379 [https://castle-engine.io/x3d_extensions.php#section_ext_shadow_maps].
2380 When using these lower-level nodes, this property does not matter
2381 This property (and related ones
2382 like ShadowMapsDefaultSize)
2383 is relevant only for handling shadows by the "receiveShadows" field. }
2384 property ShadowMaps: boolean read FShadowMaps write SetShadowMaps default true;
2385
2386 { Default shadow map texture size.
2387
2388 Affects how shadow maps are handled for the "receiveShadows"
2389 field. This is taken into account at the scene @link(Load) time,
2390 and only if @link(ShadowMaps) is @true.
2391
2392 VRML/X3D author can always override this by placing a @code(GeneratedShadowMap)
2393 node inside light's @code(defaultShadowMap) field. In this case,
2394 @code(GeneratedShadowMap.size) determines shadow map size. }
2395 property ShadowMapsDefaultSize: Cardinal
2396 read FShadowMapsDefaultSize write SetShadowMapsDefaultSize
2397 default DefaultShadowMapsDefaultSize;
2398
2399 { When loading new model, use this viewpoint index to initialize camera.
2400 VRML/X3D specification says to use the first (index = 0) viewpoint,
2401 you can change this property to bind 2nd, 3rd and so on viewpoints.
2402
2403 This is applied only at loading (actually, at ChangedAll).
2404 If you later want to bind another viewpoint, just send set_bind := true
2405 to it. }
2406 property InitialViewpointIndex: Cardinal
2407 read FInitialViewpointIndex write FInitialViewpointIndex default 0;
2408
2409 { When loading new model and looking for initial viewpoint,
2410 consider only viewpoints with this node name.
2411 Relevant only if non-empty.
2412
2413 This may cooperate with InitialViewpointIndex: InitialViewpointIndex
2414 specifies the index of viewpoint node that satisfies also
2415 InitialViewpointName condition. For example:
2416
2417 @unorderedList(
2418 @item(InitialViewpointIndex = 0 and InitialViewpointName = ''
2419 means to use the first viewpoint, ignoring nodes' names.
2420 This is the default behavior, also following VRML/X3D specification.)
2421 @item(InitialViewpointIndex = 1 and InitialViewpointName = ''
2422 means to use the 2nd viewpoint. Node name doesn't matter.)
2423 @item(InitialViewpointIndex = 1 and InitialViewpointName = 'blah'
2424 means to use the first viewpoint named 'blah'.
2425 That is, we are only counting nodes named 'blah' for this.)
2426 ) }
2427 property InitialViewpointName: String
2428 read FInitialViewpointName write FInitialViewpointName;
2429
2430 { When @true, we animate (more precisely: process time pass in @link(Update))
2431 only when the model is visible. This is a powerful optimization,
2432 but be careful if you depend on your animations
2433 for something else than just visual effect.
2434
2435 See @url(https://github.com/castle-engine/castle-engine/tree/master/examples/animations/optimize_animations_test
2436 examples/animations/optimize_animations_test) for a demo of this. }
2437 property AnimateOnlyWhenVisible: boolean
2438 read FAnimateOnlyWhenVisible write FAnimateOnlyWhenVisible default false;
2439
2440 { Non-zero values optimize the animation processing, by not updating
2441 the animation every frame. After updating the animation in one
2442 @link(Update) call, the next AnimateSkipTicks number of @link(Update)
2443 calls will go very quickly, as they will not actually change the scene
2444 at all.
2445
2446 This is an effective optimization if the scene is usually not large on
2447 the screen.
2448
2449 @unorderedList(
2450 @item(The animation is less smooth. For example, if AnimateSkipTicks = 1,
2451 then every other @link(Update) call does not change the scene.
2452 For example, if you have 60 FPS, and @link(Update) is called 60 times
2453 per second, then we will actually change the scene only 30 times per second.
2454
2455 The "skip" within every scene has a little random shift,
2456 to avoid synchronizing this skip across many created scenes.
2457 This makes this a little harder to notice.)
2458
2459 @item(In exchange, the speedup is substantial.
2460 For example, if AnimateSkipTicks = 1, then the animation on CPU effectively
2461 costs 2x less. In general, AnimateSkipTicks = N means that the cost
2462 drops to @code(1 / (1 + N)).)
2463 )
2464
2465 See @url(https://github.com/castle-engine/castle-engine/tree/master/examples/animations/optimize_animations_test
2466 examples/animations/optimize_animations_test) for a demo of this. }
2467 property AnimateSkipTicks: Cardinal read FAnimateSkipTicks write SetAnimateSkipTicks
2468 default 0;
2469
2470 { If AutoAnimation is set, this animation will be automatically played.
2471 It is useful to determine the initial animation, played once the model
2472 is loaded (each time URL changes). You can also change AutoAnimation
2473 at any other moment at runtime (set it to something non-empty to change to a new animation;
2474 set it to '' to stop any animation).
2475
2476 Note: Using @link(AutoAnimation) will under the hood call methods like @link(PlayAnimation),
2477 @link(StopAnimation) and update @link(CurrentAnimation).
2478 The reverse is not true: calling @link(PlayAnimation) doesn't change @link(AutoAnimation).
2479 So you can think of @link(AutoAnimation) as "an initial animation, activated each time
2480 we load the model, even if later we can change it to something else using @link(PlayAnimation)". }
2481 property AutoAnimation: String
2482 read FAutoAnimation write SetAutoAnimation;
2483
2484 { Does the animation indicated by AutoAnimation loops. }
2485 property AutoAnimationLoop: Boolean
2486 read FAutoAnimationLoop write SetAutoAnimationLoop default true;
2487 {$ifdef FPC} deprecated 'in future engine versions, AutoAnimationLoop may behave as always = true, and AutoAnimation will be renamed to just Animation and changing it will always cause a looping animation. Use PlayAnimation(''my_anim'',false) from code to play animation without looping.'; {$endif}
2488
2489 { Transformation nodes inside the model
2490 that are synchronized with automatically-created children TCastleTransform.
2491
2492 This allows to expose transformation nodes from glTF, X3D and other model formats
2493 as TCastleTransform.
2494 These transformation nodes include animated bones from skeletons (armatures).
2495 Such "exposed transformation" results in a creation of TCastleTransform child,
2496 with the same name and synchronized transformation (translation, rotation, scale).
2497
2498 This allows to expose e.g. "hand that may hold a weapon",
2499 or "slot of a vehicle where to attach a camera", as TCastleTransform.
2500 And this allows, in turn, to attach various things to (possibly animated) transformations,
2501 e.g. attach model of a weapon to a hand, or attach TCastleCamera to some bone.
2502 The attached things will be automatically animated when the scene skeleton animates.
2503
2504 Setting this property merely copies the contents using TStrings.Assign,
2505 as is usual for published TStrings properties.
2506 In CGE editor, there's a nice GUI editor to pick the transfomation nodes,
2507 click on "..." at this property.
2508
2509 Note: the owner of auto-created children is equal to this scene's Owner.
2510 This is most natural when you edit this in CGE editor,
2511 or load using @link(TransformLoad).
2512
2513 See the engine example in: examples/animations/expose_transformations_to_animate_children/ .
2514
2515 @seealso ExposeTransformsPrefix }
2516 property ExposeTransforms: TStrings read FExposeTransforms write SetExposeTransforms;
2517
2518 { Name prefix for all children created by ExposeTransforms.
2519 Useful to keep names unique in the scene. }
2520 property ExposeTransformsPrefix: String read FExposeTransformsPrefix write SetExposeTransformsPrefix;
2521
2522 { Use cache to load given scene.
2523 This makes sense when you have multiple TCastleScene instances using the same URL,
2524 loading them will be much faster if they share the cache,
2525 so set @name to @true for all of them.
2526
2527 If you have only one scene using given URL, using cache is not necessary
2528 and in fact it will result in a bit of wasted memory.
2529 So better to keep @name at @false then. }
2530 property Cache: Boolean read FCache write FCache default false;
2531 end;
2532
2533 var
2534 { Log changes to fields.
2535 This debugs what and why happens through TCastleSceneCore.InternalChangedField method
2536 and friends, which is central to VRML/X3D dynamic changes and events engine.
2537
2538 Meaningful only if you initialized log (see CastleLog unit) by InitializeLog first. }
2539 LogChanges: boolean = false;
2540
2541 { Set this to optimize animating transformations for scenes where you
2542 have many transformations (many Transform nodes), and many of them
2543 are animated at the same time. Often particularly effective for
2544 skeletal animations of characters, 3D and 2D (e.g. from Spine or glTF).
2545
2546 This is safe to enable, however in some cases (when you only animate
2547 a single / few transformations, and the whole scene is a big tree with
2548 many transformation) it may hurt performance more than it helps.
2549 But in many practical cases, with skeleton-based animations from Spine
2550 or glTF, it helps a lot.
2551
2552 See @url(https://github.com/castle-engine/castle-engine/tree/master/examples/animations/optimize_animations_test
2553 examples/animations/optimize_animations_test) for a demo of this. }
2554 OptimizeExtensiveTransformations: boolean = false;
2555
2556 { Experimental optimization of Transform animation.
2557 It assumes that Transform nodes affect only geometry, i.e. their only effect
2558 is moving/rotating/scaling shapes.
2559 This is *usually*, but not always, true.
2560 In X3D, Transform node can also affect lights, Background, Fog, cameras...
2561
2562 TODO: Extend it to include all cases, and use always.
2563
2564 See @url(https://github.com/castle-engine/castle-engine/tree/master/examples/animations/optimize_animations_test
2565 examples/animations/optimize_animations_test) for a demo of this. }
2566 InternalFastTransformUpdate: Boolean = false;
2567
2568 var
2569 InternalEnableAnimation: Boolean = true;
2570
2571 implementation
2572
2573 uses Math, DateUtils,
2574 X3DCameraUtils, CastleStringUtils, CastleLog,
2575 X3DLoad, CastleUriUtils, CastleQuaternions;
2576
2577 {$define read_implementation}
2578 {$I castlescenecore_collisions.inc}
2579 {$undef read_implementation}
2580
2581 { TX3DBindableStack ----------------------------------------------------- }
2582
2583 constructor TX3DBindableStack.Create(AParentScene: TCastleSceneCore);
2584 begin
2585 inherited Create(false);
2586 FParentScene := AParentScene;
2587 end;
2588
2589 procedure TX3DBindableStack.SendIsBound(Node: TAbstractBindableNode;
2590 const Value: boolean);
2591 begin
2592 if Node <> nil then
2593 begin
2594 Node.EventIsBound.Send(Value, ParentScene.NextEventTime);
2595 {$ifndef CASTLE_SLIM_NODES}
2596 Node.EventBindTime.Send(ParentScene.Time, ParentScene.NextEventTime);
2597 {$endif}
2598 end;
2599 end;
2600
2601 function TX3DBindableStack.Top: TAbstractBindableNode;
2602 begin
2603 if Count <> 0 then
2604 Result := Last as TAbstractBindableNode else
2605 Result := nil;
2606 end;
2607
2608 procedure TX3DBindableStack.Push(Node: TAbstractBindableNode);
2609 begin
2610 Add(Node);
2611 end;
2612
2613 procedure TX3DBindableStack.PushIfEmpty(Node: TAbstractBindableNode;
2614 SendEvents: boolean);
2615 begin
2616 if Count = 0 then
2617 begin
2618 Push(Node);
2619 if SendEvents then
2620 SendIsBound(Node, true);
2621 DoScheduleBoundChanged;
2622 end;
2623 end;
2624
2625 function TX3DBindableStack.Pop: TAbstractBindableNode;
2626 begin
2627 if Count <> 0 then
2628 begin
2629 Result := Last as TAbstractBindableNode;
2630 Count := Count - 1;
2631 end else
2632 Result := nil;
2633 end;
2634
2635 procedure TX3DBindableStack.CheckForDeletedNodes(
2636 const RootNode: TX3DRootNode; const SendEvents: boolean);
2637 var
2638 I: Integer;
2639 TopChanged: boolean;
2640 begin
2641 if RootNode = nil then
2642 { Just empty all, since all are possibly freed }
2643 Count := 0 else
2644 begin
2645 { Remember that pointers on Items may be wrong now.
2646 So don't call things like Top function now
2647 (it typecasts to TAbstractBindableNode). }
2648
2649 TopChanged := false;
2650
2651 I := 0;
2652 while I < Count do
2653 begin
2654 { Search also inactive part of VRML graph.
2655 VRML doesn't allow a bound node to be in inactive VRML graph part,
2656 but not bound (but present on the stack) node in inactive VRML
2657 graph part is acceptable, as far as I understand. }
2658 if not RootNode.IsNodePresent(Items[I], false) then
2659 begin
2660 TopChanged := I = Count - 1;
2661 Delete(I);
2662 end else
2663 Inc(I);
2664 end;
2665
2666 if TopChanged and SendEvents and (Count <> 0) then
2667 SendIsBound(Top, true);
2668
2669 if TopChanged then
2670 DoScheduleBoundChanged;
2671 end;
2672 end;
2673
2674 procedure TX3DBindableStack.Set_Bind(Node: TAbstractBindableNode;
2675 const Value: boolean);
2676 var
2677 NodeIndex: Integer;
2678 begin
2679 NodeIndex := IndexOf(Node);
2680 if Value then
2681 begin
2682 if NodeIndex = -1 then
2683 begin
2684 { Node not on the stack. So add it, as new top node. }
2685 SendIsBound(Top, false);
2686 Push(Node);
2687 SendIsBound(Top, true);
2688 DoScheduleBoundChanged;
2689 end else
2690 if NodeIndex <> Count - 1 then
2691 begin
2692 { Node on the stack, but not on top. So move it, as new top node. }
2693 SendIsBound(Top, false);
2694 Exchange(NodeIndex, Count - 1);
2695 SendIsBound(Top, true);
2696 DoScheduleBoundChanged;
2697 end;
2698 { set_bind = true for node already on the top is ignored. }
2699 end else
2700 begin
2701 if NodeIndex <> -1 then
2702 begin
2703 if NodeIndex = Count - 1 then
2704 begin
2705 SendIsBound(Top, false);
2706 Delete(NodeIndex);
2707 SendIsBound(Top, true);
2708 DoScheduleBoundChanged;
2709 end else
2710 begin
2711 Delete(NodeIndex);
2712 end;
2713 end;
2714 { set_bind = false for node already outside of the stack is ignored. }
2715 end;
2716 end;
2717
2718 procedure TX3DBindableStack.DoBoundChanged;
2719 begin
2720 if Assigned(OnBoundChanged) then
2721 OnBoundChanged(ParentScene);
2722 end;
2723
2724 procedure TX3DBindableStack.BeginChangesSchedule;
2725 begin
2726 { BoundChangedScheduled = false always when BoundChangedSchedule = 0. }
2727 Assert((BoundChangedSchedule <> 0) or (not BoundChangedScheduled));
2728
2729 Inc(BoundChangedSchedule);
2730 end;
2731
2732 procedure TX3DBindableStack.DoScheduleBoundChanged;
2733 begin
2734 if BoundChangedSchedule = 0 then
2735 DoBoundChanged else
2736 BoundChangedScheduled := true;
2737 end;
2738
2739 procedure TX3DBindableStack.EndChangesSchedule;
2740 begin
2741 Dec(BoundChangedSchedule);
2742 if (BoundChangedSchedule = 0) and BoundChangedScheduled then
2743 begin
2744 BoundChangedScheduled := false;
2745 DoBoundChanged;
2746 end;
2747 end;
2748
2749 { TBackgroundStack ----------------------------------------------------------- }
2750
2751 function TBackgroundStack.Top: TAbstractBackgroundNode;
2752 begin
2753 Result := (inherited Top) as TAbstractBackgroundNode;
2754 end;
2755
2756 procedure TBackgroundStack.PushIfEmpty(Node: TAbstractBackgroundNode; SendEvents: boolean);
2757 begin
2758 inherited PushIfEmpty(Node, SendEvents);
2759 end;
2760
2761 { TFogStack ------------------------------------------------------------------ }
2762
2763 function TFogStack.Top: TFogNode;
2764 begin
2765 Result := (inherited Top) as TFogNode;
2766 end;
2767
2768 procedure TFogStack.PushIfEmpty(Node: TFogNode; SendEvents: boolean);
2769 begin
2770 inherited PushIfEmpty(Node, SendEvents);
2771 end;
2772
2773 { TNavigationInfoStack ------------------------------------------------------- }
2774
2775 procedure TNavigationInfoStack.DoBoundChanged;
2776 begin
2777 ParentScene.UpdateHeadlightOnFromNavigationInfo;
2778 inherited;
2779 end;
2780
2781 function TNavigationInfoStack.Top: TNavigationInfoNode;
2782 begin
2783 Result := (inherited Top) as TNavigationInfoNode;
2784 end;
2785
2786 procedure TNavigationInfoStack.PushIfEmpty(Node: TNavigationInfoNode; SendEvents: boolean);
2787 begin
2788 inherited PushIfEmpty(Node, SendEvents);
2789 end;
2790
2791 { TViewpointStack ------------------------------------------------------------ }
2792
2793 function TViewpointStack.Top: TAbstractViewpointNode;
2794 begin
2795 Result := (inherited Top) as TAbstractViewpointNode;
2796 end;
2797
2798 procedure TViewpointStack.PushIfEmpty(Node: TAbstractViewpointNode; SendEvents: boolean);
2799 begin
2800 inherited PushIfEmpty(Node, SendEvents);
2801 end;
2802
2803 { TGeneratedTextureList -------------------------------------------------- }
2804
2805 function TCastleSceneCore.TGeneratedTextureList.IndexOfTextureNode(TextureNode: TX3DNode): Integer;
2806 begin
2807 for Result := 0 to Count - 1 do
2808 if L[Result].TextureNode = TextureNode then
2809 Exit;
2810 Result := -1;
2811 end;
2812
2813 function TCastleSceneCore.TGeneratedTextureList.FindTextureNode(TextureNode: TX3DNode): PGeneratedTexture;
2814 var
2815 Index: Integer;
2816 begin
2817 Index := IndexOfTextureNode(TextureNode);
2818 if Index <> -1 then
2819 Result := PGeneratedTexture(Ptr(Index)) else
2820 Result := nil;
2821 end;
2822
2823 function TCastleSceneCore.TGeneratedTextureList.AddShapeTexture(Shape: TShape;
2824 Tex: TAbstractTextureNode): Pointer;
2825 var
2826 GenTex: PGeneratedTexture;
2827 GenTexFunctionality: TGeneratedTextureFunctionality;
2828 begin
2829 Result := nil;
2830 GenTexFunctionality := Tex.GenTexFunctionality;
2831 if GenTexFunctionality <> nil then
2832 begin
2833 GenTex := FindTextureNode(Tex);
2834 if GenTex <> nil then
2835 begin
2836 { The same generated texture node Tex is instantiated more than once.
2837
2838 - For GeneratedShadowMap, the shape where it's used, and actually
2839 the whole place where it's used in the X3D graph, doesn't matter.
2840 (GeneratedShadowMap makes view from it's light/viewpoint,
2841 referenced explicitly in the node).
2842 Same thing for RenderedTexture (it makes view from specified viewpoint).
2843
2844 So we can simply ignore duplicates (placing them
2845 on GeneratedTextures list would make it updated many times
2846 in UpdateGeneratedTextures, instead of just once).
2847
2848 - For GeneratedCubeMapTexture, their view depends on the shape
2849 where they are used. They can be instanced many times only
2850 within a single shape (possible if you use MultiTexture
2851 and instance there the same GeneratedCubeMapTexture),
2852 then duplicates are simply ignored.
2853
2854 When GeneratedCubeMapTexture is instanced within different shapes,
2855 make a warning, and reject duplicate. }
2856
2857 if (Tex is TGeneratedCubeMapTextureNode) and
2858 (Shape <> GenTex^.Shape) then
2859 WritelnWarning('X3D', 'The same GeneratedCubeMapTexture node is used (instanced) within at least two different X3D shapes. This is incorrect, as we don''t know from which shape should environment be captured');
2860 end else
2861 begin
2862 GenTex := PGeneratedTexture(Add);
2863 GenTex^.TextureNode := Tex;
2864 GenTex^.Functionality := GenTexFunctionality;
2865 { Make sure to reset InternalUpdateNeeded to true, in case it was false because
2866 it was already generated but now some change caused ChangedAll.
2867 Testcase: projected_Spotlight.x3dv from Victor Amat. }
2868 GenTex^.Functionality.InternalUpdateNeeded := true;
2869 GenTex^.Shape := Shape;
2870 end;
2871 end;
2872 end;
2873
2874 procedure TCastleSceneCore.TGeneratedTextureList.UpdateShadowMaps(LightNode: TAbstractLightNode);
2875 var
2876 I: Integer;
2877 begin
2878 for I := 0 to Count - 1 do
2879 if (L[I].TextureNode is TGeneratedShadowMapNode) and
2880 (TGeneratedShadowMapNode(L[I].TextureNode).FdLight.Value = LightNode) then
2881 L[I].Functionality.InternalUpdateNeeded := true;
2882 end;
2883
2884 { TTimeDependentList ------------------------------------------------- }
2885
2886 procedure TCastleSceneCore.TTimeDependentList.AddIfNotExists(const Item: TTimeDependentFunctionality);
2887 begin
2888 if IndexOf(Item) = -1 then
2889 Add(Item);
2890 end;
2891
2892 { TVisibilitySensors --------------------------------------------------------- }
2893
2894 destructor TCastleSceneCore.TVisibilitySensors.Destroy;
2895 begin
2896 Clear;
2897 inherited;
2898 end;
2899
2900 procedure TCastleSceneCore.TVisibilitySensors.Clear;
2901 var
2902 V: TVisibilitySensorInstanceList;
2903 begin
2904 for V in Values do
2905 V.Free;
2906 inherited Clear;
2907 end;
2908
2909 { TCastleSceneCore.TExposedTransform ----------------------------------------- }
2910
2911 constructor TCastleSceneCore.TExposedTransform.Create(const AParentScene: TCastleSceneCore;
2912 const ANode: TTransformNode; const AChild: TCastleTransform);
2913 begin
2914 inherited Create;
2915 FParentScene := AParentScene;
2916 FNode := ANode;
2917 FTransformFunctionality := Node.TransformFunctionality;
2918 Assert(FTransformFunctionality <> nil);
2919 FChild := AChild;
2920
2921 // create ChildObserver
2922 ChildObserver := TFreeNotificationObserver.Create(nil);
2923 ChildObserver.OnFreeNotification := {$ifdef FPC}@{$endif}ChildFreeNotification;
2924 ChildObserver.Observed := Child;
2925 end;
2926
2927 destructor TCastleSceneCore.TExposedTransform.Destroy;
2928 begin
2929 FreeAndNil(ChildObserver);
2930 inherited;
2931 end;
2932
2933 procedure TCastleSceneCore.TExposedTransform.ChildFreeNotification(const Sender: TFreeNotificationObserver);
2934 begin
2935 // free this TExposedTransform instance, removing it from FExposeTransforms
2936 ParentScene.FExposedTransforms.Remove(Self);
2937 end;
2938
2939 procedure TCastleSceneCore.TExposedTransform.Synchronize;
2940 var
2941 ShapeTransform: TShapeTreeTransform;
2942 C: Integer;
2943 Translation, Scale: TVector3;
2944 Rotation: TVector4;
2945 T: TTransformation;
2946 begin
2947 C := TShapeTree.AssociatedShapesCount(Node);
2948 if C = 0 then
2949 begin
2950 if not WarningDone then
2951 begin
2952 WarningDone := true;
2953 WritelnWarning('Exposed transformation (bone) "%s" is not present in the shapes tree (which usually means it has no shapes), transformation is not updated', [
2954 Node.X3DName
2955 ]);
2956 end;
2957 Exit;
2958 end;
2959
2960 if C > 1 then
2961 begin
2962 if not WarningDone then
2963 begin
2964 WarningDone := true;
2965 WritelnWarning('Exposed transformation (bone) "%s" is present mutliple times in the shapes tree, it has no single transformation', [
2966 Node.X3DName
2967 ]);
2968 end;
2969 Exit;
2970 end;
2971
2972 Assert(C = 1);
2973 ShapeTransform := TShapeTree.AssociatedShape(Node, 0) as TShapeTreeTransform;
2974 T := ShapeTransform.TransformState.Transformation;
2975 FTransformFunctionality.ApplyTransform(T);
2976 MatrixDecompose(T.Transform, Translation, Rotation, Scale);
2977
2978 { Apply to Child the accumulated transformation within this TTransformNode,
2979 taking into account TTransformNode hierarchy. }
2980 Child.Translation := Translation;
2981 Child.Rotation := Rotation;
2982 Child.Scale := Scale;
2983
2984 { This would be incorrect, as we would not apply parent TTransformNode values.
2985 Child.Translation := Node.Translation;
2986 Child.Rotation := Node.Rotation;
2987 Child.Scale := Node.Scale;
2988 }
2989 end;
2990
2991 class function TCastleSceneCore.TExposedTransform.X3dNameToPascal(const Prefix, S: String): String; {$ifdef FPC}static;{$endif}
2992 const
2993 AllowedChars = ['a'..'z', 'A'..'Z', '0'..'9', '_'];
2994 AllowedCharsFirst = AllowedChars - ['0'..'9'];
2995 begin
2996 Result := Prefix + SReplaceChars(S, AllChars - AllowedChars, '_');
2997 if not SCharIs(Result, 1, AllowedCharsFirst) then
2998 Result := '_' + Result;
2999 end;
3000
3001 { TPlayAnimationParameters --------------------------------------------------- }
3002
3003 constructor TPlayAnimationParameters.Create;
3004 begin
3005 inherited;
3006 Loop := false;
3007 Forward := true;
3008 end;
3009
3010 { TDetectAffectedFields ------------------------------------------------------ }
3011
3012 type
3013 TDetectAffectedFields = class
3014 strict private
3015 ParentScene: TCastleSceneCore;
3016 AllRoutes: TX3DRouteList;
3017 AffectedInterpolators, AffectedTriggers: TX3DNodeList;
3018 procedure FindRoutesAndInterpolatorsEnumerate(Node: TX3DNode);
3019 function IsInterpolator(const Node: TX3DNode): Boolean;
3020 public
3021 constructor Create(const AParentScene: TCastleSceneCore);
3022 destructor Destroy; override;
3023 procedure FindRoutesAndInterpolators;
3024 procedure FindAnimationAffectedFields;
3025 end;
3026
3027 constructor TDetectAffectedFields.Create(const AParentScene: TCastleSceneCore);
3028 begin
3029 inherited Create;
3030 ParentScene := AParentScene;
3031 AllRoutes := TX3DRouteList.Create(false);
3032 AffectedInterpolators := TX3DNodeList.Create(false);
3033 AffectedTriggers := TX3DNodeList.Create(false);
3034 end;
3035
3036 destructor TDetectAffectedFields.Destroy;
3037 begin
3038 FreeAndNil(AffectedInterpolators);
3039 FreeAndNil(AffectedTriggers);
3040 FreeAndNil(AllRoutes);
3041 inherited;
3042 end;
3043
3044 procedure TDetectAffectedFields.FindRoutesAndInterpolators;
3045 begin
3046 if ParentScene.RootNode <> nil then
3047 ParentScene.RootNode.EnumerateNodes(TX3DNode,
3048 {$ifdef FPC}@{$endif}FindRoutesAndInterpolatorsEnumerate,
3049 false);
3050 end;
3051
3052 procedure TDetectAffectedFields.FindRoutesAndInterpolatorsEnumerate(Node: TX3DNode);
3053 var
3054 Route: TX3DRoute;
3055 I: Integer;
3056 begin
3057 for I := 0 to Node.RoutesCount - 1 do
3058 begin
3059 Route := Node.Routes[I];
3060 { Note that it's OK to add the same route instance multiple times
3061 to AllRoutes list below. }
3062 AllRoutes.Add(Route);
3063
3064 { Found route from TimeSensor, and check if TimeSensor has detectAffectedFields. }
3065 if (Route.SourceNode is TTimeSensorNode) and
3066 TTimeSensorNode(Route.SourceNode).DetectAffectedFields then
3067 begin
3068 { Found route from some TimeSensor.fraction_changed to some interpolator/sequencer.set_fraction. }
3069 if (Route.SourceEvent = TTimeSensorNode(Route.SourceNode).EventFraction_Changed) then
3070 begin
3071 if IsInterpolator(Route.DestinationNode) and
3072 (Route.DestinationEvent.X3DName = 'set_fraction') then
3073 begin
3074 { Note that it's OK to add the same interpolator instance multiple times below. }
3075 AffectedInterpolators.Add(Route.DestinationNode);
3076 end;
3077 end else
3078
3079 { Found route from some TimeSensor.isActive to some trigger input. }
3080 if (Route.SourceEvent = TTimeSensorNode(Route.SourceNode).EventIsActive) then
3081 begin
3082 if ( (Route.DestinationNode is TValueTriggerNode) and
3083 (Route.DestinationEvent = TValueTriggerNode(Route.DestinationNode).EventTrigger) ) or
3084 ( (Route.DestinationNode is TIntegerTriggerNode) and
3085 (Route.DestinationEvent = TIntegerTriggerNode(Route.DestinationNode).EventSet_boolean) ) or
3086 ( (Route.DestinationNode is TTimeTriggerNode) and
3087 (Route.DestinationEvent = TTimeTriggerNode(Route.DestinationNode).EventSet_boolean) ) then
3088 begin
3089 { Note that it's OK to add the same trigger instance multiple times below. }
3090 AffectedTriggers.Add(Route.DestinationNode);
3091 end;
3092 end;
3093 end;
3094 end;
3095 end;
3096
3097 function TDetectAffectedFields.IsInterpolator(const Node: TX3DNode): Boolean;
3098 begin
3099 Result :=
3100 (Node is TAbstractInterpolatorNode) or
3101 (Node is TAbstractSequencerNode);
3102 end;
3103
3104 procedure TDetectAffectedFields.FindAnimationAffectedFields;
3105
3106 { Does this event come from an exposed field interface declaration?
3107 This is used to detect ValueTrigger fields that send information.
3108 See TValueTriggerNode.EventTriggerReceive how TValueTriggerNode does it. }
3109 function ExposedCustomField(const Node: TX3DNode; const Event: TX3DEvent): Boolean;
3110 var
3111 Field: TX3DField;
3112 begin
3113 Field := Node.FieldSendingEvent(Event);
3114 Result :=
3115 (Field <> nil) and
3116 (Field.ParentInterfaceDeclaration <> nil);
3117 end;
3118
3119 { Add to the "affected" list the field indicated by given route destination
3120 (as Node and Event of this node).
3121 Node = nil is allowed here (Route.DestinationNode may be nil if node was freed,
3122 e.g. delete shape in castle-model-viewer). }
3123 procedure RouteDestinationAffectsField(const Node: TX3DNode; const Event: TX3DEvent);
3124 var
3125 Field: TX3DField;
3126 begin
3127 if Node <> nil then
3128 begin
3129 Field := Node.FieldSetByEvent(Event);
3130 if (Field <> nil) and
3131 (not ParentScene.AnimationAffectedFields.Contains(Field)) then
3132 begin
3133 // WritelnLog('Found affected field %s', [Field.NiceName]);
3134 Field.InternalSaveResetValue;
3135 ParentScene.AnimationAffectedFields.Add(Field);
3136 end;
3137 end;
3138 end;
3139
3140 var
3141 Route: TX3DRoute;
3142 begin
3143 for Route in AllRoutes do
3144 if IsInterpolator(Route.SourceNode) then
3145 begin
3146 if (Route.SourceEvent.X3DName = 'value_changed') and
3147 (AffectedInterpolators.IndexOf(Route.SourceNode) <> -1) then
3148 RouteDestinationAffectsField(Route.DestinationNode, Route.DestinationEvent);
3149 end else
3150 if Route.SourceNode is TValueTriggerNode then
3151 begin
3152 if ExposedCustomField(Route.SourceNode, Route.SourceEvent) and
3153 (AffectedTriggers.IndexOf(Route.SourceNode) <> -1) then
3154 RouteDestinationAffectsField(Route.DestinationNode, Route.DestinationEvent);
3155 end else
3156 if Route.SourceNode is TIntegerTriggerNode then
3157 begin
3158 if (Route.SourceEvent = TIntegerTriggerNode(Route.SourceNode).EventTriggerValue) and
3159 (AffectedTriggers.IndexOf(Route.SourceNode) <> -1) then
3160 RouteDestinationAffectsField(Route.DestinationNode, Route.DestinationEvent);
3161 end else
3162 if Route.SourceNode is TTimeTriggerNode then
3163 begin
3164 if (Route.SourceEvent = TTimeTriggerNode(Route.SourceNode).EventTriggerTime) and
3165 (AffectedTriggers.IndexOf(Route.SourceNode) <> -1) then
3166 RouteDestinationAffectsField(Route.DestinationNode, Route.DestinationEvent);
3167 end;
3168 end;
3169
3170 { TCastleSceneCore ----------------------------------------------------------- }
3171
3172 constructor TCastleSceneCore.Create(AOwner: TComponent);
3173 begin
3174 inherited Create(AOwner);
3175
3176 FRootNode := nil;
3177 FOwnsRootNode := true;
3178 FShapesHash := 1;
3179
3180 FTriangleOctreeLimits := DefTriangleOctreeLimits;
3181 FShapeOctreeLimits := DefShapeOctreeLimits;
3182
3183 FShapes := TShapeTreeGroup.Create(Self);
3184 ShapeLODs := TObjectList.Create(false);
3185 FGlobalLights := TLightInstancesList.Create;
3186
3187 FBackgroundStack := TBackgroundStack.Create(Self);
3188 FFogStack := TFogStack.Create(Self);
3189 FNavigationInfoStack := TNavigationInfoStack.Create(Self);
3190 FViewpointStack := TViewpointStack.Create(Self);
3191 FViewpointsArray := TAbstractViewpointNodeList.Create(false);
3192
3193 FPointingDeviceActiveSensors := TX3DNodeList.Create(false);
3194
3195 FCompiledScriptHandlers := TCompiledScriptHandlerInfoList.Create;
3196 GeneratedTextures := TGeneratedTextureList.Create;
3197 ProximitySensors := TProximitySensorInstanceList.Create(false);
3198 FVisibilitySensors := TVisibilitySensors.Create;
3199 ScreenEffectNodes := TX3DNodeList.Create(false);
3200 ScheduledHumanoidAnimateSkin := TX3DNodeList.Create(false);
3201 KeyDeviceSensorNodes := TX3DNodeList.Create(false);
3202 BillboardNodes := TX3DNodeList.Create(false);
3203 TimeDependentList := TTimeDependentList.Create(false);
3204 FAnimationsList := TStringList.Create;
3205 TStringList(FAnimationsList).CaseSensitive := true; // X3D node names are case-sensitive
3206 AnimationAffectedFields := TX3DFieldList.Create(false);
3207
3208 FTimePlaying := true;
3209 FTimePlayingSpeed := 1.0;
3210
3211 FShadowMaps := true;
3212 FShadowMapsDefaultSize := DefaultShadowMapsDefaultSize;
3213 FAnimationPrefix := DefaultAnimationPrefix;
3214
3215 FAutoAnimationLoop := true;
3216
3217 FExposeTransforms := TStringList.Create;
3218 TStringList(FExposeTransforms).OnChange := {$ifdef FPC}@{$endif} ExposeTransformsChange;
3219 FExposedTransforms := TExposedTransformList.Create(true);
3220
3221 { We could call here ScheduleChangedAll (or directly ChangedAll),
3222 but there should be no need. FRootNode remains nil,
3223 and our current state should be equal to what ScheduleChangedAll
3224 would set. This is (potentially) a small time saving,
3225 as ScheduleChangedAll does a lot of calls (although probably is fast
3226 anyway when RootNode = nil). }
3227
3228 FUrlMonitoring.Init({$ifdef FPC}@{$endif} ReloadUrl);
3229 end;
3230
3231 procedure TCastleSceneCore.BeforeDestruction;
3232 begin
3233 FreeRootNode;
3234
3235 { This also deinitializes script nodes. }
3236 ProcessEvents := false;
3237
3238 FUrlMonitoring.Finish(FUrl);
3239
3240 inherited;
3241 end;
3242
3243 destructor TCastleSceneCore.Destroy;
3244 begin
3245 FreeAndNil(FExposeTransforms);
3246 FreeAndNil(FExposedTransforms);
3247 FreeAndNil(ScheduledHumanoidAnimateSkin);
3248 FreeAndNil(ScreenEffectNodes);
3249 FreeAndNil(ProximitySensors);
3250 FreeAndNil(FVisibilitySensors);
3251 FreeAndNil(GeneratedTextures);
3252 FreeAndNil(FCompiledScriptHandlers);
3253 FreeAndNil(KeyDeviceSensorNodes);
3254 FreeAndNil(BillboardNodes);
3255 FreeAndNil(TimeDependentList);
3256
3257 FreeAndNil(FBackgroundStack);
3258 FreeAndNil(FFogStack);
3259 FreeAndNil(FNavigationInfoStack);
3260 FreeAndNil(FViewpointStack);
3261 FreeAndNil(FViewpointsArray);
3262
3263 FreeAndNil(FPointingDeviceActiveSensors);
3264
3265 FreeAndNil(FShapes);
3266 FreeAndNil(ShapeLODs);
3267 FreeAndNil(FGlobalLights);
3268
3269 FreeAndNil(FOctreeRendering);
3270 FreeAndNil(FOctreeDynamicCollisions);
3271 FreeAndNil(FOctreeVisibleTriangles);
3272 FreeAndNil(FOctreeStaticCollisions);
3273 FreeAndNil(FAnimationsList);
3274 FreeAndNil(AnimationAffectedFields);
3275 FreeAndNil(PreviousPartialAffectedFields);
3276
3277 inherited;
3278 end;
3279
3280 procedure TCastleSceneCore.FreeRootNode;
3281 begin
3282 { These must be done always before freeing }
3283 BeforeNodesFree;
3284 PointingDeviceClear;
3285
3286 if FRootNodeCacheOrigin <> nil then
3287 X3DCache.FreeNode(FRootNodeCacheOrigin);
3288 Assert(FRootNodeCacheOrigin = nil);
3289
3290 { Not calling UnregisterScene when FOwnsRootNode=true is just an optimization.
3291 There's no point in calling recursive UnregisterScene if the FRootNode
3292 will be freed right afterwards.
3293
3294 TODO: This optimization is actually not without a problem.
3295 If the RootNode has some child that has other parents (outside of this
3296 scene, or with KeepExistingBegin) then they will remain existing,
3297 and will have a dangling reference to this Scene.
3298 This happened with internal TAppearanceNode in CastleTerrain at one point.
3299
3300 In general, we do not guarantee detaching invalid Scene reference now.
3301 E.g. if a node will stop being part of a scene,
3302 because we do
3303
3304 Appearance.Material := OldMaterial;
3305 // add Appearance to Scene in any way
3306 Appearance.Material := NewMaterial;
3307 FreeAndNil(Scene);
3308
3309 ... then OldMaterial will have invalid reference in OldMaterial.Scene.
3310 }
3311 if (FRootNode <> nil) and (not FOwnsRootNode) then
3312 FRootNode.UnregisterScene;
3313
3314 if FOwnsRootNode then
3315 FreeAndNil(FRootNode)
3316 else
3317 FRootNode := nil;
3318 Assert(FRootNode = nil);
3319 end;
3320
3321 procedure TCastleSceneCore.Load(const ARootNode: TX3DRootNode; const AOwnsRootNode: Boolean;
3322 const AOptions: TSceneLoadOptions);
3323 begin
3324 LoadCore(ARootNode, nil, AOwnsRootNode, AOptions);
3325 end;
3326
3327 procedure TCastleSceneCore.LoadCore(const ARootNode: TX3DRootNode;
3328 const ARootNodeCacheOrigin: TX3DRootNode;
3329 const AOwnsRootNode: boolean;
3330 const AOptions: TSceneLoadOptions);
3331 var
3332 RestoreProcessEvents: boolean;
3333 begin
3334 { ARootNodeCacheOrigin can be non-nil only if ARootNode is non-nil. }
3335 Assert(not ((ARootNodeCacheOrigin <> nil) and (ARootNode = nil)));
3336
3337 { temporarily turn off events, to later initialize and turn them on }
3338 RestoreProcessEvents := ProcessEvents;
3339 ProcessEvents := false;
3340
3341 FreeRootNode;
3342
3343 FRootNode := ARootNode; // set using FRootNode, we will call ChangedAll later
3344 FRootNodeCacheOrigin := ARootNodeCacheOrigin;
3345 FOwnsRootNode := AOwnsRootNode;
3346 ScheduledShadowMapsProcessing := true;
3347
3348 { We can't call UpdateHeadlightOnFromNavigationInfo here,
3349 as NavigationInfoStack may contain now already freed nodes
3350 (testcase: castle-model-viewer anchor_test and click on key_sensor anchor).
3351 So only schedule it. }
3352 ScheduleHeadlightOnFromNavigationInfoInChangedAll := true;
3353
3354 { Disable smooth camera transitions up to the of next ChangedAll.
3355 This way initial Viewpoint at loading (this will also catch
3356 a viewpoint given as #viewpoint_name at LoadAnchor, see there for
3357 comments) will be set immediately. }
3358 ForceTeleportTransitions := true;
3359
3360 { Call ChangedAll instead of ScheduleChangedAll.
3361 That's because below we potentially do SetProcessEvents(true)
3362 (if loading a scene when ProcessEvents already enabled),
3363 and it may require that ChangedAll already run (e.g. it may
3364 initialize Script nodes, that require Node.Scene to be set,
3365 see https://github.com/castle-engine/castle-model-viewer/issues/16 ). }
3366 ChangedAll;
3367
3368 if not (slDisableResetTime in AOptions) then
3369 ResetTimeAtLoad;
3370
3371 { restore events processing, initialize new scripts and such }
3372 ProcessEvents := RestoreProcessEvents;
3373
3374 UpdateAutoAnimation(false);
3375 end;
3376
3377 procedure TCastleSceneCore.Load(const AUrl: String; const AllowStdIn: boolean;
3378 const AResetTime: boolean);
3379 var
3380 Options: TSceneLoadOptions;
3381 begin
3382 Options := [];
3383 if not AResetTime then
3384 Include(Options, slDisableResetTime);
3385 Load(AUrl, Options);
3386 end;
3387
3388 procedure TCastleSceneCore.Load(const AUrl: String; const AOptions: TSceneLoadOptions);
3389 var
3390 TimeStart: TCastleProfilerTime;
3391 NewRoot, NewRootCacheOrigin: TX3DRootNode;
3392 C: TCastleCollider;
3393 begin
3394 TimeStart := Profiler.Start('Loading "' + UriDisplay(AUrl) + '" (TCastleSceneCore)');
3395 try
3396 NewRoot := nil; // set this as RootNode when AUrl is ''
3397 NewRootCacheOrigin := nil;
3398
3399 if AUrl <> '' then
3400 begin
3401 { If LoadNode fails:
3402
3403 - When CastleDesignMode is false:
3404 We make an exception (just pass the exception from LoadNode),
3405 and we do not change the RootNode or URL.
3406 So currently loaded scene will remain 100% valid.
3407
3408 - When CastleDesignMode is true:
3409 We *do* change the RootNode (to empty) and URL
3410 (to allow user to comfortably correct the URL in editor),
3411 and we make a warning.
3412 This way the design with invalid URL will still load nicely in the editor.
3413 }
3414
3415 try
3416 if Cache then
3417 begin
3418 NewRootCacheOrigin := X3DCache.LoadNode(AUrl);
3419 NewRoot := NewRootCacheOrigin.DeepCopy as TX3DRootNode;
3420 end else
3421 begin
3422 { Load using cache, in case the scene was cached using
3423 <warmup_cache> or Cache. This way we use cache (without incrementing
3424 reference count in cache) even when Cache=false. }
3425 NewRoot := X3DCache.TryCopyNode(AUrl);
3426 if NewRoot = nil then
3427 NewRoot := LoadNode(AUrl);
3428 end;
3429 except
3430 on E: Exception do
3431 begin
3432 if CastleDesignMode then
3433 begin
3434 WritelnWarning('TCastleSceneCore', 'Failed to load scene "%s": %s',
3435 [UriDisplay(AUrl), ExceptMessage(E)]);
3436 NewRoot := nil;
3437 NewRootCacheOrigin := nil;
3438 end else
3439 raise;
3440 end;
3441 end;
3442 end;
3443
3444 { Set FUrl before calling Load below.
3445 This way eventual warning from Load (like "animation not found",
3446 in case AutoAnimation is used) will mention the new URL, not the old one. }
3447 FUrlMonitoring.ChangeUrl(FUrl, AUrl);
3448
3449 LoadCore(NewRoot, NewRootCacheOrigin, true, AOptions);
3450
3451 { After loading a new model we need to
3452 - update sizes calculated by AutoSize for simple colliders
3453 - update triangles used by TCastleMeshCollider (note that this code
3454 will only update TCastleMeshCollider that is our behavior,
3455 it doesn't notify TCastleMeshCollider instances elsewhere that may refer to us). }
3456 C := FindBehavior(TCastleCollider) as TCastleCollider;
3457 if C <> nil then
3458 C.InternalTransformChanged(Self);
3459 finally Profiler.Stop(TimeStart) end;
3460 end;
3461
3462 procedure TCastleSceneCore.UpdateAutoAnimation(const StopIfPlaying: Boolean);
3463 begin
3464 // when IsLoading, delay this to Loaded
3465 if not IsLoading then
3466 begin
3467 if AutoAnimation <> '' then
3468 begin
3469 {$warnings off} // using deprecated AutoAnimationLoop to keep it working
3470 if PlayAnimation(AutoAnimation, AutoAnimationLoop) then
3471 { call ForceInitialAnimationPose, to avoid blinking with "setup pose"
3472 right after loading the UI design from file. }
3473 ForceInitialAnimationPose;
3474 {$warnings on}
3475 end else
3476 if StopIfPlaying then
3477 begin
3478 StopAnimation;
3479 ResetAnimationState;
3480 end;
3481 end;
3482 end;
3483
3484 procedure TCastleSceneCore.Loaded;
3485 begin
3486 inherited;
3487 if FPendingSetUrl <> '' then
3488 begin
3489 Url := FPendingSetUrl;
3490 FPendingSetUrl := '';
3491 end;
3492 {$warnings off} // using deprecated just to make a warning
3493 if not AutoAnimationLoop then
3494 begin
3495 WritelnWarning('AutoAnimationLoop is deprecated, but you set it to false on "%s". In future engine versions, AutoAnimationLoop may behave as always = true, and AutoAnimation will be renamed to just Animation and changing it will always cause a looping animation.' + ' Use PlayAnimation(''my_anim'',false) from code to play animation without looping.', [
3496 Name
3497 ]);
3498 end;
3499 {$warnings on}
3500 UpdateAutoAnimation(false);
3501 ExposeTransformsChange(nil);
3502 end;
3503
3504 procedure TCastleSceneCore.SetAutoAnimationLoop(const Value: Boolean);
3505 begin
3506 if FAutoAnimationLoop <> Value then
3507 begin
3508 FAutoAnimationLoop := Value;
3509 UpdateAutoAnimation(true);
3510 end;
3511 end;
3512
3513 procedure TCastleSceneCore.SetAutoAnimation(const Value: String);
3514 begin
3515 if FAutoAnimation <> Value then
3516 begin
3517 FAutoAnimation := Value;
3518 UpdateAutoAnimation(true);
3519 end;
3520 end;
3521
3522 procedure TCastleSceneCore.SetRootNode(const Value: TX3DRootNode);
3523 begin
3524 if FRootNode <> Value then
3525 begin
3526 FreeRootNode;
3527 FRootNode := Value;
3528 ScheduleChangedAll;
3529 end;
3530 end;
3531
3532 procedure TCastleSceneCore.Save(const AUrl: String);
3533 begin
3534 if RootNode <> nil then
3535 SaveNode(RootNode, AUrl, ApplicationName);
3536 FUrlMonitoring.ChangeUrl(FUrl, AUrl);
3537 end;
3538
3539 procedure TCastleSceneCore.SetUrl(const AValue: String);
3540 begin
3541 if AValue <> FUrl then
3542 begin
3543 if IsLoading and (AValue <> '') then
3544 { Defer actually loading URL to later, when Loading is called, to use proper Cache value. }
3545 FPendingSetUrl := AValue
3546 else
3547 Load(AValue);
3548 end;
3549 end;
3550
3551 procedure TCastleSceneCore.ReloadUrl;
3552 begin
3553 { Naive implementation:
3554 TempUrl := Url;
3555 Url := '';
3556 Url := TempUrl;
3557 But this would make warning in case of non-empty AutoAnimation,
3558 that such animation doesn't exist in empty scene. }
3559 Load(Url);
3560 end;
3561
3562 (* This is working, and ultra-fast thanks to TShapeTree.AssociatedShape,
3563 but in practice it's unused now.
3564
3565 function TCastleSceneCore.ShapeBoundingBox(const Node: TShapeNode): TBox3D;
3566 var
3567 I: Integer;
3568 begin
3569 C := TShapeTree.AssociatedShapesCount(Node);
3570 case C of
3571 0: Result := TBox3D.Empty;
3572 1: Result := TShape(TShapeTree.AssociatedShape(Node, 0)).BoundingBox;
3573 else
3574 begin
3575 Result := TBox3D.Empty;
3576 for I := 0 to C - 1 do
3577 Result.Include(TShape(TShapeTree.AssociatedShape(Node, I)).BoundingBox);
3578 end;
3579 end;
3580 end;
3581 *)
3582
3583 function TCastleSceneCore.ShapesActiveCount: Cardinal;
3584 begin
3585 if not (fvShapesActiveCount in Validities) then
3586 begin
3587 FShapesActiveCount := Shapes.ShapesCount(true);
3588 Include(Validities, fvShapesActiveCount);
3589 end;
3590 Result := FShapesActiveCount;
3591 end;
3592
3593 function TCastleSceneCore.ShapesActiveVisibleCount: Cardinal;
3594 begin
3595 if not (fvShapesActiveVisibleCount in Validities) then
3596 begin
3597 FShapesActiveVisibleCount := Shapes.ShapesCount(true, true);
3598 Include(Validities, fvShapesActiveVisibleCount);
3599 end;
3600 Result := FShapesActiveVisibleCount;
3601 end;
3602
3603 function TCastleSceneCore.CalculateLocalBoundingBox: TBox3D;
3604 var
3605 ShapeList: TShapeList;
3606 Shape: TShape;
3607 begin
3608 Result := TBox3D.Empty;
3609 ShapeList := Shapes.TraverseList(true);
3610 for Shape in ShapeList do
3611 Result.Include(Shape.BoundingBox);
3612 end;
3613
3614 function TCastleSceneCore.CalculateVerticesCount: Cardinal;
3615 var
3616 ShapeList: TShapeList;
3617 Shape: TShape;
3618 begin
3619 Result := 0;
3620 ShapeList := Shapes.TraverseList(true);
3621 for Shape in ShapeList do
3622 Result := Result + Shape.VerticesCount;
3623 end;
3624
3625 function TCastleSceneCore.CalculateTrianglesCount: Cardinal;
3626 var
3627 ShapeList: TShapeList;
3628 Shape: TShape;
3629 begin
3630 Result := 0;
3631 ShapeList := Shapes.TraverseList(true);
3632 for Shape in ShapeList do
3633 Result := Result + Shape.TrianglesCount;
3634 end;
3635
3636 function TCastleSceneCore.LocalBoundingBoxNoChildren: TBox3D;
3637 begin
3638 if Exists then
3639 begin
3640 if not (fvLocalBoundingBox in Validities) then
3641 begin
3642 FLocalBoundingBox := CalculateLocalBoundingBox;
3643 Include(Validities, fvLocalBoundingBox);
3644 end;
3645 Result := FLocalBoundingBox;
3646 end else
3647 Result := TBox3D.Empty;
3648 end;
3649
3650 function TCastleSceneCore.LocalBoundingBox: TBox3D;
3651 begin
3652 Result := LocalBoundingBoxNoChildren;
3653 Result.Include(inherited LocalBoundingBox);
3654 end;
3655
3656 function TCastleSceneCore.VerticesCount: Cardinal;
3657 begin
3658 if not (fvVerticesCount in Validities) then
3659 begin
3660 FVerticesCount := CalculateVerticesCount;
3661 Include(Validities, fvVerticesCount);
3662 end;
3663 Result := FVerticesCount;
3664 end;
3665
3666 function TCastleSceneCore.TrianglesCount: Cardinal;
3667 begin
3668 if not (fvTrianglesCount in Validities) then
3669 begin
3670 FTrianglesCount := CalculateTrianglesCount;
3671 Include(Validities, fvTrianglesCount);
3672 end;
3673 Result := FTrianglesCount;
3674 end;
3675
3676 function TCastleSceneCore.CreateShape(const AGeometry: TAbstractGeometryNode;
3677 const AState: TX3DGraphTraverseState; const ParentInfo: PTraversingInfo): TShape;
3678 begin
3679 Result := TShape.Create(Self, AGeometry, AState, ParentInfo);
3680 end;
3681
3682 type
3683 { Traverses on ChangedAll event, single TChangedAllTraverser
3684 instance traverses into a single ShapesGroup (but may
3685 recursively create other TChangedAllTraverser instances
3686 to create recursive groups). }
3687 TChangedAllTraverser = class
3688 ParentScene: TCastleSceneCore;
3689 ShapesGroup: TShapeTreeGroup;
3690 Active: boolean;
3691 function Traverse(
3692 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
3693 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
3694 end;
3695
3696 function TChangedAllTraverser.Traverse(
3697 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
3698 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
3699
3700 { Handle node with TTransformFunctionality }
3701 procedure HandleTransform(const TransformFunctionality: TTransformFunctionality);
3702 var
3703 TransformNode: TX3DNode;
3704 TransformTree: TShapeTreeTransform;
3705 Traverser: TChangedAllTraverser;
3706 begin
3707 TransformNode := TransformFunctionality.Parent;
3708
3709 TransformTree := TShapeTreeTransform.Create(ParentScene);
3710 TransformTree.TransformFunctionality := TransformFunctionality;
3711
3712 { We want to save at TransformState the state right before traversing
3713 inside this TransformNode.
3714
3715 StateStack.Top is bad --- it is already modified by TransformNode
3716 transformation, we don't want this, the very purpose of TransformState
3717 is to later restart traversing from a TransformNode that changed
3718 it's transformation. Clearly, TransformState must not depend on
3719 current TransformNode transformation.
3720
3721 So we cheat a little, knowing that internally every node implementing TTransformFunctionality
3722 does StateStack.Push inside BeforeTraverse exactly once and then
3723 modifies transformation.
3724 (This happens for both TAbstractInternalGroupingNode and THAnimHumanoidNode.
3725 Right now, node with TTransformFunctionality is always one of those.)
3726 So we know that previous state lies safely at PreviousTop.
3727
3728 Exception: As TX3DRootNode.SeparateGroup is false now,
3729 it needs special case to look at just StateStack.Top.
3730 TODO: This is wrong though, i.e. the StateStack.Top has the TX3DRootNode
3731 already applied. There's no state without the TX3DRootNode applied... }
3732 if TransformNode is TX3DRootNode then
3733 TransformTree.TransformState.Assign(StateStack.Top)
3734 else
3735 TransformTree.TransformState.Assign(StateStack.PreviousTop);
3736
3737 ShapesGroup.Children.Add(TransformTree);
3738
3739 { update ParentScene.BillboardNodes }
3740 if TransformNode is TBillboardNode then
3741 ParentScene.BillboardNodes.Add(TransformNode);
3742
3743 Traverser := TChangedAllTraverser.Create;
3744 try
3745 Traverser.ParentScene := ParentScene;
3746 { No need to create another TShapeTreeGroup, like ChildGroup
3747 for Switch/LOD nodes. We can just add new shapes to our TransformTree.
3748 Reason: unlike Switch/LOD nodes, we don't care about keeping
3749 the indexes of children stable. }
3750 Traverser.ShapesGroup := TransformTree;
3751 Traverser.Active := Active;
3752
3753 TransformNode.TraverseIntoChildren(StateStack, TX3DNode,
3754 {$ifdef FPC}@{$endif}Traverser.Traverse, ParentInfo);
3755 finally FreeAndNil(Traverser) end;
3756
3757 TraverseIntoChildren := false;
3758 end;
3759
3760 procedure HandleSwitch(SwitchNode: TSwitchNode);
3761 var
3762 SwitchTree: TShapeTreeSwitch;
3763 Traverser: TChangedAllTraverser;
3764 ChildNode: TX3DNode;
3765 ChildGroup: TShapeTreeGroup;
3766 I: Integer;
3767 begin
3768 SwitchTree := TShapeTreeSwitch.Create(ParentScene);
3769 SwitchTree.SwitchNode := SwitchNode;
3770 ShapesGroup.Children.Add(SwitchTree);
3771
3772 for I := 0 to SwitchNode.FdChildren.Count - 1 do
3773 begin
3774 ChildNode := SwitchNode.FdChildren[I];
3775 ChildGroup := TShapeTreeGroup.Create(ParentScene);
3776 SwitchTree.Children.Add(ChildGroup);
3777
3778 Traverser := TChangedAllTraverser.Create;
3779 try
3780 Traverser.ParentScene := ParentScene;
3781 Traverser.ShapesGroup := ChildGroup;
3782 Traverser.Active := Active and (I = SwitchNode.FdWhichChoice.Value);
3783 ChildNode.TraverseInternal(StateStack, TX3DNode,
3784 {$ifdef FPC}@{$endif}Traverser.Traverse, ParentInfo);
3785 finally FreeAndNil(Traverser) end;
3786 end;
3787
3788 TraverseIntoChildren := false;
3789 end;
3790
3791 procedure HandleLOD(LODNode: TLODNode);
3792 var
3793 LODTree: TShapeTreeLOD;
3794 Traverser: TChangedAllTraverser;
3795 ChildNode: TX3DNode;
3796 ChildGroup: TShapeTreeGroup;
3797 I: Integer;
3798 CameraLocalPosition: TVector3;
3799 begin
3800 LODTree := TShapeTreeLOD.Create(ParentScene);
3801 LODTree.LODNode := LODNode;
3802 LODTree.LODInverseTransform^ := StateStack.Top.Transformation.InverseTransform;
3803 ShapesGroup.Children.Add(LODTree);
3804 ParentScene.ShapeLODs.Add(LODTree);
3805
3806 { First add TShapeTreeGroup.Create as children, as many times
3807 as there are LODNode.FdChildren. Reason: LODTree.CalculateLevel
3808 uses this Count. }
3809
3810 for I := 0 to LODNode.FdChildren.Count - 1 do
3811 LODTree.Children.Add(TShapeTreeGroup.Create(ParentScene));
3812
3813 if ParentScene.ProcessEvents and
3814 ParentScene.GetCameraLocal(CameraLocalPosition) then
3815 ParentScene.UpdateLODLevel(LODTree, CameraLocalPosition);
3816
3817 for I := 0 to LODNode.FdChildren.Count - 1 do
3818 begin
3819 ChildNode := LODNode.FdChildren[I];
3820 ChildGroup := TShapeTreeGroup(LODTree.Children.Items[I]);
3821
3822 Traverser := TChangedAllTraverser.Create;
3823 try
3824 Traverser.ParentScene := ParentScene;
3825 Traverser.ShapesGroup := ChildGroup;
3826 Traverser.Active := Active and (Cardinal(I) = LODTree.Level);
3827 ChildNode.TraverseInternal(StateStack, TX3DNode,
3828 {$ifdef FPC}@{$endif}Traverser.Traverse, ParentInfo);
3829 finally FreeAndNil(Traverser) end;
3830 end;
3831
3832 TraverseIntoChildren := false;
3833 end;
3834
3835 procedure HandleProximitySensor(const Node: TProximitySensorNode);
3836 var
3837 PSI: TProximitySensorInstance;
3838 begin
3839 PSI := TProximitySensorInstance.Create(ParentScene);
3840 PSI.Node := Node;
3841 PSI.InverseTransform := StateStack.Top.Transformation.InverseTransform;
3842 PSI.IsActive := false; { IsActive = false initially }
3843
3844 ShapesGroup.Children.Add(PSI);
3845 ParentScene.ProximitySensors.Add(PSI);
3846 end;
3847
3848 procedure HandleVisibilitySensor(const Node: TVisibilitySensorNode);
3849 var
3850 VSI: TVisibilitySensorInstance;
3851 Instances: TCastleSceneCore.TVisibilitySensorInstanceList;
3852 begin
3853 VSI := TVisibilitySensorInstance.Create(ParentScene);
3854 VSI.Node := Node;
3855 VSI.Transform := StateStack.Top.Transformation.Transform;
3856 VSI.Box := Node.Box.Transform(VSI.Transform);
3857
3858 ShapesGroup.Children.Add(VSI);
3859
3860 { add to ParentScene.VisibilitySensors map }
3861 if not ParentScene.VisibilitySensors.TryGetValue(Node, Instances) then
3862 begin
3863 Instances := TCastleSceneCore.TVisibilitySensorInstanceList.Create(false);
3864 ParentScene.VisibilitySensors.Add(Node, Instances);
3865 end;
3866 Instances.Add(VSI);
3867 end;
3868
3869 var
3870 Shape: TShape;
3871 begin
3872 Result := nil;
3873
3874 if Node is TAbstractGeometryNode then
3875 begin
3876 if (not (Node is TAbstractGeometryNode_1)) and
3877 ( (ParentInfo = nil) or
3878 (not (ParentInfo^.Node is TShapeNode) ) ) then
3879 begin
3880 { Detect and reject trying to use geometry nodes incorrectly in X3D or
3881 VRML 2.0.
3882
3883 Testcase: tests/data/geometry_not_in_shape.x3dv
3884
3885 Without this safeguard, in debug mode, it would cause failure
3886 at "Assert(State.ShapeNode <> nil)" in
3887 src/scene/castleinternalarraysgenerator.pas .
3888 }
3889 WritelnWarning('Node "%s" is a geometry node, it has to be placed within a Shape node', [
3890 Node.NiceName
3891 ]);
3892 end else
3893 begin
3894 { Add shape to Shapes }
3895 Shape := ParentScene.CreateShape(Node as TAbstractGeometryNode,
3896 TX3DGraphTraverseState.CreateCopy(StateStack.Top), ParentInfo);
3897 ShapesGroup.Children.Add(Shape);
3898
3899 { When Spatial contain ssDynamicCollisions, then each collidable
3900 shape must have octree created. Normally, this is watched over by
3901 SetSpatial. In this case, we just created new Shape, so we have
3902 to set it's Spatial property correctly. }
3903 if (ssDynamicCollisions in ParentScene.FSpatial) and
3904 Shape.Collidable then
3905 begin
3906 Shape.InternalSpatial := [ssTriangles];
3907 end;
3908 end;
3909 end else
3910
3911 if Node is TAbstractLightNode then
3912 begin
3913 (*Global lights within inactive Switch child are not active.
3914 Although I didn't find where specification explicitly says this,
3915 but it's natural. Allows e.g. to do
3916
3917 Switch {
3918 DEF SomeGroup1 { .. some lights and shapes .. }
3919 DEF SomeGroup2 { .. some lights and shapes .. }
3920 }
3921 USE SomeGroup1
3922
3923 which is a trick used e.g. by our Collada importer.
3924 Without this rule, SomeGroup1 would be affected be it's own lights
3925 *two* times (and in addition by SomeGroup2 lights).
3926
3927 TODO: Changing things like Switch.FdWhichChoice should update
3928 global lights set. *)
3929
3930 { Add lights to GlobalLights }
3931 if Active and (TAbstractLightNode(Node).Scope = lsGlobal) then
3932 ParentScene.InternalGlobalLights.Add(
3933 TAbstractLightNode(Node).CreateLightInstance(StateStack.Top));
3934 end else
3935
3936 if Node is TSwitchNode then
3937 begin
3938 HandleSwitch(TSwitchNode(Node));
3939 end else
3940 if Node is TLODNode then
3941 begin
3942 HandleLOD(TLODNode(Node));
3943 end else
3944 if Node.TransformFunctionality <> nil then
3945 begin
3946 HandleTransform(Node.TransformFunctionality);
3947 end else
3948
3949 if (Node is TAbstractBindableNode) and
3950 { Do not look for first bindable node within inlined content,
3951 this is following VRML spec. }
3952 (StateStack.Top.InsideInline = 0) and
3953 { Do not look for first bindable node within inactive content.
3954 TODO: Actually, where does spec precisely say that first bindable node
3955 must be in active part? Although it seems most sensible... }
3956 Active then
3957 begin
3958 { If some bindable stack is empty, push the node to it.
3959 This way, upon reading VRML file, we will bind the first found
3960 node for each stack. }
3961 if Node is TAbstractBackgroundNode then
3962 ParentScene.BackgroundStack.PushIfEmpty( TAbstractBackgroundNode(Node), true) else
3963 if Node is TFogNode then
3964 ParentScene.FogStack.PushIfEmpty( TFogNode(Node), true) else
3965 if Node is TNavigationInfoNode then
3966 ParentScene.NavigationInfoStack.PushIfEmpty( TNavigationInfoNode(Node), true) else
3967 if Node is TAbstractViewpointNode then
3968 begin
3969 { before binding viewpoint, check InitialViewpoint* conditions }
3970 if (ParentScene.InitialViewpointName = '') or
3971 (ParentScene.InitialViewpointName = Node.X3DName) then
3972 begin
3973 if (ParentScene.InitialViewpointIndex =
3974 ParentScene.ChangedAllCurrentViewpointIndex) then
3975 ParentScene.ViewpointStack.PushIfEmpty( TAbstractViewpointNode(Node), true);
3976 Inc(ParentScene.ChangedAllCurrentViewpointIndex);
3977 end;
3978 ParentScene.FViewpointsArray.Add(TAbstractViewpointNode(Node));
3979 end;
3980 end else
3981 if Node is TProximitySensorNode then
3982 HandleProximitySensor(Node as TProximitySensorNode) else
3983 if Node is TVisibilitySensorNode then
3984 HandleVisibilitySensor(Node as TVisibilitySensorNode) else
3985 if Node is TScreenEffectNode then
3986 begin
3987 ParentScene.ScreenEffectNodes.Add(Node);
3988 end;
3989 end;
3990
3991 procedure TCastleSceneCore.UpdateLODLevel(const LODTree: TShapeTreeLOD;
3992 const CameraLocalPosition: TVector3);
3993 var
3994 OldLevel, NewLevel: Cardinal;
3995 begin
3996 Assert(ProcessEvents);
3997
3998 OldLevel := LODTree.Level;
3999 NewLevel := LODTree.CalculateLevel(CameraLocalPosition);
4000 LODTree.Level := NewLevel;
4001
4002 if ( (OldLevel <> NewLevel) or
4003 (not LODTree.WasLevel_ChangedSend) ) and
4004 { If LODTree.Children.Count = 0, then Level = 0, but we don't
4005 want to send Level_Changed since the children 0 doesn't really exist. }
4006 (LODTree.Children.Count <> 0) then
4007 begin
4008 LODTree.WasLevel_ChangedSend := true;
4009 LODTree.LODNode.EventLevel_Changed.Send(Integer(NewLevel), NextEventTime);
4010 end;
4011
4012 if OldLevel <> NewLevel then
4013 begin
4014 { This means that active shapes changed, so we have to change things
4015 depending on them. Just like after Switch.whichChoice change. }
4016
4017 Validities := Validities - [
4018 { Calculation traverses over active shapes. }
4019 fvShapesActiveCount,
4020 fvShapesActiveVisibleCount,
4021 { Calculation traverses over active nodes (uses RootNode.Traverse). }
4022 fvMainLightForShadows];
4023
4024 DoGeometryChanged(gcActiveShapesChanged, nil);
4025
4026 InternalIncShapesHash; // TShapeTreeLOD returns now different things
4027 end;
4028 end;
4029
4030 procedure TCastleSceneCore.BeforeNodesFree(const InternalChangedAll: boolean);
4031 begin
4032 // paranoid check is the World valid before accessing it
4033 if (World <> nil) and
4034 (not (csDestroying in World.ComponentState)) and
4035 Assigned(World.InternalOnNodesFree) then
4036 World.InternalOnNodesFree(Self);
4037
4038 { Stuff that will be recalculated by ChangedAll }
4039 BillboardNodes.Count := 0;
4040 GeneratedTextures.Count := 0;
4041 ProximitySensors.Count := 0;
4042 VisibilitySensors.Clear;
4043 ScreenEffectNodes.Count := 0;
4044 ScheduledHumanoidAnimateSkin.Count := 0;
4045 KeyDeviceSensorNodes.Clear;
4046 TimeDependentList.Clear;
4047 FExposedTransforms.Clear;
4048
4049 { clear animation stuff, since any TTimeSensorNode may be freed soon }
4050 if PlayingAnimationNode <> nil then
4051 PlayingAnimationNode.EventIsActive.RemoveNotification(
4052 {$ifdef FPC}@{$endif}PlayingAnimationIsActive);
4053 PlayingAnimationNode := nil;
4054 PlayingAnimationStopNotification := nil;
4055 FCurrentAnimation := nil;
4056 NewPlayingAnimationNode := nil;
4057 NewPlayingAnimationUse := false;
4058 PreviousPlayingAnimation := nil;
4059 FreeAndNil(PreviousPartialAffectedFields);
4060
4061 if not InternalChangedAll then
4062 begin
4063 { Clean Shapes, ShapeLODs.
4064 TShapeTree and descendants keep references to Nodes. }
4065 FreeAndNil(FShapes);
4066 FShapes := TShapeTreeGroup.Create(Self);
4067 ShapeLODs.Clear;
4068 InternalIncShapesHash;
4069 end;
4070 end;
4071
4072 procedure TCastleSceneCore.NodeFreeRemovingFromAllParents(Node: TX3DNode);
4073 begin
4074 BeforeNodesFree;
4075 Node.FreeRemovingFromAllParents;
4076 ChangedAll;
4077 end;
4078
4079 procedure TCastleSceneCore.RemoveShape(Shape: TShape);
4080 begin
4081 if Shape.Node <> nil then
4082 NodeFreeRemovingFromAllParents(Shape.Node) else
4083 { Do not use Shape.Geometry here, as it may be a temporary result
4084 of OriginalGeometry.Proxy.
4085
4086 When the shape is freed (which happens in BeforeNodesFree called
4087 at the beginning of NodeFreeRemovingFromAllParents),
4088 the proxy result is freed too. So using here Shape.Geometry
4089 would not only not free what you think, it would also cause segfault. }
4090 NodeFreeRemovingFromAllParents(Shape.OriginalGeometry);
4091 end;
4092
4093 procedure TCastleSceneCore.ChangedAllEnumerateCallback(Node: TX3DNode);
4094 begin
4095 if (Node.Scene <> nil) and
4096 (Node.Scene <> Self) and
4097 (not InternalNodeSharing) then
4098 WritelnWarning('X3D node %s is already part of another TCastleScene instance.' + ' You cannot use the same X3D node in multiple instances of TCastleScene. Instead you must copy the node, using "Node.DeepCopy". It is usually most comfortable to copy the entire scene, using "TCastleScene.Clone".',
4099 [Node.NiceName]);
4100 Node.Scene := Self;
4101
4102 { We're using AddIfNotExists, not simple Add, below:
4103
4104 - for time-dependent nodes (TimeSensor, MovieTexture etc.),
4105 duplicates would cause time to be then incremented many times
4106 during single SetTime, so their local time would grow too fast.
4107
4108 - for other sensors, events would be passed twice.
4109 }
4110
4111 if Node is TAbstractKeyDeviceSensorNode then
4112 KeyDeviceSensorNodes.AddIfNotExists(Node)
4113 else
4114 if Node.TimeFunctionality <> nil then
4115 begin
4116 TimeDependentList.AddIfNotExists(Node.TimeFunctionality);
4117
4118 // update NeedsDetectAffectedFields if necessary
4119 if (Node is TTimeSensorNode) and TTimeSensorNode(Node).DetectAffectedFields then
4120 NeedsDetectAffectedFields := true;
4121 end;
4122 end;
4123
4124 procedure TCastleSceneCore.ChangedAll(const OnlyAdditions: Boolean);
4125
4126 { Add where necessary lights with scope = global. }
4127 procedure AddGlobalLights;
4128
4129 procedure AddLightEverywhere(const L: TLightInstance);
4130 var
4131 ShapeList: TShapeList;
4132 Shape: TShape;
4133 begin
4134 ShapeList := Shapes.TraverseList(false);
4135 for Shape in ShapeList do
4136 Shape.State.AddLight(L);
4137 end;
4138
4139 var
4140 I: Integer;
4141 L: PLightInstance;
4142 begin
4143 { Here we only deal with light scope = lsGlobal case.
4144 Other scopes are handled during traversing. }
4145 for I := 0 to InternalGlobalLights.Count - 1 do
4146 begin
4147 L := PLightInstance(InternalGlobalLights.Ptr(I));
4148 AddLightEverywhere(L^);
4149 end;
4150 end;
4151
4152 { Assigns nodes TX3DNode.Scene, and adds nodes to KeyDeviceSensorNodes
4153 and TimeDependentList lists. }
4154 procedure EnumerateNodes;
4155 begin
4156 if RootNode <> nil then
4157 RootNode.EnumerateNodes(TX3DNode,
4158 {$ifdef FPC}@{$endif}ChangedAllEnumerateCallback, false);
4159 end;
4160
4161 procedure DetectAffectedFields;
4162 var
4163 Detector: TDetectAffectedFields;
4164 begin
4165 Detector := TDetectAffectedFields.Create(Self);
4166 try
4167 Detector.FindRoutesAndInterpolators;
4168 Detector.FindAnimationAffectedFields;
4169 finally FreeAndNil(Detector) end;
4170 end;
4171
4172 var
4173 Traverser: TChangedAllTraverser;
4174 TimeStart: TCastleProfilerTime;
4175 begin
4176 { Whether this is called by EndChangesSchedule, or from other places,
4177 we can always reset the ChangedAllScheduled flag.
4178
4179 Note that ChangedAll calls ChangedAllEnumerate inside,
4180 which in turn calls Begin/EndChangesSchedule.
4181 So ChangedAllScheduled flag must be ready for this,
4182 so it should be reset early, at the very beginning of ChangedAll implementation. }
4183 ChangedAllScheduled := false;
4184
4185 TimeStart := Profiler.Start('ChangedAll for ' + Name + ' from ' + UriDisplay(Url));
4186 try
4187
4188 { We really need to use InternalDirty here, to forbid rendering during this.
4189
4190 For example, ProcessShadowMapsReceivers work assumes this:
4191 otherwise, RootNode.Traverse may cause some progress Step call
4192 (note: this is old comment, progress is not possible now)
4193 which may call Render which may prepare GLSL shadow map shader
4194 that will be freed by the following ProcessShadowMapsReceivers call.
4195 Testcase: castle-model-viewer open simple_shadow_map_teapots.x3dv, turn off
4196 shadow maps "receiveShadows" handling, then turn it back on
4197 --- will crash without "InternalDirty" variable safety. }
4198 Inc(InternalDirty);
4199 try
4200
4201 if LogChanges then
4202 WritelnLog('X3D changes', 'ChangedAll (OnlyAdditions: %s)',
4203 [BoolToStr(OnlyAdditions, true)]);
4204
4205 { TODO:
4206 We ignore OnlyAdditions now.
4207 We have to even do BeforeNodesFree always, even when OnlyAdditions,
4208 the code below (may) assume it is always done, e.g. all lists are cleared in BeforeNodesFree. }
4209
4210 BeforeNodesFree(true);
4211
4212 { Call DoGeometryChanged already here, as our old shapes already
4213 stopped to exist. }
4214 DoGeometryChanged(gcAll, nil);
4215
4216 { Delay calling OnBoundChanged from bindable stack changes.
4217
4218 Reason: CheckForDeletedNodes below, or PushIfEmpty during traversing,
4219 should not cause immediate OnBoundChanged, as a receiver may expect
4220 us to be in initialized state (and e.g. use BoundingBox function).
4221 And before traversing finished, our Shapes tree is not calculated,
4222 so we're not ready to answer e.g. BoundingBox correctly.
4223
4224 Besides, this was often causing two OnBoundChanged calls,
4225 while only one was needed. E.g. if your previous scene has
4226 a Viewpoint node, and newly loaded scene also has Viewpoint,
4227 then we would call OnBoundChanged twice (1st time by CheckForDeletedNodes). }
4228 BackgroundStack.BeginChangesSchedule;
4229 FogStack.BeginChangesSchedule;
4230 NavigationInfoStack.BeginChangesSchedule;
4231 ViewpointStack.BeginChangesSchedule;
4232
4233 try
4234 BackgroundStack.CheckForDeletedNodes(RootNode, true);
4235 FogStack.CheckForDeletedNodes(RootNode, true);
4236 NavigationInfoStack.CheckForDeletedNodes(RootNode, true);
4237 ViewpointStack.CheckForDeletedNodes(RootNode, true);
4238
4239 Validities := [];
4240
4241 { Clean Shapes and other stuff initialized by traversing }
4242 FreeAndNil(FShapes);
4243 FShapes := TShapeTreeGroup.Create(Self);
4244 ShapeLODs.Clear;
4245 InternalGlobalLights.Clear;
4246 FViewpointsArray.Clear;
4247 FAnimationsList.Clear;
4248 AnimationAffectedFields.Clear;
4249 NeedsDetectAffectedFields := false;
4250 InternalIncShapesHash;
4251
4252 if RootNode <> nil then
4253 begin
4254 ChangedAllCurrentViewpointIndex := 0;
4255 Traverser := TChangedAllTraverser.Create;
4256 try
4257 Traverser.ParentScene := Self;
4258 { We just created FShapes as TShapeTreeGroup, so this cast
4259 is safe }
4260 Traverser.ShapesGroup := TShapeTreeGroup(FShapes);
4261 Traverser.Active := true;
4262 RootNode.Traverse(TX3DNode,
4263 {$ifdef FPC}@{$endif}Traverser.Traverse);
4264 finally FreeAndNil(Traverser) end;
4265
4266 AddGlobalLights;
4267
4268 EnumerateNodes;
4269
4270 if NeedsDetectAffectedFields then
4271 DetectAffectedFields;
4272 end;
4273
4274 { Wait until loading finished before calling ExposeTransformsChange.
4275 Otherwise we would create new TCastleTransform children in ExposeTransformsChange,
4276 instead of reusing existing ones. }
4277 if not IsLoading then
4278 ExposeTransformsChange(nil);
4279
4280 { Call DoGeometryChanged here, as our new shapes are added.
4281 Probably, only one DoGeometryChanged(gcAll) is needed, but for safety
4282 --- we can call it twice, it's ultra-fast right now. }
4283 DoGeometryChanged(gcAll, nil);
4284
4285 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4286 DoViewpointsChanged;
4287
4288 { recreate FAnimationsList now }
4289 FreeAndNil(FAnimationsList);
4290 FAnimationsList := CreateAnimations;
4291 finally
4292 BackgroundStack.EndChangesSchedule;
4293 FogStack.EndChangesSchedule;
4294 NavigationInfoStack.EndChangesSchedule;
4295 ViewpointStack.EndChangesSchedule;
4296 end;
4297
4298 if ScheduledShadowMapsProcessing then
4299 begin
4300 ProcessShadowMapsReceivers(RootNode, Shapes, ShadowMaps,
4301 ShadowMapsDefaultSize);
4302 ScheduledShadowMapsProcessing := false;
4303 end;
4304
4305 { Add items to GeneratedTextures for this Shape, if it has any
4306 generated textures.
4307
4308 Do this *after* ProcessShadowMapsReceivers was run
4309 (before ProcessShadowMapsReceivers we may have old GeneratedShadowMap nodes
4310 that will be freed during ProcessShadowMapsReceivers,
4311 and new nodes added by ProcessShadowMapsReceivers would be missing.)
4312
4313 Note that clearing GeneratedTextures was already done at the beginning
4314 of ChangedAll (as part of BeforeNodesFree(true) call). }
4315 Shapes.EnumerateTextures(
4316 {$ifdef FPC}@{$endif}GeneratedTextures.AddShapeTexture);
4317
4318 if ScheduleHeadlightOnFromNavigationInfoInChangedAll then
4319 begin
4320 ScheduleHeadlightOnFromNavigationInfoInChangedAll := false;
4321 UpdateHeadlightOnFromNavigationInfo;
4322 end;
4323
4324 ForceTeleportTransitions := false;
4325
4326 if LogShapes then
4327 WritelnLogMultiline('Shapes tree', Shapes.DebugInfo);
4328
4329 finally Dec(InternalDirty) end;
4330
4331 finally Profiler.Stop(TimeStart, true, true) end;
4332 end;
4333
4334 type
4335 { When Transform changes, we have to traverse Shapes tree simultaneously
4336 with traversing VRML graph. So we have to know at each point
4337 the TShapeTree we're on. To record this, we'll manage a linked list
4338 of PShapesParentInfo records.
4339
4340 We will traverse Shapes tree knowing
4341 it's structure, since it must have been created by ChangedAll code. }
4342
4343 PShapesParentInfo = ^TShapesParentInfo;
4344 TShapesParentInfo = record
4345 Group: TShapeTreeGroup;
4346 Index: Integer;
4347 end;
4348
4349 { We need a separate class to keep various helpful state
4350 during traversal when Transform changed.
4351 Changing VRML >= 2.0 Transform fields must be highly optimized.
4352
4353 Reason: one change of Transform may cause, during traversal,
4354 another change of Transform and another traversal.
4355 Consider e.g. proximity_sensor_transformed.x3dv: ProximitySensorUpdate
4356 causes sending of Position_Changed, which may be routed to something
4357 like Transform.set_translation.
4358
4359 So many TransformChange traversals may run at once, so they must
4360 have different state variables. }
4361 TTransformChangeHelper = class
4362 ParentScene: TCastleSceneCore;
4363 Shapes: PShapesParentInfo;
4364 ChangingNode: TX3DNode;
4365 AnythingChanged: boolean;
4366 Inside: boolean;
4367 { If = 0, we're in active or inactive graph part (we don't know).
4368 If > 0, we're in inactive graph part (TransformChangeTraverse
4369 may enter there, since our changing Transform node (or some of it's
4370 children) may be inactive; but we have to update all shapes,
4371 active or not). }
4372 Inactive: Cardinal;
4373 function TransformChangeTraverse(
4374 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
4375 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
4376 end;
4377
4378 function TTransformChangeHelper.TransformChangeTraverse(
4379 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
4380 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
4381
4382 { Handle node with TTransformFunctionality }
4383 procedure HandleTransform(const TransformNode: TX3DNode);
4384 var
4385 ShapeTransform: TShapeTreeTransform;
4386 OldShapes: PShapesParentInfo;
4387 NewShapes: TShapesParentInfo;
4388 begin
4389 if TransformNode = ChangingNode then
4390 begin
4391 if Inside then
4392 WritelnLog('X3D transform', 'Cycle in X3D graph detected: transform node is a child of itself');
4393 Inside := true;
4394 { Nothing to do, in particular: do not enter inside below by
4395 TransformNode.TraverseIntoChildren.
4396 Instead we leave TraverseIntoChildren = true and let regular Traverse
4397 logic to visit our children.
4398 Our Shapes^.Group and Shapes^.Index is already correctly set
4399 at the inside of this transform by our HandleChangeTransform. }
4400 Exit;
4401 end;
4402
4403 { get Shape and increase Shapes^.Index }
4404 ShapeTransform := Shapes^.Group.Children[Shapes^.Index] as TShapeTreeTransform;
4405 Inc(Shapes^.Index);
4406 Assert(ShapeTransform.TransformFunctionality <> nil);
4407 Assert(ShapeTransform.TransformNode = TransformNode);
4408
4409 { update transformation inside Transform nodes that are *within*
4410 the modified Transform node.
4411
4412 As in TChangedAllTraverser.Traverse, we apply special treatment
4413 for TX3DRootNode.
4414 TODO: As in TChangedAllTraverser.Traverse, this StateStack.Top is actually
4415 not correct in case TX3DRootNode does any scaling. StateStack.Top has the scaling
4416 applied, we want transformation before. }
4417 if TransformNode is TX3DRootNode then
4418 ShapeTransform.TransformState.AssignTransform(StateStack.Top)
4419 else
4420 ShapeTransform.TransformState.AssignTransform(StateStack.PreviousTop);
4421
4422 OldShapes := Shapes;
4423 try
4424 { NewShapes group is just our ShapeTransform. Transform children do not
4425 have addition TShapeTreeGroup, unlike Switch/LOD nodes. }
4426 NewShapes.Group := ShapeTransform;
4427 NewShapes.Index := 0;
4428 Shapes := @NewShapes;
4429
4430 TransformNode.TraverseIntoChildren(
4431 StateStack, TX3DNode,
4432 {$ifdef FPC}@{$endif}Self.TransformChangeTraverse, ParentInfo);
4433 finally Shapes := OldShapes end;
4434
4435 TraverseIntoChildren := false;
4436 end;
4437
4438 procedure HandleSwitch(SwitchNode: TSwitchNode);
4439 var
4440 I: Integer;
4441 ChildInactive: boolean;
4442 ShapeSwitch: TShapeTreeSwitch;
4443 OldShapes: PShapesParentInfo;
4444 NewShapes: TShapesParentInfo;
4445 begin
4446 { get Shape and increase Shapes^.Index }
4447 ShapeSwitch := Shapes^.Group.Children[Shapes^.Index] as TShapeTreeSwitch;
4448 Inc(Shapes^.Index);
4449 Assert(ShapeSwitch.SwitchNode = SwitchNode);
4450
4451 OldShapes := Shapes;
4452 try
4453 { We have to enter *every* Switch child (while normal
4454 Traverse would enter only active child), because changing Transform
4455 node may be in inactive graph parts. }
4456
4457 for I := 0 to SwitchNode.FdChildren.Count - 1 do
4458 begin
4459 NewShapes.Group := ShapeSwitch.Children[I] as TShapeTreeGroup;
4460 NewShapes.Index := 0;
4461 Shapes := @NewShapes;
4462
4463 ChildInactive := I <> SwitchNode.FdWhichChoice.Value;
4464 if ChildInactive then Inc(Inactive);
4465
4466 SwitchNode.FdChildren[I].TraverseInternal(
4467 StateStack, TX3DNode,
4468 {$ifdef FPC}@{$endif}Self.TransformChangeTraverse,
4469 ParentInfo);
4470
4471 if ChildInactive then Dec(Inactive);
4472 end;
4473
4474 finally Shapes := OldShapes end;
4475
4476 TraverseIntoChildren := false;
4477 end;
4478
4479 procedure HandleLOD(LODNode: TLODNode);
4480 var
4481 I: Integer;
4482 ShapeLOD: TShapeTreeLOD;
4483 OldShapes: PShapesParentInfo;
4484 NewShapes: TShapesParentInfo;
4485 CameraLocalPosition: TVector3;
4486 begin
4487 { get Shape and increase Shapes^.Index }
4488 ShapeLOD := Shapes^.Group.Children[Shapes^.Index] as TShapeTreeLOD;
4489 Inc(Shapes^.Index);
4490 Assert(ShapeLOD.LODNode = LODNode);
4491
4492 { by the way, update LODInverseTransform, since it changed }
4493 if Inside then
4494 begin
4495 ShapeLOD.LODInverseTransform^ := StateStack.Top.Transformation.InverseTransform;
4496 if ParentScene.ProcessEvents and
4497 ParentScene.GetCameraLocal(CameraLocalPosition) then
4498 ParentScene.UpdateLODLevel(ShapeLOD, CameraLocalPosition);
4499 end;
4500
4501 OldShapes := Shapes;
4502 try
4503 { Just like in HandleSwitch: we have to enter *every* LOD child
4504 (while normal Traverse would enter only active child),
4505 because changing Transform node may be in inactive graph parts. }
4506
4507 for I := 0 to LODNode.FdChildren.Count - 1 do
4508 begin
4509 NewShapes.Group := ShapeLOD.Children[I] as TShapeTreeGroup;
4510 NewShapes.Index := 0;
4511 Shapes := @NewShapes;
4512
4513 if Cardinal(I) <> ShapeLOD.Level then Inc(Inactive);
4514
4515 LODNode.FdChildren[I].TraverseInternal(
4516 StateStack, TX3DNode,
4517 {$ifdef FPC}@{$endif}Self.TransformChangeTraverse,
4518 ParentInfo);
4519
4520 if Cardinal(I) <> ShapeLOD.Level then Dec(Inactive);
4521 end;
4522
4523 finally Shapes := OldShapes end;
4524
4525 TraverseIntoChildren := false;
4526 end;
4527
4528 procedure HandleLight(LightNode: TAbstractLightNode);
4529 { When the transformation of light node changes, we should update every
4530 TLightInstance record of this light in every shape.
4531
4532 TODO: code below updates too much, if the light was instantiated
4533 many times then only some occurrences should be updated, not all.
4534
4535 TODO: for global lights, limited by radius field,
4536 we should also add / remove this light from some TX3DGraphTraverseState.Lights. }
4537
4538 procedure HandleLightsList(List: TLightInstancesList);
4539 var
4540 I: Integer;
4541 begin
4542 if List <> nil then
4543 for I := 0 to List.Count - 1 do
4544 if List.L[I].Node = LightNode then
4545 LightNode.UpdateLightInstanceState(List.L[I], StateStack.Top);
4546 end;
4547
4548 var
4549 ShapeList: TShapeList;
4550 Shape: TShape;
4551 begin
4552 // TODO: Optimize using TShapeTree.AssociatedShape
4553
4554 ShapeList := ParentScene.Shapes.TraverseList(false);
4555 for Shape in ShapeList do
4556 begin
4557 HandleLightsList(Shape.OriginalState.Lights);
4558 if Shape.State <> Shape.OriginalState then
4559 HandleLightsList(Shape.State.Lights);
4560 end;
4561
4562 { Update also light state on GlobalLights list, in case other scenes
4563 depend on this light. Testcase: planets-demo. }
4564 HandleLightsList(ParentScene.InternalGlobalLights);
4565
4566 { force update of GeneratedShadowMap textures that used this light }
4567 ParentScene.GeneratedTextures.UpdateShadowMaps(LightNode);
4568
4569 ParentScene.VisibleChangeHere([vcVisibleNonGeometry]);
4570 end;
4571
4572 procedure HandleProximitySensor(Node: TProximitySensorNode);
4573 var
4574 Instance: TProximitySensorInstance;
4575 CameraVectors: TViewVectors;
4576 begin
4577 Check(Shapes^.Index < Shapes^.Group.Children.Count,
4578 'Missing shape in Shapes tree');
4579 Instance := Shapes^.Group.Children[Shapes^.Index] as TProximitySensorInstance;
4580 Inc(Shapes^.Index);
4581 Assert(Instance.Node = Node);
4582
4583 Instance.InverseTransform := StateStack.Top.Transformation.InverseTransform;
4584
4585 { We only care about ProximitySensor in active graph parts.
4586
4587 TODO: (Inactive = 0) does not guarantee that we're in active part,
4588 it only says we're *possibly* in an active part, and we cannot fix it
4589 (without sacrificing transform optimization).
4590 This is bad, it means we make ProximitySensor events also for
4591 sensors in inactive graph parts. Although, should we really
4592 look at this? Maybe ProximitySensor ignore active/inactive,
4593 and we should just remove the test for "(Inactive = 0)" and that's it? }
4594 if Inactive = 0 then
4595 begin
4596 { Call ProximitySensorUpdate, since the sensor's box is transformed,
4597 so possibly it should be activated/deactivated,
4598 position/orientation_changed called etc. }
4599 if ParentScene.GetCameraLocal(CameraVectors) then
4600 ParentScene.ProximitySensorUpdate(Instance, CameraVectors);
4601 end;
4602 end;
4603
4604 procedure HandleVisibilitySensor(Node: TVisibilitySensorNode);
4605 var
4606 Instance: TVisibilitySensorInstance;
4607 begin
4608 Check(Shapes^.Index < Shapes^.Group.Children.Count,
4609 'Missing shape in Shapes tree');
4610 Instance := Shapes^.Group.Children[Shapes^.Index] as TVisibilitySensorInstance;
4611 Inc(Shapes^.Index);
4612 Assert(Instance.Node = Node);
4613
4614 Instance.Transform := StateStack.Top.Transformation.Transform;
4615 Instance.Box := Node.Box.Transform(Instance.Transform);
4616 end;
4617
4618 var
4619 Shape: TShape;
4620 begin
4621 Result := nil;
4622
4623 case Node.TransformationChange of
4624 ntcNone: ;
4625 ntcSwitch: HandleSwitch(TSwitchNode(Node));
4626 ntcLOD: HandleLOD(TLODNode(Node));
4627 ntcTransform: HandleTransform(Node);
4628 ntcGeometry:
4629 begin
4630 { get Shape and increase Shapes^.Index }
4631 Check(Shapes^.Index < Shapes^.Group.Children.Count,
4632 'Missing shape in Shapes tree');
4633 Shape := Shapes^.Group.Children[Shapes^.Index] as TShape;
4634 Inc(Shapes^.Index);
4635
4636 Shape.State.AssignTransform(StateStack.Top);
4637 Shape.Changed(Inactive <> 0, [chTransform]);
4638
4639 if Inactive = 0 then
4640 begin
4641 if Shape.Visible then
4642 ParentScene.DoGeometryChanged(gcVisibleTransformChanged, nil);
4643
4644 if Shape.Collidable then
4645 ParentScene.DoGeometryChanged(gcCollidableTransformChanged, nil);
4646
4647 AnythingChanged := true;
4648 end;
4649 end;
4650 ntcBackground:
4651 begin
4652 { Just make redraw. It will redraw the background with
4653 new transform correctly. }
4654 AnythingChanged := true;
4655 end;
4656 ntcFog:
4657 begin
4658 { There's no need to do anything more here.
4659 Fog node TransformScale was already updated by
4660 TAbstractBindableNode.BeforeTraverse.
4661 Renderer in TCastleScene will detect that TransformScale changed,
4662 and eventually destroy display lists and such when rendering next time. }
4663 if Inactive = 0 then
4664 ParentScene.VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4665 end;
4666 ntcViewpoint:
4667 begin
4668 if (Node = ParentScene.ViewpointStack.Top) and
4669 { See TAbstractBindableNode.BeforeTraverse comments for
4670 explanation why LastBeforeTraverseChangedTransform is important. }
4671 ParentScene.ViewpointStack.Top.InternalLastBeforeTraverseChangedTransform then
4672 ParentScene.DoBoundViewpointVectorsChanged;
4673
4674 { TODO: Transformation of viewpoint should also affect NavigationInfo,
4675 according to spec: "The speed, avatarSize and visibilityLimit values
4676 are all scaled by the transformation being applied to
4677 the currently bound X3DViewpointNode node."
4678 When this will be implemented, then also when transformation
4679 of viewpoint changes here we'll have to do something. }
4680 end;
4681 ntcLight: HandleLight(TAbstractLightNode(Node));
4682 ntcProximitySensor: HandleProximitySensor(TProximitySensorNode(Node));
4683 ntcVisibilitySensor: HandleVisibilitySensor(TVisibilitySensorNode(Node));
4684 {$ifndef COMPILER_CASE_ANALYSIS}
4685 else raise EInternalError.Create('HandleTransform: NodeTransformationChange?');
4686 {$endif}
4687 end;
4688 end;
4689
4690 procedure TCastleSceneCore.TransformationChanged(const TransformFunctionality: TTransformFunctionality);
4691 var
4692 TransformChangeHelper: TTransformChangeHelper;
4693 TransformShapesParentInfo: TShapesParentInfo;
4694 TraverseStack: TX3DGraphTraverseStateStack;
4695 C, I: Integer;
4696 TransformShapeTree: TShapeTreeTransform;
4697 DoVisibleChanged: boolean;
4698 TransformNode: TX3DNode;
4699 begin
4700 TransformNode := TransformFunctionality.Parent;
4701
4702 { This is the optimization for changing VRML >= 2.0 transformation
4703 (most fields of Transform node like translation, scale, center etc.,
4704 also some HAnim nodes like Joint and Humanoid have this behavior.).
4705
4706 In the simple cases, Transform node simply changes
4707 TX3DGraphTraverseState.Transform for children nodes.
4708
4709 So we have to re-traverse from this Transform node, and change
4710 states of affected children. Our TransformNodesInfo gives us
4711 a list of TShapeTreeTransform corresponding to this transform node,
4712 so we know we can traverse from this point.
4713
4714 In some cases, children of this Transform node may
4715 be affected in other ways by transformation. For example,
4716 Fog and Background nodes are affected by their parents transform.
4717 }
4718
4719 Assert(not OptimizeExtensiveTransformations);
4720
4721 C := TShapeTree.AssociatedShapesCount(TransformNode);
4722
4723 if LogChanges then
4724 WritelnLog('X3D changes', Format('Transform node %s change: present %d times in the scene graph',
4725 [TransformNode.X3DType, C]));
4726
4727 DoVisibleChanged := false;
4728
4729 if InternalFastTransformUpdate then
4730 begin
4731 for I := 0 to C - 1 do
4732 TShapeTree.AssociatedShape(TransformNode, I).FastTransformUpdate(DoVisibleChanged);
4733 if DoVisibleChanged then
4734 Validities := Validities - [fvLocalBoundingBox];
4735 end else
4736 begin
4737 TraverseStack := nil;
4738 TransformChangeHelper := nil;
4739 try
4740 TraverseStack := TX3DGraphTraverseStateStack.Create;
4741
4742 { initialize TransformChangeHelper, set before the loop properties
4743 that cannot change }
4744 TransformChangeHelper := TTransformChangeHelper.Create;
4745 TransformChangeHelper.ParentScene := Self;
4746 TransformChangeHelper.ChangingNode := TransformNode;
4747
4748 for I := 0 to C - 1 do
4749 begin
4750 TransformShapeTree := TShapeTree.AssociatedShape(TransformNode, I) as TShapeTreeTransform;
4751 TraverseStack.Clear;
4752 TraverseStack.Push(TransformShapeTree.TransformState);
4753
4754 TransformShapesParentInfo.Group := TransformShapeTree;
4755 TransformShapesParentInfo.Index := 0;
4756
4757 { initialize TransformChangeHelper properties that may be changed
4758 during Node.Traverse later }
4759 TransformChangeHelper.Shapes := @TransformShapesParentInfo;
4760 TransformChangeHelper.AnythingChanged := false;
4761 TransformChangeHelper.Inside := false;
4762 TransformChangeHelper.Inactive := 0;
4763
4764 TransformNode.TraverseInternal(TraverseStack, TX3DNode,
4765 {$ifdef FPC}@{$endif}TransformChangeHelper.TransformChangeTraverse,
4766 nil);
4767
4768 if TransformChangeHelper.AnythingChanged then
4769 DoVisibleChanged := true;
4770
4771 { take care of calling THAnimHumanoidNode.AnimateSkin when joint is
4772 animated. Secure from Humanoid = nil (may happen if Joint
4773 is outside Humanoid node, see VRML 97 test
4774 ~/3dmodels/vrmlx3d/hanim/tecfa.unige.ch/vrml/objects/avatars/blaxxun/kambi_hanim_10_test.wrl) }
4775 if (TransformNode is THAnimJointNode) and
4776 (TransformShapeTree.TransformState.Humanoid <> nil) then
4777 ScheduledHumanoidAnimateSkin.AddIfNotExists(
4778 TransformShapeTree.TransformState.Humanoid);
4779 end;
4780 finally
4781 FreeAndNil(TraverseStack);
4782 FreeAndNil(TransformChangeHelper);
4783 end;
4784 end;
4785
4786 if DoVisibleChanged then
4787 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4788 end;
4789
4790 procedure TCastleSceneCore.RootTransformationChanged;
4791 var
4792 TransformChangeHelper: TTransformChangeHelper;
4793 TransformShapesParentInfo: TShapesParentInfo;
4794 TraverseStack: TX3DGraphTraverseStateStack;
4795 DoVisibleChanged: boolean;
4796 begin
4797 if LogChanges then
4798 WritelnLog('X3D changes', 'Transform root node change');
4799
4800 if RootNode = nil then Exit;
4801 if not (Shapes is TShapeTreeGroup) then
4802 begin
4803 WritelnWarning('X3D changes', 'Root node did not create corresponding TShapeTreeGroup, transformation will not be applied correctly. Submit a bug');
4804 Exit;
4805 end;
4806
4807 DoVisibleChanged := false;
4808
4809 if InternalFastTransformUpdate then
4810 begin
4811 Shapes.FastTransformUpdate(DoVisibleChanged);
4812 { Manually adjust Validities, because FastTransformUpdate doesn't call DoGeometryChanged.
4813
4814 TODO: If uncommenting Changed(false, [chTransform]) in TShape.FastTransformUpdateCore,
4815 it should call DoGeometryChanged, but it still doesn't? Why?
4816 In any case, it doesn't matter, it's faster to fix Validities manually below. }
4817 if DoVisibleChanged then
4818 Validities := Validities - [fvLocalBoundingBox];
4819 end else
4820 begin
4821 TraverseStack := nil;
4822 TransformChangeHelper := nil;
4823 try
4824 TraverseStack := TX3DGraphTraverseStateStack.Create;
4825
4826 { initialize TransformChangeHelper, set before the loop properties
4827 that cannot change }
4828 TransformChangeHelper := TTransformChangeHelper.Create;
4829 TransformChangeHelper.ParentScene := Self;
4830 TransformChangeHelper.ChangingNode := RootNode;
4831
4832 if not
4833 ( (Shapes is TShapeTreeGroup) and
4834 (TShapeTreeGroup(Shapes).Children.Count = 1) and
4835 (TShapeTreeGroup(Shapes).Children[0] is TShapeTreeTransform) and
4836 (TShapeTreeTransform(TShapeTreeGroup(Shapes).Children[0]).TransformFunctionality <> nil) and
4837 (TShapeTreeTransform(TShapeTreeGroup(Shapes).Children[0]).TransformNode = RootNode) ) then
4838 begin
4839 raise EInternalError.Create('Scene Shapes should be TShapeTreeGroup with TShapeTreeTransform representing RootNode');
4840 end;
4841
4842 { The logic in HandleTransform in TTransformChangeHelper.TransformChangeTraverse,
4843 when Node = ChangingNode, assumes that TransformShapesParentInfo.Group
4844 given here matches the *inside* of the node that is changing,
4845 which is RootNode in this case.
4846 So we don't set "TransformShapesParentInfo.Group := Shapes",
4847 we go inside. }
4848
4849 TransformShapesParentInfo.Group := TShapeTreeGroup(Shapes).Children[0] as TShapeTreeGroup;
4850 TransformShapesParentInfo.Index := 0;
4851
4852 { initialize TransformChangeHelper properties that may be changed
4853 during Node.Traverse later }
4854 TransformChangeHelper.Shapes := @TransformShapesParentInfo;
4855 TransformChangeHelper.AnythingChanged := false;
4856 TransformChangeHelper.Inside := false;
4857 TransformChangeHelper.Inactive := 0;
4858
4859 RootNode.Traverse(TX3DNode,
4860 {$ifdef FPC}@{$endif}TransformChangeHelper.TransformChangeTraverse);
4861
4862 if TransformChangeHelper.AnythingChanged then
4863 DoVisibleChanged := true;
4864
4865 { take care of calling THAnimHumanoidNode.AnimateSkin when joint is
4866 animated. Secure from Humanoid = nil (may happen if Joint
4867 is outside Humanoid node, see VRML 97 test
4868 ~/3dmodels/vrmlx3d/hanim/tecfa.unige.ch/vrml/objects/avatars/blaxxun/kambi_hanim_10_test.wrl) }
4869 { TODO:
4870 if (RootNode is THAnimJointNode) and
4871 (TransformShapeTree.TransformState.Humanoid <> nil) then
4872 ScheduledHumanoidAnimateSkin.AddIfNotExists(
4873 TransformShapeTree.TransformState.Humanoid);
4874 }
4875 finally
4876 FreeAndNil(TraverseStack);
4877 FreeAndNil(TransformChangeHelper);
4878 end;
4879 end;
4880
4881 if DoVisibleChanged then
4882 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4883 end;
4884
4885 procedure TCastleSceneCore.InternalChangedField(const Field: TX3DField; const Change: TX3DChange);
4886 var
4887 ANode: TX3DNode;
4888
4889 procedure DoLogChanges(const Additional: String = '');
4890 var
4891 S: String;
4892 begin
4893 S := 'InternalChangedField: ' + X3DChangeToStr[Change] +
4894 Format(', node: %s (%s %s) at %s',
4895 [ ANode.X3DName, ANode.X3DType, ANode.ClassName, PointerToStr(ANode) ]);
4896 if Field <> nil then
4897 S := S + Format(', field %s (%s)', [ Field.X3DName, Field.X3DType ]);
4898 if Additional <> '' then
4899 S := S + '. ' + Additional;
4900 WritelnLog('X3D change', S);
4901 end;
4902
4903 { Handle VRML >= 2.0 transformation changes (node with TTransformFunctionality). }
4904 procedure HandleChangeTransform;
4905 begin
4906 if OptimizeExtensiveTransformations then
4907 begin
4908 TransformationDirty := true
4909 end else
4910 begin
4911 Check(ANode.TransformFunctionality <> nil, 'chTransform flag may be set only for node with TTransformFunctionality');
4912 TransformationChanged(ANode.TransformFunctionality);
4913 end;
4914
4915 if not ProcessEvents then
4916 { Otherwise FinishTransformationChanges would not be called in nearest Update,
4917 leaving transformation effects unapplied to the Shapes tree. }
4918 FinishTransformationChanges;
4919 end;
4920
4921 procedure HandleChangeCoordinate;
4922 var
4923 C, I: Integer;
4924 begin
4925 { TCoordinateNode is special, although it's part of VRML 1.0 state,
4926 it can also occur within coordinate-based nodes of VRML >= 2.0.
4927 So it affects coordinate-based nodes with this node.
4928
4929 In fact, code below takes into account both VRML 1.0 and 2.0 situation.
4930 That's why chCoordinate should not be used with chVisibleVRML1State
4931 --- chVisibleVRML1State handling is not needed after this. }
4932
4933 { Note that both shape's OriginalGeometry, and actualy Geometry,
4934 have associated shapes.
4935 This is good, as a change to OriginalGeometry.Coord should also be handled,
4936 since it may cause FreeProxy for shape. This is necessary
4937 for animation of NURBS controlPoint to work. }
4938
4939 C := TShapeTree.AssociatedShapesCount(ANode);
4940 if C <> 0 then
4941 begin
4942 for I := 0 to C - 1 do
4943 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
4944 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4945 end;
4946 end;
4947
4948 procedure HandleChangeNormalTangent;
4949 var
4950 C, I: Integer;
4951 begin
4952 { Similar to chCoordinate, this takes into account both VRML 1.0 and VRML 2.0/X3D.
4953 So performing chVisibleVRML1State after this is not necessary. }
4954 C := TShapeTree.AssociatedShapesCount(ANode);
4955 if C <> 0 then
4956 begin
4957 for I := 0 to C - 1 do
4958 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
4959 VisibleChangeHere([vcVisibleNonGeometry]);
4960 end;
4961 end;
4962
4963 { Good for both chVisibleVRML1State and chGeometryVRML1State
4964 (TShape.Changed actually cares about the difference between these two.) }
4965 procedure HandleVRML1State;
4966 var
4967 VRML1StateNode: TVRML1StateNode;
4968 ShapeList: TShapeList;
4969 Shape: TShape;
4970 begin
4971 if ANode.VRML1StateNode(VRML1StateNode) then
4972 begin
4973 { ANode is part of VRML 1.0 state, so it affects Shapes where
4974 it's present on State.VRML1State list. }
4975 ShapeList := Shapes.TraverseList(false);
4976 for Shape in ShapeList do
4977 if (Shape.State.VRML1State.Nodes[VRML1StateNode] = ANode) or
4978 (Shape.OriginalState.VRML1State.Nodes[VRML1StateNode] = ANode) then
4979 Shape.Changed(false, [Change]);
4980 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
4981 end;
4982 end;
4983
4984 procedure HandleChangeLightInstanceProperty;
4985 var
4986 J: integer;
4987 ShapeList: TShapeList;
4988 Shape: TShape;
4989 LightInstance: PLightInstance;
4990 LightNode: TAbstractLightNode;
4991 begin
4992 // TODO: Optimize using TShapeTree.AssociatedShape
4993
4994 LightNode := ANode as TAbstractLightNode;
4995
4996 { Update all TLightInstance records with LightNode = this ANode.
4997
4998 TODO: what if some TX3DGraphTraverseState.Lights need to be updated?
4999 Code below fails for this.
5000
5001 To be fixed (at the same time taking into account that in X3D
5002 "global" is exposed field and so may change during execution) by
5003 constructing TX3DGraphTraverseState.Lights always with global = TRUE assumption.
5004 RenderShapeLights will have to take care of eventual "radius"
5005 constraints. Or not --- this will hurt performance, global = FALSE
5006 is a good optimization for local lights, we don't want long lights list. }
5007
5008 ShapeList := Shapes.TraverseList(false);
5009 for Shape in ShapeList do
5010 if Shape.State.Lights <> nil then
5011 for J := 0 to Shape.State.Lights.Count - 1 do
5012 begin
5013 LightInstance := PLightInstance(Shape.State.Lights.Ptr(J));
5014 if LightInstance^.Node = LightNode then
5015 begin
5016 LightNode.UpdateLightInstance(LightInstance^);
5017 VisibleChangeHere([vcVisibleNonGeometry]);
5018 end;
5019 end;
5020
5021 GeneratedTextures.UpdateShadowMaps(LightNode);
5022 end;
5023
5024 procedure HandleChangeLightForShadowVolumes;
5025 begin
5026 { When some shadowVolumes or shadowVolumesMain field changes,
5027 then MainLightForShadows must be recalculated. }
5028 Exclude(Validities, fvMainLightForShadows);
5029 VisibleChangeHere([vcVisibleNonGeometry]);
5030 end;
5031
5032 procedure HandleChangeLightLocationDirection;
5033 var
5034 L: PLightInstance;
5035 I: Integer;
5036 begin
5037 { If we had calculated MainLightForShadows, and this ANode is the
5038 main light for shadows, then update FMainLightForShadows.
5039 Thanks to varius FMainLightForShadows* properties, we can check
5040 and recalculate it very fast --- this is good for scenes where main
5041 shadow light location is moving. }
5042
5043 if (fvMainLightForShadows in Validities) and
5044 FMainLightForShadowsExists and
5045 (FMainLightForShadowsNode = ANode) then
5046 begin
5047 CalculateMainLightForShadowsPosition;
5048 VisibleChangeHere([vcVisibleNonGeometry]);
5049 end;
5050
5051 { Change light instance on GlobalLights list, if any.
5052 This way other scenes, using our lights by
5053 @link(TCastleScene.CastGlobalLights) feature,
5054 also have updated light location/direction.
5055 See https://sourceforge.net/p/castle-engine/discussion/general/thread/0bbaaf38/
5056 for a testcase. }
5057 for I := 0 to InternalGlobalLights.Count - 1 do
5058 begin
5059 L := PLightInstance(InternalGlobalLights.Ptr(I));
5060 if L^.Node = ANode then
5061 L^.Node.UpdateLightInstance(L^);
5062 end;
5063
5064 { changing Location/Direction implies also changing "any light source property" }
5065 HandleChangeLightInstanceProperty;
5066 end;
5067
5068 procedure HandleChangeSwitch2;
5069 begin
5070 { Changing Switch.whichChoice changes the shapes that are considered
5071 active (in VRML/X3D graph, and in Shapes tree).
5072 This means that things calculated based
5073 on traverse/iterator over Shapes with "OnlyActive = true"
5074 are invalid now.
5075
5076 DoGeometryChanged (scheduled by ScheduleGeometryChanged)
5077 actually does most of this work, it invalidates already most
5078 of the needed things when ScheduledGeometryActiveShapesChanged:
5079
5080 fvLocalBoundingBox,
5081 fvVerticesCount,
5082 fvTrianglesCount
5083 }
5084
5085 Validities := Validities - [
5086 { Calculation traverses over active shapes. }
5087 fvShapesActiveCount,
5088 fvShapesActiveVisibleCount,
5089 { Calculation traverses over active nodes (uses RootNode.Traverse). }
5090 fvMainLightForShadows];
5091
5092 DoGeometryChanged(gcActiveShapesChanged, nil);
5093
5094 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
5095
5096 InternalIncShapesHash; // TShapeTreeSwitch returns now different things
5097 end;
5098
5099 procedure HandleChangeColorNode;
5100 var
5101 C, I: Integer;
5102 begin
5103 { Affects all geometry nodes with "color" field referencing this node.
5104
5105 Note: also TParticleSystemNode may have color in FdcolorRamp field.
5106 This is not detected for now, and doesn't matter (we do not handle
5107 particle systems at all now). }
5108
5109 C := TShapeTree.AssociatedShapesCount(ANode);
5110 if C <> 0 then
5111 begin
5112 for I := 0 to C - 1 do
5113 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5114 end;
5115 end;
5116
5117 procedure HandleChangeTextureCoordinate;
5118 var
5119 C, I: Integer;
5120 begin
5121 C := TShapeTree.AssociatedShapesCount(ANode);
5122 for I := 0 to C - 1 do
5123 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5124 end;
5125
5126 procedure HandleChangeTextureTransform;
5127
5128 { If Appearance.TextureTransform contains TextureTransform
5129 (which should be some TextureTransform* VRML/X3D node,
5130 but not nil and not TMultiTextureTransformNode). }
5131 function AppearanceUsesTextureTransform(Appearance: TAppearanceNode;
5132 TextureTransform: TX3DNode): boolean;
5133 var
5134 MultiTrans: TMFNode;
5135 I: Integer;
5136 begin
5137 Result := Appearance.FdTextureTransform.Value = TextureTransform;
5138 if (not Result) and
5139 (Appearance.FdTextureTransform.Value <> nil) and
5140 (Appearance.FdTextureTransform.Value is TMultiTextureTransformNode) then
5141 begin
5142 MultiTrans := TMultiTextureTransformNode(
5143 Appearance.FdTextureTransform.Value).FdTextureTransform;
5144 for I := 0 to MultiTrans.Count - 1 do
5145 if MultiTrans[I] = TextureTransform then
5146 Exit(true);
5147 end;
5148 end;
5149
5150 var
5151 ShapeList: TShapeList;
5152 Shape: TShape;
5153 begin
5154 // TODO: Optimize and simplify to use TShapeTree.AssociatedShape
5155
5156 { VRML 2.0 / X3D TextureTransform* affects only shapes where it's
5157 placed inside textureTransform field. }
5158 ShapeList := Shapes.TraverseList(false);
5159 for Shape in ShapeList do
5160 if (Shape.State.ShapeNode <> nil) and
5161 (Shape.State.ShapeNode.FdAppearance.Value <> nil) and
5162 (Shape.State.ShapeNode.FdAppearance.Value is TAppearanceNode) and
5163 AppearanceUsesTextureTransform(
5164 TAppearanceNode(Shape.State.ShapeNode.FdAppearance.Value), ANode) then
5165 Shape.Changed(false, [Change]);
5166 end;
5167
5168 procedure HandleChangeGeometry;
5169 var
5170 C, I: Integer;
5171 begin
5172 C := TShapeTree.AssociatedShapesCount(ANode);
5173 for I := 0 to C - 1 do
5174 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5175 end;
5176
5177 procedure HandleChangeEnvironmentalSensorBounds;
5178 var
5179 I: Integer;
5180 VSInstances: TVisibilitySensorInstanceList;
5181 VS: TVisibilitySensorNode;
5182 CameraVectors: TViewVectors;
5183 begin
5184 if ANode is TProximitySensorNode then
5185 begin
5186 { Update state for this ProximitySensor node. }
5187 if GetCameraLocal(CameraVectors) then
5188 for I := 0 to ProximitySensors.Count - 1 do
5189 begin
5190 if ProximitySensors[I].Node = ANode then
5191 ProximitySensorUpdate(ProximitySensors[I], CameraVectors);
5192 end;
5193 end else
5194 if ANode is TVisibilitySensorNode then
5195 begin
5196 VS := TVisibilitySensorNode(ANode);
5197 { local Box of this node changed,
5198 so update transformed Box in all TVisibilitySensorInstance for this node }
5199 if VisibilitySensors.TryGetValue(VS, VSInstances) then
5200 begin
5201 for I := 0 to VSInstances.Count - 1 do
5202 VSInstances[I].Box := VS.Box.Transform(VSInstances[I].Transform);
5203 end;
5204 end;
5205 end;
5206
5207 procedure HandleChangeTimeStopStart;
5208 begin
5209 if ANode.TimeFunctionality = nil then Exit; {< ANode not time-dependent. }
5210
5211 { Why do we want to call TimeFunctionality.SetTime now?
5212
5213 Although (de)activation of time-dependent nodes will be also caught
5214 by the nearest IncreaseTime run, it's good to explicitly
5215 call SetTime to catch it here.
5216
5217 Reason: if cycleInterval is very small, and not looping, then
5218 we could "miss" the fact that node should be activated (if it
5219 was inactive, and next IncreaseTime will happen after
5220 cycleInterval time already passed).
5221
5222 Code below will make sure that no matter how small cycleInterval,
5223 no matter how seldom IncreaseTime occur, the node will get
5224 activated when doing something like startTime := Time.
5225
5226 Note that we don't reset time here (ResetTime = false), otherwise
5227 we would mistakenly interpret resuming (from paused state) just like
5228 activation (from stopped state), testcase time_sensor_3.x3dv. }
5229
5230 ANode.TimeFunctionality.SetTime(Time, 0, false);
5231
5232 { No need to do VisibleChangeHere.
5233 Redisplay will be done by next IncreaseTime run, if active now. }
5234 end;
5235
5236 procedure HandleChangeViewpointVectors;
5237 begin
5238 if ANode = ViewpointStack.Top then
5239 DoBoundViewpointVectorsChanged;
5240 { Nothing needs to be done if
5241 - non-bound viewpoint changed,
5242 - or a field of bound viewpoint that doesn't affect it's vectors. }
5243 end;
5244
5245 { Handle chTextureImage, chTextureRendererProperties }
5246 procedure HandleChangeTextureImageOrRenderer(const ANode: TX3DNode; const Change: TX3DChange);
5247 var
5248 ShapeList: TShapeList;
5249 Shape: TShape;
5250 begin
5251 // TODO: Optimize using TShapeTree.AssociatedShape
5252 if Change = chTextureImage then
5253 begin
5254 { On change of TAbstractTexture2DNode field that changes the result of
5255 TAbstractTexture2DNode.LoadTextureData, we have to explicitly release
5256 old texture (otherwise, LoadTextureData will not be called
5257 to reload the texture). }
5258 if ANode is TAbstractTexture2DNode then
5259 TAbstractTexture2DNode(ANode).IsTextureLoaded := false;
5260 if ANode is TAbstractTexture3DNode then
5261 TAbstractTexture3DNode(ANode).TextureLoaded := false;
5262 end;
5263
5264 ShapeList := Shapes.TraverseList(false);
5265 for Shape in ShapeList do
5266 begin
5267 if Shape.UsesTexture(TAbstractTextureNode(ANode)) then
5268 Shape.Changed(false, [Change]);
5269 end;
5270 end;
5271
5272 { React to change of TTexturePropertiesNode fields.
5273
5274 Testcase that this is needed: create new TCastleImageTransform
5275 and change TCastleImageTransform.RepeatImage between (0.1, 0.1) and (10, 10),
5276 effectively changing the TextureProperties.BoundaryModeS/T under the hood between
5277 clamp and repeat. }
5278 procedure HandleChangeTextureProperties;
5279 var
5280 ParentField: TX3DField;
5281 TextureNode: TX3DNode;
5282 I: Integer;
5283 begin
5284 Assert(ANode is TTexturePropertiesNode, 'Only TTexturePropertiesNode should send chTexturePropertiesNode');
5285 for I := 0 to ANode.ParentFieldsCount - 1 do
5286 begin
5287 ParentField := ANode.ParentFields[I];
5288 if not (ParentField is TSFNode) then
5289 begin
5290 WritelnWarning('TTexturePropertiesNode change', 'ParentField is not TSFNode. This should not happen in normal usage of TTexturePropertiesNode, submit a bug');
5291 Continue;
5292 end;
5293
5294 TextureNode := TSFNode(ParentField).ParentNode;
5295 if TextureNode = nil then
5296 begin
5297 WritelnWarning('TTexturePropertiesNode change', 'ParentField.Node is nil. This should not happen in usual usage of TCastleScene, submit a bug');
5298 Continue;
5299 end;
5300
5301 { Make the same effect as when texture node's repeatS/T/R field changes }
5302 HandleChangeTextureImageOrRenderer(TextureNode, chTextureRendererProperties);
5303 end;
5304 end;
5305
5306 procedure HandleChangeShadowCasters;
5307 begin
5308 { When Appearance.shadowCaster field changed, then
5309 TrianglesListShadowCasters and Manifold/BorderEdges changed in shapes. }
5310 FreeResources([frShadowVolume]);
5311 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
5312 end;
5313
5314 procedure HandleChangeGeneratedTextureUpdateNeeded;
5315 var
5316 GenTexFunctionality: TGeneratedTextureFunctionality;
5317 begin
5318 GenTexFunctionality := ANode.GenTexFunctionality;
5319 if GenTexFunctionality = nil then
5320 Exit;
5321 GenTexFunctionality.InternalUpdateNeeded := true;
5322 VisibleChangeHere([]);
5323 end;
5324
5325 procedure HandleFontStyle;
5326 (* Naive version to seek all shapes. Left only for educational purposes.
5327 var
5328 ShapeList: TShapeList;
5329 Shape: TShape;
5330 begin
5331 ShapeList := Shapes.TraverseList({ OnlyActive } false);
5332 for Shape in ShapeList do
5333 if (Shape.OriginalGeometry is TTextNode) and
5334 (TTextNode(Shape.OriginalGeometry).FontStyle = ANode) then
5335 Shape.Changed(false, [Change]);
5336 end;
5337 *)
5338 var
5339 ParentField: TX3DField;
5340 TextNode: TX3DNode;
5341 C, I, J: Integer;
5342 begin
5343 { ANode is TFontStyleNode, child of (maybe many) TTextNodes.
5344 For each TTextNode, we want to call Changed on all TShape instances associated it.
5345 This accounts for various complicated X3D setups:
5346 TFontStyleNode may be referenced multiple times,
5347 TTextNode may be referenced multiple times. }
5348
5349 Assert(ANode is TFontStyleNode, 'Only TFontStyleNode should send chFontStyle');
5350 for I := 0 to ANode.ParentFieldsCount - 1 do
5351 begin
5352 ParentField := ANode.ParentFields[I];
5353 if not (ParentField is TSFNode) then
5354 begin
5355 WritelnWarning('TFontStyleNode change', 'ParentField is not TSFNode. This should not happen in normal usage of TFontStyleNode, submit a bug');
5356 Continue;
5357 end;
5358
5359 TextNode := TSFNode(ParentField).ParentNode;
5360 if TextNode = nil then
5361 begin
5362 WritelnWarning('TFontStyleNode change', 'ParentField.Node is nil. This should not happen in usual usage of TCastleScene, submit a bug');
5363 Continue;
5364 end;
5365 if not (TextNode is TTextNode) then
5366 begin
5367 WritelnWarning('TFontStyleNode change', 'ParentField.Node is not TTextNode. This should not happen in normal usage of TFontStyleNode, submit a bug');
5368 Continue;
5369 end;
5370
5371 C := TShapeTree.AssociatedShapesCount(TextNode);
5372 for J := 0 to C - 1 do
5373 TShape(TShapeTree.AssociatedShape(TextNode, J)).Changed(false, [Change]);
5374 end;
5375 end;
5376
5377 procedure HandleChangeHeadLightOn;
5378 begin
5379 { Recalculate HeadlightOn based on NavigationInfo.headlight. }
5380 UpdateHeadlightOnFromNavigationInfo;
5381 VisibleChangeHere([]);
5382 end;
5383
5384 procedure HandleChangeClipPlane;
5385 var
5386 C, I: Integer;
5387 begin
5388 Assert(ANode is TClipPlaneNode);
5389
5390 C := TShapeTree.AssociatedShapesCount(ANode);
5391 if C <> 0 then
5392 begin
5393 for I := 0 to C - 1 do
5394 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5395 VisibleChangeHere([vcVisibleGeometry]);
5396 end;
5397 end;
5398
5399 procedure HandleChangeEverything(const OnlyAdditions: Boolean = false);
5400 begin
5401 { An arbitrary change occurred. }
5402 ScheduleChangedAll(OnlyAdditions);
5403 end;
5404
5405 { Handle Change in [chVisibleGeometry, chVisibleNonGeometry, chRedisplay] }
5406 procedure HandleVisibleChange;
5407 var
5408 VisibleChanges: TVisibleChanges;
5409 begin
5410 VisibleChanges := [];
5411 if Change = chVisibleGeometry then Include(VisibleChanges, vcVisibleGeometry);
5412 if Change = chVisibleNonGeometry then Include(VisibleChanges, vcVisibleNonGeometry);
5413 VisibleChangeHere(VisibleChanges);
5414 end;
5415
5416 procedure HandleChangeDragSensorEnabled;
5417 var
5418 Enabled: boolean;
5419 DragSensor: TAbstractDragSensorNode;
5420 begin
5421 Enabled := (Field as TSFBool).Value;
5422 DragSensor := ANode as TAbstractDragSensorNode;
5423
5424 { When we disable an active drag sensor, specification says to
5425 deactivate it. This cannot be handled fully by TAbstractDragSensorNode
5426 implementation, because we have to remove it from our property
5427 PointingDeviceActiveSensors. }
5428
5429 if (not Enabled) and (PointingDeviceActiveSensors.IndexOf(DragSensor) <> -1) then
5430 begin
5431 DragSensor.Deactivate(NextEventTime);
5432 FPointingDeviceActiveSensors.Remove(DragSensor);
5433 DoPointingDeviceSensorsChange;
5434 end;
5435 end;
5436
5437 procedure HandleChangeNavigationInfo;
5438 begin
5439 if ANode = NavigationInfoStack.Top then
5440 DoBoundNavigationInfoFieldsChanged;
5441 end;
5442
5443 procedure HandleChangeScreenEffectEnabled;
5444 begin
5445 (ANode as TScreenEffectNode).InternalRendererResourceFree;
5446 VisibleChangeHere([vcVisibleNonGeometry]);
5447 end;
5448
5449 procedure HandleChangeBackground;
5450 begin
5451 InternalInvalidateBackgroundRenderer;
5452 VisibleChangeHere([vcVisibleNonGeometry]);
5453 end;
5454
5455 procedure HandleChangeShadowMaps;
5456 begin
5457 if ShadowMaps then { if not ShadowMaps, then no need to reprocess }
5458 begin
5459 ScheduledShadowMapsProcessing := true;
5460 ScheduleChangedAll;
5461 end;
5462 end;
5463
5464 procedure HandleChangeWireframe;
5465 var
5466 C, I: Integer;
5467 begin
5468 C := TShapeTree.AssociatedShapesCount(ANode);
5469 if C <> 0 then
5470 begin
5471 for I := 0 to C - 1 do
5472 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5473 end;
5474 VisibleChangeHere([vcVisibleNonGeometry]);
5475 end;
5476
5477 procedure HandleChangeChildren(const OnlyAdditions: Boolean);
5478 begin
5479 HandleChangeEverything(OnlyAdditions);
5480 end;
5481
5482 procedure HandleChangeBBox;
5483 var
5484 C, I: Integer;
5485 begin
5486 C := TShapeTree.AssociatedShapesCount(ANode);
5487 if C <> 0 then
5488 begin
5489 for I := 0 to C - 1 do
5490 TShape(TShapeTree.AssociatedShape(ANode, I)).Changed(false, [Change]);
5491
5492 { Bounding box of the scene changed, and rendering octree changed,
5493 because bbox of shape changed.
5494 Testcase: knight.gltf (from examples/fps_game/ ) animations or
5495 lizardman.gltf (from demo-models/bump_mapping/ ) animations.
5496 We deliberately pass Shape=nil, to cause MaybeBoundingBoxChanged=true
5497 inside DoGeometryChanged. }
5498 DoGeometryChanged(gcLocalGeometryChanged, nil);
5499 end;
5500 end;
5501
5502 begin
5503 ANode := TX3DNode(Field.ParentNode);
5504 Assert(ANode <> nil);
5505
5506 { We used to check here RootNode.IsNodePresent(ANode), to eliminate
5507 changes to nodes not in our graph. This is not done now, because:
5508
5509 1. This check is not usually needed, and usually it wastes quite
5510 some time (for example, profile animate_3d_model_by_code_2 example).
5511
5512 In most cases, when modifying graph by code, and always when
5513 modifying graph by VRML/X3D events, the Node is known to be inside
5514 our VRML/X3D graph...
5515
5516 2. Also, there are nodes that affect our graph but are outside
5517 of it: VRML1DefaultState, and also all the nodes created
5518 by Proxy methods (geometry and new state nodes).
5519 }
5520
5521 if LogChanges then
5522 DoLogChanges;
5523
5524 { Optimize Change = chNone case: no need even for Begin/EndChangesSchedule }
5525 if Change = chNone then
5526 Exit;
5527
5528 BeginChangesSchedule;
5529 try
5530 case Change of
5531 chTransform: HandleChangeTransform;
5532 chCoordinate: HandleChangeCoordinate;
5533 chNormal, chTangent: HandleChangeNormalTangent;
5534 chVisibleVRML1State, chGeometryVRML1State: HandleVRML1State;
5535 chLightInstanceProperty: HandleChangeLightInstanceProperty;
5536 chLightForShadowVolumes: HandleChangeLightForShadowVolumes;
5537 chLightLocationDirection: HandleChangeLightLocationDirection;
5538 chSwitch2: HandleChangeSwitch2;
5539 chColorNode: HandleChangeColorNode;
5540 chTextureCoordinate: HandleChangeTextureCoordinate;
5541 chTextureTransform: HandleChangeTextureTransform;
5542 chGeometry, chGeometryFontChanged: HandleChangeGeometry;
5543 chEnvironmentalSensorBounds: HandleChangeEnvironmentalSensorBounds;
5544 chTimeStopStart: HandleChangeTimeStopStart;
5545 chViewpointVectors: HandleChangeViewpointVectors;
5546 // TODO: chViewpointProjection: HandleChangeViewpointProjection
5547 chTextureImage, chTextureRendererProperties: HandleChangeTextureImageOrRenderer(ANode, Change);
5548 chTexturePropertiesNode: HandleChangeTextureProperties;
5549 chShadowCasters: HandleChangeShadowCasters;
5550 chGeneratedTextureUpdateNeeded: HandleChangeGeneratedTextureUpdateNeeded;
5551 { The HandleFontStyle implementation matches
5552 both chFontStyle, chFontStyleFontChanged.
5553 Onlt the TShape.Changed processing handles
5554 chFontStyle, chFontStyleFontChanged differently. }
5555 chFontStyle, chFontStyleFontChanged: HandleFontStyle;
5556 chHeadLightOn: HandleChangeHeadLightOn;
5557 chClipPlane: HandleChangeClipPlane;
5558 chDragSensorEnabled: HandleChangeDragSensorEnabled;
5559 chNavigationInfo: HandleChangeNavigationInfo;
5560 chScreenEffectEnabled: HandleChangeScreenEffectEnabled;
5561 chBackground: HandleChangeBackground;
5562 chEverything: HandleChangeEverything;
5563 chShadowMaps: HandleChangeShadowMaps;
5564 chWireframe: HandleChangeWireframe;
5565 chGroupChildren, chGroupChildrenAdd: HandleChangeChildren(Change = chGroupChildrenAdd);
5566 chBBox: HandleChangeBBox;
5567 chVisibleGeometry, chVisibleNonGeometry, chRedisplay: HandleVisibleChange;
5568 else ;
5569 end;
5570 finally EndChangesSchedule end;
5571 end;
5572
5573 procedure TCastleSceneCore.DoGeometryChanged(const Change: TGeometryChange;
5574 LocalGeometryShape: TShape);
5575 var
5576 MaybeBoundingBoxChanged: boolean;
5577 const
5578 { Whether LocalGeometryChanged was called, which means that octree and/or
5579 bounding box/sphere of some shape changed. }
5580 SomeLocalGeometryChanged = [gcAll, gcLocalGeometryChanged, gcLocalGeometryChangedCoord];
5581 begin
5582 MaybeBoundingBoxChanged := not (
5583 { Box stayed the same if we changed shape geometry,
5584 but TShapeNode provides explicit bbox information,
5585 so this shape has still the same bbox.
5586 This is the case with glTF skinned animation. }
5587 (Change in [gcLocalGeometryChanged, gcLocalGeometryChangedCoord]) and
5588 (LocalGeometryShape <> nil) and
5589 (LocalGeometryShape.Node <> nil) and
5590 (not LocalGeometryShape.Node.BBox.IsEmpty)
5591 );
5592
5593 Validities := Validities - [
5594 fvVerticesCount,
5595 fvTrianglesCount
5596 ];
5597
5598 if MaybeBoundingBoxChanged then
5599 begin
5600 Validities := Validities - [fvLocalBoundingBox];
5601
5602 if (FOctreeRendering <> nil) and
5603 (Change in [gcVisibleTransformChanged, gcActiveShapesChanged] + SomeLocalGeometryChanged) then
5604 FreeAndNil(FOctreeRendering);
5605
5606 if (FOctreeDynamicCollisions <> nil) and
5607 (Change in [gcCollidableTransformChanged, gcActiveShapesChanged] + SomeLocalGeometryChanged) then
5608 begin
5609 FreeAndNil(FOctreeDynamicCollisions);
5610 // PointingDeviceClear; // do not free PTriangle records, the per-shape octrees remain valid. Testcase: Unholy clicking
5611 end;
5612 end;
5613
5614 if FOctreeStaticCollisions <> nil then
5615 begin
5616 WritelnWarning('ssStaticCollisions used on scene "' + Name + '" but the geometry changed. Freeing the spatial structure. You should use ssDynamicCollisions for this scene');
5617 FreeAndNil(FOctreeStaticCollisions);
5618 PointingDeviceClear; // remove any reference to (no longer valid) PTriangle records
5619 end;
5620
5621 if Assigned(OnGeometryChanged) then
5622 OnGeometryChanged(Self, Change in SomeLocalGeometryChanged,
5623 { We know LocalGeometryShape is nil now if Change does not contain
5624 gcLocalGeometryChanged*. }
5625 LocalGeometryShape);
5626 end;
5627
5628 procedure TCastleSceneCore.InternalMoveShapeAssociations(const OldNode, NewNode: TX3DNode; const ContainingShapes: TObject);
5629 var
5630 S: TShapeTree;
5631 L: TShapeTreeList;
5632 I: Integer;
5633 begin
5634 if (OldNode <> NewNode) and (ContainingShapes <> nil) then
5635 begin
5636 { For shapes on ContainingShapes, they should be removed from OldNode,
5637 and added to NewNode.
5638
5639 Otherwise we have no chance to clean them from OldNode, as change notification
5640 reaches TCastleSceneCore / TShapeTree after the old value changed into new. }
5641
5642 if ContainingShapes.ClassType = TShapeTreeList then
5643 begin
5644 // ContainingShapes is a list
5645 L := TShapeTreeList(ContainingShapes);
5646
5647 { Using downto just for future safety,
5648 in case S.UnAssociateNode would remove from L -- but it is not the case now,
5649 L is from containing node InternalSceneShape (e.g. from Appearance containing this Material,
5650 or Shape containing this Appearance), and its contents don't change during this loop. }
5651 for I := L.Count - 1 downto 0 do
5652 begin
5653 S := L[I];
5654 if OldNode <> nil then
5655 S.UnAssociateNode(OldNode);
5656 if NewNode <> nil then
5657 S.AssociateNode(NewNode);
5658 end;
5659 end else
5660 begin
5661 // ContainingShapes is a single TShapeTree
5662 S := TShapeTree(ContainingShapes);
5663 if OldNode <> nil then
5664 S.UnAssociateNode(OldNode);
5665 if NewNode <> nil then
5666 S.AssociateNode(NewNode);
5667 end;
5668 end;
5669 end;
5670
5671 procedure TCastleSceneCore.DoViewpointsChanged;
5672 begin
5673 if Assigned(OnViewpointsChanged) then
5674 OnViewpointsChanged(Self);
5675 end;
5676
5677 procedure TCastleSceneCore.DoBoundViewpointVectorsChanged;
5678 begin
5679 if Assigned(OnBoundViewpointVectorsChanged) then
5680 OnBoundViewpointVectorsChanged(Self);
5681 end;
5682
5683 procedure TCastleSceneCore.DoBoundNavigationInfoFieldsChanged;
5684 begin
5685 if Assigned(OnBoundNavigationInfoFieldsChanged) then
5686 OnBoundNavigationInfoFieldsChanged(Self);
5687 end;
5688
5689 function TCastleSceneCore.InfoTriangleVerticesCounts: String;
5690 begin
5691 Result := Format('Scene contains %d triangles and %d vertices.',
5692 [TrianglesCount, VerticesCount]) + NL;
5693 end;
5694
5695 function TCastleSceneCore.InfoBoundingBox: String;
5696 var
5697 BBox: TBox3D;
5698 begin
5699 BBox := BoundingBox;
5700 Result := 'Bounding box : ' + BBox.ToString;
5701 if not BBox.IsEmpty then
5702 begin
5703 Result := Result + Format(', average size : %f', [BBox.AverageSize]);
5704 end;
5705 Result := Result + NL;
5706 end;
5707
5708 procedure TCastleSceneCore.EdgesCount(out ManifoldEdges, BorderEdges: Cardinal);
5709 var
5710 ShapeList: TShapeList;
5711 Shape: TShape;
5712 begin
5713 ManifoldEdges := 0;
5714 BorderEdges := 0;
5715 ShapeList := Shapes.TraverseList(true);
5716 for Shape in ShapeList do
5717 begin
5718 ManifoldEdges := ManifoldEdges + Shape.InternalShadowVolumes.ManifoldEdges.Count;
5719 BorderEdges := BorderEdges + Shape.InternalShadowVolumes.BorderEdges.Count;
5720 end;
5721 end;
5722
5723 function TCastleSceneCore.InfoManifoldAndBorderEdges: String;
5724 var
5725 ManifoldEdges, BorderEdges: Cardinal;
5726 begin
5727 EdgesCount(ManifoldEdges, BorderEdges);
5728 Result := Format('Edges detection: all edges split into %d manifold edges and %d border edges. Remember that for shadow volumes, only the shapes that are perfect manifold (have zero border edges) can cast shadows.',
5729 [ManifoldEdges, BorderEdges]) + NL;
5730 end;
5731
5732 function TCastleSceneCore.Info(
5733 ATriangleVerticesCounts,
5734 ABoundingBox,
5735 AManifoldAndBorderEdges: boolean): String;
5736 begin
5737 Result := '';
5738
5739 if ATriangleVerticesCounts then
5740 begin
5741 {$warnings off}
5742 { deliberately using deprecated function in another deprecated function }
5743 Result := Result + InfoTriangleVerticesCounts;
5744 {$warnings on}
5745 end;
5746
5747 if ABoundingBox then
5748 begin
5749 if Result <> '' then Result := Result + NL;
5750 {$warnings off}
5751 { deliberately using deprecated function in another deprecated function }
5752 Result := Result + InfoBoundingBox;
5753 {$warnings on}
5754 end;
5755
5756 if AManifoldAndBorderEdges then
5757 begin
5758 if Result <> '' then Result := Result + NL;
5759 {$warnings off}
5760 { deliberately using deprecated function in another deprecated function }
5761 Result := Result + InfoManifoldAndBorderEdges;
5762 {$warnings on}
5763 end;
5764 end;
5765
5766 { octrees -------------------------------------------------------------------- }
5767
5768 function TCastleSceneCore.TriangleOctreeLimits: POctreeLimits;
5769 begin
5770 Result := @FTriangleOctreeLimits;
5771 end;
5772
5773 function TCastleSceneCore.ShapeOctreeLimits: POctreeLimits;
5774 begin
5775 Result := @FShapeOctreeLimits;
5776 end;
5777
5778 procedure TCastleSceneCore.SetSpatial(const Value: TSceneSpatialStructures);
5779
5780 procedure SetShapeSpatial(const Value: TShapeSpatialStructures;
5781 OnlyCollidable: boolean);
5782 var
5783 ShapeList: TShapeList;
5784 Shape: TShape;
5785 begin
5786 ShapeList := Shapes.TraverseList(false);
5787 for Shape in ShapeList do
5788 { When Value <> [], we honor OnlyCollidable. }
5789 if (Value = []) or
5790 (not OnlyCollidable) or
5791 (Shape.Collidable) then
5792 begin
5793 { Note: do not change here
5794 Shape.TriangleOctreeLimits :=
5795 Our own TriangleOctreeLimits properties may be *not* suitable
5796 for this (as our properties are for global octrees).
5797 Just let programmer change per-shape properties if (s)he wants. }
5798
5799 Shape.InternalSpatial := Value;
5800 end;
5801 end;
5802
5803 var
5804 Old, New: Boolean;
5805 TimeStart: TCastleProfilerTime;
5806 begin
5807 if Value <> FSpatial then
5808 begin
5809 if ( (Value <> []) and
5810 (Value <> [ssRendering, ssDynamicCollisions]) and
5811 (Value <> [ssDynamicCollisions])
5812 ) then
5813 WritelnWarning('%s: Spatial values different than [], [ssRendering,ssDynamicCollisions], [ssDynamicCollisions] may not be allowed in future engine versions. We advise to use TCastleScene.PreciseCollisions instead of TCastleScene.Spatial.', [
5814 Name
5815 ]);
5816
5817 { Handle OctreeRendering }
5818
5819 Old := ssRendering in FSpatial;
5820 New := ssRendering in Value;
5821
5822 if Old and not New then
5823 FreeAndNil(FOctreeRendering);
5824
5825 { Handle OctreeDynamicCollisions and Shapes[I].Spatial }
5826
5827 Old := ssDynamicCollisions in FSpatial;
5828 New := ssDynamicCollisions in Value;
5829
5830 if Old and not New then
5831 begin
5832 FreeAndNil(FOctreeDynamicCollisions);
5833 // PointingDeviceClear; // do not free PTriangle records, the per-shape octrees remain valid. Testcase: Unholy clicking
5834 SetShapeSpatial([], true);
5835 end else
5836 if New and not Old then
5837 begin
5838 TimeStart := Profiler.Start('Creating octrees for all shapes from Scene.Spatial := [...]');
5839 try
5840 { SetShapeSpatial cannot be done by the way of doing CreateShapeOctree,
5841 since in CreateShapeOctree we iterate over OnlyActive shapes,
5842 but SetShapeSpatial must iterate over all shapes. }
5843 SetShapeSpatial([ssTriangles], true);
5844 finally
5845 Profiler.Stop(TimeStart, true, true);
5846 end;
5847 end;
5848
5849 { Handle OctreeVisibleTriangles }
5850
5851 Old := ssVisibleTriangles in FSpatial;
5852 New := ssVisibleTriangles in Value;
5853
5854 if Old and not New then
5855 FreeAndNil(FOctreeVisibleTriangles);
5856
5857 { Handle OctreeStaticCollisions }
5858
5859 Old := ssStaticCollisions in FSpatial;
5860 New := ssStaticCollisions in Value;
5861
5862 if Old and not New then
5863 begin
5864 FreeAndNil(FOctreeStaticCollisions);
5865 PointingDeviceClear; // remove any reference to (no longer valid) PTriangle records
5866 end;
5867
5868 FSpatial := Value;
5869 end;
5870 end;
5871
5872 function TCastleSceneCore.GetPreciseCollisions: Boolean;
5873 begin
5874 {$warnings off} // this uses deprecated Spatial, which should be Internal at some point
5875 Result := Spatial <> [];
5876 {$warnings on}
5877 end;
5878
5879 procedure TCastleSceneCore.SetPreciseCollisions(const Value: Boolean);
5880 begin
5881 {$warnings off} // this uses deprecated Spatial, which should be Internal at some point
5882 if Value then
5883 Spatial := [ssRendering, ssDynamicCollisions]
5884 else
5885 Spatial := [];
5886 {$warnings on}
5887 end;
5888
5889 function TCastleSceneCore.InternalOctreeRendering: TShapeOctree;
5890 begin
5891 if (ssRendering in FSpatial) and (FOctreeRendering = nil) then
5892 begin
5893 FOctreeRendering := CreateShapeOctree(
5894 FShapeOctreeLimits,
5895 false);
5896 if LogChanges then
5897 WritelnLog('X3D changes (octree)', 'OctreeRendering updated');
5898 end;
5899
5900 Result := FOctreeRendering;
5901 end;
5902
5903 function TCastleSceneCore.InternalOctreeDynamicCollisions: TShapeOctree;
5904 begin
5905 if (ssDynamicCollisions in FSpatial) and (FOctreeDynamicCollisions = nil) then
5906 begin
5907 FOctreeDynamicCollisions := CreateShapeOctree(
5908 FShapeOctreeLimits,
5909 true);
5910 if LogChanges then
5911 WritelnLog('X3D changes (octree)', 'OctreeDynamicCollisions updated');
5912 end;
5913
5914 Result := FOctreeDynamicCollisions;
5915 end;
5916
5917 function TCastleSceneCore.InternalOctreeVisibleTriangles: TTriangleOctree;
5918 begin
5919 if (ssVisibleTriangles in FSpatial) and (FOctreeVisibleTriangles = nil) then
5920 FOctreeVisibleTriangles := CreateTriangleOctree(
5921 FTriangleOctreeLimits,
5922 false);
5923 Result := FOctreeVisibleTriangles;
5924 end;
5925
5926 function TCastleSceneCore.InternalOctreeStaticCollisions: TTriangleOctree;
5927 begin
5928 if (ssStaticCollisions in FSpatial) and (FOctreeStaticCollisions = nil) then
5929 FOctreeStaticCollisions := CreateTriangleOctree(
5930 FTriangleOctreeLimits,
5931 true);
5932 Result := FOctreeStaticCollisions;
5933 end;
5934
5935 function TCastleSceneCore.InternalOctreeCollisions: TBaseTrianglesOctree;
5936 begin
5937 if InternalOctreeStaticCollisions <> nil then
5938 Result := InternalOctreeStaticCollisions else
5939 if InternalOctreeDynamicCollisions <> nil then
5940 Result := InternalOctreeDynamicCollisions else
5941 Result := nil;
5942 end;
5943
5944 function TCastleSceneCore.UseInternalOctreeCollisions: boolean;
5945 begin
5946 Result := FSpatial * [ssStaticCollisions, ssDynamicCollisions] <> [];
5947 Assert((not Result) or (InternalOctreeCollisions <> nil));
5948
5949 { We check whether to use InternalOctreeCollisions
5950 not by checking InternalOctreeCollisions <> nil,
5951 but by checking Spatial.
5952
5953 If you switch Spatial from non-empty to empty,
5954 then the octree in InternalOctreeCollisions remains assigned
5955 as long as there's no need to rebuild it.
5956 This is nice, in case you change Spatial again
5957 (e.g. by switching "Collisions" in castle-model-viewer),
5958 the octree is immediately available.
5959
5960 But we don't want to use this octree.
5961 When Spatial = [], you can *expect* that collisions revert to simpler
5962 mechanism (using bounding boxes).
5963 This is important only if you may have Collides = true with Spatial empty. }
5964 end;
5965
5966 function TCastleSceneCore.CreateTriangleOctree(
5967 const Limits: TOctreeLimits;
5968 const Collidable: boolean): TTriangleOctree;
5969
5970 procedure FillOctree(TriangleEvent: TTriangleEvent);
5971 var
5972 ShapeList: TShapeList;
5973 Shape: TShape;
5974 begin
5975 ShapeList := Shapes.TraverseList(true);
5976 for Shape in ShapeList do
5977 if (Collidable and Shape.Collidable) or
5978 ((not Collidable) and Shape.Visible) then
5979 Shape.Triangulate(TriangleEvent);
5980 end;
5981
5982 begin
5983 Inc(InternalDirty);
5984 try
5985
5986 Result := TTriangleOctree.Create(Limits, LocalBoundingBoxNoChildren);
5987 try
5988 Result.Triangles.Capacity := TrianglesCount;
5989 FillOctree({$ifdef FPC} @ {$endif} Result.AddItemTriangle);
5990 except Result.Free; raise end;
5991
5992 finally Dec(InternalDirty) end;
5993
5994 { $define CASTLE_DEBUG_OCTREE_DUPLICATION}
5995 {$ifdef CASTLE_DEBUG_OCTREE_DUPLICATION}
5996 WritelnLog('Triangles Octree Stats', '%d items in octree, %d items in octree''s leafs, duplication %f',
5997 [Result.TotalItemsInOctree,
5998 Result.TotalItemsInLeafs,
5999 Result.TotalItemsInLeafs / Result.TotalItemsInOctree]);
6000 {$endif}
6001 end;
6002
6003 function TCastleSceneCore.CreateShapeOctree(
6004 const Limits: TOctreeLimits;
6005 const Collidable: boolean): TShapeOctree;
6006 var
6007 I: Integer;
6008 ShapesList: TShapeList;
6009 begin
6010 Inc(InternalDirty);
6011 try
6012
6013 if Collidable then
6014 { Add only active and collidable shapes }
6015 ShapesList := Shapes.TraverseList(true, false, true) else
6016 { Add only active and visible shapes }
6017 ShapesList := Shapes.TraverseList(true, true, false);
6018
6019 Result := TShapeOctree.Create(Limits, LocalBoundingBoxNoChildren, ShapesList);
6020 try
6021 for I := 0 to Result.ShapesList.Count - 1 do
6022 if not Result.ShapesList[I].BoundingBox.IsEmpty then
6023 Result.TreeRoot.AddItem(I);
6024 except Result.Free; raise end;
6025
6026 finally Dec(InternalDirty) end;
6027
6028 {$ifdef CASTLE_DEBUG_OCTREE_DUPLICATION}
6029 WritelnLog('Shapes Octree Stats', '%d items in octree, %d items in octree''s leafs, duplication %f',
6030 [Result.TotalItemsInOctree,
6031 Result.TotalItemsInLeafs,
6032 Result.TotalItemsInLeafs / Result.TotalItemsInOctree]);
6033 {$endif}
6034 end;
6035
6036 { viewpoints ----------------------------------------------------------------- }
6037
6038 type
6039 TFirstViewpointSeeker = class
6040 OnlyPerspective: boolean;
6041 ViewpointDescription: String;
6042 function Seek(
6043 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
6044 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
6045 end;
6046
6047 function TFirstViewpointSeeker.Seek(
6048 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
6049 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
6050 var
6051 V: TAbstractViewpointNode;
6052 begin
6053 V := Node as TAbstractViewpointNode;
6054 if ( (not OnlyPerspective) or
6055 (V.ProjectionType = ptPerspective) ) and
6056 ( (ViewpointDescription = '') or
6057 (V.Description = ViewpointDescription) ) then
6058 Result := V else
6059 Result := nil;
6060 end;
6061
6062 function TCastleSceneCore.GetViewpointCore(
6063 const OnlyPerspective: boolean;
6064 out ProjectionType: TProjectionType;
6065 out CamPos, CamDir, CamUp, GravityUp: TVector3;
6066 const ViewpointDescription: String): TAbstractViewpointNode;
6067 var
6068 Seeker: TFirstViewpointSeeker;
6069 begin
6070 Result := nil;
6071
6072 if RootNode <> nil then
6073 begin
6074 Seeker := TFirstViewpointSeeker.Create;
6075 try
6076 Seeker.OnlyPerspective := OnlyPerspective;
6077 Seeker.ViewpointDescription := ViewpointDescription;
6078 Result := TAbstractViewpointNode(
6079 RootNode.Traverse(TAbstractViewpointNode,
6080 {$ifdef FPC}@{$endif}Seeker.Seek));
6081 finally FreeAndNil(Seeker) end;
6082 end;
6083
6084 if Result <> nil then
6085 begin
6086 Result.GetView(CamPos, CamDir, CamUp, GravityUp);
6087 ProjectionType := Result.ProjectionType;
6088 end else
6089 begin
6090 { use default camera settings }
6091 CamPos := DefaultX3DCameraPosition[cvVrml2_X3d];
6092 CamDir := DefaultX3DCameraDirection;
6093 CamUp := DefaultX3DCameraUp;
6094 GravityUp := DefaultX3DGravityUp;
6095 ProjectionType := ptPerspective;
6096 end;
6097 end;
6098
6099 function TCastleSceneCore.GetViewpoint(
6100 out ProjectionType: TProjectionType;
6101 out CamPos, CamDir, CamUp, GravityUp: TVector3;
6102 const ViewpointDescription: String): TAbstractViewpointNode;
6103 begin
6104 Result := GetViewpointCore(false, ProjectionType, CamPos, CamDir, CamUp, GravityUp,
6105 ViewpointDescription);
6106 end;
6107
6108 function TCastleSceneCore.GetPerspectiveViewpoint(
6109 out CamPos, CamDir, CamUp, GravityUp: TVector3;
6110 const ViewpointDescription: String): TAbstractViewpointNode;
6111 var
6112 ProjectionType: TProjectionType;
6113 begin
6114 Result := GetViewpointCore(true, ProjectionType, CamPos, CamDir, CamUp, GravityUp,
6115 ViewpointDescription);
6116 Assert(ProjectionType = ptPerspective);
6117 end;
6118
6119 { freeing resources ---------------------------------------------------------- }
6120
6121 procedure TCastleSceneCore.FreeResources_UnloadTextureData(Node: TX3DNode);
6122 begin
6123 (Node as TAbstractTexture2DNode).IsTextureLoaded := false;
6124 end;
6125
6126 procedure TCastleSceneCore.FreeResources_UnloadTexture3DData(Node: TX3DNode);
6127 begin
6128 (Node as TAbstractTexture3DNode).TextureLoaded := false;
6129 end;
6130
6131 procedure TCastleSceneCore.FreeResources(Resources: TSceneFreeResources);
6132
6133 procedure FreeShadowVolumes;
6134 var
6135 ShapeList: TShapeList;
6136 Shape: TShape;
6137 begin
6138 ShapeList := Shapes.TraverseList(false);
6139 for Shape in ShapeList do
6140 Shape.InternalShadowVolumes.FreeResources;
6141 end;
6142
6143 begin
6144 if (frTextureDataInNodes in Resources) and (RootNode <> nil) then
6145 begin
6146 RootNode.EnumerateNodes(TAbstractTexture2DNode,
6147 {$ifdef FPC}@{$endif}FreeResources_UnloadTextureData, false);
6148 RootNode.EnumerateNodes(TAbstractTexture3DNode,
6149 {$ifdef FPC}@{$endif}FreeResources_UnloadTexture3DData, false);
6150 end;
6151
6152 if frShadowVolume in Resources then
6153 FreeShadowVolumes;
6154 end;
6155
6156 { events --------------------------------------------------------------------- }
6157
6158 procedure TCastleSceneCore.ScriptsInitializeCallback(Node: TX3DNode);
6159 begin
6160 // TODO: Delphi Support
6161 {$ifdef FPC}
6162 // Node.Scene must be set in order for TScriptNode.SetInitialized to work
6163 Assert(Node.Scene = Self);
6164 TScriptNode(Node).Initialized := true;
6165 {$endif}
6166 end;
6167
6168 procedure TCastleSceneCore.ScriptsInitialize;
6169 begin
6170 // TODO: Delphi Support
6171 {$ifdef FPC}
6172 if RootNode <> nil then
6173 begin
6174 BeginChangesSchedule;
6175 try
6176 { We have to initialize scripts only after all other initialization
6177 is done, in particular after Node.Scene was set by ChangedAll.
6178 Reason: scripts initialize() methods may already cause some events,
6179 that should notify us appropriately.
6180 This is also why Begin/EndChangesSchedule around is useful. }
6181 RootNode.EnumerateNodes(TScriptNode, @ScriptsInitializeCallback, false);
6182 finally EndChangesSchedule end;
6183 end;
6184 {$endif}
6185 end;
6186
6187 procedure TCastleSceneCore.ScriptsFinalizeCallback(Node: TX3DNode);
6188 begin
6189 // TODO: Delphi Support
6190 {$ifdef FPC}
6191 TScriptNode(Node).Initialized := false;
6192 {$endif}
6193 end;
6194
6195 procedure TCastleSceneCore.ScriptsFinalize;
6196 begin
6197 // TODO: Delphi Support
6198 {$ifdef FPC}
6199 if RootNode <> nil then
6200 begin
6201 BeginChangesSchedule;
6202 try
6203 { We have to deinitialize scripts before any other deinitialization
6204 is done. Just like for ScriptsInitialize. }
6205 RootNode.EnumerateNodes(TScriptNode, @ScriptsFinalizeCallback, false);
6206 finally EndChangesSchedule end;
6207 end;
6208 {$endif}
6209 end;
6210
6211 procedure TCastleSceneCore.SetProcessEvents(const Value: boolean);
6212 begin
6213 if FProcessEvents <> Value then
6214 begin
6215 if Value then
6216 begin
6217 FProcessEvents := Value;
6218
6219 ScriptsInitialize;
6220
6221 { When ProcessEvents is set to @true, you want to initialize stuff
6222 for things depending on camera (and X3D events):
6223 - position/orientation_changed events on ProximitySensors,
6224 - update camera information on all Billboard nodes,
6225 - LOD nodes. }
6226 InternalCameraChanged;
6227 end else
6228 begin
6229 ScriptsFinalize;
6230 PointingDeviceClear;
6231
6232 FProcessEvents := Value;
6233 end;
6234 end;
6235 end;
6236
6237 { key sensors handling ------------------------------------------------------- }
6238
6239 function TCastleSceneCore.Press(const Event: TInputPressRelease): boolean;
6240 var
6241 I: Integer;
6242 begin
6243 Result := inherited;
6244 if Result or (not Exists) or (Event.EventType <> itKey) then Exit;
6245
6246 if ProcessEvents then
6247 begin
6248 BeginChangesSchedule;
6249 try
6250 for I := 0 to KeyDeviceSensorNodes.Count - 1 do
6251 (KeyDeviceSensorNodes.Items[I] as TAbstractKeyDeviceSensorNode).
6252 KeyDown(Event.Key, Event.KeyString, NextEventTime);
6253 finally EndChangesSchedule; end;
6254
6255 { Never treat the event as handled here,
6256 even if some X3DKeyDeviceSensorNode was found and did something.
6257 That is because we don't get enough information
6258 from VRML/X3D events (which may come down to calling some scripts in VRML/X3D)
6259 to be sure that the event is handled (and should not be passed to others).
6260 Result := false; }
6261 end;
6262 end;
6263
6264 function TCastleSceneCore.Release(const Event: TInputPressRelease): boolean;
6265 var
6266 I: Integer;
6267 begin
6268 Result := inherited;
6269 if Result or (not Exists) or (Event.EventType <> itKey) then Exit;
6270
6271 if ProcessEvents then
6272 begin
6273 BeginChangesSchedule;
6274 try
6275 for I := 0 to KeyDeviceSensorNodes.Count - 1 do
6276 (KeyDeviceSensorNodes.Items[I] as TAbstractKeyDeviceSensorNode).
6277 KeyUp(Event.Key, Event.KeyString, NextEventTime);
6278 finally EndChangesSchedule; end;
6279
6280 { Never treat the event as handled here,
6281 even if some X3DKeyDeviceSensorNode was found and did something.
6282 That is because we don't get enough information
6283 from VRML/X3D events (which may come down to calling some scripts in VRML/X3D)
6284 to be sure that the event is handled (and should not be passed to others).
6285 Result := false; }
6286 end;
6287 end;
6288
6289 { pointing device handling --------------------------------------------------- }
6290
6291 function TCastleSceneCore.PointingDeviceMove(const Pick: TRayCollisionNode;
6292 const Distance: Single): boolean;
6293 var
6294 TouchSensor: TTouchSensorNode;
6295 ActiveSensor: TAbstractPointingDeviceSensorNode;
6296 OldIsOver, NewIsOver: boolean;
6297 OldSensors: TX3DNodeList;
6298 NewSensors: TX3DNodeList;
6299 I: Integer;
6300 OverItem: PTriangle;
6301 begin
6302 Result := inherited;
6303 if Result or (not Exists) then Exit;
6304
6305 OverItem := Pick.Triangle;
6306
6307 { Never treat the event as handled here, as we don't get enough information
6308 from VRML/X3D events (which may come down to calling some scripts in VRML/X3D)
6309 to be sure that the event is handled (and should not be passed to others).
6310 Result := false; }
6311
6312 if ProcessEvents then
6313 begin
6314 { Note that using Begin/EndChangesSchedule is not only for efficiency
6315 here. It's also sometimes needed to keep the code correct: note
6316 that ChangedAll changes everything, including State pointers.
6317 So OverItem.State becomes invalid. (Once octree will be rebuild, also
6318 OverItem will be invalid.) Obviously, we can't let this happen
6319 in the middle of PointingDeviceMove. }
6320 BeginChangesSchedule;
6321 try
6322 { Handle isOver events }
6323
6324 if PointingDeviceOverItem <> OverItem then
6325 begin
6326 if PointingDeviceActiveSensors.Count <> 0 then
6327 begin
6328 Assert(PointingDeviceActive);
6329
6330 { This is quite special situation, as it means that
6331 PointingDeviceActiveSensors grabbed all events.
6332 isOver (either TRUE or FALSE) may be generated for active
6333 sensors, but no other sensors should receive any events. }
6334
6335 for I := 0 to PointingDeviceActiveSensors.Count - 1 do
6336 begin
6337 ActiveSensor := PointingDeviceActiveSensors.Items[I] as
6338 TAbstractPointingDeviceSensorNode;
6339
6340 if ActiveSensor.FdEnabled.Value then
6341 begin
6342 OldIsOver := (PointingDeviceOverItem <> nil) and
6343 (PointingDeviceOverItem^.State.PointingDeviceSensors.
6344 IndexOf(ActiveSensor) <> -1);
6345
6346 NewIsOver := (OverItem <> nil) and
6347 (OverItem^.State.PointingDeviceSensors.IndexOf(ActiveSensor) <> -1);
6348
6349 if OldIsOver <> NewIsOver then
6350 ActiveSensor.EventIsOver.Send(NewIsOver, NextEventTime);
6351 end;
6352 end;
6353 end else
6354 if (PointingDeviceOverItem <> nil) and
6355 (OverItem <> nil) then
6356 begin
6357 OldSensors := PointingDeviceOverItem^.State.PointingDeviceSensors;
6358 NewSensors := OverItem^.State.PointingDeviceSensors;
6359
6360 { X3D spec says about isOver events that
6361 "Events are not generated if the geometry itself is
6362 animating and moving underneath the pointing device."
6363
6364 I understand that they mean that you don't have to call
6365 PointingDeviceMove continuously, you can only check this on
6366 actual mouse move. That is, isOver state changes are not
6367 intended to be caught immediately if they happened because
6368 the geometry is animating. But, still, all isOver changes *are*
6369 reported. I hope they don't mean that isOver changes because
6370 of underlying geometry animating should not be reported at all.
6371
6372 The latter interpretation:
6373 - Would be unhandy for implementation, as I would have to call
6374 raycollision twice for each Motion (to get
6375 OverItemBeforeMove and OverItem).
6376 - Would be unhandy for users. You want
6377 to catch isOver changes eventually, right? Otherwise,
6378 user may be forced to move mouse out and then back in to generate
6379 isOver event = TRUE. Worse, user has to move mouse inside and
6380 then back outside to generate isOver = FALSE event.
6381 }
6382
6383 for I := 0 to OldSensors.Count - 1 do
6384 if NewSensors.IndexOf(OldSensors[I]) = -1 then
6385 begin
6386 if (OldSensors[I] is TAbstractPointingDeviceSensorNode) and
6387 TAbstractPointingDeviceSensorNode(OldSensors[I]).FdEnabled.Value then
6388 TAbstractPointingDeviceSensorNode(OldSensors[I]).EventIsOver.Send(false, NextEventTime);
6389 end;
6390
6391 for I := 0 to NewSensors.Count - 1 do
6392 if OldSensors.IndexOf(NewSensors[I]) = -1 then
6393 begin
6394 if (NewSensors[I] is TAbstractPointingDeviceSensorNode) and
6395 TAbstractPointingDeviceSensorNode(NewSensors[I]).FdEnabled.Value then
6396 TAbstractPointingDeviceSensorNode(NewSensors[I]).EventIsOver.Send(true, NextEventTime);
6397 end;
6398 end else
6399 if PointingDeviceOverItem <> nil then
6400 begin
6401 { So we previously pointed as something, and now at nothing.
6402 So simply call isOver = FALSE for all. }
6403
6404 OldSensors := PointingDeviceOverItem^.State.PointingDeviceSensors;
6405
6406 for I := 0 to OldSensors.Count - 1 do
6407 if (OldSensors[I] is TAbstractPointingDeviceSensorNode) and
6408 TAbstractPointingDeviceSensorNode(OldSensors[I]).FdEnabled.Value then
6409 TAbstractPointingDeviceSensorNode(OldSensors[I]).EventIsOver.Send(false, NextEventTime);
6410 end else
6411 begin
6412 Assert(OverItem <> nil);
6413
6414 { So we previously pointed as nothing, and now at something.
6415 So simply call isOver = TRUE for all. }
6416
6417 NewSensors := OverItem^.State.PointingDeviceSensors;
6418
6419 for I := 0 to NewSensors.Count - 1 do
6420 if (NewSensors[I] is TAbstractPointingDeviceSensorNode) and
6421 TAbstractPointingDeviceSensorNode(NewSensors[I]).FdEnabled.Value then
6422 TAbstractPointingDeviceSensorNode(NewSensors[I]).EventIsOver.Send(true, NextEventTime);
6423 end;
6424
6425 FPointingDeviceOverItem := OverItem;
6426
6427 DoPointingDeviceSensorsChange;
6428 end;
6429
6430 { When OverItem <> nil => Pick.Point is meaningful.
6431 Right now OverItem = FPointingDeviceOverItem,
6432 so take care to make PointingDeviceOverPoint also meaningful. }
6433 FPointingDeviceOverPoint := Pick.Point;
6434
6435 { Handle hitXxx_changed events }
6436
6437 if OverItem <> nil then
6438 begin
6439 NewSensors := OverItem^.State.PointingDeviceSensors;
6440
6441 for I := 0 to NewSensors.Count - 1 do
6442 if NewSensors[I] is TTouchSensorNode then
6443 begin
6444 TouchSensor := TTouchSensorNode(NewSensors[I]);
6445 if TouchSensor.FdEnabled.Value then
6446 begin
6447 TouchSensor.EventHitPoint_Changed.Send(
6448 { hitPoint_changed event wants a point in local coords,
6449 we can get this by InverseTransform. }
6450 OverItem^.State.Transformation.InverseTransform.MultPoint(Pick.Point), NextEventTime);
6451
6452 {$ifndef CONSERVE_TRIANGLE_MEMORY}
6453 if TouchSensor.EventHitNormal_Changed.SendNeeded then
6454 TouchSensor.EventHitNormal_Changed.Send(
6455 OverItem^.INormal(Pick.Point), NextEventTime);
6456
6457 if TouchSensor.EventHitTexCoord_Changed.SendNeeded then
6458 TouchSensor.EventHitTexCoord_Changed.Send(
6459 OverItem^.ITexCoord2D(Pick.Point), NextEventTime);
6460 {$endif not CONSERVE_TRIANGLE_MEMORY}
6461 end;
6462 end;
6463 end;
6464
6465 { Call Drag on active drag sensors }
6466 for I := 0 to PointingDeviceActiveSensors.Count - 1 do
6467 begin
6468 ActiveSensor := PointingDeviceActiveSensors.Items[I] as
6469 TAbstractPointingDeviceSensorNode;
6470 if ActiveSensor is TAbstractDragSensorNode then
6471 TAbstractDragSensorNode(ActiveSensor).Drag(
6472 NextEventTime, Pick.RayOrigin, Pick.RayDirection);
6473 end;
6474 finally
6475 EndChangesSchedule;
6476 end;
6477 end;
6478 end;
6479
6480 procedure TCastleSceneCore.DoPointingDeviceSensorsChange;
6481 begin
6482 if Assigned(OnPointingDeviceSensorsChange) then
6483 OnPointingDeviceSensorsChange(Self);
6484 end;
6485
6486 procedure TCastleSceneCore.PointingDeviceClear;
6487 var
6488 SensorsChanged: boolean;
6489 begin
6490 SensorsChanged :=
6491 (FPointingDeviceOverItem <> nil) or
6492 { This may be called from destructor (through
6493 TShape.FreeOctreeTriangles when freeing shapes), so prepare for
6494 the FPointingDeviceActiveSensors = nil case. }
6495 ( (FPointingDeviceActiveSensors <> nil) and
6496 (FPointingDeviceActiveSensors.Count <> 0) );
6497
6498 FPointingDeviceOverItem := nil;
6499 { PointingDeviceOverPoint may be left undefined now, but let's set it
6500 to something deterministic to ease debugging. }
6501 FPointingDeviceOverPoint := TVector3.Zero;
6502 FPointingDeviceActive := false;
6503 if FPointingDeviceActiveSensors <> nil then
6504 FPointingDeviceActiveSensors.Count := 0;
6505
6506 if SensorsChanged then
6507 DoPointingDeviceSensorsChange;
6508 end;
6509
6510 function TCastleSceneCore.PointingDevicePress(const Pick: TRayCollisionNode;
6511 const Distance: Single): Boolean;
6512 begin
6513 Result := inherited;
6514 if Result then Exit;
6515
6516 { If the Scene was just added to Viewport (and no mouse move occurred),
6517 or if the Scene was modified by ChangedAll, e.g. by removing some items
6518 (and no mouse move occurred),
6519 then PointingDevicePress would not fire for sensors (like TouchSensor)
6520 under mouse, because PointingDeviceOverItem is not set.
6521 See https://github.com/castle-engine/castle-engine/issues/227 .
6522 Using PointingDeviceMove sets PointingDeviceOverItem. }
6523 PointingDeviceMove(Pick, Distance);
6524
6525 Result := PointingDevicePressRelease(true, Distance, { ignored } false);
6526 end;
6527
6528 function TCastleSceneCore.PointingDeviceRelease(const Pick: TRayCollisionNode;
6529 const Distance: Single; const CancelAction: Boolean): Boolean;
6530 begin
6531 Result := inherited;
6532 if Result then Exit;
6533 Result := PointingDevicePressRelease(false, Distance, CancelAction);
6534 end;
6535
6536 function TCastleSceneCore.PointingDevicePressRelease(const DoPress: boolean;
6537 const Distance: Single; const CancelAction: boolean): boolean;
6538
6539 function AnchorActivate(Anchor: TAnchorNode): boolean;
6540 var
6541 NewRootNode: TX3DRootNode;
6542 NewViewpoint: TAbstractViewpointNode;
6543 begin
6544 Result := Anchor.LoadAnchor(NewRootNode, NewViewpoint, RootNode);
6545 if Result then
6546 begin
6547 { activating Anchor clears other sensors, since Anchor
6548 loads completely different scene. }
6549 FPointingDeviceActiveSensors.Count := 0;
6550
6551 if NewRootNode <> nil then
6552 Load(NewRootNode, true, [slDisableResetTime]);
6553
6554 { When NewRootNode <> nil, it's important here that we know
6555 we're inside BeginChangesSchedule.
6556
6557 This means that ForceTeleportTransitions (set to true by Load)
6558 is still true during the following Set_Bind := true call.
6559 That's because ChangedAll (that resets ForceTeleportTransitions
6560 to false) was not called yet. }
6561
6562 if NewViewpoint <> nil then
6563 NewViewpoint.Bound := true;
6564 end;
6565 end;
6566
6567 var
6568 Sensors: TPointingDeviceSensorList;
6569
6570 function PDSensorActivate(Sensor: TAbstractPointingDeviceSensorNode): boolean;
6571 begin
6572 Result := Sensor.FdEnabled.Value and
6573 { Send isActive = true and make DoPointingDeviceSensorsChange
6574 only if FPointingDeviceActiveSensor changes. }
6575 (PointingDeviceActiveSensors.IndexOf(Sensor) = -1);
6576 if Result then
6577 begin
6578 PointingDeviceActiveSensors.Add(Sensor);
6579 { We do this only when PointingDeviceOverItem <> nil,
6580 so we know that PointingDeviceOverPoint is meaningful. }
6581 Sensor.Activate(NextEventTime,
6582 Sensors.Transformation.Transform,
6583 Sensors.Transformation.InverseTransform,
6584 PointingDeviceOverPoint);
6585 end;
6586 end;
6587
6588 var
6589 I: Integer;
6590 ToActivate: TX3DNode;
6591 ActiveChanged: boolean;
6592 ActiveSensor: TAbstractPointingDeviceSensorNode;
6593 begin
6594 Result := false;
6595
6596 if ProcessEvents and (FPointingDeviceActive <> DoPress) then
6597 begin
6598 BeginChangesSchedule;
6599 try
6600 ActiveChanged := false;
6601 FPointingDeviceActive := DoPress;
6602 if DoPress then
6603 begin
6604 if PointingDeviceOverItem <> nil then
6605 begin
6606 Sensors := PointingDeviceOverItem^.State.PointingDeviceSensors;
6607 for I := 0 to Sensors.Count - 1 do
6608 begin
6609 { Activate all the enabled sensors. Spec says to activate
6610 simultaneouly all Sensors (tied for this mouse down). }
6611 ToActivate := Sensors[I];
6612 if ToActivate is TAbstractPointingDeviceSensorNode then
6613 begin
6614 if PDSensorActivate(TAbstractPointingDeviceSensorNode(ToActivate)) then
6615 ActiveChanged := true;
6616 end else
6617 if ToActivate is TAnchorNode then
6618 begin
6619 if AnchorActivate(TAnchorNode(ToActivate)) then
6620 begin
6621 ActiveChanged := true;
6622 Break;
6623 end;
6624 end;
6625 end;
6626 end;
6627 end else
6628 begin
6629 { Deactivate all PointingDeviceActiveSensors (if any) }
6630 if PointingDeviceActiveSensors.Count <> 0 then
6631 begin
6632 for I := 0 to PointingDeviceActiveSensors.Count -1 do
6633 begin
6634 ActiveSensor := PointingDeviceActiveSensors.Items[I]
6635 as TAbstractPointingDeviceSensorNode;
6636 ActiveSensor.Deactivate(NextEventTime);
6637 { If we're still over the sensor, generate touchTime for TouchSensor }
6638 if (not CancelAction) and
6639 (PointingDeviceOverItem <> nil) and
6640 (PointingDeviceOverItem^.State.PointingDeviceSensors.
6641 IndexOf(ActiveSensor) <> -1) and
6642 (ActiveSensor is TTouchSensorNode) then
6643 begin
6644 TTouchSensorNode(ActiveSensor).EventTouchTime.Send(Time, NextEventTime);
6645 end;
6646 end;
6647 FPointingDeviceActiveSensors.Count := 0;
6648 ActiveChanged := true;
6649 end;
6650 end;
6651
6652 if ActiveChanged then DoPointingDeviceSensorsChange;
6653
6654 { We try hard to leave Result as false when nothing happened.
6655 This is important for TCastleViewport, that wants to retry
6656 press around if ApproximateActivation, and for other TCastleTransform objects
6657 along the same TRayCollision list. So we really must set
6658 Result := false if nothing happened, to enable other objects
6659 to have a better chance of catching press/release event.
6660 At the same time, we really must set Result := true if something
6661 (possibly) happened. Otherwise, simultaneously two objects may be activated,
6662 and TCastleViewport.PointingDevicePressFailed may do a sound
6663 warning that activation was unsuccessful.
6664
6665 Fortunately, our ActiveChanged right now precisely tells us
6666 when something happened. When not ActiveChanged, nothing happened,
6667 no X3D event was send. }
6668 Result := ActiveChanged;
6669 finally
6670 EndChangesSchedule;
6671 end;
6672 end;
6673 end;
6674
6675 function TCastleSceneCore.PointingDeviceSensors: TPointingDeviceSensorList;
6676 begin
6677 if PointingDeviceOverItem <> nil then
6678 Result := PointingDeviceOverItem^.State.PointingDeviceSensors else
6679 Result := nil;
6680 end;
6681
6682 (*
6683 // Not needed now
6684 function TCastleSceneCore.Dragging: boolean;
6685
6686 function ActiveDraggingSensor: boolean;
6687 var
6688 I: Integer;
6689 begin
6690 Result := false;
6691 for I := 0 to PointingDeviceActiveSensors.Count - 1 do
6692 if PointingDeviceActiveSensors.Items[I] is TAbstractDragSensorNode then
6693 Exit(true);
6694 end;
6695
6696 begin
6697 Result := (inherited Dragging) or
6698 ((PointingDeviceActiveSensors.Count <> 0) and
6699 { minor optimization, do not even call ActiveDraggingSensor if
6700 PointingDeviceActiveSensors.Count = 0 (most usual case) }
6701 ActiveDraggingSensor and
6702 ProcessEvents);
6703 end;
6704 *)
6705
6706 { Time stuff ------------------------------------------------------------ }
6707
6708 function TCastleSceneCore.Time: TFloatTime;
6709 begin
6710 Result := FTimeNow.Seconds;
6711 end;
6712
6713 function TCastleSceneCore.NextEventTime: TX3DTime;
6714 begin
6715 { Increase @link(FTime) by some infinitely small value.
6716 This allows events to pass through the ROUTEs
6717 without the fear of being rejected as "recursive (cycle) events"
6718 from previous events. }
6719
6720 Inc(FTimeNow.PlusTicks);
6721 Result := FTimeNow;
6722 end;
6723
6724 procedure TCastleSceneCore.SetAnimateSkipTicks(const Value: Cardinal);
6725 begin
6726 if FAnimateSkipTicks <> Value then
6727 begin
6728 FAnimateSkipTicks := Value;
6729 { randomizing it now desynchronizes the skipped frames across many scenes
6730 created in a single frame }
6731 AnimateSkipNextTicks := Random(FAnimateSkipTicks + 1);
6732 end;
6733 end;
6734
6735 procedure TCastleSceneCore.UpdateNewPlayingAnimation(out NeedsUpdateTimeDependent: Boolean);
6736 begin
6737 NeedsUpdateTimeDependent := false;
6738
6739 if NewPlayingAnimationUse then
6740 begin
6741 NewPlayingAnimationUse := false;
6742 if PlayingAnimationNode <> nil then
6743 begin
6744 PlayingAnimationNode.Stop;
6745 if Assigned(PlayingAnimationStopNotification) then
6746 begin
6747 PlayingAnimationStopNotification(Self, PlayingAnimationNode);
6748 PlayingAnimationStopNotification := nil;
6749 end;
6750 PlayingAnimationNode.EventIsActive.RemoveNotification(
6751 {$ifdef FPC}@{$endif}PlayingAnimationIsActive);
6752 end;
6753 Assert({$ifndef FPC}@{$endif}PlayingAnimationStopNotification = nil);
6754
6755 { If calling PlayAnimation on already-playing node,
6756 we have to make sure it actually starts playing from the start.
6757 For the StartTime below to be correctly applied, we have to make
6758 sure the node actually *stops* temporarily (otherwise the
6759 TTimeDependentFunctionality.SetTime never "sees" the node
6760 in the Enabled = false state). }
6761 if (PlayingAnimationNode = NewPlayingAnimationNode) and
6762 (PlayingAnimationNode <> nil) then
6763 PlayingAnimationNode.TimeFunctionality.SetTime(Time, 0, false);
6764
6765 { set PreviousPlayingAnimationXxx }
6766 PreviousPlayingAnimation := PlayingAnimationNode;
6767 if PreviousPlayingAnimation <> nil then
6768 begin
6769 PreviousPlayingAnimationLoop := PreviousPlayingAnimation.Loop;
6770 PreviousPlayingAnimationForward := PreviousPlayingAnimation.FractionIncreasing;
6771 PreviousPlayingAnimationTimeInAnimation := PreviousPlayingAnimation.TimeFunctionality.ElapsedTime;
6772 end;
6773
6774 { If current animation node changes (to non-nil) call ResetAnimatedFields,
6775 to restore fields *not* affected by new animation to their "reset" state.
6776
6777 Note: This must be called before we pass time to a new TimeSensor
6778 (since otherwise, ResetAnimationState would override some state set by new TimeSensor)
6779 and after the old TimeSensor is stopped.
6780 In particular, this must be called before PlayingAnimationNode.Start done lower
6781 (after PlayingAnimationNode:=NewPlayingAnimationNode) since TTimeSensorNode.Start
6782 sets StartTime and this calls HandleChangeTimeStopStart which applies
6783 the new TimeSensor.
6784
6785 How does this work with blending (cross-fading) animations (using TransitionDuration)?
6786
6787 For each field X, there are 4 cases possible:
6788
6789 1. Neither old nor new animation affects the field X.
6790
6791 Then everything trivially works.
6792 Old animation doesn't change X,
6793 ResetAnimationState doesn't change X
6794 (maybe even it doesn't touch X, if X is not affected by *any* animation),
6795 new animation doesn't change X.
6796
6797 2. Old animation doesn't affect field X, new animation affects field X.
6798
6799 Then ResetAnimationState on X doesn't do anything
6800 (since X already has the same value as ResetAnimationState sets).
6801
6802 In TX3DField.InternalAffectedPartial
6803 we will blend (fade-in) new animation with FResetValue recorded
6804 in the field.
6805
6806 3. Old animation affects field X, new animation doesn't affect X.
6807
6808 We will blend (fade-out) old animation value with the FResetValue
6809 in the field.
6810
6811 4. Both old and new animations touch field X.
6812
6813 In this case field's FResetValue value is not useful
6814 (we don't want to it use since neither old nor new animation
6815 corresponds to the "reset" state).
6816
6817 Luckily, in this case FResetValue will be ignored!
6818 The field X will receive two values (during cross-fade):
6819 old one (let's call it's strength Alpha), and new one (with strength 1-Alpha).
6820 Since their strengths sum to 1.0, in TX3DField.InternalAffectedPartial
6821 we will have PartialReceived.Partial = 1.0,
6822 which means that FResetValue will be ignored.
6823
6824 To test it all in a simple case,
6825 open the Spine JSON file
6826 from https://github.com/castle-engine/demo-models/tree/master/animation/spine_animation_blending_test/exported
6827 with castle-model-viewer and run animations with TransitionDuration > 0.
6828
6829 Note that above assumes that the field X supports lerp (TX3DField.CanAssignLerp).
6830 Otherwise the AD 3 case is broken (new animation would not correctly "reset"
6831 the field X, value of old animation would override it if TransitionDuration > 0).
6832 Testcase: TransitionDuration > 0 with Roseanne, switch between
6833 die and attack_monster.
6834 To fix this, we use IgnoreIfCannotLerp.
6835 }
6836
6837 if (PlayingAnimationNode <> NewPlayingAnimationNode) and
6838 (NewPlayingAnimationNode <> nil) then
6839 begin
6840 ResetAnimationState(NewPlayingAnimationNode);
6841 { As soon as possible, we need to process TimeSensors, otherwise user would
6842 see a default animation pose. }
6843 NeedsUpdateTimeDependent := true;
6844 end;
6845
6846 PlayingAnimationNode := NewPlayingAnimationNode;
6847
6848 if PlayingAnimationNode <> nil then
6849 begin
6850 { Assign these before PartialSendBegin/End }
6851 PlayingAnimationTransitionDuration := NewPlayingAnimationTransitionDuration;
6852 { save current Time to own variable,
6853 do not trust PlayingAnimationNode.StartTime to remain reliable,
6854 it can be changed by user later. }
6855 PlayingAnimationStartTime := Time;
6856
6857 PlayingAnimationNode.Start(
6858 NewPlayingAnimationLoop,
6859 NewPlayingAnimationForward,
6860 NewPlayingAnimationInitialTime);
6861
6862 PlayingAnimationNode.EventIsActive.AddNotification(
6863 {$ifdef FPC}@{$endif}PlayingAnimationIsActive);
6864 PlayingAnimationStopNotification := NewPlayingAnimationStopNotification;
6865 end;
6866 end;
6867 end;
6868
6869 procedure TCastleSceneCore.UpdateTimeDependentList(
6870 const TimeIncrease: TFloatTime; const ResetTime: boolean);
6871 var
6872 SomethingVisibleChanged, SomePartialSend: boolean;
6873 T: TFloatTime;
6874 TimeFunctionality: TTimeDependentFunctionality;
6875 begin
6876 SomethingVisibleChanged := false;
6877 T := Time;
6878 SomePartialSend := false;
6879
6880 for TimeFunctionality in TimeDependentList do
6881 begin
6882 PartialSendBegin(TimeFunctionality);
6883 if TimeFunctionality.PartialSend <> nil then
6884 SomePartialSend := true;
6885
6886 if TimeFunctionality.SetTime(T, TimeIncrease, ResetTime) and
6887 (TimeFunctionality.Parent is TMovieTextureNode) then
6888 SomethingVisibleChanged := true;
6889
6890 PartialSendEnd(TimeFunctionality);
6891 end;
6892
6893 if not SomePartialSend then
6894 NoPartialSend;
6895
6896 { If SomethingVisibleChanged (in MovieTexture nodes), we have to redisplay. }
6897 if SomethingVisibleChanged then
6898 VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
6899 end;
6900
6901 procedure TCastleSceneCore.InternalSetTime(
6902 const NewValue: TFloatTime; const TimeIncrease: TFloatTime; const ResetTime: boolean);
6903
6904 { Call UpdateTimeDependentList, but only if AnimateOnlyWhenVisible logic agrees.
6905 When ResetTime, we force always an UpdateTimeDependentList(0.0) call.
6906 @param NeedsUpdate Forces always *some* UpdateTimeDependentList call. }
6907 procedure UpdateTimeDependentListIfVisible(const NeedsUpdate: Boolean);
6908 begin
6909 if ResetTime then
6910 begin
6911 { Call UpdateTimeDependentList and reset FAnimateGatheredTime.
6912 However, do not reset AnimateSkipNextTicks (this would synchronize
6913 all skipping ticks if multiple animations are reset at the beginning
6914 of game, making randomization in SetAnimateSkipTicks pointless). }
6915 FAnimateGatheredTime := 0;
6916 UpdateTimeDependentList(TimeIncrease + FAnimateGatheredTime, ResetTime);
6917 end else
6918 if NeedsUpdate then
6919 begin
6920 { Call UpdateTimeDependentList regardless of visibility and
6921 of AnimateSkipNextTicks. Note that we do not reset AnimateSkipNextTicks
6922 (to avoid synchronizing AnimateSkipNextTicks of multiple animations
6923 started in the sam frame). }
6924 UpdateTimeDependentList(TimeIncrease + FAnimateGatheredTime, ResetTime);
6925 FAnimateGatheredTime := 0;
6926 end else
6927 if FAnimateOnlyWhenVisible and (not IsVisibleNow) then
6928 begin
6929 FAnimateGatheredTime := FAnimateGatheredTime + TimeIncrease;
6930 end else
6931 if AnimateSkipNextTicks <> 0 then
6932 begin
6933 Dec(AnimateSkipNextTicks);
6934 FAnimateGatheredTime := FAnimateGatheredTime + TimeIncrease;
6935 end else
6936 begin
6937 UpdateTimeDependentList(TimeIncrease + FAnimateGatheredTime, ResetTime);
6938 AnimateSkipNextTicks := AnimateSkipTicks;
6939 FAnimateGatheredTime := 0;
6940 end;
6941 IsVisibleNow := false;
6942 end;
6943
6944 { Call humanoids AnimateSkin.
6945 This could actually be done from anywhere, as long as it gets called
6946 fairly soon after every HAnimJoint animation. }
6947 procedure UpdateHumanoidSkin;
6948 var
6949 I: Integer;
6950 ChangedSkin: TMFVec3f;
6951 begin
6952 for I := 0 to ScheduledHumanoidAnimateSkin.Count - 1 do
6953 begin
6954 ChangedSkin := (ScheduledHumanoidAnimateSkin.Items[I]
6955 as THAnimHumanoidNode).AnimateSkin;
6956 if ChangedSkin <> nil then
6957 ChangedSkin.Changed;
6958 end;
6959 ScheduledHumanoidAnimateSkin.Count := 0;
6960 end;
6961
6962 var
6963 NeedsUpdateTimeDependent: Boolean;
6964 begin
6965 FTimeNow.Seconds := NewValue;
6966 FTimeNow.PlusTicks := 0; // using InternalSetTime always resets PlusTicks
6967
6968 if ProcessEvents and InternalEnableAnimation then
6969 begin
6970 BeginChangesSchedule;
6971 try
6972 { UpdateNewPlayingAnimation must be called before UpdateTimeDependentListIfVisible.
6973 This way if we called StopAnimation, then UpdateNewPlayingAnimation
6974 first stops it (preventing from sending any events),
6975 so a stopped animation will *not* send any events after StopAnimation
6976 (making it useful to call ResetAnimationState right after StopAnimation call). }
6977 UpdateNewPlayingAnimation(NeedsUpdateTimeDependent);
6978 UpdateTimeDependentListIfVisible(NeedsUpdateTimeDependent);
6979 UpdateHumanoidSkin;
6980 { Process TransformationDirty at the end of increasing time, to apply scheduled
6981 TransformationDirty in the same Update, as soon as possible
6982 (useful e.g. for mana shot animation in dragon_squash). }
6983 FinishTransformationChanges;
6984 finally
6985 EndChangesSchedule;
6986 end;
6987 end;
6988 end;
6989
6990 procedure TCastleSceneCore.FinishTransformationChanges;
6991 var
6992 E: TExposedTransform;
6993 begin
6994 if TransformationDirty then
6995 begin
6996 RootTransformationChanged;
6997 TransformationDirty := false;
6998 end;
6999
7000 for E in FExposedTransforms do
7001 E.Synchronize;
7002 end;
7003
7004 procedure TCastleSceneCore.SetTime(const NewValue: TFloatTime);
7005 var
7006 TimeIncrease: TFloatTime;
7007 begin
7008 TimeIncrease := NewValue - FTimeNow.Seconds;
7009 if TimeIncrease > 0 then
7010 InternalSetTime(NewValue, TimeIncrease, false);
7011 end;
7012
7013 procedure TCastleSceneCore.IncreaseTime(const TimeIncrease: TFloatTime);
7014 begin
7015 if TimeIncrease > 0 then
7016 InternalSetTime(FTimeNow.Seconds + TimeIncrease, TimeIncrease, false);
7017 end;
7018
7019 procedure TCastleSceneCore.ResetLastEventTime(Node: TX3DNode);
7020 var
7021 I: Integer;
7022 begin
7023 for I := 0 to Node.RoutesCount - 1 do
7024 Node.Routes[I].ResetLastEventTime;
7025 // TODO: Delphi Support
7026 {$ifdef FPC}
7027 if Node is TAbstractScriptNode then
7028 TAbstractScriptNode(Node).ResetLastEventTimes;
7029 {$endif}
7030 end;
7031
7032 procedure TCastleSceneCore.ResetTime(const NewValue: TFloatTime);
7033 begin
7034 if RootNode <> nil then
7035 RootNode.EnumerateNodes({$ifdef FPC}@{$endif}ResetLastEventTime,
7036 false);
7037 InternalSetTime(NewValue, 0, true);
7038 end;
7039
7040 procedure TCastleSceneCore.ResetTimeAtLoad;
7041 begin
7042 if (NavigationInfoStack.Top <> nil) and
7043 NavigationInfoStack.Top.TimeOriginAtLoad then
7044 FTimeAtLoad := 0.0
7045 else
7046 FTimeAtLoad := DateTimeToUnix(CastleNow);
7047 ResetTime(TimeAtLoad);
7048 end;
7049
7050 procedure TCastleSceneCore.IncreaseTimeTick;
7051 begin
7052 Inc(FTimeNow.PlusTicks);
7053 end;
7054
7055 procedure TCastleSceneCore.InternalCameraChanged;
7056
7057 { Does CameraProcessing needs to be called (does it actually do anything). }
7058 function CameraProcessingNeeded: boolean;
7059 begin
7060 Result :=
7061 (ShapeLODs.Count <> 0) or
7062 (ProximitySensors.Count <> 0) or
7063 (BillboardNodes.Count <> 0);
7064 end;
7065
7066 { Update things depending on camera information and X3D events.
7067 Call it only when ProcessEvents. }
7068 procedure CameraProcessing(const CameraVectors: TViewVectors);
7069 var
7070 I: Integer;
7071 begin
7072 Assert(ProcessEvents);
7073
7074 for I := 0 to ShapeLODs.Count - 1 do
7075 UpdateLODLevel(TShapeTreeLOD(ShapeLODs.Items[I]), CameraVectors.Translation);
7076
7077 for I := 0 to ProximitySensors.Count - 1 do
7078 ProximitySensorUpdate(ProximitySensors[I], CameraVectors);
7079
7080 { Update camera information on all Billboard nodes,
7081 and retraverse scene from Billboard nodes. So we treat Billboard nodes
7082 much like Transform nodes, except that their transformation animation
7083 is caused by camera changes, not by changes to field values.
7084
7085 TODO: If one Billboard is under transformation of another Billboard,
7086 this will be a little wasteful. We should update first all camera
7087 information, and then update only Billboard nodes that do not have
7088 any parent Billboard nodes. }
7089 for I := 0 to BillboardNodes.Count - 1 do
7090 begin
7091 (BillboardNodes[I] as TBillboardNode).InternalCameraChanged(CameraVectors);
7092 { Apply transformation change to Shapes tree.
7093 Note that we should never call TransformationChanged when
7094 OptimizeExtensiveTransformations. }
7095 if OptimizeExtensiveTransformations then
7096 TransformationDirty := true
7097 else
7098 TransformationChanged(BillboardNodes[I].TransformFunctionality);
7099 end;
7100 end;
7101
7102 var
7103 CameraVectors: TViewVectors;
7104 begin
7105 if World <> nil then // may be called from SetProcessEvents when World may be nil
7106 LastCameraStateId := World.InternalMainCameraStateId;
7107
7108 if ProcessEvents and
7109 CameraProcessingNeeded and
7110 { call GetCameraLocal only when necessary, as it does some calculations }
7111 GetCameraLocal(CameraVectors) then
7112 begin
7113 BeginChangesSchedule;
7114 try
7115 CameraProcessing(CameraVectors);
7116 finally EndChangesSchedule end;
7117 end;
7118
7119 { handle WatchForTransitionComplete, looking at ACamera.Animation }
7120 (* TODO: we don't camera TCamera reference now,
7121 - we do not generate EventTransitionComplete now,
7122 - we never update WatchForTransitionComplete to false.
7123 This is not a critical feature, for X3D authors or Pascal developers.
7124
7125 if ProcessEvents and WatchForTransitionComplete and not ACamera.Animation then
7126 begin
7127 BeginChangesSchedule;
7128 try
7129 WatchForTransitionComplete := false;
7130 if NavigationInfoStack.Top <> nil then
7131 NavigationInfoStack.Top.EventTransitionComplete.Send(true, NextEventTime);
7132 finally EndChangesSchedule end;
7133 end;
7134 *)
7135 end;
7136
7137 procedure TCastleSceneCore.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
7138 var
7139 SP: Single;
7140 begin
7141 inherited;
7142 if not Exists then Exit;
7143
7144 { in case the same scene is present many times on Viewport.Items list,
7145 do not process it's Update() many times (would cause time to move too fast). }
7146 if LastUpdateFrameId = TFramesPerSecond.FrameId then Exit;
7147 LastUpdateFrameId := TFramesPerSecond.FrameId;
7148
7149 FrameProfiler.Start(fmUpdateScene);
7150
7151 if (World <> nil) and
7152 (LastCameraStateId <> World.InternalMainCameraStateId) then
7153 InternalCameraChanged; // sets LastCameraStateId
7154
7155 { Most of the "update" job happens inside InternalSetTime.
7156 Reasons are partially historiec: TCastlePrecalculatedAnimation
7157 called only SetTime, not Update. }
7158
7159 { Ignore calls when SecondsPassed is precisely zero
7160 (this may happen, and is correct, see TFramesPerSecond.ZeroNextSecondsPassed).
7161 In this case, time increase will be zero so the whole code
7162 will not do anything anyway.
7163
7164 (Well, time dependent nodes like TimeSensor could "realize" that startTime
7165 happened *now*, and send initial events to start animation.
7166 But actually we take care of it in HandleChangeTimeStopStart.) }
7167 SP := TimePlayingSpeed * SecondsPassed;
7168 if TimePlaying and (SP <> 0) then
7169 IncreaseTime(SP);
7170
7171 FrameProfiler.Stop(fmUpdateScene);
7172 end;
7173
7174 procedure TCastleSceneCore.PartialSendBegin(const TimeFunctionality: TTimeDependentFunctionality);
7175 var
7176 T: TFloatTime;
7177 PartialSend: TPartialSend;
7178 begin
7179 T := Time;
7180
7181 if (PlayingAnimationTransitionDuration <> 0) { often early exit } and
7182 (TimeFunctionality.Parent = PlayingAnimationNode) and
7183 (T >= PlayingAnimationStartTime) { only sanity check } and
7184 (T < PlayingAnimationStartTime + PlayingAnimationTransitionDuration) then
7185 begin
7186 PartialSend := TPartialSend.Create;
7187 TimeFunctionality.PartialSend := PartialSend;
7188
7189 if PreviousPlayingAnimation <> nil then
7190 begin
7191 PartialSend.Partial := 1 - (T - PlayingAnimationStartTime) /
7192 PlayingAnimationTransitionDuration;
7193 PartialSend.IgnoreIfCannotLerp := true;
7194
7195 { First fade-out previous animation.
7196 Note that
7197 - PreviousPlayingAnimation may be equal to PlayingAnimationNode
7198 (in case when PlayAnimation starts the same animation from beginning)
7199 and we still must work correctly.
7200 - We do not use FadingOutAnimation.TimeFunctionality.SetTime,
7201 as we do not want to activate/deactivate PreviousPlayingAnimation
7202 time sensor,
7203 and we do not want to look at enabled state of time sensor.
7204 }
7205 PreviousPlayingAnimation.FakeTime(PreviousPlayingAnimationTimeInAnimation
7206 + (T - PlayingAnimationStartTime),
7207 PreviousPlayingAnimationLoop,
7208 PreviousPlayingAnimationForward,
7209 NextEventTime,
7210 PartialSend);
7211 end;
7212
7213 { calculate Result.Partial that should be passed
7214 to PlayingAnimationNode }
7215 PartialSend.Partial := (T - PlayingAnimationStartTime) /
7216 PlayingAnimationTransitionDuration;
7217 PartialSend.IgnoreIfCannotLerp := false;
7218 end else
7219 TimeFunctionality.PartialSend := nil;
7220 end;
7221
7222 procedure TCastleSceneCore.PartialSendEnd(const TimeFunctionality: TTimeDependentFunctionality);
7223
7224 function FieldsEqual(const L1, L2: TX3DFieldList): boolean;
7225 var
7226 I: Integer;
7227 begin
7228 Result := L1.Count = L2.Count;
7229 if Result then
7230 for I := 0 to L1.Count - 1 do
7231 if L1[I] <> L2[I] then
7232 Exit(false);
7233 end;
7234
7235 var
7236 F: TX3DField;
7237 AffectedFields: TX3DFieldList;
7238 begin
7239 if TimeFunctionality.PartialSend <> nil then
7240 begin
7241 AffectedFields := TimeFunctionality.PartialSend.AffectedFields;
7242 TimeFunctionality.PartialSend.AffectedFields := nil; // do not free by TPartialSend.Destroy
7243 FreeAndNil(TimeFunctionality.PartialSend);
7244
7245 { call InternalAffectedPartial on all AffectedFields, to correctly update
7246 their values. }
7247 for F in AffectedFields do
7248 F.InternalAffectedPartial;
7249
7250 { call InternalRemovePartial on all fields affected in previous frame,
7251 but not affected this frame. }
7252 if PreviousPartialAffectedFields <> nil then
7253 begin
7254 { optimize the most common case, when PreviousPartialAffectedFields
7255 is equal to AffectedFields. }
7256 if not FieldsEqual(PreviousPartialAffectedFields, AffectedFields) then
7257 for F in PreviousPartialAffectedFields do
7258 if not AffectedFields.Contains(F) then
7259 F.InternalRemovePartial;
7260 FreeAndNil(PreviousPartialAffectedFields);
7261 end;
7262
7263 PreviousPartialAffectedFields := AffectedFields;
7264 end;
7265 end;
7266
7267 procedure TCastleSceneCore.NoPartialSend;
7268 var
7269 F: TX3DField;
7270 begin
7271 if PreviousPartialAffectedFields <> nil then
7272 begin
7273 for F in PreviousPartialAffectedFields do
7274 F.InternalRemovePartial;
7275 FreeAndNil(PreviousPartialAffectedFields);
7276 end;
7277 end;
7278
7279 { changes schedule ----------------------------------------------------------- }
7280
7281 procedure TCastleSceneCore.BeginChangesSchedule;
7282 begin
7283 { ChangedAllScheduled = false always when ChangedAllSchedule = 0. }
7284 Assert((ChangedAllSchedule <> 0) or (not ChangedAllScheduled));
7285
7286 ChangedAllScheduledOnlyAdditions := true; // may be changed to false by ScheduleChangedAll
7287
7288 Inc(ChangedAllSchedule);
7289 end;
7290
7291 procedure TCastleSceneCore.ScheduleChangedAll(const OnlyAdditions: Boolean);
7292 begin
7293 if ChangedAllSchedule = 0 then
7294 ChangedAll
7295 else
7296 begin
7297 ChangedAllScheduled := true;
7298 ChangedAllScheduledOnlyAdditions := ChangedAllScheduledOnlyAdditions and OnlyAdditions;
7299 end;
7300 end;
7301
7302 procedure TCastleSceneCore.EndChangesSchedule;
7303 begin
7304 Dec(ChangedAllSchedule);
7305 if (ChangedAllSchedule = 0) and ChangedAllScheduled then
7306 begin
7307 { Note that ChangedAll will set ChangedAllScheduled to false. }
7308 ChangedAll(ChangedAllScheduledOnlyAdditions);
7309 end;
7310 end;
7311
7312 { proximity sensor ----------------------------------------------------------- }
7313
7314 procedure TCastleSceneCore.ProximitySensorUpdate(const PSI: TProximitySensorInstance;
7315 const CameraVectors: TViewVectors);
7316 var
7317 APosition, ADirection, AUp: TVector3;
7318 ProxNode: TProximitySensorNode;
7319 NewIsActive: boolean;
7320 begin
7321 if ProcessEvents then
7322 begin
7323 BeginChangesSchedule;
7324 try
7325 ProxNode := PSI.Node;
7326 if not ProxNode.FdEnabled.Value then Exit;
7327
7328 { In each ProximitySensorUpdate we transform CameraPosition to
7329 ProximitySensor coordinate-space. This allows us to check
7330 whether the camera is inside ProximitySensor precisely
7331 (otherwise transforming ProximitySensor box could make a larger
7332 box, as we do not support oriented bounding boxes, only
7333 axis-aligned).
7334
7335 This is also needed to generate position_changed value,
7336 as it has to be in ProximitySensor coordinate-space.
7337
7338 Also, since we don't store precalculated box of ProximitySensor,
7339 we can gracefully react in InternalChangedField to changes:
7340 - changes to ProximitySensor center and size must only produce
7341 new ProximitySensorUpdate to eventually activate/deactivate ProximitySensor
7342 - changes to transforms affecting ProximitySensor must only update
7343 it's InverseTransform and call ProximitySensorUpdate.
7344 }
7345
7346 APosition := PSI.InverseTransform.MultPoint(CameraVectors.Translation);
7347
7348 NewIsActive :=
7349 (APosition.X >= ProxNode.FdCenter.Value.X - ProxNode.FdSize.Value.X / 2) and
7350 (APosition.X <= ProxNode.FdCenter.Value.X + ProxNode.FdSize.Value.X / 2) and
7351 (APosition.Y >= ProxNode.FdCenter.Value.Y - ProxNode.FdSize.Value.Y / 2) and
7352 (APosition.Y <= ProxNode.FdCenter.Value.Y + ProxNode.FdSize.Value.Y / 2) and
7353 (APosition.Z >= ProxNode.FdCenter.Value.Z - ProxNode.FdSize.Value.Z / 2) and
7354 (APosition.Z <= ProxNode.FdCenter.Value.Z + ProxNode.FdSize.Value.Z / 2) and
7355 { ... and the box is not empty, which for ProximitySensor
7356 is signalled by any size <= 0 (yes, equal 0 also means empty).
7357 We check this at the end, as this is the least common situation? }
7358 (ProxNode.FdSize.Value.X > 0) and
7359 (ProxNode.FdSize.Value.Y > 0) and
7360 (ProxNode.FdSize.Value.Z > 0);
7361
7362 if NewIsActive <> PSI.IsActive then
7363 begin
7364 PSI.IsActive := NewIsActive;
7365 ProxNode.EventIsActive.Send(NewIsActive, NextEventTime);
7366 if NewIsActive then
7367 ProxNode.EventEnterTime.Send(Time, NextEventTime) else
7368 ProxNode.EventExitTime.Send(Time, NextEventTime);
7369 end;
7370
7371 { Call position_changed, orientation_changed, even if this is just
7372 the first time NewIsActive = true (that is, even when it was
7373 NewIsActive <> PSI.IsActive). Reasoning: this allows to activate
7374 ProximitySensor when world starts (before player moves),
7375 which is a wanted feature. }
7376
7377 if NewIsActive then
7378 begin
7379 ProxNode.EventPosition_Changed.Send(APosition, NextEventTime);
7380 if ProxNode.EventOrientation_Changed.SendNeeded then
7381 begin
7382 ADirection := PSI.InverseTransform.MultDirection(CameraVectors.Direction);
7383 AUp := PSI.InverseTransform.MultDirection(CameraVectors.Up);
7384 ProxNode.EventOrientation_Changed.Send(
7385 OrientationFromDirectionUp(ADirection, AUp), NextEventTime);
7386 end;
7387 { TODO: centerOfRotation_changed }
7388 end;
7389 finally
7390 EndChangesSchedule;
7391 end;
7392 end;
7393 end;
7394
7395 { camera --------------------------------------------------------------------- }
7396
7397 function TCastleSceneCore.GetCameraLocal(
7398 out CameraVectors: TViewVectors): boolean;
7399 begin
7400 // note that HasWorldTransform implies also World <> nil
7401 Result := HasWorldTransform and (World.MainCamera <> nil);
7402 if Result then
7403 begin
7404 World.MainCamera.GetWorldView(
7405 CameraVectors.Translation,
7406 CameraVectors.Direction,
7407 CameraVectors.Up);
7408 CameraVectors.Translation := WorldInverseTransform.MultPoint (CameraVectors.Translation);
7409 CameraVectors.Direction := WorldInverseTransform.MultDirection(CameraVectors.Direction);
7410 CameraVectors.Up := WorldInverseTransform.MultDirection(CameraVectors.Up);
7411 end;
7412 end;
7413
7414 function TCastleSceneCore.GetCameraLocal(
7415 out CameraLocalPosition: TVector3): boolean;
7416 begin
7417 // note that HasWorldTransform implies also World <> nil
7418 Result := HasWorldTransform and (World.MainCamera <> nil);
7419 if Result then
7420 CameraLocalPosition := WorldInverseTransform.MultPoint(World.MainCamera.WorldTranslation);
7421 end;
7422
7423 procedure TCastleSceneCore.ChangedTransform;
7424 begin
7425 inherited;
7426 { WorldInverseTransform changed, so update things depending on camera view.
7427 TODO: This way doesn't make a notification when WorldInverseTransform
7428 changed because parent transform changed.
7429 We should look at FWorldTransformAndInverseId changes to detect this? }
7430 InternalCameraChanged;
7431 end;
7432
7433 procedure TCastleSceneCore.ChangeWorld(const Value: TCastleAbstractRootTransform);
7434 begin
7435 inherited;
7436
7437 { World changed, so update things depending on camera view.
7438 This is important to make ProximitySensors, Billboard etc. work immediately
7439 when item is part of the world (and knows the camera),
7440 and has ProcessEvents = true.
7441
7442 Testcase:
7443
7444 - 1st frame rendering not using BlendingSort for non-MainScene scenes:
7445 trees_blending/CW_demo.lpr testcase from Eugene.
7446 - Billboards test from Kagamma:
7447 https://sourceforge.net/p/castle-engine/discussion/general/thread/882ca037/
7448 https://gist.github.com/michaliskambi/9520282717870d3be1511412754958e9
7449
7450 }
7451 if Value <> nil then
7452 InternalCameraChanged;
7453 end;
7454
7455 { compiled scripts ----------------------------------------------------------- }
7456
7457 procedure TCastleSceneCore.RegisterCompiledScript(const HandlerName: String;
7458 Handler: TCompiledScriptHandler);
7459 var
7460 HandlerInfo: PCompiledScriptHandlerInfo;
7461 begin
7462 HandlerInfo := PCompiledScriptHandlerInfo(CompiledScriptHandlers.Add);
7463 HandlerInfo^.Handler := Handler;
7464 HandlerInfo^.Name := HandlerName;
7465 end;
7466
7467 procedure TCastleSceneCore.ExecuteCompiledScript(const HandlerName: String;
7468 ReceivedValue: TX3DField);
7469 var
7470 I: Integer;
7471 begin
7472 for I := 0 to CompiledScriptHandlers.Count - 1 do
7473 if CompiledScriptHandlers.L[I].Name = HandlerName then
7474 begin
7475 CompiledScriptHandlers.L[I].Handler(ReceivedValue, NextEventTime);
7476 Break;
7477 end;
7478 end;
7479
7480 { camera ------------------------------------------------------------------ }
7481
7482 function TCastleSceneCore.SensibleCameraRadius(out RadiusAutoCalculated: Boolean): Single;
7483 var
7484 NavigationNode: TNavigationInfoNode;
7485 begin
7486 Result := 0;
7487 RadiusAutoCalculated := false;
7488
7489 NavigationNode := NavigationInfoStack.Top;
7490 if (NavigationNode <> nil) and
7491 (NavigationNode.FdAvatarSize.Count >= 1) then
7492 Result := NavigationNode.FdAvatarSize.Items[0];
7493
7494 { if avatarSize doesn't specify Radius, or specifies invalid <= 0,
7495 use DefaultCameraRadius. }
7496 if Result <= 0 then
7497 begin
7498 Result := DefaultCameraRadius;
7499 RadiusAutoCalculated := true;
7500 end;
7501 end;
7502
7503 procedure TCastleSceneCore.InternalUpdateNavigation(
7504 const Navigation: TCastleNavigation);
7505 var
7506 NavigationNode: TNavigationInfoNode;
7507 ViewpointNode: TAbstractViewpointNode;
7508 Radius: Single;
7509 RadiusAutoCalculated: Boolean;
7510
7511 procedure UpdateWalkNavigation(const Navigation: TCastleWalkNavigation);
7512 begin
7513 { calculate Navigation.PreferredHeight }
7514 if (NavigationNode <> nil) and
7515 (NavigationNode.FdAvatarSize.Count >= 2) then
7516 Navigation.PreferredHeight := NavigationNode.FdAvatarSize.Items[1]
7517 else
7518 Navigation.PreferredHeight := Max(TCastleNavigation.DefaultPreferredHeight, Radius * RadiusToPreferredHeightMin);
7519
7520 Navigation.CorrectPreferredHeight;
7521
7522 { calculate Navigation.ClimbHeight }
7523 if (NavigationNode <> nil) and
7524 (NavigationNode.FdAvatarSize.Count >= 3) then
7525 Navigation.ClimbHeight := Max(NavigationNode.FdAvatarSize.Items[2], 0.0)
7526 else
7527 Navigation.ClimbHeight := 0;
7528
7529 { calculate Navigation.HeadBobbing* }
7530 if NavigationNode <> nil then
7531 begin
7532 Navigation.HeadBobbing := NavigationNode.HeadBobbing;
7533 Navigation.HeadBobbingTime := NavigationNode.HeadBobbingTime;
7534 end else
7535 begin
7536 Navigation.HeadBobbing := TCastleWalkNavigation.DefaultHeadBobbing;
7537 Navigation.HeadBobbingTime := TCastleWalkNavigation.DefaultHeadBobbingTime;
7538 end;
7539
7540 { calculate Navigation.MoveSpeed }
7541 if NavigationNode = nil then
7542 { Since we don't have NavigationNode.speed, we just calculate some
7543 speed that should "feel sensible". We base it on Radius,
7544 that was set above. }
7545 Navigation.MoveSpeed := Navigation.Radius * 20
7546 else
7547 { This is OK, also for NavigationNode.FdSpeed.Value = 0 case. }
7548 Navigation.MoveSpeed := NavigationNode.FdSpeed.Value;
7549 end;
7550
7551 procedure UpdateExamineNavigation(const Navigation: TCastleExamineNavigation);
7552 begin
7553 if ViewpointNode <> nil then
7554 begin
7555 Navigation.AutoCenterOfRotation := ViewpointNode.AutoCenterOfRotation;
7556 Navigation.CenterOfRotation := ViewpointNode.Transform.MultPoint(
7557 ViewpointNode.CenterOfRotation);
7558 end else
7559 begin
7560 Navigation.AutoCenterOfRotation := true;
7561 Navigation.CenterOfRotation := TVector3.Zero; // remove previous customization of this property
7562 end;
7563 end;
7564
7565 begin
7566 NavigationNode := NavigationInfoStack.Top;
7567 ViewpointNode := ViewpointStack.Top;
7568
7569 { calculate Radius }
7570 Radius := SensibleCameraRadius(RadiusAutoCalculated);
7571 Navigation.Radius := Radius;
7572
7573 if Navigation is TCastleWalkNavigation then
7574 UpdateWalkNavigation(TCastleWalkNavigation(Navigation));
7575 if Navigation is TCastleExamineNavigation then
7576 UpdateExamineNavigation(TCastleExamineNavigation(Navigation));
7577 end;
7578
7579 procedure TCastleSceneCore.InternalUpdateCamera(const ACamera: TCastleCamera;
7580 const WorldBox: TBox3D;
7581 const RelativeCameraTransform, AllowTransitionAnimate: boolean);
7582 var
7583 APosition: TVector3;
7584 ADirection: TVector3;
7585 AUp: TVector3;
7586 GravityUp: TVector3;
7587 Radius, OriginX, OriginY: Single;
7588 RadiusAutoCalculated: Boolean;
7589 ViewpointNode: TAbstractViewpointNode;
7590 NavigationNode: TNavigationInfoNode;
7591 FieldOfView: TSingleList;
7592 begin
7593 Radius := SensibleCameraRadius(RadiusAutoCalculated);
7594 if RadiusAutoCalculated then
7595 { Set ProjectionNear to zero, this way we avoid serializing value
7596 when it is not necessary to serialize it
7597 (because it can be calculated by each TCastleViewport.CalculateProjection). }
7598 ACamera.ProjectionNear := 0
7599 else
7600 ACamera.ProjectionNear := Radius * RadiusToProjectionNear;
7601
7602 { Default projection parameters.
7603 Reset here anything that is determined by TCastleSceneCore.InternalUpdateCamera. }
7604 ACamera.ProjectionType := ptPerspective;
7605 ACamera.ProjectionFar := 0;
7606 ACamera.Perspective.FieldOfView := TCastlePerspective.DefaultFieldOfView;
7607 ACamera.Perspective.FieldOfViewAxis := TCastlePerspective.DefaultFieldOfViewAxis;
7608 ACamera.Orthographic.Width := 0;
7609 ACamera.Orthographic.Height := 0;
7610 ACamera.Orthographic.Origin := TVector2.Zero;
7611 {$warnings off} // using deprecated to keep it working
7612 ACamera.Orthographic.Stretch := false;
7613 {$warnings on}
7614
7615 ViewpointNode := ViewpointStack.Top;
7616 NavigationNode := NavigationInfoStack.Top;
7617
7618 if ViewpointNode <> nil then
7619 begin
7620 ViewpointNode.GetView(APosition, ADirection, AUp, GravityUp);
7621
7622 { Transform into world coordinates, as camera is set in world coordinates.
7623 As an exception for backward compatibility: when HasWorldTransform = false,
7624 we just assume that this scene will be added to world without any transformations.
7625
7626 This is possible when you load a scene to Viewport.Items.MainScene,
7627 but MainScene is not yet part of Viewport.Items, like
7628
7629 Viewport.Items.MainScene := TCastleScene.Create(Self);
7630 Viewport.Items.MainScene.Load(...);
7631 Viewport.Items.Insert(0, Items.MainScene);
7632
7633 ... which is even done by src/deprecated_units/castlelevels.pas.
7634 Then MainScene.Load causes InternalUpdateCamera, with MainScene being used.
7635 In the long-term future, some day MainScene will be removed and this
7636 complication should disappear.
7637
7638 Testcase: mountains-of-fire. }
7639 if HasWorldTransform then
7640 begin
7641 APosition := WorldTransform.MultPoint (APosition);
7642 ADirection := WorldTransform.MultDirection(ADirection);
7643 AUp := WorldTransform.MultDirection(AUp);
7644 GravityUp := WorldTransform.MultDirection(GravityUp);
7645 end;
7646
7647 if ViewpointNode is TViewpointNode then
7648 begin
7649 ACamera.Perspective.FieldOfView :=
7650 TViewpointNode(ViewpointNode).FieldOfView;
7651 if TViewpointNode(ViewpointNode).FieldOfViewForceVertical then
7652 ACamera.Perspective.FieldOfViewAxis := faVertical;
7653 end else
7654 if ViewpointNode is TPerspectiveCameraNode_1 then
7655 begin
7656 ACamera.Perspective.FieldOfView :=
7657 TPerspectiveCameraNode_1(ViewpointNode).FdHeightAngle.Value;
7658 end else
7659 if ViewpointNode is TOrthoViewpointNode then
7660 begin
7661 ACamera.ProjectionType := ptOrthographic;
7662
7663 { default Dimensions, for default OrthoViewpoint.fieldOfView }
7664 ACamera.Orthographic.Width := 2;
7665 ACamera.Orthographic.Height := 2;
7666 OriginX := 0.5;
7667 OriginY := 0.5;
7668
7669 FieldOfView := TOrthoViewpointNode(ViewpointNode).FdFieldOfView.Items;
7670
7671 if FieldOfView.Count > 2 then ACamera.Orthographic.Width := FieldOfView.Items[2] - FieldOfView.Items[0];
7672 if FieldOfView.Count > 3 then ACamera.Orthographic.Height := FieldOfView.Items[3] - FieldOfView.Items[1];
7673
7674 if FieldOfView.Count > 0 then OriginX := - FieldOfView.Items[0] / ACamera.Orthographic.Width;
7675 if FieldOfView.Count > 1 then OriginY := - FieldOfView.Items[1] / ACamera.Orthographic.Height;
7676
7677 ACamera.Orthographic.Origin := Vector2(OriginX, OriginY);
7678 end else
7679 if ViewpointNode is TOrthographicCameraNode_1 then
7680 begin
7681 ACamera.ProjectionType := ptOrthographic;
7682 ACamera.Orthographic.Width := TOrthographicCameraNode_1(ViewpointNode).FdHeight.Value;
7683 ACamera.Orthographic.Height := TOrthographicCameraNode_1(ViewpointNode).FdHeight.Value;
7684 ACamera.Orthographic.Origin := Vector2(0.5, 0.5);
7685 end;
7686 end else
7687 begin
7688 { Suitable viewpoint,
7689 with dir -Z and up +Y (like standard VRML/X3D viewpoint) }
7690 CameraViewpointForWholeScene(WorldBox, 2, 1, false, true,
7691 APosition, ADirection, AUp, GravityUp);
7692 end;
7693
7694 if NavigationNode <> nil then
7695 ACamera.ProjectionFar := NavigationNode.VisibilityLimit;
7696
7697 ACamera.GravityUp := GravityUp;
7698
7699 { TODO:
7700 If RelativeCameraTransform, then we should move relative to initial camera changes,
7701 to honor X3D dictated Viewpoint animation behavior.
7702 Right now, we always behave like RelativeCameraTransform=false. }
7703
7704 if AllowTransitionAnimate and (not ForceTeleportTransitions) then
7705 {$warnings off} // using deprecated, it really should be internal - camera transition following X3D events
7706 CameraTransition(ACamera, APosition, ADirection, AUp)
7707 {$warnings on}
7708 else
7709 ACamera.SetWorldView(APosition, ADirection, AUp);
7710 end;
7711
7712 procedure TCastleSceneCore.CameraTransition(const Camera: TCastleCamera;
7713 const APosition, ADirection, AUp: TVector3);
7714 var
7715 TransitionAnimate: boolean;
7716 TransitionTime: TFloatTime;
7717 NavigationNode: TNavigationInfoNode;
7718 TransitionType: String;
7719 I: Integer;
7720 begin
7721 NavigationNode := NavigationInfoStack.Top;
7722
7723 TransitionAnimate := true;
7724 TransitionTime := 1;
7725
7726 { check NavigationInfo.transitionType, update TransitionAnimate.
7727 If we have LINEAR or ANIMATE or only unknown transition types,
7728 spec says to use animation. }
7729 if NavigationNode <> nil then
7730 for I := 0 to NavigationNode.FdTransitionType.Count - 1 do
7731 begin
7732 TransitionType := NavigationNode.FdTransitionType.Items[I];
7733 if TransitionType = 'TELEPORT' then
7734 begin
7735 TransitionAnimate := false;
7736 Break;
7737 end else
7738 if (TransitionType = 'LINEAR') or (TransitionType = 'ANIMATE') then
7739 { Leave TransitionAnimate as true }
7740 Break else
7741 WritelnWarning('X3D', Format('Unrecognized transitionType "%s"', [TransitionType]));
7742 end;
7743
7744 { calculate TransitionTime }
7745 if NavigationNode <> nil then
7746 begin
7747 TransitionTime := NavigationNode.FdTransitionTime.Value;
7748 { correct TransitionAnimate in case TransitionTime invalid }
7749 if TransitionTime <= 0 then
7750 TransitionAnimate := false;
7751 end;
7752
7753 if TransitionAnimate then
7754 begin
7755 Camera.AnimateTo(APosition, ADirection, AUp, TransitionTime);
7756 WatchForTransitionComplete := true;
7757 end else
7758 begin
7759 Camera.SetWorldView(APosition, ADirection, AUp);
7760 if NavigationInfoStack.Top <> nil then
7761 NavigationInfoStack.Top.EventTransitionComplete.Send(true, NextEventTime);
7762 end;
7763 end;
7764
7765 procedure TCastleSceneCore.CameraTransition(const Camera: TCastleCamera;
7766 const APosition, ADirection, AUp, GravityUp: TVector3);
7767 begin
7768 Camera.GravityUp := GravityUp;
7769 {$warnings off} // using deprecated in deprecated
7770 CameraTransition(Camera, APosition, ADirection, AUp);
7771 {$warnings on}
7772 end;
7773
7774 procedure TCastleSceneCore.CameraTransition(const Navigation: TCastleNavigation;
7775 const APosition, ADirection, AUp: TVector3);
7776 begin
7777 {$warnings off} // using deprecated in deprecated
7778 CameraTransition(Navigation.Camera, APosition, ADirection, AUp);
7779 {$warnings on}
7780 end;
7781
7782 procedure TCastleSceneCore.CameraTransition(const Navigation: TCastleNavigation;
7783 const APosition, ADirection, AUp, GravityUp: TVector3);
7784 begin
7785 {$warnings off} // using deprecated in deprecated
7786 CameraTransition(Navigation.Camera, APosition, ADirection, AUp, GravityUp);
7787 {$warnings on}
7788 end;
7789
7790 { misc ----------------------------------------------------------------------- }
7791
7792 function TCastleSceneCore.GetViewpointStack: TX3DBindableStackBasic;
7793 begin
7794 Result := FViewpointStack;
7795 end;
7796
7797 function TCastleSceneCore.GetNavigationInfoStack: TX3DBindableStackBasic;
7798 begin
7799 Result := FNavigationInfoStack;
7800 end;
7801
7802 function TCastleSceneCore.GetBackgroundStack: TX3DBindableStackBasic;
7803 begin
7804 Result := FBackgroundStack;
7805 end;
7806
7807 function TCastleSceneCore.GetFogStack: TX3DBindableStackBasic;
7808 begin
7809 Result := FFogStack;
7810 end;
7811
7812 procedure TCastleSceneCore.CalculateMainLightForShadowsPosition;
7813 begin
7814 if FMainLightForShadowsNode is TAbstractPositionalLightNode then
7815 FMainLightForShadows := Vector4(
7816 FMainLightForShadowsTransform.MultPoint(
7817 TAbstractPositionalLightNode(FMainLightForShadowsNode).FdLocation.Value), 1) else
7818 if FMainLightForShadowsNode is TAbstractDirectionalLightNode then
7819 FMainLightForShadows := Vector4(
7820 FMainLightForShadowsTransform.MultDirection(
7821 TAbstractDirectionalLightNode(FMainLightForShadowsNode).FdDirection.Value).Normalize, 0) else
7822 raise Exception.CreateFmt('TCastleSceneCore.MainLightForShadows: ' +
7823 'light node "%s" cannot be used to cast shadows, it has no position ' +
7824 'and no direction', [FMainLightForShadowsNode.X3DType]);
7825 end;
7826
7827 function TCastleSceneCore.SearchMainLightForShadows(
7828 Node: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
7829 ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean): Pointer;
7830 var
7831 L: TAbstractPunctualLightNode absolute Node;
7832 begin
7833 if L.FdShadowVolumes.Value and
7834 L.FdShadowVolumesMain.Value then
7835 begin
7836 FMainLightForShadowsNode := L;
7837 FMainLightForShadowsTransform := StateStack.Top.Transformation.Transform;
7838 FMainLightForShadowsExists := true;
7839 CalculateMainLightForShadowsPosition;
7840 Result := Node; // anything non-nil to break traversing
7841 end else
7842 Result := nil;
7843 end;
7844
7845 procedure TCastleSceneCore.ValidateMainLightForShadows;
7846
7847 procedure CalculateMainLightForShadows;
7848 begin
7849 FMainLightForShadowsExists := false;
7850 if RootNode <> nil then
7851 RootNode.Traverse(TAbstractPunctualLightNode,
7852 {$ifdef FPC}@{$endif}SearchMainLightForShadows);
7853 end;
7854
7855 begin
7856 if not (fvMainLightForShadows in Validities) then
7857 begin
7858 CalculateMainLightForShadows;
7859 Include(Validities, fvMainLightForShadows);
7860 end;
7861 end;
7862
7863 function TCastleSceneCore.InternalMainLightForShadowVolumes(
7864 out AMainLightPosition: TVector4): boolean;
7865 begin
7866 ValidateMainLightForShadows;
7867 Result := FMainLightForShadowsExists;
7868 if Result then
7869 AMainLightPosition := FMainLightForShadows;
7870 end;
7871
7872 procedure TCastleSceneCore.SetHeadlightOn(const Value: boolean);
7873 begin
7874 if FHeadlightOn <> Value then
7875 begin
7876 FHeadlightOn := Value;
7877 if Assigned(OnHeadlightOnChanged) then OnHeadlightOnChanged(Self);
7878 if NavigationInfoStack.Top <> nil then
7879 NavigationInfoStack.Top.FdHeadlight.Send(HeadlightOn);
7880 end;
7881 end;
7882
7883 function TCastleSceneCore.CustomHeadlight: TAbstractLightNode;
7884 begin
7885 if NavigationInfoStack.Top <> nil then
7886 Result := NavigationInfoStack.Top.HeadlightNode
7887 else
7888 Result := nil;
7889 end;
7890
7891 procedure TCastleSceneCore.UpdateHeadlightOnFromNavigationInfo;
7892 begin
7893 if NavigationInfoStack.Top <> nil then
7894 HeadlightOn := NavigationInfoStack.Top.Headlight
7895 else
7896 HeadlightOn := DefaultNavigationInfoHeadlight;
7897 end;
7898
7899 procedure TCastleSceneCore.PrepareResources(const Options: TPrepareResourcesOptions;
7900 const Params: TPrepareParams);
7901
7902 { PrepareShapesOctrees and PrepareShadowVolumes could be optimized
7903 into one run }
7904
7905 procedure PrepareShapesOctrees;
7906 var
7907 ShapeList: TShapeList;
7908 Shape: TShape;
7909 begin
7910 ShapeList := Shapes.TraverseList(false);
7911 for Shape in ShapeList do
7912 Shape.InternalOctreeTriangles;
7913 end;
7914
7915 procedure PrepareShadowVolumes;
7916 var
7917 ShapeList: TShapeList;
7918 Shape: TShape;
7919 begin
7920 ShapeList := Shapes.TraverseList(false);
7921 for Shape in ShapeList do
7922 Shape.InternalShadowVolumes.PrepareResources;
7923 end;
7924
7925 begin
7926 inherited;
7927
7928 if prBoundingBox in Options then
7929 LocalBoundingBox { ignore the result };
7930
7931 if prShadowVolume in Options then
7932 PrepareShadowVolumes;
7933
7934 if prSpatial in Options then
7935 begin
7936 InternalOctreeRendering;
7937 InternalOctreeDynamicCollisions;
7938 InternalOctreeVisibleTriangles;
7939 InternalOctreeStaticCollisions;
7940 PrepareShapesOctrees;
7941 end;
7942 end;
7943
7944 procedure TCastleSceneCore.SetShadowMaps(const Value: boolean);
7945 begin
7946 if FShadowMaps <> Value then
7947 begin
7948 FShadowMaps := Value;
7949
7950 ScheduledShadowMapsProcessing := true;
7951 ScheduleChangedAll;
7952 end;
7953 end;
7954
7955 procedure TCastleSceneCore.SetShadowMapsDefaultSize(const Value: Cardinal);
7956 begin
7957 if FShadowMapsDefaultSize <> Value then
7958 begin
7959 FShadowMapsDefaultSize := Value;
7960
7961 if ShadowMaps then { if not ShadowMaps, then no need to reprocess }
7962 begin
7963 ScheduledShadowMapsProcessing := true;
7964 ScheduleChangedAll;
7965 end;
7966 end;
7967 end;
7968
7969 function TCastleSceneCore.Caption: String;
7970 var
7971 WorldInfoNode: TWorldInfoNode;
7972 begin
7973 if RootNode <> nil then
7974 {$warnings off} // using deprecated, as for now there's no way to search for unnamed nodes
7975 WorldInfoNode := RootNode.TryFindNode(TWorldInfoNode, true) as TWorldInfoNode
7976 {$warnings on}
7977 else
7978 WorldInfoNode := nil;
7979
7980 if (WorldInfoNode <> nil) and
7981 (WorldInfoNode.FdTitle.Value <> '') then
7982 Result := WorldInfoNode.FdTitle.Value else
7983 Result := UriCaption(Url);
7984 end;
7985
7986 function TCastleSceneCore.Node(const NodeClass: TX3DNodeClass; const NodeName: String;
7987 const Options: TFindNodeOptions): TX3DNode;
7988 begin
7989 if RootNode = nil then
7990 begin
7991 if fnNilOnMissing in Options then
7992 Result := nil
7993 else
7994 raise EX3DNotFound.CreateFmt('Cannot find node "%s" because no model is loaded', [NodeName]);
7995 end else
7996 Result := RootNode.FindNode(NodeClass, NodeName, Options);
7997 end;
7998
7999 function TCastleSceneCore.Node(const NodeName: String): TX3DNode;
8000 begin
8001 Result := Node(TX3DNode, NodeName);
8002 end;
8003
8004 function TCastleSceneCore.Field(const NodeName, FieldName: String): TX3DField;
8005 begin
8006 Result := Node(TX3DNode, NodeName).Field(FieldName);
8007 if Result = nil then
8008 raise EX3DNotFound.CreateFmt('Field name "%s" not found', [FieldName]);
8009 end;
8010
8011 function TCastleSceneCore.Event(const NodeName, EventName: String): TX3DEvent;
8012 begin
8013 Result := Node(TX3DNode, NodeName).AnyEvent(EventName);
8014 if Result = nil then
8015 raise EX3DNotFound.CreateFmt('Event name "%s" not found', [EventName]);
8016 end;
8017
8018 {$ifdef GENERIC_METHODS}
8019
8020 {$ifdef FPC}generic{$endif} function TCastleSceneCore.Node<T>(const NodeName: String;
8021 const Options: TFindNodeOptions): T;
8022 begin
8023 if RootNode = nil then
8024 raise EX3DNotFound.CreateFmt('Cannot find node "%s" because no model is loaded', [NodeName])
8025 else
8026 Result := RootNode.{$ifdef FPC}specialize{$endif} Find<T>(NodeName, Options);
8027 end;
8028
8029 {$ifdef FPC}generic{$endif} function TCastleSceneCore.Field<T>(const NodeName, FieldName: String): TX3DField;
8030 begin
8031 Result := {$ifdef FPC}specialize{$endif} Node<T>(NodeName).Field(FieldName);
8032 if Result = nil then
8033 raise EX3DNotFound.CreateFmt('Field name "%s" not found', [FieldName]);
8034 end;
8035
8036 {$ifdef FPC}generic{$endif} function TCastleSceneCore.Event<T>(const NodeName, EventName: String): TX3DEvent;
8037 begin
8038 Result := {$ifdef FPC}specialize{$endif} Node<T>(NodeName).AnyEvent(EventName);
8039 if Result = nil then
8040 raise EX3DNotFound.CreateFmt('Event name "%s" not found', [EventName]);
8041 end;
8042
8043 {$endif}
8044
8045 procedure TCastleSceneCore.InternalInvalidateBackgroundRenderer;
8046 begin
8047 end;
8048
8049 procedure TCastleSceneCore.UnregisterScene(Node: TX3DNode);
8050 begin
8051 Node.UnregisterScene;
8052 end;
8053
8054 function TCastleSceneCore.ViewpointsCount: Cardinal;
8055 begin
8056 Result := FViewpointsArray.Count;
8057 end;
8058
8059 function TCastleSceneCore.GetViewpointName(const Idx: integer): String;
8060 var
8061 ViewpointNode: TAbstractViewpointNode;
8062 begin
8063 ViewpointNode := GetViewpointNode(Idx); // returns nil for invalid Idx
8064 if ViewpointNode <> nil then
8065 Result := ViewpointNode.SmartDescription
8066 else
8067 Result := '';
8068 end;
8069
8070 function TCastleSceneCore.GetViewpointNode(const Idx: integer): TAbstractViewpointNode;
8071 begin
8072 if Between(Idx, 0, FViewpointsArray.Count - 1) then
8073 Result := FViewpointsArray[Idx]
8074 else
8075 Result := nil;
8076 end;
8077
8078 procedure TCastleSceneCore.MoveToViewpoint(const Idx: integer; const Animated: boolean);
8079 var
8080 SavedForceTeleport: boolean;
8081 ViewpointNode: TAbstractViewpointNode;
8082 begin
8083 ViewpointNode := GetViewpointNode(Idx); // returns nil for invalid Idx
8084 if ViewpointNode = nil then
8085 Exit;
8086
8087 if not Animated then
8088 begin
8089 SavedForceTeleport := ForceTeleportTransitions;
8090 ForceTeleportTransitions := true;
8091 end else
8092 SavedForceTeleport := false; // silence warning
8093
8094 if ViewpointNode = FViewpointStack.Top then
8095 ViewpointNode.Bound := false;
8096 ViewpointNode.Bound := true;
8097
8098 if not Animated then
8099 ForceTeleportTransitions := SavedForceTeleport;
8100 end;
8101
8102 procedure TCastleSceneCore.AddViewpointFromNavigation(
8103 const Navigation: TCastleNavigation; const AName: String);
8104 var
8105 APosition: TVector3;
8106 ADirection: TVector3;
8107 AUp: TVector3;
8108 GravityUp: TVector3;
8109 Version: TX3DCameraVersion;
8110 NewViewNodeMake: TMakeX3DViewpoint;
8111 NewViewNode: TAbstractChildNode;
8112 NewViewpointNode: TAbstractViewpointNode;
8113 NavigationType: String;
8114 Walk: TCastleWalkNavigation;
8115 Examine: TCastleExamineNavigation;
8116 WalkSpeed, VisibilityLimit: Single;
8117 AvatarSize: TVector3;
8118 NewNavigationNode: TNavigationInfoNode;
8119 NewGroupNode: TGroupNode;
8120 NewRoute: TX3DRoute;
8121 begin
8122 if RootNode = nil then
8123 raise Exception.Create('You have to initialize RootNode, usually just by loading some scene to TCastleSceneCore.Load, before adding viewpoints');
8124 if Navigation.Camera = nil then
8125 raise Exception.Create('Navigation must be part of some Viewport before using AddViewpointFromNavigation');
8126
8127 Navigation.Camera.GetWorldView(APosition, ADirection, AUp);
8128 GravityUp := Navigation.Camera.GravityUp;
8129
8130 if RootNode.HasForceVersion and (RootNode.ForceVersion.Major <= 1) then
8131 Version := cvVrml1_Inventor
8132 else
8133 Version := cvVrml2_X3d;
8134 NewViewNodeMake := TMakeX3DViewpoint.Create;
8135 try
8136 NewViewNodeMake.Version := Version;
8137 NewViewNodeMake.Position := APosition;
8138 NewViewNodeMake.Direction := ADirection;
8139 NewViewNodeMake.Up := AUp;
8140 NewViewNodeMake.GravityUp := GravityUp;
8141
8142 if Navigation is TCastleExamineNavigation then
8143 begin
8144 NewViewNodeMake.AutoCenterOfRotation := TCastleExamineNavigation(Navigation).AutoCenterOfRotation;
8145 NewViewNodeMake.CenterOfRotation := TCastleExamineNavigation(Navigation).CenterOfRotation;
8146 end;
8147
8148 NewViewNode := NewViewNodeMake.ToNode(NewViewpointNode);
8149 finally FreeAndNil(NewViewNodeMake) end;
8150
8151 NewViewpointNode.FdDescription.Value := AName;
8152 NewViewpointNode.X3DName := 'Viewpoint' + IntToStr(Random(10000));
8153 NewViewpointNode.Scene := Self;
8154
8155 { Create NavigationInfo node }
8156 Walk := nil;
8157 Examine := nil;
8158 if Navigation is TCastleWalkNavigation then
8159 begin
8160 Walk := Navigation as TCastleWalkNavigation;
8161 if Walk.Gravity then
8162 NavigationType := 'WALK'
8163 else
8164 NavigationType := 'FLY';
8165 end else
8166 if Navigation is TCastleExamineNavigation then
8167 begin
8168 Examine := Navigation as TCastleExamineNavigation;
8169 if Examine.Turntable then
8170 NavigationType := 'TURNTABLE'
8171 else
8172 NavigationType := 'EXAMINE';
8173 end;
8174
8175 AvatarSize.X := Navigation.Radius;
8176 if Walk <> nil then begin
8177 WalkSpeed := Walk.MoveSpeed;
8178 AvatarSize.Y := Walk.PreferredHeight;
8179 AvatarSize.Z := Walk.ClimbHeight;
8180 end
8181 else begin
8182 WalkSpeed := 0;
8183 AvatarSize.Y := 0;
8184 AvatarSize.Z := 0;
8185 end;
8186 VisibilityLimit := 0;
8187
8188 NewNavigationNode := MakeCameraNavNode(Version, '', NavigationType, WalkSpeed,
8189 VisibilityLimit, AvatarSize, HeadlightOn);
8190 NewNavigationNode.X3DName := 'NavInfo' + IntToStr(Random(10000));
8191 NewNavigationNode.Scene := Self;
8192
8193 // Connect viewpoint with navigation info
8194 NewRoute := TX3DRoute.Create;
8195 NewRoute.SetSourceDirectly(NewViewpointNode.EventIsBound);
8196 NewRoute.SetDestinationDirectly(NewNavigationNode.EventSet_Bind);
8197
8198 // Add both nodes to the scene
8199 NewGroupNode := TGroupNode.Create;
8200 NewGroupNode.AddChildren(NewViewNode);
8201 NewGroupNode.AddChildren(NewNavigationNode);
8202 NewGroupNode.AddRoute(NewRoute);
8203
8204 RootNode.AddChildren(NewGroupNode);
8205 { The 100% safe version would now call RootNode.FdChildren.Changed,
8206 and it would automatically refresh FViewpointsArray.
8207 But RootNode.FdChildren.Changed is a little costly, it processes the whole
8208 scene again, so it's faster to directly add to FViewpointsArray. }
8209 FViewpointsArray.Add(NewViewpointNode);
8210 end;
8211
8212 type
8213 TAnimationsEnumerator = class
8214 //Parent: TCastleSceneCore;
8215 AnimationPrefix: String;
8216 List: TStringList;
8217 procedure EnumerateWithAlias(const Node: TX3DNode; const NodeName: String;
8218 const Overwrite: boolean);
8219 procedure Enumerate(Node: TX3DNode);
8220 end;
8221
8222 procedure TAnimationsEnumerator.Enumerate(Node: TX3DNode);
8223 begin
8224 EnumerateWithAlias(Node, Node.X3DName, false);
8225 end;
8226
8227 procedure TAnimationsEnumerator.EnumerateWithAlias(const Node: TX3DNode;
8228 const NodeName: String; const Overwrite: boolean);
8229 var
8230 AnimationName: String;
8231 ExistingIndex: Integer;
8232 begin
8233 if IsPrefix(AnimationPrefix, NodeName, false) then
8234 begin
8235 AnimationName := PrefixRemove(AnimationPrefix, NodeName, false);
8236 if AnimationName = '' then
8237 begin
8238 if AnimationPrefix <> '' then // this is normal with AnimationPrefix = '' on many scenes
8239 WritelnWarning('Named Animations', Format('TimeSensor node name is exactly "%s", this indicates named animation with empty name, ignoring',
8240 [AnimationName]));
8241 Exit;
8242 end;
8243 ExistingIndex := List.IndexOf(AnimationName);
8244 if ExistingIndex <> -1 then
8245 begin
8246 if (not Overwrite) and (AnimationPrefix <> '') then
8247 { Warn in case of multiple animation (TimeSensor) names
8248 only when AnimationPrefix set.
8249 Bacause this is normal on some models, and is valid X3D.
8250 - You can repeat the same node name multiple times in X3D (although
8251 it's discouraged).
8252 - You can use PROTO and DEF with TimeSensor inside, and use it multiple
8253 times. Both these usage scenarios result in multiple instances
8254 of the animation in scene.
8255 - Even our own mechanism for renaming castle-anim-frames animations from
8256 https://github.com/castle-engine/demo-models/blob/master/castle-anim-frames/simple/two_animations.x3dv
8257 results in multiple "Animation" names in scene. }
8258 WritelnWarning('Named Animations', Format('Animation name "%s" occurs multiple times in scene',
8259 [AnimationName]));
8260 List.Objects[ExistingIndex] := Node;
8261 end else
8262 begin
8263 List.AddObject(AnimationName, Node);
8264 end;
8265 end;
8266 end;
8267
8268 function TCastleSceneCore.CreateAnimations: TStringList;
8269 var
8270 Enum: TAnimationsEnumerator;
8271 I: Integer;
8272 begin
8273 Result := TStringList.Create;
8274 Result.CaseSensitive := true; // X3D node names are case-sensitive
8275 if RootNode <> nil then
8276 begin
8277 Enum := TAnimationsEnumerator.Create;
8278 try
8279 //Enum.Parent := Self;
8280 Enum.List := Result;
8281 {$ifdef FPC}
8282 {$warnings off} // knowingly using deprecated, to keep it working
8283 Enum.AnimationPrefix := AnimationPrefix;
8284 {$warnings on}
8285 {$endif}
8286 { OnlyActive = false, to also find animations under inactive Switch clauses.
8287 Since the Switch.WhichChoice may change at runtime,
8288 while the animations list should stay constant. }
8289 RootNode.EnumerateNodes(TTimeSensorNode,
8290 {$ifdef FPC}@{$endif}Enum.Enumerate, false);
8291
8292 { recognize named animations also from IMPORTed node names.
8293 This alllows to import and rename animations, which is useful. }
8294 if RootNode.ImportedNames <> nil then
8295 for I := 0 to RootNode.ImportedNames.Count - 1 do
8296 if RootNode.ImportedNames[I].Node is TTimeSensorNode then
8297 Enum.EnumerateWithAlias(
8298 RootNode.ImportedNames[I].Node,
8299 RootNode.ImportedNames[I].Name, true);
8300 finally FreeAndNil(Enum) end;
8301 end;
8302 end;
8303
8304 function TCastleSceneCore.HasAnimation(const AnimationName: String): boolean;
8305 begin
8306 Result := FAnimationsList.IndexOf(AnimationName) <> -1;
8307 end;
8308
8309 function TCastleSceneCore.AnimationTimeSensor(const AnimationName: String): TTimeSensorNode;
8310 begin
8311 Result := AnimationTimeSensor(FAnimationsList.IndexOf(AnimationName));
8312 end;
8313
8314 function TCastleSceneCore.AnimationTimeSensor(const Index: Integer): TTimeSensorNode;
8315 begin
8316 if Between(Index, 0, FAnimationsList.Count - 1) then
8317 Result := FAnimationsList.Objects[Index] as TTimeSensorNode
8318 else
8319 Result := nil;
8320 end;
8321
8322 function TCastleSceneCore.ForceAnimationPose(const AnimationName: String;
8323 const TimeInAnimation: TFloatTime;
8324 const Loop: boolean;
8325 const Forward: boolean): boolean;
8326 var
8327 Index: Integer;
8328 TimeNode: TTimeSensorNode;
8329 begin
8330 Index := FAnimationsList.IndexOf(AnimationName);
8331 Result := Index <> -1;
8332 if Result then
8333 begin
8334 TimeNode := FAnimationsList.Objects[Index] as TTimeSensorNode;
8335 ResetAnimationState(TimeNode);
8336 TimeNode.FakeTime(TimeInAnimation, Loop, Forward, NextEventTime);
8337 FinishTransformationChanges;
8338 end;
8339 end;
8340
8341 procedure TCastleSceneCore.ForceInitialAnimationPose;
8342 begin
8343 if NewPlayingAnimationUse then
8344 begin
8345 ResetAnimationState(NewPlayingAnimationNode);
8346 { After StopAnimation,
8347 we may have NewPlayingAnimationUse and (NewPlayingAnimationNode = nil),
8348 this is a valid state. }
8349 if NewPlayingAnimationNode <> nil then
8350 begin
8351 NewPlayingAnimationNode.FakeTime(
8352 NewPlayingAnimationInitialTime,
8353 NewPlayingAnimationLoop,
8354 NewPlayingAnimationForward,
8355 NextEventTime);
8356 FinishTransformationChanges;
8357 end;
8358 end;
8359 end;
8360
8361 function TCastleSceneCore.PlayAnimation(const AnimationName: String;
8362 const Loop: boolean; const Forward: boolean): boolean;
8363 var
8364 Params: TPlayAnimationParameters;
8365 begin
8366 Params := TPlayAnimationParameters.Create;
8367 try
8368 Params.Name := AnimationName;
8369 Params.Loop := Loop;
8370 Params.Forward := Forward;
8371 if PlayingAnimationNode <> nil then
8372 Params.TransitionDuration := DefaultAnimationTransition;
8373 Result := PlayAnimation(Params);
8374 finally FreeAndNil(Params) end;
8375 end;
8376
8377 function TCastleSceneCore.PlayAnimation(
8378 const Parameters: TPlayAnimationParameters): boolean;
8379 var
8380 Index: Integer;
8381 begin
8382 ProcessEvents := true;
8383
8384 Index := FAnimationsList.IndexOf(Parameters.Name);
8385 Result := Index <> -1;
8386 if Result then
8387 begin
8388 { If we already have NewPlayingAnimationUse scheduled
8389 (another PlayAnimation was done right before this),
8390 then Parameters.TransitionDuration indicates to do blending from
8391 NewPlayingAnimationNode to Parameters.Name animation.
8392 In this case, we need to "apply" NewPlayingAnimationNode
8393 (make it actually present in X3D nodes),
8394 otherwise we would accidentally do blending with *even older* animation.
8395
8396 Testcase in Unholy:
8397 - going out of sewers with keys or mouse
8398 ('going_up_on_ladder' finishes, changes to 'idle', which changes to 'stealth_idle' immediately)
8399 - going up the ladder to warehouse, only when using mouse
8400 ('going_up_on_ladder' finishes, changes to 'idle', which changes to 'walking' immediately then)
8401 }
8402 if NewPlayingAnimationUse and (Parameters.TransitionDuration <> 0) then
8403 ApplyNewPlayingAnimation;
8404
8405 { We defer actual sending of stopTime and startTime to Update method.
8406 This way multiple calls to PlayAnimation within the same frame
8407 behave Ok, only last one matters.
8408
8409 Otherwise we're left
8410 with TimeSensor having equal stopTime and startTime on animations
8411 executed by non-last PlayAnimation call within the same frame,
8412 and so these animations play (while they should not), simultaneously
8413 with desired animations.
8414 (reproduction: escape_universe, boss flying + flying_left/right + dying
8415 animations.)
8416
8417 Don't even set TimeNode.Loop here --- setting Loop property
8418 on a node, and then not controlling it's startTime / stopTime,
8419 means that it will play infinitely (because the default values
8420 mean that stopTime is ignored).
8421 }
8422 FCurrentAnimation := FAnimationsList.Objects[Index] as TTimeSensorNode;
8423 NewPlayingAnimationNode := FCurrentAnimation;
8424 NewPlayingAnimationLoop := Parameters.Loop;
8425 NewPlayingAnimationForward := Parameters.Forward;
8426 NewPlayingAnimationStopNotification := Parameters.StopNotification;
8427 NewPlayingAnimationTransitionDuration := Parameters.TransitionDuration;
8428 NewPlayingAnimationInitialTime := Parameters.InitialTime;
8429 NewPlayingAnimationUse := true;
8430 end else
8431 begin
8432 WritelnWarning('Animation "%s" not found on scene %s (loaded from %s)', [
8433 Parameters.Name,
8434 Name,
8435 UriDisplay(Url)
8436 ]);
8437 end;
8438 end;
8439
8440 procedure TCastleSceneCore.PlayingAnimationIsActive(
8441 const Event: TX3DEvent; const Value: TX3DField; const ATime: TX3DTime);
8442 var
8443 Val: boolean;
8444 begin
8445 Val := (Value as TSFBool).Value;
8446 if (not Val) and Assigned(PlayingAnimationStopNotification) then
8447 begin
8448 PlayingAnimationStopNotification(Self, PlayingAnimationNode);
8449 { Always after calling PlayingAnimationStopNotification,
8450 make it nil, to not call it 2nd time when PlayAnimation plays another
8451 animation. }
8452 PlayingAnimationStopNotification := nil;
8453 end;
8454 end;
8455
8456 function TCastleSceneCore.AnimationDuration(const AnimationName: String): TFloatTime;
8457 var
8458 Index: Integer;
8459 TimeNode: TTimeSensorNode;
8460 begin
8461 Index := FAnimationsList.IndexOf(AnimationName);
8462 if Index <> -1 then
8463 begin
8464 TimeNode := FAnimationsList.Objects[Index] as TTimeSensorNode;
8465 Result := TimeNode.CycleInterval;
8466 end else
8467 Result := 0;
8468 end;
8469
8470 function TCastleSceneCore.ApplyNewPlayingAnimation: Boolean;
8471 var
8472 NeedsUpdateTimeDependent: Boolean;
8473 begin
8474 Result := true;
8475 if NewPlayingAnimationUse then
8476 begin
8477 UpdateNewPlayingAnimation(NeedsUpdateTimeDependent);
8478
8479 { The case of NeedsUpdateTimeDependent = true is normal,
8480 and we should handle it.
8481 It can easily occur if the first thing you do with Scene is call Scene.PlayAnimation(...),
8482 then Scene.StopAnimation within the same frame.
8483 This will cause ApplyNewPlayingAnimation that will initialize the animation,
8484 only to have it stopped immediately.
8485 Such ApplyNewPlayingAnimation cannot Exit(false), as it would make StopAnimation to fail,
8486 see https://github.com/castle-engine/castle-engine/issues/273 .
8487
8488 It is tempting to do nothing and ignore NeedsUpdateTimeDependent here.
8489 It could be often OK, since we stop the animation?
8490 But doing UpdateTimeDependentList is what is consistent with normal code flow,
8491 so safest. }
8492 if NeedsUpdateTimeDependent then
8493 UpdateTimeDependentList(0, false); // update TimeSensors
8494
8495 if NewPlayingAnimationUse then
8496 begin
8497 WritelnWarning('StopNotification callback of an old animation initialized another animation, bypassing the CurrentAnimation. ' + 'The StopAnimation will not actually stop the animation, and the StopNotification callback of the CurrentAnimation is now overridden so we cannot call it anymore.');
8498 Exit(false);
8499 end;
8500 end;
8501 end;
8502
8503 procedure TCastleSceneCore.StopAnimation(const DisableStopNotification: Boolean = false);
8504 begin
8505 if DisableStopNotification then
8506 begin
8507 PlayingAnimationStopNotification := nil;
8508 end else
8509 begin
8510 { If new animation was requested, but not yet processed by UpdateNewPlayingAnimation:
8511 Make it start, to early call the "stop notification" callback
8512 for the previous animation (before calling the "stop notification"
8513 callback for the new animation).
8514 This also makes all behavior consistent with
8515 "what if the new animation was actually applied already", i.e. the same calls
8516 to TTimeSensorNode.Stop and TTimeSensorNode.Start will be done. }
8517 if not ApplyNewPlayingAnimation then
8518 Exit;
8519 end;
8520
8521 { Stop animation by setting NewPlayingAnimationNode to nil,
8522 this way the "stop notification" callback
8523 for new animation will be correctly called.
8524
8525 The next Update (with UpdateNewPlayingAnimation) will set PlayingAnimationNode
8526 to nil this way. }
8527 FCurrentAnimation := nil;
8528 NewPlayingAnimationNode := FCurrentAnimation;
8529 NewPlayingAnimationUse := true;
8530 { No need to set other NewPlayingAnimationXxx,
8531 like NewPlayingAnimationStopNotification,
8532 they will be ignored when NewPlayingAnimationNode = nil. }
8533 end;
8534
8535 procedure TCastleSceneCore.ResetAnimationState(const IgnoreAffectedBy: TTimeSensorNode);
8536 var
8537 F: TX3DField;
8538 begin
8539 { set fields in AnimationAffectedFields to their reset values }
8540 for F in AnimationAffectedFields do
8541 F.InternalRestoreSaveValue;
8542 FinishTransformationChanges;
8543 end;
8544
8545 procedure TCastleSceneCore.FontChanged_TextNode(Node: TX3DNode);
8546 begin
8547 (Node as TTextNode).FontChanged;
8548 end;
8549
8550 procedure TCastleSceneCore.FontChanged_AsciiTextNode_1(Node: TX3DNode);
8551 begin
8552 (Node as TAsciiTextNode_1).FontChanged;
8553 end;
8554
8555 procedure TCastleSceneCore.FontChanged;
8556 begin
8557 if RootNode <> nil then
8558 begin
8559 GLContextClose; // force TRenderer.Prepare on shapes
8560 { Free and recalculate all proxy nodes...
8561 TODO: this could be done much more efficiently,
8562 we only need to free proxies on text nodes. }
8563 ChangedAll;
8564 RootNode.EnumerateNodes(TTextNode,
8565 {$ifdef FPC}@{$endif}FontChanged_TextNode, false);
8566 RootNode.EnumerateNodes(TAsciiTextNode_1,
8567 {$ifdef FPC}@{$endif}FontChanged_AsciiTextNode_1, false);
8568 end;
8569 end;
8570
8571 function TCastleSceneCore.Clone(const AOwner: TComponent): TCastleSceneCore;
8572 begin
8573 Result := TComponentClass(ClassType).Create(AOwner) as TCastleSceneCore;
8574 Result.FUrlMonitoring.ChangeUrl(Result.FUrl, FUrl);
8575 if RootNode <> nil then
8576 Result.Load(RootNode.DeepCopy as TX3DRootNode, true);
8577 end;
8578
8579 function TCastleSceneCore.PropertySections(
8580 const PropertyName: String): TPropertySections;
8581 begin
8582 if ArrayContainsString(PropertyName, [
8583 'Url', 'ProcessEvents', 'AutoAnimation',
8584 'DefaultAnimationTransition', 'PreciseCollisions', 'ExposeTransforms',
8585 'TimePlaying', 'TimePlayingSpeed', 'Cache'
8586 ]) then
8587 Result := [psBasic]
8588 else
8589 Result := inherited PropertySections(PropertyName);
8590 end;
8591
8592 procedure TCastleSceneCore.LocalRender(const Params: TRenderParams);
8593
8594 procedure RenderingCameraChanged(const RenderingCamera: TRenderingCamera);
8595 var
8596 Viewpoint: TAbstractViewpointNode;
8597 begin
8598 Viewpoint := ViewpointStack.Top;
8599
8600 if ProcessEvents and
8601 (Viewpoint <> nil) and
8602 ( (RenderingCamera.Target = rtScreen) or
8603 Viewpoint.FdcameraMatrixSendAlsoOnOffscreenRendering.Value ) then
8604 begin
8605 BeginChangesSchedule;
8606 try
8607 if Viewpoint.EventCameraMatrix.SendNeeded then
8608 Viewpoint.EventCameraMatrix.Send(RenderingCamera.Matrix, NextEventTime);
8609
8610 if Viewpoint.EventCameraInverseMatrix.SendNeeded then
8611 begin
8612 RenderingCamera.InverseMatrixNeeded;
8613 Viewpoint.EventCameraInverseMatrix.Send(RenderingCamera.InverseMatrix, NextEventTime);
8614 end;
8615
8616 if Viewpoint.EventCameraRotationMatrix.SendNeeded then
8617 Viewpoint.EventCameraRotationMatrix.Send(RenderingCamera.RotationMatrix3, NextEventTime);
8618
8619 if Viewpoint.EventCameraRotationInverseMatrix.SendNeeded then
8620 begin
8621 RenderingCamera.RotationInverseMatrixNeeded;
8622 Viewpoint.EventCameraRotationInverseMatrix.Send(RenderingCamera.RotationInverseMatrix3, NextEventTime);
8623 end;
8624 finally EndChangesSchedule end;
8625 end;
8626 end;
8627
8628 begin
8629 inherited;
8630 RenderingCameraChanged(Params.RenderingCamera);
8631 end;
8632
8633 procedure TCastleSceneCore.InternalIncShapesHash;
8634 begin
8635 // WritelnLog('Scene %s shapes hash changed to %d', [Name, FShapesHash]);
8636 if FShapesHash = High(FShapesHash) then
8637 begin
8638 WritelnWarning('Scene %s state hash reached the highest number of 64-bit value. Resetting', [Name]);
8639 FShapesHash := 1;
8640 end else
8641 Inc(FShapesHash);
8642 end;
8643
8644 procedure TCastleSceneCore.SetExposeTransforms(const Value: TStrings);
8645 begin
8646 FExposeTransforms.Assign(Value);
8647 end;
8648
8649 procedure TCastleSceneCore.ExposeTransformsChange(Sender: TObject);
8650 var
8651 TransformName, TransformNamePascal: String;
8652 TransformNode: TTransformNode;
8653 TransformChild: TCastleTransform;
8654 E: TExposedTransform;
8655 I: Integer;
8656 begin
8657 FExposedTransforms.Clear;
8658 if RootNode = nil then // needed for subsequent RootNode.TryFindNodeByName
8659 Exit;
8660
8661 for TransformName in FExposeTransforms do
8662 begin
8663 if TransformName = '' then // ignore empty lines on FExposeTransforms list
8664 Continue;
8665
8666 // calculate TransformNode
8667 TransformNode := RootNode.FindNode(TTransformNode, TransformName, [fnNilOnMissing]) as TTransformNode;
8668 if TransformNode = nil then
8669 begin
8670 WritelnWarning('No TTransformNode (bone) named "%s" found in model', [TransformName]);
8671 Continue;
8672 end;
8673
8674 for E in FExposedTransforms do
8675 if E.Node = TransformNode then
8676 Continue; // ignore duplicates on FExposeTransforms list
8677
8678 TransformNamePascal := TExposedTransform.X3dNameToPascal(ExposeTransformsPrefix, TransformName);
8679
8680 // calculate TransformChild
8681 TransformChild := nil;
8682 for I := 0 to Count - 1 do
8683 if Items[I].Name = TransformNamePascal then
8684 begin
8685 TransformChild := Items[I];
8686 Break;
8687 end;
8688 if TransformChild = nil then
8689 begin
8690 { Create new TCastleTransform.
8691 Note
8692 - We connect to it only by Name, not any other internal reference.
8693 This is important, as we need to restore the connection
8694 e.g. after deserializing it from design file.
8695 - We use current Owner as the owner, not Self.
8696 This makes it work in case of editor or TransformLoad nicely.
8697 Intuitively, we don't want to manage the lifetime of these scenes
8698 here: the lifetime of them should be up to our owner.
8699 }
8700 TransformChild := TCastleTransform.Create(Owner);
8701 TransformChild.Name := TransformNamePascal;
8702 Add(TransformChild);
8703
8704 // otherwise changing TCastleSceneCore.ExposeTransforms would not update CGE editor hierarchy view
8705 if not (csTransient in ComponentStyle) then
8706 InternalCastleDesignInvalidate := true;
8707 end;
8708
8709 // create TExposedTransform
8710 E := TExposedTransform.Create(Self, TransformNode, TransformChild);
8711 E.Synchronize;
8712 FExposedTransforms.Add(E);
8713 end;
8714 end;
8715
8716 procedure TCastleSceneCore.SetExposeTransformsPrefix(const Value: String);
8717 var
8718 E: TExposedTransform;
8719 begin
8720 if FExposeTransformsPrefix <> Value then
8721 begin
8722 FExposeTransformsPrefix := Value;
8723 // rename existing children
8724 for E in FExposedTransforms do
8725 begin
8726 E.Child.Name := TExposedTransform.X3dNameToPascal(ExposeTransformsPrefix, E.Node.X3DName);
8727 InternalCastleDesignInvalidate := true;
8728 end;
8729 end;
8730 end;
8731
8732 end.