Debian Codegraph @

src/scene/castleviewport.pas

raw
1 {
2 Copyright 2009-2023 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 { Viewport to display scenes (TCastleViewport). }
17 unit CastleViewport;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections,
24 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
25 CastleVectors, X3DNodes, CastleInternalBaseTriangleOctree, CastleScene,
26 CastleSceneCore, CastleCameras, CastleRenderOptions,
27 CastleInternalGLShadowVolumes, CastleUIControls, CastleTransform, CastleTriangles,
28 CastleKeysMouse, CastleBoxes, CastleInternalBackgroundRenderer, CastleUtils,
29 CastleClassUtils, CastleShapes,
30 CastleGLShaders, CastleGLImages, CastleTimeUtils, CastleControls,
31 CastleInputs, CastleRectangles, CastleColors, CastleComponentSerialize,
32 CastleProjection, CastleScreenEffects, CastleInternalShapesRenderer,
33 CastleInternalScreenEffects;
34
35 type
36 TCastleViewport = class;
37 TCastleSceneManager = class;
38
39 TRenderOnePassEvent = procedure (Viewport: TCastleViewport;
40 const Params: TRenderParams) of object;
41
42 { Event for @link(TCastleViewport.OnProjection). }
43 TProjectionEvent = procedure (var Parameters: TProjection) of object;
44
45 TInternalDesignNavigationType = (dnFly, dnExamine, dn2D);
46
47 { Viewport displays a tree of scenes and transformations
48 (TCastleTransform and descendants of it, like TCastleScene).
49 Add the scenes and transformations to @link(Items).
50 See https://castle-engine.io/viewport_and_scenes .
51
52 Each viewport has a @link(Camera) with a position and orientation.
53 Viewport may have multiple cameras.
54
55 Viewport may also have a navigation that allows to move
56 camera by keyboard, mouse and other inputs.
57 You can use any navigation method implemented in the engine
58 (TCastleExamineNavigation, TCastleWalkNavigation, TCastleThirdPersonNavigation)
59 or implement your own
60 (you can create your own descendants of @link(TCastleNavigation),
61 or just move/rotate the camera by calling @link(TCastleTransform.SetWorldView Viewport.Camera.SetWorldView) from anywhere).
62 Just add @link(TCastleNavigation) as a child of @link(TCastleViewport).
63
64 Viewport may display a background.
65 It may be a solid color, a 3D skybox or a gradient.
66 See @link(Background), @link(BackgroundColor) properties and
67 https://castle-engine.io/background .
68 Alternatively, viewport background may be transparent
69 (so other TCastleUserInterface underneath will be visible)
70 if @link(Transparent).
71
72 Multiple viewports can display the same world.
73 To do this, simply copy @link(Items) reference from one
74 TCastleViewport to another. You can also just create your own @link(TCastleRootTransform)
75 instance and then assign it to multiple viewports.
76 This allows e.g. to make a split-screen game (played by 2 people,
77 with 2 viewports, on a single monitor).
78 Or you can show in a 3D FPS game an additional view from some security camera,
79 or from a flying rocket.
80 See https://castle-engine.io/multiple_viewports_to_display_one_world . }
81 TCastleViewport = class(TCastleScreenEffects)
82 strict private
83 type
84 TSSAOScreenEffect = class(TGLSLScreenEffect)
85 Viewport: TCastleViewport;
86 function SetupUniforms(var BoundTextureUnits: Cardinal): Boolean; override;
87 end;
88 TSSRScreenEffect = class(TGLSLScreenEffect)
89 Viewport: TCastleViewport;
90 function SetupUniforms(var BoundTextureUnits: Cardinal): Boolean; override;
91 end;
92 TViewportRenderParams = class(TRenderParams)
93 private
94 FGlobalLights: TLightInstancesList;
95 public
96 constructor Create;
97 destructor Destroy; override;
98 function GlobalLights: TAbstractLightInstancesList; override;
99 end;
100
101 var
102 FCamera: TCastleCamera;
103 FCameraObserver: TFreeNotificationObserver;
104 FRenderParams: TViewportRenderParams;
105 FPrepareParams: TPrepareParams;
106 FBackgroundWireframe: boolean;
107 FBackgroundColor: TCastleColor;
108 FUseGlobalLights, FUseGlobalFog: boolean;
109 FApproximateActivation: boolean;
110 FTransparent, FClearDepth: boolean;
111 LastPressEvent: TInputPressRelease;
112 FOnProjection: TProjectionEvent;
113 FEnableParentDragging: boolean;
114 AssignDefaultCameraDone: Boolean;
115 FAutoCamera: Boolean;
116
117 FShadowVolumes: boolean;
118 FShadowVolumesRender: boolean;
119
120 FScreenSpaceAmbientOcclusion: boolean;
121 SSAOShader: TSSAOScreenEffect;
122 SSAOShaderInitialized: Boolean;
123
124 FScreenSpaceReflections: Boolean;
125 SSRShader: TSSRScreenEffect;
126 SSRShaderInitialized: Boolean;
127 FScreenSpaceReflectionsSurfaceGlossiness: Single;
128
129 FOnCameraChanged: TNotifyEvent;
130 { Renderer of shadow volumes. You can use this to optimize rendering
131 of your shadow quads in RenderShadowVolume, and you can read
132 it's statistics (TGLShadowVolumeRenderer.Count and related properties).
133
134 @nil when OpenGL context is not yet initialized. }
135 FShadowVolumeRenderer: TGLShadowVolumeRenderer;
136 FItems: TCastleRootTransform;
137 FItemsObserver: TFreeNotificationObserver;
138 LastVisibleStateIdForVisibleChange: TFrameId;
139
140 FOnBoundViewpointChanged: TNotifyEvent;
141 FOnBoundNavigationInfoChanged: TNotifyEvent;
142 FMouseRayHit: TRayCollision;
143 FMouseRayHitValid: Boolean;
144 MouseRayOrigin, MouseRayDirection: TVector3;
145 FAvoidNavigationCollisions: TCastleTransform;
146 PrepareResourcesDone: Boolean;
147 FPreventInfiniteFallingDown: Boolean;
148 FCapturePointingDevice: TCastleTransform;
149 FCapturePointingDeviceObserver: TFreeNotificationObserver;
150 FLastSeenMainScene: TCastleScene; // only used by editor
151 FBackground: TCastleBackground;
152 FBackgroundObserver: TFreeNotificationObserver;
153 FFog: TCastleFog;
154 FFogObserver: TFreeNotificationObserver;
155 // reused between frames for speed
156 FRenderWithoutScreenEffectsRenderingCamera: TRenderingCamera;
157 FMissingCameraRect: TCastleRectangleControl;
158 FMissingCameraLabel: TCastleLabel;
159 FInternalDesignManipulation: Boolean;
160 FInternalDesignNavigationType: TInternalDesignNavigationType;
161 FInternalDesignNavigations: array [TInternalDesignNavigationType] of TCastleNavigation;
162 FInternalGridAxis: Boolean;
163 FGizmoGridAxis: TInternalCastleEditorGizmo;
164 FWarningZFarInfinityDone: Boolean;
165 FDynamicBatching: Boolean;
166 FOcclusionCulling: Boolean;
167 FOcclusionSort: TShapeSort;
168 FBlendingSort: TShapeSort;
169 FOnCustomShapeSort: TShapeSortEvent;
170 FUpdateSoundListener: Boolean;
171
172 ShapesCollector: TShapesCollector;
173 ShapesRenderer: TShapesRenderer;
174
175 procedure CommonCreate(const AOwner: TComponent; const ADesignManipulation: Boolean);
176 function FillsWholeContainer: boolean;
177 procedure SetScreenSpaceAmbientOcclusion(const Value: boolean);
178 procedure SetScreenSpaceReflections(const Value: Boolean);
179 procedure SetScreenSpaceReflectionsSurfaceGlossiness(const Value: Single);
180 procedure SetupDesignTimeCamera;
181 procedure SetupChildren2D;
182 procedure SetupChildren3D;
183 procedure SSAOShaderInitialize;
184 procedure SSRShaderInitialize;
185 procedure SetAutoCamera(const Value: Boolean);
186 procedure SetItems(Value: TCastleRootTransform);
187 function GetPaused: Boolean;
188 procedure SetPaused(const Value: Boolean);
189 procedure SetBackground(const Value: TCastleBackground);
190 procedure BackgroundFreeNotification(const Sender: TFreeNotificationObserver);
191 procedure SetFog(const Value: TCastleFog);
192 procedure FogFreeNotification(const Sender: TFreeNotificationObserver);
193 procedure SetInternalDesignNavigationType(const Value: TInternalDesignNavigationType);
194 procedure SetInternalGridAxis(const Value: Boolean);
195 function GetMouseRayHit: TRayCollision;
196
197 { Callbacks when MainCamera is notified that MainScene changes camera/navigation }
198 procedure MainSceneAndCamera_BoundViewpointChanged(Sender: TObject);
199 procedure MainSceneAndCamera_BoundViewpointVectorsChanged(Sender: TObject);
200 procedure MainSceneAndCamera_BoundNavigationInfoChanged(Sender: TObject);
201
202 { Change FMouseRayHit. Should be called only by
203
204 - GetMouseRayHit (when it's updated on-demand), with nil or non-nli,
205 that also sets FMouseRayHitValid = true
206
207 - or by ClearMouseRayHit (only with nil parameter in this case)
208 that also sets FMouseRayHitValid = false
209 }
210 procedure SetMouseRayHit(const Value: TRayCollision);
211
212 { Sets FMouseRayHit to nil and FMouseRayHitValid to false.
213 Removes all free notifications for items in FMouseRayHit. }
214 procedure ClearMouseRayHit;
215
216 { Whether FMouseRayHit contains given Item.
217 This doesn't update FMouseRayHit if it is invalid right now,
218 so it is safer to use even during destruction.
219 And so it should be used only on some free notification. }
220 function MouseRayHitContains(const Item: TCastleTransform): boolean;
221
222 procedure SetAvoidNavigationCollisions(const Value: TCastleTransform);
223
224 function GetNavigation: TCastleNavigation;
225 procedure SetNavigation(const Value: TCastleNavigation);
226
227 { Cast a ray that can collide with whole world (except AvoidNavigationCollisions).
228 Given parameters are in world coordinates. }
229 function CameraRayCollision(const RayOrigin, RayDirection: TVector3): TRayCollision;
230
231 procedure SetSceneManager(const Value: TCastleSceneManager);
232 { Get current Container.MousePosition.
233 Secured in case Container not assigned (returns @false)
234 or when Navigation uses MouseLook (in which case, returns the middle of our area,
235 the actual mouse position should not be even visible to the user). }
236 function GetMousePosition(out MousePosition: TVector2): Boolean;
237
238 procedure SetCapturePointingDevice(const Value: TCastleTransform);
239 { Once a TCastleTransform will handle a PointingDevicePress event,
240 we make sure to pass subsequent PointingDeviceMove and PointingDeviceRelease to it too,
241 before other TCastleTransform instances,
242 and regardless if ray hits this TCastleTransform still.
243 This way TCastleTransform can handle e.g. dragging with mouse/touch,
244 regardless if mouse/touch stays over this transform.
245
246 The reason and implementation of this mechanism is similar to
247 TCastleContainer.FCaptureInput. }
248 property CapturePointingDevice: TCastleTransform
249 read FCapturePointingDevice write SetCapturePointingDevice;
250 procedure CapturePointingDeviceFreeNotification(const Sender: TFreeNotificationObserver);
251
252 { Initialize TRayCollisionNode to specify collision with given TCastleTransform
253 without any specific Triangle/Point.
254 The given RayOrigin / RayOrigin are in world coordinates
255 (internally we will convert them to TCastleTransform coordinates). }
256 function FakeRayCollisionNode(const RayOriginWorld, RayDirectionWorld: TVector3;
257 const Item: TCastleTransform): TRayCollisionNode;
258
259 { Whether to look at AvoidNavigationCollisions.
260 Checks that AvoidNavigationCollisions is set, and it is part of current @link(Items). }
261 function UseAvoidNavigationCollisions: Boolean;
262
263 { Ensure Camera and FProjection are initialized for PositionToXxx family of methods. }
264 procedure PositionToPrerequisites;
265
266 { Notification done by TCastleCamera when our Camera state changed. }
267 procedure InternalCameraChanged(Sender: TObject);
268
269 procedure SetCamera(const Value: TCastleCamera);
270 procedure CameraFreeNotification(const Sender: TFreeNotificationObserver);
271 procedure ItemsFreeNotification(const Sender: TFreeNotificationObserver);
272 procedure SetDynamicBatching(const Value: Boolean);
273 procedure SetOcclusionCulling(const Value: Boolean);
274 private
275 var
276 FProjection: TProjection;
277 FSceneManager: TCastleSceneManager;
278 ItemsNodesFreeOccurred: Boolean;
279
280 { Make sure to call AssignDefaultCamera, if needed because of AutoCamera. }
281 procedure EnsureCameraDetected;
282
283 class procedure CreateComponentWithChildren2D(Sender: TObject);
284 class procedure CreateComponentWithChildren3D(Sender: TObject);
285
286 procedure ItemsNodesFree(Sender: TObject);
287
288 { Bounding box of everything non-design.
289 Similar to just using Items.BoundingBox, but
290
291 1. handles Items=nil case OK
292
293 2. ignores bbox at design-time of gizmos (lights, cameras, visualize transform).
294 This is important to avoid AutoCamera at design-time to calculate something unexpected
295 (move camera far away), because it would adjust to the camera and lights gizmo bbox
296 (see TTestCastleViewport.TestAutoCameraIgnoresGizmos).
297
298 Note: By default, what does Items.BoundingBox return wrt to gizmos?
299 When not called as ItemsBoundingBox or ItemsWithGizmosBoundingBox?
300 Answer: By default it doesn't count *some* gizmos pieces, the ones marked as
301 InternalExcludeFromParentBoundingVolume.
302 And TInternalCastleEditorGizmo uses InternalExcludeFromParentBoundingVolume
303 on a subset of its stuff, see TInternalCastleEditorGizmo.Create
304 implementation.
305 So e.g. Items.BoundingBox
306 - counts the gizmo invisible "select box"
307 inside TInternalCastleEditorGizmo,
308 - does not count specialized lights or cameras line visualizations
309 inside TInternalCastleEditorGizmo.
310 (they use InternalExcludeFromParentBoundingVolume=true).
311 - does not count to "visualize transform" gizmo (used in editor
312 to translate / rotate / scale).
313 (they use InternalExcludeFromParentBoundingVolume=true).
314 }
315 function ItemsBoundingBox: TBox3D;
316
317 { Bounding box of everything, including design-time gizmos
318 (because you also want to see
319 them accounted for in design-time ortho camera ProjectionNear/Far).
320 Similar to just usign Items.BoundingBox, but handles Items=nil case OK.
321
322 Note: We need to use ItemsWithGizmosBoundingBox to auto-calculate
323 projection near/far, not merely ItemsBoundingBox.
324 Otherwise 2D projection in editor could cut off some gizmos.
325
326 Testcase:
327 - 2d viewport
328 - add a few TCastleImageTransform with some image loaded with Z = -1000.
329 - add TCastleTransform with translation 0,0,0, select it
330 - -> the gizmo of it has to be visible, even though everything visible
331 (excluding gizmos) is at Z = -1000. }
332 function ItemsWithGizmosBoundingBox: TBox3D;
333
334 { Set the projection parameters and matrix.
335 Used by our Render method.
336
337 This cooperates closely with current @link(Camera) definition.
338
339 If AutoCamera then the initial and current @link(Camera) vectors
340 are also initialized here (see TCastleCamera.Init
341 and @link(AssignDefaultCamera).
342
343 This takes care to always update Camera.ProjectionMatrix, Projection. }
344 procedure ApplyProjection; virtual;
345
346 { Render shadow quads for all the things rendered by @link(RenderOnePass).
347 You can use here ShadowVolumeRenderer instance, which is guaranteed
348 to be initialized with TGLShadowVolumeRenderer.InitFrustumAndLight,
349 so you can do shadow volumes culling. }
350 procedure RenderShadowVolume(const Params: TRenderParams);
351
352 { Detect position/direction of the main light that produces shadow volumes.
353 Looks at MainScene.InternalMainLightForShadowVolumes.
354 Returns light position (or direction, if W = 0) in world space. }
355 function MainLightForShadowVolumes(out AMainLightPosition: TVector4): boolean;
356
357 { Pass pointing device (mouse or touch) press event
358 to TCastleTransform instances in @link(Items).
359 Depends that MouseRayHit, MouseRayOrigin, MouseRayDirection are already updated. }
360 function PointingDevicePress: boolean;
361
362 { Pass pointing device (mouse or touch) press event
363 to TCastleTransform instances in @link(Items).
364 Depends that MouseRayHit, MouseRayOrigin, MouseRayDirection are already updated. }
365 function PointingDeviceRelease: boolean;
366
367 { Pass pointing device (mouse or touch) move event
368 to TCastleTransform instances in @link(Items).
369 Depends that MouseRayHit, MouseRayOrigin, MouseRayDirection are already updated. }
370 function PointingDeviceMove: boolean;
371 protected
372 { @exclude }
373 function InternalOverride2DProjectionSizing: TCastleUserInterface; virtual;
374
375 { Calculate projection parameters. Determines if the view is perspective
376 or orthogonal and exact field of view parameters.
377 Called each time at the beginning of rendering.
378
379 The default implementation of this method in TCastleViewport
380 calculates projection based on the @link(Camera) parameters.
381
382 In turn, the @link(Camera) parameters may be automatically
383 calculated (if @link(AutoCamera))
384 based on the nodes in the @link(TCastleRootTransform.MainScene).
385 Nodes like TViewpointNode or TOrthoViewpointNode or TNavigationInfoNode
386 determine the default camera and projection details.
387
388 You can override this method, or assign the @link(OnProjection) event
389 to adjust the projection settings.
390 But please note: instead of overriding this method,
391 it's usually easier (and more advised) to simply change the @link(Camera) properties,
392 like @link(TCastleCamera.ProjectionType Camera.ProjectionType)
393 or @link(TCastleOrthographic.Width Camera.Orthographic.Width)
394 or @link(TCastlePerspective.FieldOfView Camera.Perspective.FieldOfView). }
395 function CalculateProjection: TProjection; virtual;
396
397 { Prepare lights shining on everything.
398 GlobalLights contents should be initialized here.
399 The implementation in this class adds headlight determined
400 by the @link(TCastleRootTransform.UseHeadlight Items.UseHeadlight) value. }
401 procedure InitializeGlobalLights(const GlobalLights: TLightInstancesList); virtual;
402
403 procedure InitializeLights(const GlobalLights: TLightInstancesList); deprecated 'use InitializeGlobalLights';
404
405 { Render everything from given camera view (as TRenderingCamera).
406 Given RenderingCamera.Target says to where we generate the image.
407 This method must take care of making many rendering passes
408 for shadow volumes, but doesn't take care of updating generated textures. }
409 procedure RenderFromViewEverything(const RenderingCamera: TRenderingCamera); virtual;
410
411 { Render the scene, assuming that buffers were already cleared and background
412 was rendered. Called by RenderFromViewEverything at the end.
413 Lights are calculated in Params at this point.
414
415 This will change Params.Transparent, Params.InShadow and Params.ShadowVolumesReceivers
416 as needed. Their previous values do not matter. }
417 procedure RenderFromView3D(const Params: TRenderParams); virtual;
418
419 { Render one pass, with current camera and parameters (e.g. only transparent
420 or only opaque shapes).
421 All current camera settings are saved in RenderParams.RenderingCamera.
422 @param(Params Rendering parameters, see @link(TRenderParams).) }
423 procedure RenderOnePass(const Params: TRenderParams); virtual;
424
425 procedure Render3D(const Params: TRenderParams); virtual; deprecated 'use RenderOnePass';
426
427 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
428
429 function InternalExtraGetScreenEffects(
430 const Index: Integer): TGLSLProgram; override;
431 function InternalExtraScreenEffectsCount: Integer; override;
432 function InternalExtraScreenEffectsNeedDepth: Boolean; override;
433
434 { Called when PointingDevicePress was not handled by any TCastleTransform object.
435 You can override this to make a message / sound signal to notify user
436 that his Input_Interact click was not successful. }
437 procedure PointingDevicePressFailed; virtual;
438
439 procedure BoundNavigationInfoChanged; virtual;
440 procedure BoundViewpointChanged; virtual;
441
442 procedure RenderWithoutScreenEffects; override;
443
444 procedure Loaded; override;
445 public
446 const
447 DefaultScreenSpaceAmbientOcclusion = false;
448 DefaultScreenSpaceReflections = False;
449 DefaultScreenSpaceReflectionsSurfaceGlossiness = 0.5;
450 DefaultUseGlobalLights = true;
451 DefaultUseGlobalFog = true;
452 DefaultShadowVolumes = true;
453 DefaultBackgroundColor: TVector4 = (X: 0.1; Y: 0.1; Z: 0.1; W: 1);
454 {$warnings off} // referencing deprecated in deprecated
455 Default2DProjectionFar = CastleTransform.Default2DProjectionFar deprecated 'this default is not used; ProjectionFar in orthographic projection is now automatically adjusted to what you display';
456 Default2DProjectionNear = CastleTransform.Default2DProjectionNear deprecated 'this default is not used; ProjectionNear in orthographic projection is now automatically adjusted to what you display';
457 {$warnings on}
458 Default2DCameraZ = CastleTransform.Default2DCameraZ;
459 DefaultPrepareOptions = [prRenderSelf, prRenderClones, prBackground, prBoundingBox, prScreenEffects];
460 { @exclude }
461 DefaultInternalDesignNavigationType = dnFly;
462 DefaultInternalGridAxis = false;
463
464 var
465 { Rendering pass, for user purposes.
466 Useful to keep shaders cached when you render the same scene multiple times
467 in the same frame (under different lighting conditions or other things
468 that change shaders).
469 By default this is always 0, the engine doesn't modify this.
470 You can set this field manually. }
471 CustomRenderingPass: TUserRenderingPass;
472
473 { Set these to non-1 to deliberately distort field of view / aspect ratio.
474 This is useful for special effects when you want to create unrealistic
475 projection.
476 @exclude }
477 InternalDistortFieldOfViewY, InternalDistortViewAspect: Single;
478
479 { Do not navigate by dragging when we're already dragging a TCastleTransform item.
480 This means that if you drag
481
482 - X3D sensors like TouchSensor,
483 - gizmo in CGE editor,
484
485 ... then your dragging will not simultaneously also affect the navigation
486 (which would be very disorienting).
487
488 Set to true when some TCastleTransform handles PointingDevicePress,
489 set to false in PointingDeviceRelease.
490 @exclude }
491 InternalPointingDeviceDragging: Boolean;
492
493 { At design-time (in CGE editor), this is the camera used by the editor.
494 Usually use InternalCamera, to automatically pick either design-time camera
495 or runtime Camera. }
496 InternalDesignCamera: TCastleCamera;
497
498 constructor Create(AOwner: TComponent); override;
499 destructor Destroy; override;
500
501 function AllowSuspendForInput: boolean; override;
502 function Press(const Event: TInputPressRelease): boolean; override;
503 function Release(const Event: TInputPressRelease): boolean; override;
504 function Motion(const Event: TInputMotion): boolean; override;
505 procedure Update(const SecondsPassed: Single;
506 var HandleInput: boolean); override;
507 procedure BeforeRender; override;
508 function PropertySections(const PropertyName: String): TPropertySections; override;
509 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
510
511 { Return either @link(Camera) or @link(InternalDesignCamera),
512 depending on whether we're in design mode (InternalDesignManipulation) or not.
513 May return @nil.
514 @exclude }
515 function InternalCamera: TCastleCamera;
516
517 { Determines if viewport is in design-mode.
518
519 Initialized from CastleDesignMode, unless viewport is created using InternalCreateNonDesign
520 in which case it is always false.
521 (useful only in CGE editor, when it wants to use viewports
522 with "normal" Camera and Navigation treatment, without
523 InternalDesignCamera / InternalDesignNavigation).
524
525 When false, the InternalDesignCamera and InternalDesignNavigation don't matter,
526 viewport behaves as regular viewport.
527
528 Note that you cannot change it after creation, it would not be so easy
529 (we'd have to destroy InternalDesignCamera, InternalDesignNavigation,
530 figure out what should be Items.MainCamera...).
531
532 @exclude }
533 property InternalDesignManipulation: Boolean read FInternalDesignManipulation;
534
535 { Change design-time navigation.
536 @exclude }
537 property InternalDesignNavigationType: TInternalDesignNavigationType
538 read FInternalDesignNavigationType write SetInternalDesignNavigationType
539 default DefaultInternalDesignNavigationType;
540
541 { At design-time (in CGE editor), this is the navigation used by the editor.
542 @exclude }
543 function InternalDesignNavigation: TCastleNavigation;
544
545 { At design-time, show grid and axis visualization.
546 @exclude }
547 property InternalGridAxis: Boolean read FInternalGridAxis write SetInternalGridAxis
548 default DefaultInternalGridAxis;
549
550 { Constructor that disables special design-mode viewport camera/navigation.
551 Useful in editor.
552 @exclude }
553 constructor InternalCreateNonDesign(AOwner: TComponent; const Ignored: Integer);
554
555 function GetMainScene: TCastleScene; deprecated 'use Items.MainScene';
556
557 {$ifdef FPC}
558 { Current projection parameters,
559 calculated by last @link(CalculateProjection) call,
560 adjusted by @link(OnProjection).
561 @bold(This is read only). To change the projection parameters,
562 override @link(CalculateProjection) or handle event @link(OnProjection). }
563 property Projection: TProjection read FProjection;
564 deprecated 'in most cases, you can instead read Camera parameters, like Camera.Orthographic.EffectiveWidth, Camera.Orthographic.EffectiveHeight';
565 {$endif}
566
567 { Assign current camera vectors and projection.
568 This only fills existing @link(Camera) with contents, it doesn't change
569 the @link(Camera) to new component.
570
571 This is automatically used at first rendering if @link(AutoCamera).
572 You can also use it explicitly. }
573 procedure AssignDefaultCamera; virtual;
574
575 { Does the graphic card support our ScreenSpaceAmbientOcclusion shader.
576 This does @italic(not) depend on the current state of
577 ScreenSpaceAmbientOcclusion property.
578 You can use it e.g. to disable the menu item to switch SSAO in 3D viewer. }
579 function ScreenSpaceAmbientOcclusionAvailable: boolean;
580
581 { Does the graphic card support our ScreenSpaceReflections shader.
582 This does @italic(not) depend on the current state of
583 ScreenSpaceReflections property.
584 You can use it e.g. to disable the menu item to switch SSR in 3D viewer. }
585 function ScreenSpaceReflectionsAvailable: boolean;
586
587 procedure GLContextOpen; override;
588 procedure GLContextClose; override;
589
590 { Parameters to prepare items that are to be rendered
591 within this world. This should be passed to
592 @link(TCastleTransform.PrepareResources).
593
594 Note: Instead of using @link(TCastleTransform.PrepareResources),
595 and this method,
596 it's usually easier to call @link(TCastleViewport.PrepareResources).
597 Then the appropriate TPrepareParams will be passed automatically. }
598 function PrepareParams: TPrepareParams; deprecated 'use TCastleViewport.PrepareResources to prepare transforms';
599
600 function BaseLights: TLightInstancesList; deprecated 'this is internal info, you should not need this; use PrepareParams to get opaque information to pass to TCastleTransform.PrepareResources';
601
602 { Statistics about last rendering frame. See TRenderStatistics docs. }
603 function Statistics: TRenderStatistics;
604
605 { Background color.
606 Displayed only if @link(Background) is @nil and
607 @link(TCastleRootTransform.MainScene MainScene) doesn't define any background either.
608
609 Ignored if @link(Transparent).
610
611 Dark gray (DefaultBackgroundColor) by default. }
612 property BackgroundColor: TCastleColor
613 read FBackgroundColor write FBackgroundColor;
614
615 { Current 3D triangle under the mouse cursor.
616 Updated in every mouse move. May be @nil. }
617 function TriangleHit: PTriangle;
618
619 { Instance for headlight that should be used for this scene.
620 Uses @link(InternalHeadlight) method, applies appropriate camera position/direction.
621 Returns @true only if @link(InternalHeadlight) method returned @true
622 and a suitable camera was present.
623
624 Instance should be considered undefined ("out" parameter)
625 when we return @false.
626
627 @exclude }
628 function HeadlightInstance(out Instance: TLightInstance): boolean;
629 deprecated 'internal information, do not use this';
630
631 { Camera that makes a headlight (if only TCastleRootTransform.UseHeadlight).
632 @exclude}
633 function InternalHeadlightCamera: TCastleCamera; virtual;
634
635 { Enable built-in SSAO screen effect in the world. }
636 property ScreenSpaceAmbientOcclusion: boolean
637 read FScreenSpaceAmbientOcclusion write SetScreenSpaceAmbientOcclusion
638 default DefaultScreenSpaceAmbientOcclusion;
639
640 { Enable built-in SSR screen effect in the world. }
641 property ScreenSpaceReflections: Boolean
642 read FScreenSpaceReflections write SetScreenSpaceReflections
643 default DefaultScreenSpaceReflections;
644
645 { Adjust SSR default surface glossiness. }
646 property ScreenSpaceReflectionsSurfaceGlossiness: Single
647 read FScreenSpaceReflectionsSurfaceGlossiness write SetScreenSpaceReflectionsSurfaceGlossiness;
648
649 { Called on any camera change. }
650 property OnCameraChanged: TNotifyEvent read FOnCameraChanged write FOnCameraChanged;
651
652 { Utility method to set camera to a suitable state for 2D games.
653
654 @unorderedList(
655 @item(
656 Sets both initial and current camera vectors like this:
657 @unorderedList(
658 @itemSpacing compact
659 @item Position camera at @code((0, 0, 500)),
660 @item Looks along the -Z direction,
661 @item "Up" vector is in +Y.
662 )
663
664 This way the 2D world spans horizontally in X and vertically in Y.
665 The Z (depth) can be used to put things in front/behind each other.
666
667 Since this initialized the camera sensibly,
668 we also set @link(AutoCamera) to false.
669 )
670
671 @item(
672 Sets orthographic projection for the camera
673 (@link(TCastleCamera.ProjectionType) set to ptOrthographic).
674
675 By default our visible X range is @code([0..viewport width in pixels]),
676 visible Y range is @code([0..viewport height in pixels]).
677 Use the properties of @link(TCastleOrthographic Camera.Orthographic)
678 to control the projection.
679 For example set
680 @link(TCastleOrthographic.Width Camera.Orthographic.Width) and/or
681 @link(TCastleOrthographic.Height Camera.Orthographic.Height)
682 to define visible projection size (horizontal or vertical) explicitly,
683 regardless of the viewport size.
684
685 Setting @link(TCastleOrthographic.Origin Camera.Orthographic.Origin)
686 is also often useful, e.g. set it to (0.5,0.5) to make the things positioned
687 at (0,0) in the world visible at the middle of the viewport.
688
689 By default our visible Z range is [-1500, 500],
690 because this sets ProjectionNear to -1000, ProjectionFar to 1000,
691 and camera default depth (@code(Camera.Translation.Z)) is 500.
692 This was chosen to be comfortable for all cases -- you can
693 keep camera Z unchanged and comfortably position things around [-500, 500],
694 or set camera Z to zero and then comfortably position things around [-1000, 1000].
695 )
696 )
697 }
698 procedure Setup2D;
699
700 { Convert 2D position on the viewport into 3D "world coordinates",
701 by colliding camera ray with a plane parallel to the viewport at given Depth.
702 "World coordinates" are coordinates
703 space seen by TCastleTransform / TCastleScene inside viewport @link(Items).
704 Use Depth > 0 for positions in front of the camera.
705
706 This is similar to "Unproject" GLU routine.
707 It allows to map points from the 2D viewport back to the 3D space inside viewport.
708
709 The interpretation of Position depends on ContainerCoordinates:
710
711 @unorderedList(
712 @item(When ContainerCoordinates = @true,
713 then Position is relative to the whole container
714 (like TCastleWindow or TCastleControl).
715
716 And it is expressed in real device coordinates,
717 just like @link(TInputPressRelease.Position)
718 when mouse is being clicked, or like @link(TInputMotion.Position)
719 when mouse is moved.
720 )
721
722 @item(When ContainerCoordinates = @false,
723 then Position is relative to this UI control.
724
725 And it is expressed in coordinates after UI scaling.
726 IOW, if the size of this control is @link(Width) = 100,
727 then Position.X between 0 and 100 reflects the visible range of this control.
728 )
729 )
730
731 Returns true and sets 3D PlanePosition if such intersection is found.
732 Returns false if it's not possible to determine such point (which
733 should not be possible, unless camera field of view is larger than 180 degrees).
734 }
735 function PositionToCameraPlane(const Position: TVector2;
736 const ContainerCoordinates: Boolean;
737 const Depth: Single; out PlanePosition: TVector3): Boolean;
738
739 { Convert 2D position on the viewport into 3D ray.
740
741 The interpretation of Position depends on ContainerCoordinates:
742
743 @unorderedList(
744 @item(When ContainerCoordinates = @true,
745 then Position is relative to the whole container
746 (like TCastleWindow or TCastleControl).
747
748 And it is expressed in real device coordinates,
749 just like @link(TInputPressRelease.Position)
750 when mouse is being clicked, or like @link(TInputMotion.Position)
751 when mouse is moved.
752 )
753
754 @item(When ContainerCoordinates = @false,
755 then Position is relative to this UI control.
756
757 And it is expressed in coordinates after UI scaling.
758 IOW, if the size of this control is @link(Width) = 100,
759 then Position.X between 0 and 100 reflects the visible range of this control.
760 )
761 )
762 }
763 procedure PositionToRay(const Position: TVector2;
764 const ContainerCoordinates: Boolean; out RayOrigin, RayDirection: TVector3);
765
766 { Convert 2D position on the viewport into 3D "world coordinates",
767 by colliding camera ray with a plane at constant X, Y or Z.
768 "World coordinates" are coordinates
769 space seen by TCastleTransform / TCastleScene inside viewport @link(Items).
770
771 This works with any projection (perspective or orthographic).
772
773 You can use it to pick a point on any plane with constant X (PlaneConstCoord = 0),
774 constant Y (PlaneConstCoord = 1), constant Z (PlaneConstCoord = 2).
775
776 This intersects the ray cast by @link(Camera) with a plane where given coordinate (PlaneConstCoord)
777 has value equal to PlaneConstValue.
778 The parameter names and interpretation is consistent e.g. with
779 @link(TrySimplePlaneRayIntersection).
780
781 The interpretation of Position depends on ContainerCoordinates:
782
783 @unorderedList(
784 @item(When ContainerCoordinates = @true,
785 then Position is relative to the whole container
786 (like TCastleWindow or TCastleControl).
787
788 And it is expressed in real device coordinates,
789 just like @link(TInputPressRelease.Position)
790 when mouse is being clicked, or like @link(TInputMotion.Position)
791 when mouse is moved.
792 )
793
794 @item(When ContainerCoordinates = @false,
795 then Position is relative to this UI control.
796
797 And it is expressed in coordinates after UI scaling.
798 IOW, if the size of this control is @link(Width) = 100,
799 then Position.X between 0 and 100 reflects the visible range of this control.
800 )
801 )
802
803 Returns true and sets 3D PlanePosition (the PlaneConstCoord component of this vector
804 must always be equal to PlaneConstValue) if such intersection is found.
805 Returns false if it's not possible to determine such point (when
806 the camera looks in the other direction).
807 }
808 function PositionToWorldPlane(const Position: TVector2;
809 const ContainerCoordinates: Boolean;
810 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
811 out PlanePosition: TVector3): Boolean; overload;
812
813 function PositionToWorldPlane(const Position: TVector2;
814 const ContainerCoordinates: Boolean;
815 const PlaneConstValue: Single;
816 out PlanePosition: TVector3): Boolean; overload;
817 deprecated 'use PositionToWorldPlane overload with PlaneConstCoord parameter; this version assumes PlaneConstCoord = 2';
818
819 { Convert 2D position into "world coordinates", which is the coordinate
820 space seen by TCastleTransform / TCastleScene inside viewport @link(Items),
821 assuming that we use orthographic projection in XY axes.
822
823 The interpretation of Position depends on ContainerCoordinates:
824
825 @unorderedList(
826 @item(When ContainerCoordinates = @true,
827 then Position is relative to the whole container
828 (like TCastleWindow or TCastleControl).
829
830 And it is expressed in real device coordinates,
831 just like @link(TInputPressRelease.Position)
832 when mouse is being clicked, or like @link(TInputMotion.Position)
833 when mouse is moved.
834 )
835
836 @item(When ContainerCoordinates = @false,
837 then Position is relative to this UI control.
838
839 And it is expressed in coordinates after UI scaling.
840 IOW, if the size of this control is @link(Width) = 100,
841 then Position.X between 0 and 100 reflects the visible range of this control.
842 )
843 )
844
845 This assumes that camera "up vector" is +Y, and it is looking along the negative Z
846 axis. It also assumes orthographic projection (@link(TCastleCamera.ProjectionType Camera.ProjectionType)
847 equal @link(ptOrthographic)).
848 These are default camera direction, up and projection types set
849 by @link(Setup2D). }
850 function PositionTo2DWorld(const Position: TVector2;
851 const ContainerCoordinates: Boolean): TVector2;
852
853 { Invert @link(PositionTo2DWorld), converting the "world coordinates" (the coordinate
854 space seen by TCastleTransform / TCastleScene inside viewport @link(Items))
855 into final screen position.
856
857 Just like @link(PositionTo2DWorld),
858 this assumes that camera "up vector" is +Y, and it is looking along the negative Z
859 axis. It also assumes orthographic projection (@link(TCastleCamera.ProjectionType Camera.ProjectionType)
860 equal @link(ptOrthographic)).
861 These are default camera direction, up and projection types set
862 by @link(Setup2D). }
863 function PositionFrom2DWorld(const WorldPosition: TVector2;
864 const ContainerCoordinates: Boolean): TVector2;
865
866 { Project 3D coordinates (the coordinate
867 space seen by TCastleTransform / TCastleScene inside viewport @link(Items))
868 into 2D position on the viewport UI.
869
870 The resulting position is relative to this viewport control
871 and it is expressed in coordinates after UI scaling.
872 IOW, if the size of this control is @link(EffectiveWidth) = 100,
873 then Position.X between 0 and 100 reflects the visible range of this control.
874 This is like using ContainerCoordinates = @false with PositionToRay. }
875 function PositionFromWorld(const WorldPosition: TVector3): TVector2;
876
877 procedure PrepareResources(const DisplayProgressTitle: string;
878 const Options: TPrepareResourcesOptions = DefaultPrepareOptions); overload;
879 deprecated 'use overload without DisplayProgressTitle: String';
880 procedure PrepareResources(const Item: TCastleTransform;
881 const DisplayProgressTitle: string;
882 Options: TPrepareResourcesOptions = DefaultPrepareOptions); overload;
883 deprecated 'use overload without DisplayProgressTitle: String';
884
885 { Prepare resources, to make various methods (like @link(Render)) execute fast.
886 Call it only when rendering context is initialized (ApplicationProperties.IsGLContextOpen). }
887 procedure PrepareResources(
888 const Options: TPrepareResourcesOptions = DefaultPrepareOptions); overload;
889 procedure PrepareResources(const Item: TCastleTransform;
890 Options: TPrepareResourcesOptions = DefaultPrepareOptions); overload; virtual;
891
892 { Current components (TCastleTransform hierarchy) pointed by the mouse cursor
893 position. This is the @italic(first) object being hit by the ray from camera
894 through the mouse cursor position.
895
896 Automatically updated to always reflect the current mouse position.
897 May be @nil if nothing is hit.
898
899 The "mouse cursor position" on touch devices is just the last touch point.
900 When the navigation uses mouse look (like TCastleWalkNavigation.MouseLook),
901 we automatically use viewport center as the "mouse cursor position".
902
903 @seealso TransformUnderMouse }
904 property MouseRayHit: TRayCollision read GetMouseRayHit;
905
906 { Current TCastleTransform pointed by the mouse cursor
907 position. This is the @italic(first) object being hit by the ray from camera
908 through the mouse cursor position.
909
910 Automatically updated to always reflect the current mouse position.
911 May be @nil if nothing is hit.
912
913 The "mouse cursor position" on touch devices is just the last touch point.
914 When the navigation uses mouse look (like TCastleWalkNavigation.MouseLook),
915 we automatically use viewport center as the "mouse cursor position".
916
917 @seealso MouseRayHit
918 @seealso TRayCollision.Transform }
919 function TransformUnderMouse: TCastleTransform;
920
921 { Do not collide with this object when moving by @link(Navigation).
922 It makes sense to put here player avatar (in 3rd person view)
923 or player collision volume (in 1st person view)
924 to allow player to move, not colliding with its own body. }
925 property AvoidNavigationCollisions: TCastleTransform
926 read FAvoidNavigationCollisions
927 write SetAvoidNavigationCollisions;
928
929 {$ifdef FPC}
930 { See @link(TCastleAbstractRootTransform.Paused). }
931 property Paused: boolean read GetPaused write SetPaused default false;
932 deprecated 'use Items.Paused';
933
934 property SceneManager: TCastleSceneManager read FSceneManager write SetSceneManager;
935 deprecated 'assign Items from one TCastleViewport to another to view the same world from multiple viewports';
936 {$endif}
937
938 { Create new camera and make it used by this viewport.
939 This creates new unnamed TCastleCamera, owned by this viewport,
940 assigns it to @link(Camera) and adds it to @link(Items).
941
942 Call this only when @link(Camera) is @nil.
943
944 This is done automatically when creating TCastleViewport (not in design-mode,
945 not at deserialization) using the standard TCastleViewport.Create constructor.
946 So you likely don't need to call this in typical applications.
947
948 Note: Even when used from CGE editor (CastleDesignMode), this creates non-design camera.
949 This way viewports created with InternalCreateNonDesign have also non-design cameras.
950 This is important, so that e.g. camera has no bounding box, and thus
951 AssignDefaultCamera in sprite sheet editor doesn't put camera further and further away. }
952 procedure SetupCamera;
953
954 { Navigation method is an optional component that handles
955 the user input to control the camera.
956
957 @deprecated
958 This is a deprecated property.
959 There's no point in assigning current navigation like this.
960 Instead add the @link(TCastleNavigation) instance
961 as a child of TCastleViewport and it will affect the viewport
962 automatically.
963 This property is now only a shortcut to
964
965 - get the current @link(TCastleNavigation) child (if multiple present,
966 it is undefined which is returned)
967
968 - make the given set @link(TCastleNavigation) as the only child.
969
970 You can assign here an instance of @link(TCastleNavigation),
971 like @link(TCastleWalkNavigation) or @link(TCastleExamineNavigation).
972 Or you can leave it as @nil. }
973 property Navigation: TCastleNavigation read GetNavigation write SetNavigation
974 stored false;
975 {$ifdef FPC}deprecated 'instead of this property: to get, just remember current navigation instance on your side; to set, add it like "MyViewport.InsertBack(MyNavigation)"';{$endif}
976
977 { Check collisions (for move) with whole world (except AvoidNavigationCollisions).
978 Given parameters are in world coordinates.
979 @exclude }
980 function InternalNavigationMoveAllowed(const Sender: TCastleNavigation;
981 const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3;
982 const Radius: Single; const BecauseOfGravity: Boolean): Boolean;
983
984 { Check collisions (to query height) with whole world (except AvoidNavigationCollisions).
985 Given parameters are in world coordinates.
986 @exclude }
987 function InternalNavigationHeight(const Sender: TCastleNavigation;
988 const Position: TVector3;
989 out AboveHeight: Single; out AboveGround: PTriangle): Boolean;
990 published
991 { Transformations and scenes visible in this viewport.
992 You should add here your @link(TCastleTransform) and @link(TCastleScene)
993 instances.
994
995 It is by default created (not @nil), but you can also assign here your own
996 TCastleRootTransform instance.
997 You can also copy a TCastleRootTransform from one TCastleViewport to another,
998 that is multiple TCastleViewport can refer to the same TCastleRootTransform
999 instance.
1000
1001 Note that assigning here @nil is allowed, but under the hood it just creates
1002 an empty TCastleRootTransform instance. So this property is never @nil when reading.
1003 But try to not depend on it for the future, at some point this property may be
1004 allowed to be @nil, for consistency. }
1005 property Items: TCastleRootTransform read FItems write SetItems;
1006
1007 { Camera determines the viewer position and orientation.
1008
1009 You should create TCastleCamera, assign to this property,
1010 and add it somewhere to @link(Items).
1011
1012 Note that camera can be placed anywhere within @link(Items),
1013 not necessary as direct child of @link(Items).
1014 For example it can be a children of some deeper TCastleTransform,
1015 this way you can attach camera e.g. to some bone or to a moving object.
1016
1017 Generally, TCastleCamera is a regular component that can be added and removed
1018 freely from @link(Items), renamed, freed etc.
1019 And setting this property is an independent action
1020 that doesn't add/remove any camera from @link(Items).
1021 This property can also be set to @nil.
1022
1023 For convenience, there are however some moments when we set up this property and
1024 add camera to @link(Items) automatically:
1025
1026 @orderedList(
1027 @item(
1028 When you create TCastleViewport from code (not by deserializing some
1029 @code(xxx.castle-user-interface) file, not in design-mode in editor)
1030 then we automatically add new (unnamed) camera and set
1031 Viewport.Camera and add it to Viewport.Items.)
1032
1033 @item(
1034 Only at design-time (in editor): creating new viewport by editor menu
1035 also adds a default camera to it.
1036 In this case camera component is named and owned by the same owner as viewport.
1037 This is done right after TCastleViewport creation and only at design-time.)
1038
1039 @item(
1040 For backward compatibility, after deserializing file from previous engine versions,
1041 we add the camera from it to Viewport.Items.
1042 This is made strictly for backward compatibility, only when deserializing,
1043 and it shouldn't occur when reading new design files.)
1044 )
1045
1046 It's important to note that when deserializing camera from new engine versions, there's no "magic".
1047 We just expect that Viewport.Camera and Viewport.Items are good.
1048 Trying to do something automatic/smart in this case turned out to be quite troublesome
1049 and breaking more than helping. }
1050 property Camera: TCastleCamera read FCamera write SetCamera;
1051
1052 { Should we render with shadow volumes.
1053 You can change this at any time, to switch rendering shadows on/off.
1054
1055 This works only if OpenGL context actually can render shadow volumes,
1056 checked by GLFeatures.ShadowVolumesPossible, which means that you have
1057 to initialize OpenGL context with stencil buffer.
1058
1059 The shadow volumes algorithm is used only if shadow caster
1060 is 2-manifold, that is has a correctly closed volume.
1061 Also you need a light source
1062 marked as the main shadow volumes light (shadowVolumes = shadowVolumesMain = TRUE).
1063 See [https://castle-engine.io/x3d_extensions.php#section_ext_shadows]
1064 for details. }
1065 property ShadowVolumes: boolean
1066 read FShadowVolumes write FShadowVolumes default DefaultShadowVolumes;
1067
1068 { Actually draw the shadow volumes to the color buffer, for debugging.
1069 If shadows are rendered (see GLFeatures.ShadowVolumesPossible and ShadowVolumes),
1070 you can use this to actually see shadow volumes, for debug / demo
1071 purposes. Shadow volumes will be rendered on top of the scene,
1072 as yellow blended polygons. }
1073 property ShadowVolumesRender: boolean read FShadowVolumesRender write FShadowVolumesRender default false;
1074
1075 { Background (like a skybox) to display behind the @link(Items).
1076 Displayed only when not @link(Transparent).
1077 See https://castle-engine.io/background }
1078 property Background: TCastleBackground read FBackground write SetBackground;
1079
1080 { Fog to use to display viewport contents in @link(Items).
1081 See https://castle-engine.io/fog }
1082 property Fog: TCastleFog read FFog write SetFog;
1083
1084 { If @true then the background (from @link(Background) or
1085 @link(TCastleRootTransform.MainScene MainScene)) will be rendered wireframe,
1086 over the solid background filled with BackgroundColor.
1087 Useful for debugging when you want to see how your background
1088 geometry looks like.
1089
1090 Ignored if @link(Transparent). }
1091 property BackgroundWireframe: boolean
1092 read FBackgroundWireframe write FBackgroundWireframe default false;
1093
1094 { If @true then the viewport will not draw a background and the UI underneath
1095 will be visible.
1096 The UI underneath is visible at pixels which are not covered by items on @link(Items),
1097 and where items @link(Items) have partially-transparent materials.
1098
1099 If @true, the @link(Background), @link(BackgroundColor), @link(BackgroundWireframe),
1100 and any background defined inside
1101 @link(TCastleRootTransform.MainScene MainScene) will be ignored. }
1102 property Transparent: boolean read FTransparent write FTransparent default false;
1103
1104 { At the beginning of rendering, viewport by default clears
1105 the depth buffer. This makes every viewport draw everything
1106 on top of the previous 2D and 3D stuff (including on top
1107 of previous viewport), like a layer.
1108
1109 You can disable this, which allows to combine together the 3D objects rendered
1110 by various viewports (and by custom OpenGL rendering),
1111 such that the 3D positions determime what overlaps what.
1112 This only makes sense if you have a number of TCastleViewport instances,
1113 that share the same size and position on the screen,
1114 same projection and the same camera.
1115
1116 It's your responsibility in such case to clear the depth buffer.
1117 E.g. place one viewport in the back that has ClearDepth = @true.
1118 Or place a TCastleUserInterface descendant in the back, that calls
1119 @code(TRenderContext.Clear RenderContext.Clear) in overridden
1120 @link(TCastleUserInterface.Render).
1121
1122 Note: to disable clearning the color buffer, set @link(Transparent)
1123 to @false.
1124
1125 Note: if you use shadow volumes, we will still clear the stencil buffer
1126 at the beginning of rendering.
1127 }
1128 property ClearDepth: boolean read FClearDepth write FClearDepth default true;
1129
1130 { Let lights in MainScene shine on every other TCastleScene, not only
1131 MainScene. This is an easy way to lit your whole world with lights
1132 defined inside MainScene file. Be sure to set X3D lights global=TRUE. }
1133 property UseGlobalLights: boolean
1134 read FUseGlobalLights write FUseGlobalLights default DefaultUseGlobalLights;
1135 {$ifdef FPC} deprecated 'if you need to tweak this, then do not use MainScene; use regular TCastleScene and set CastGlobalLights as needed'; {$endif}
1136
1137 { Let the fog defined in MainScene affect all objects, not only MainScene.
1138 This is consistent with @link(UseGlobalLights), that allows lights
1139 from MainScene to shine on all objects. }
1140 property UseGlobalFog: boolean
1141 read FUseGlobalFog write FUseGlobalFog default DefaultUseGlobalFog;
1142 {$ifdef FPC} deprecated 'configure fog by assigning to TCastleViewport.Fog component; leave deprecated TCastleViewport.MainScene nil'; {$endif}
1143
1144 { Help user to activate pointing device sensors and pick items.
1145 Every time you press Input_Interact (by default
1146 just left mouse button), we look if current mouse/touch position hits an object (TCastleTransform)
1147 that actually does something on activation. The object may do various stuff
1148 inside TCastleTransform.PointingDevicePress, generally this causes various
1149 picking/interaction with the object (like pulling a level, opening a door),
1150 possibly dragging, possibly with the help of VRML/X3D pointing device
1151 and drag sensors.
1152
1153 When this is @true, we try harder to hit some 3D object that handles
1154 PointingDevicePress. If there's nothing interesting under mouse/touch,
1155 we will retry a couple of other positions around the current mouse/touch.
1156
1157 This should be usually used when you use TCastleMouseLookNavigation.MouseLook,
1158 or other navigation when mouse cursor is hidden.
1159 It allows user to only approximately look at interesting item and hit
1160 interaction button or key.
1161 Otherwise, activating a small object is difficult,
1162 as you don't see the cursor. }
1163 property ApproximateActivation: boolean
1164 read FApproximateActivation write FApproximateActivation default false;
1165
1166 {$ifdef FPC}
1167 { Adjust the projection parameters. This event is called before every render.
1168 See the @link(CalculateProjection) for a description how to default
1169 projection parameters are calculated. }
1170 property OnProjection: TProjectionEvent read FOnProjection write FOnProjection;
1171 deprecated 'adjust projection by changing Camera.ProjectionType and other projection parameters inside Camera';
1172 {$endif}
1173
1174 { Enable to drag a parent control, for example to drag a TCastleScrollView
1175 that contains this TCastleViewport, even when the scene inside contains
1176 clickable elements (using TouchSensor node).
1177
1178 To do this, you need to turn on
1179 TCastleScrollView.EnableDragging, and set EnableParentDragging=@true
1180 here. In effect, viewport will cancel the click operation
1181 once you start dragging, which allows the parent to handle
1182 all the motion events for dragging. }
1183 property EnableParentDragging: boolean
1184 read FEnableParentDragging write FEnableParentDragging default false;
1185
1186 { Assign initial camera properties
1187 (initial position, direction, up, TCastleCamera.ProjectionNear)
1188 by looking at the initial world (@link(Items)) when rendering the first frame.
1189
1190 The @link(AssignDefaultCamera) is automatically called only if this property is @true.
1191
1192 Also, only if this property is @true, we synchronize
1193 camera when X3D Viewpoint node changes, or a new X3D Viewpoint node is bound.
1194
1195 By default it is @false, which means you control @link(Camera) properties on your own.
1196 }
1197 property AutoCamera: Boolean
1198 read FAutoCamera write SetAutoCamera default false;
1199 {$ifdef FPC} deprecated 'it is simpler to set camera at design-time explicitly, or use CameraViewpointForWholeScene to auto-adjust camera; if you want to animate the camera, attach TCastleCamera to a bone transformation exposed by Scene.ExposeTransforms'; {$endif}
1200
1201 { Called when bound Viewpoint node changes.
1202 Called exactly when TCastleSceneCore.ViewpointStack.OnBoundChanged is called. }
1203 property OnBoundViewpointChanged: TNotifyEvent read FOnBoundViewpointChanged write FOnBoundViewpointChanged;
1204
1205 { Called when bound NavigationInfo changes (to a different node,
1206 or just a field changes). }
1207 property OnBoundNavigationInfoChanged: TNotifyEvent read FOnBoundNavigationInfoChanged write FOnBoundNavigationInfoChanged;
1208
1209 { Protect from falling down because of gravity when position is outside
1210 of world bounding box.
1211 This is a nice thing for general model viewers (like castle-model-viewer),
1212 to prevent from accidentally falling down when using "Walk" mode.
1213
1214 This is only used by navigations performing gravity internally,
1215 that is right now: @link(TCastleWalkNavigation) (when @link(TCastleWalkNavigation.Gravity) = @true). }
1216 property PreventInfiniteFallingDown: Boolean
1217 read FPreventInfiniteFallingDown write FPreventInfiniteFallingDown default false;
1218
1219 { Combine (right before rendering) multiple shapes with a similar appearance into one.
1220 This can drastically reduce the number of "draw calls",
1221 making rendering much faster.
1222
1223 To debug effectiveness of this, display @link(TCastleViewport.Statistics).
1224 In CGE editor (at design-time), use menu item "Edit -> Show Statistics" (F8).
1225 When dynamic batching works, the number of rendered shapes
1226 and the number of "Draw Calls" should be much smaller. }
1227 property DynamicBatching: Boolean
1228 read FDynamicBatching write SetDynamicBatching default false;
1229
1230 { Use the occlusion culling to optimize the rendering.
1231 The shapes obscured by other shapes will not be rendered.
1232 This makes sense when in your view, many shapes are typically obscured by others.
1233
1234 See the https://castle-engine.io/occlusion_culling
1235 for details how does this work.
1236
1237 To debug effectiveness of this, display @link(TCastleViewport.Statistics).
1238 In CGE editor (at design-time), use menu item "Edit -> Show Statistics" (F8).
1239 If you look closely at a wall that obscures many shapes behind it,
1240 you should see the number of rendered shapes drop significantly
1241 using occlusion culling.
1242
1243 This is ignored if GPU doesn't support the necessary functionality
1244 (@link(TGLFeatures.OcclusionQuery)). }
1245 property OcclusionCulling: boolean
1246 read FOcclusionCulling write SetOcclusionCulling default false;
1247
1248 { Sort the opaque shapes when rendering, from front to back.
1249 This may make a speedup when big shapes in front of camera obscure
1250 many shapes behind.
1251 This is only an optimization: regardless of the value of this,
1252 rendering opaque objects will be always correct.
1253 Different values of this properly may merely increase / decrease
1254 rendering performance (frames per second).
1255
1256 In general this is an independent optimization from @link(OcclusionCulling),
1257 albeit it makes sense in similar situations.
1258
1259 When combined with @link(OcclusionCulling), it makes occlusion culling
1260 even more effective. Occlusion culling can reject more shapes,
1261 because the things that obscure them are rendered earlier to the depth buffer.
1262
1263 See https://castle-engine.io/occlusion_culling#occlusion_sort for more details.
1264
1265 The default value, sortAuto, for now is equivalent to sortNone.
1266 It may change in the future to perform sorting esp. when OcclusionCulling
1267 is @true, as OcclusionCulling and sorting are a natural pair,
1268 sorting make occlusion culling even more effective.
1269 }
1270 property OcclusionSort: TShapeSort
1271 read FOcclusionSort write FOcclusionSort default sortAuto;
1272
1273 { Sort the blending (partially-transparent) shapes when rendering,
1274 from back to front.
1275
1276 This makes blending correct when there are multiple partially-transparent
1277 objects visible.
1278 See @url(https://castle-engine.io/blending blending manual).
1279 Invalid value of this may cause rendering artifacts when rendering
1280 multiple partially-transparent objects.
1281
1282 The default value, sortAuto, automatically detects if camera
1283 is 2D (orthographic, looking in -Z) and if yes, it behaves like sort2D.
1284 Otherwise it behaves like sort3D. }
1285 property BlendingSort: TShapeSort
1286 read FBlendingSort write FBlendingSort default sortAuto;
1287
1288 { Used to sort shapes, if @link(TCastleViewport.BlendingSort) or
1289 @link(TCastleViewport.OcclusionSort) indicate sortCustom.
1290 See TShapeSortEvent for usage details and example. }
1291 property OnCustomShapeSort: TShapeSortEvent
1292 read FOnCustomShapeSort write FOnCustomShapeSort;
1293
1294 { Should the sound listener (that determines how the sounds are heard)
1295 be updated to reflect this viewport's active camera.
1296 This is @true by default, so that 3D sound "just works" out-of-the-box
1297 when you have 3D sounds in the TCastleViewport.
1298 However, if you use @url(https://castle-engine.io/multiple_viewports_to_display_one_world multiple viewports)
1299 to display the same world from multiple cameras,
1300 you should set this to @false for all but one viewport.
1301
1302 Active camera comes from @code(Items.MainCamera) and should match
1303 @link(Camera) in all normal circumstances, if you haven't customized
1304 @code(Items.MainCamera) manually. }
1305 property UpdateSoundListener: Boolean
1306 read FUpdateSoundListener write FUpdateSoundListener default true;
1307
1308 {$define read_interface_class}
1309 {$I auto_generated_persistent_vectors/tcastleviewport_persistent_vectors.inc}
1310 {$undef read_interface_class}
1311 end;
1312
1313 TCastleViewportList = class({$ifdef FPC}specialize{$endif} TObjectList<TCastleViewport>)
1314 private
1315 SceneManager: TCastleSceneManager;
1316 protected
1317 procedure Notify({$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Value: TCastleViewport;
1318 Action: TCollectionNotification); override;
1319 end deprecated 'internal for TCastleSceneManager';
1320
1321 {$define read_interface}
1322 {$I castleviewport_autonavigation.inc}
1323 {$I castleviewport_scenemanager.inc}
1324 {$I castleviewport_touchnavigation.inc}
1325 {$I castleviewport_serialize.inc}
1326 {$I castleviewport_design_navigation.inc}
1327 {$undef read_interface}
1328
1329 var
1330 { Key/mouse combination to interact with clickable things in TCastleViewport.Items.
1331 More precisely, this input will activate pointing device sensors in X3D,
1332 which are used to touch (click) or drag things.
1333 By default this is left mouse button click.
1334
1335 You can change it to any other mouse button or even to key combination.
1336 Simply change properties like TInputShortcut.Key1
1337 or TInputShortcut.MouseButtonUse. }
1338 Input_Interact: TInputShortcut;
1339
1340 implementation
1341
1342 uses DOM, Math, TypInfo,
1343 CastleGLUtils, CastleLog, CastleStringUtils,
1344 CastleSoundEngine, CastleGLVersion, CastleTextureImages,
1345 CastleInternalSettings, CastleXmlUtils, CastleUriUtils, CastleInternalRenderer,
1346 CastleRenderContext, CastleApplicationProperties, X3DLoad, CastleInternalGLUtils;
1347
1348 {$define read_implementation}
1349 {$I castleviewport_autonavigation.inc}
1350 {$I castleviewport_scenemanager.inc}
1351 {$I castleviewport_touchnavigation.inc}
1352 {$I castleviewport_warmup_cache.inc}
1353 {$I castleviewport_serialize.inc}
1354 {$I castleviewport_design_navigation.inc}
1355 {$undef read_implementation}
1356
1357 { TViewportRenderParams ------------------------------------------------------- }
1358
1359 constructor TCastleViewport.TViewportRenderParams.Create;
1360 begin
1361 inherited;
1362 FGlobalLights := TLightInstancesList.Create;
1363 end;
1364
1365 destructor TCastleViewport.TViewportRenderParams.Destroy;
1366 begin
1367 FreeAndNil(FGlobalLights);
1368 inherited;
1369 end;
1370
1371 function TCastleViewport.TViewportRenderParams.GlobalLights: TAbstractLightInstancesList;
1372 begin
1373 Result := FGlobalLights;
1374 end;
1375
1376 { TSSAOScreenEffect ---------------------------------------------------------- }
1377
1378 function TCastleViewport.TSSAOScreenEffect.SetupUniforms(var BoundTextureUnits: Cardinal): Boolean;
1379 begin
1380 Result := inherited;
1381
1382 { set special uniforms for SSAO shader }
1383
1384 { TODO: use actual projection near/far values, instead of hardcoded ones.
1385 Assignment below works, but it seems that effect is much less noticeable
1386 then?
1387
1388 Note: Viewport.ProjectionFar may be ZFarInfinity, this will also have to be accounted for,
1389 maybe use ItemsBoundingBox.PointsDistance (max distance to camera) or MaxSize.
1390
1391 WritelnLog('setting near to %f', [Viewport.ProjectionNear]); // testing
1392 WritelnLog('setting far to %f', [Viewport.ProjectionFar]); // testing
1393 Uniform('near').SetValue(Viewport.ProjectionNear);
1394 Uniform('far').SetValue(Viewport.ProjectionFar);
1395 }
1396
1397 Uniform('near').SetValue(1.0);
1398 Uniform('far').SetValue(1000.0);
1399 end;
1400
1401 { TSSRScreenEffect ---------------------------------------------------------- }
1402
1403 function TCastleViewport.TSSRScreenEffect.SetupUniforms(var BoundTextureUnits: Cardinal): Boolean;
1404 var
1405 ViewProjectionMatrix,
1406 ViewProjectionMatrixInverse: TMatrix4;
1407 begin
1408 Result := inherited;
1409
1410 { set special uniforms for SSR shader }
1411
1412 { TODO: instead of relying on Viewport.InternalCamera,
1413 it should get and use RenderingCamera reference. }
1414
1415 Uniform('near').SetValue(0.1);
1416 Uniform('far').SetValue(1000.0);
1417 ViewProjectionMatrix := Viewport.InternalCamera.ProjectionMatrix * Viewport.InternalCamera.Matrix;
1418 if not ViewProjectionMatrix.TryInverse(ViewProjectionMatrixInverse) then
1419 ViewProjectionMatrixInverse := TMatrix4.Identity;
1420 Uniform('defaultSurfaceGlossiness').SetValue(Viewport.ScreenSpaceReflectionsSurfaceGlossiness);
1421 Uniform('castle_ViewProjectionMatrix').SetValue(ViewProjectionMatrix);
1422 Uniform('castle_ViewProjectionMatrixInverse').SetValue(ViewProjectionMatrixInverse);
1423 Uniform('castle_CameraPosition').SetValue(Viewport.InternalCamera.WorldTranslation);
1424 end;
1425
1426 { TCastleViewport ------------------------------------------------------- }
1427
1428 procedure TCastleViewport.CommonCreate(const AOwner: TComponent; const ADesignManipulation: Boolean);
1429 begin
1430 inherited Create(AOwner);
1431
1432 FBackgroundColor := DefaultBackgroundColor;
1433 FUseGlobalLights := DefaultUseGlobalLights;
1434 FUseGlobalFog := DefaultUseGlobalFog;
1435 FRenderParams := TViewportRenderParams.Create;
1436 FPrepareParams := TPrepareParams.Create;
1437 FRenderWithoutScreenEffectsRenderingCamera := TRenderingCamera.Create;
1438 FShadowVolumes := DefaultShadowVolumes;
1439 FScreenSpaceReflectionsSurfaceGlossiness := DefaultScreenSpaceReflectionsSurfaceGlossiness;
1440 FClearDepth := true;
1441 InternalDistortFieldOfViewY := 1;
1442 InternalDistortViewAspect := 1;
1443 ShapesCollector := TShapesCollector.Create;
1444 ShapesRenderer := TShapesRenderer.Create;
1445 FUpdateSoundListener := true;
1446
1447 FItems := TCastleRootTransform.Create(Self);
1448 FItems.SetSubComponent(true);
1449 FItems.Name := 'Items';
1450 FItems.InternalOnNodesFree := {$ifdef FPC}@{$endif} ItemsNodesFree;
1451
1452 FCapturePointingDeviceObserver := TFreeNotificationObserver.Create(Self);
1453 FCapturePointingDeviceObserver.OnFreeNotification := {$ifdef FPC}@{$endif} CapturePointingDeviceFreeNotification;
1454
1455 FBackgroundObserver := TFreeNotificationObserver.Create(Self);
1456 FBackgroundObserver.OnFreeNotification := {$ifdef FPC}@{$endif} BackgroundFreeNotification;
1457
1458 FFogObserver := TFreeNotificationObserver.Create(Self);
1459 FFogObserver.OnFreeNotification := {$ifdef FPC}@{$endif} FogFreeNotification;
1460
1461 FCameraObserver := TFreeNotificationObserver.Create(Self);
1462 FCameraObserver.OnFreeNotification := {$ifdef FPC}@{$endif} CameraFreeNotification;
1463
1464 FItemsObserver := TFreeNotificationObserver.Create(Self);
1465 FItemsObserver.OnFreeNotification := {$ifdef FPC}@{$endif} ItemsFreeNotification;
1466
1467 FMissingCameraRect := TCastleRectangleControl.Create(Self);
1468 FMissingCameraRect.SetTransient;
1469 FMissingCameraRect.Exists := false;
1470 FMissingCameraRect.FullSize := true;
1471 InsertBack(FMissingCameraRect);
1472
1473 FMissingCameraLabel := TCastleLabel.Create(Self);
1474 FMissingCameraLabel.Caption :=
1475 'No camera selected.' + NL +
1476 NL +
1477 'To see the viewport contents,' + NL +
1478 'set TCastleViewport.Camera.';
1479 FMissingCameraLabel.SetTransient;
1480 FMissingCameraLabel.Alignment := hpMiddle;
1481 FMissingCameraLabel.FontSize := 20;
1482 FMissingCameraLabel.Anchor(hpMiddle);
1483 FMissingCameraLabel.Anchor(vpMiddle);
1484 FMissingCameraRect.InsertFront(FMissingCameraLabel);
1485
1486 FInternalDesignManipulation := ADesignManipulation;
1487
1488 { only when not deserializing, and not in editor: create automatic Camera
1489 - unnamed, to not collide with name of sthg else
1490 - owned by Self (viewport), to not assume anything about AOwner }
1491 if (InternalLoadingComponent = 0) and (not InternalDesignManipulation) then
1492 SetupCamera;
1493
1494 if InternalDesignManipulation then
1495 begin
1496 { We need to use TCastleCamera.InternalCreateNonDesign,
1497 otherwise InternalDesignCamera would be visible in preview of other camera. }
1498 InternalDesignCamera := TCastleCamera.InternalCreateNonDesign(Self, 0);
1499 InternalDesignCamera.SetTransient;
1500 // this somewhat replicates what happens at SetCamera
1501 InternalDesignCamera.InternalOnCameraChanged := {$ifdef FPC}@{$endif} InternalCameraChanged;
1502 Items.Add(InternalDesignCamera);
1503
1504 { when InternalDesignManipulation,
1505 then Items.MainCamera just always follows InternalDesignCamera,
1506 ignoring Camera. This way
1507 - gizmos adjust to design-time camera, so they have proper size
1508 - billboards adjust to design-time camera, so e.g. light gizmos look OK. }
1509 Items.MainCamera := InternalDesignCamera;
1510
1511 FInternalDesignNavigationType := DefaultInternalDesignNavigationType;
1512 FInternalGridAxis := DefaultInternalGridAxis;
1513
1514 FInternalDesignNavigations[dnFly] := TCastleWalkNavigationDesign.Create(Self);
1515 FInternalDesignNavigations[dnFly].SetTransient;
1516 FInternalDesignNavigations[dnFly].Exists := FInternalDesignNavigationType = dnFly;
1517 InsertControl(0, FInternalDesignNavigations[dnFly]);
1518
1519 FInternalDesignNavigations[dnExamine] := TCastleExamineNavigationDesign.Create(Self);
1520 FInternalDesignNavigations[dnExamine].SetTransient;
1521 FInternalDesignNavigations[dnExamine].Exists := FInternalDesignNavigationType = dnExamine;
1522 InsertControl(0, FInternalDesignNavigations[dnExamine]);
1523
1524 FInternalDesignNavigations[dn2D] := TCastle2DNavigationDesign.Create(Self);
1525 FInternalDesignNavigations[dn2D].SetTransient;
1526 FInternalDesignNavigations[dn2D].Exists := FInternalDesignNavigationType = dn2D;
1527 InsertControl(0, FInternalDesignNavigations[dn2D]);
1528
1529 FGizmoGridAxis := TInternalCastleEditorGizmo.Create(Self);
1530 if InternalCastleDesignData <> '' then
1531 FGizmoGridAxis.LoadVisualization(LoadNode(InternalCastleDesignData + 'gizmos/grid_axis/grid_axis.gltf'));
1532 FGizmoGridAxis.Exists := InternalGridAxis;
1533 { Note: This will not work (Gizmo state and our property InternalGridAxis
1534 will become desynchronized) if Items are shared across other viewports.
1535 But it doesn't matter for CGE editor now, because you cannot share
1536 Items in this case. }
1537 Items.Add(FGizmoGridAxis);
1538 end;
1539
1540 {$define read_implementation_constructor}
1541 {$I auto_generated_persistent_vectors/tcastleviewport_persistent_vectors.inc}
1542 {$undef read_implementation_constructor}
1543 end;
1544
1545 constructor TCastleViewport.Create(AOwner: TComponent);
1546 begin
1547 CommonCreate(AOwner, CastleDesignMode);
1548 end;
1549
1550 constructor TCastleViewport.InternalCreateNonDesign(AOwner: TComponent; const Ignored: Integer);
1551 begin
1552 CommonCreate(AOwner, false);
1553 end;
1554
1555 function TCastleViewport.InternalCamera: TCastleCamera;
1556 begin
1557 if InternalDesignManipulation then
1558 Result := InternalDesignCamera
1559 else
1560 Result := Camera;
1561 end;
1562
1563 procedure TCastleViewport.SetInternalDesignNavigationType(const Value: TInternalDesignNavigationType);
1564 begin
1565 if FInternalDesignNavigationType <> Value then
1566 begin
1567 if InternalDesignManipulation then
1568 FInternalDesignNavigations[FInternalDesignNavigationType].Exists := false;
1569 FInternalDesignNavigationType := Value;
1570 if InternalDesignManipulation then
1571 FInternalDesignNavigations[FInternalDesignNavigationType].Exists := true;
1572 end;
1573 end;
1574
1575 procedure TCastleViewport.SetInternalGridAxis(const Value: Boolean);
1576 begin
1577 if FInternalGridAxis <> Value then
1578 begin
1579 FInternalGridAxis := Value;
1580 if FGizmoGridAxis <> nil then
1581 FGizmoGridAxis.Exists := Value;
1582 end;
1583 end;
1584
1585 function TCastleViewport.InternalDesignNavigation: TCastleNavigation;
1586 begin
1587 Result := FInternalDesignNavigations[FInternalDesignNavigationType];
1588 end;
1589
1590 procedure TCastleViewport.SetupCamera;
1591 var
1592 NewCamera: TCastleCamera;
1593 begin
1594 { This could actually work fine also when previous Camera <> nil.
1595 But for now, leave it not allowed -- we need to decide whether,
1596 in case of Camera <> nil, it would:
1597 - do nothing
1598 - or replace existing camera. }
1599 Assert(Camera = nil);
1600
1601 NewCamera := TCastleCamera.InternalCreateNonDesign(Self, 0);
1602 Camera := NewCamera;
1603 Items.Add(NewCamera);
1604 end;
1605
1606 procedure TCastleViewport.SetupDesignTimeCamera;
1607 var
1608 NewCamera: TCastleCamera;
1609 begin
1610 { Do this only when adding viewport in editor.
1611 Otherwise, we'd always create some useless camera,
1612 each time when deserializing the viewport.
1613
1614 This makes the camera a regular user-controlled component,
1615 that user can freely
1616 - remove (and eventually free),
1617 - rename,
1618 - see in editor (e.g. in dropdown Viewport.Camera),
1619 - access at runtime using TCastleView.DesignedComponent }
1620
1621 Assert(Owner <> nil); // Use SetupDesignTimeCamera only on viewports with owner
1622
1623 NewCamera := TCastleCamera.Create(Owner);
1624 NewCamera.Name := ProposeComponentName(TCastleCamera, Owner);
1625 Camera := NewCamera;
1626 Assert(Camera = NewCamera);
1627
1628 { FItems.MainCamera is left *unsynchronized* with NewCamera,
1629 because in InternalDesignManipulation the design-time camera is set as MainCamera. }
1630 if InternalDesignManipulation then
1631 Assert(FItems.MainCamera <> Camera);
1632
1633 // SetCamera doesn't add to World automatically
1634 Assert(Camera.World = nil);
1635 Assert(Camera.Parent = nil);
1636 Items.Add(NewCamera);
1637 Assert(Camera.World = Items);
1638 Assert(Camera.Parent = Items);
1639 end;
1640
1641 destructor TCastleViewport.Destroy;
1642 begin
1643 {$ifdef FPC}
1644 {$warnings off} // only to keep deprecated feature working
1645 SceneManager := nil; { remove Self from SceneManager.Viewports }
1646 {$warnings on}
1647 {$endif}
1648
1649 { unregister free notification from these objects }
1650 ClearMouseRayHit;
1651 AvoidNavigationCollisions := nil;
1652
1653 FreeAndNil(FRenderParams);
1654 FreeAndNil(FPrepareParams);
1655 FreeAndNil(FRenderWithoutScreenEffectsRenderingCamera);
1656 FreeAndNil(ShapesCollector);
1657 FreeAndNil(ShapesRenderer);
1658
1659 {$define read_implementation_destructor}
1660 {$I auto_generated_persistent_vectors/tcastleviewport_persistent_vectors.inc}
1661 {$undef read_implementation_destructor}
1662 inherited;
1663 end;
1664
1665 procedure TCastleViewport.SetCamera(const Value: TCastleCamera);
1666 var
1667 WasMainCamera: Boolean;
1668 begin
1669 if FCamera <> Value then
1670 begin
1671 { Note that this is also true when both FCamera and Items.MainCamera are nil,
1672 useful at initialization of TCastleViewport. }
1673 WasMainCamera := (Items <> nil) and (FCamera = Items.MainCamera);
1674
1675 if FCamera <> nil then
1676 begin
1677 Check(TMethod(FCamera.InternalOnCameraChanged).Data = TMethod(FCamera.InternalOnSceneBoundViewpointChanged).Data, 'Inconsistent values of internal TCastleCamera callbacks; do not modify TCastleCamera.InternalXxx callbacks manually.');
1678 Check(TMethod(FCamera.InternalOnCameraChanged).Data = TMethod(FCamera.InternalOnSceneBoundViewpointVectorsChanged).Data, 'Inconsistent values of internal TCastleCamera callbacks; do not modify TCastleCamera.InternalXxx callbacks manually.');
1679 Check(TMethod(FCamera.InternalOnCameraChanged).Data = TMethod(FCamera.InternalOnSceneBoundNavigationInfoChanged).Data, 'Inconsistent values of internal TCastleCamera callbacks; do not modify TCastleCamera.InternalXxx callbacks manually.');
1680
1681 { Note that we don't remove/add Camera to Viewport.Items.
1682 This would conflict with the deserialization, when camera is *already* added explicitly
1683 to Viewport.Items. }
1684
1685 FCamera.InternalOnCameraChanged := nil;
1686 FCamera.InternalOnSceneBoundViewpointChanged := nil;
1687 FCamera.InternalOnSceneBoundViewpointVectorsChanged := nil;
1688 FCamera.InternalOnSceneBoundNavigationInfoChanged := nil;
1689 end;
1690
1691 FCamera := Value;
1692 FCameraObserver.Observed := Value;
1693
1694 if FCamera <> nil then
1695 begin
1696 FCamera.InternalOnCameraChanged := {$ifdef FPC}@{$endif} InternalCameraChanged;
1697 FCamera.InternalOnSceneBoundViewpointChanged := {$ifdef FPC}@{$endif} MainSceneAndCamera_BoundViewpointChanged;
1698 FCamera.InternalOnSceneBoundViewpointVectorsChanged := {$ifdef FPC}@{$endif} MainSceneAndCamera_BoundViewpointVectorsChanged;
1699 FCamera.InternalOnSceneBoundNavigationInfoChanged := {$ifdef FPC}@{$endif} MainSceneAndCamera_BoundNavigationInfoChanged;
1700 end;
1701
1702 if WasMainCamera then
1703 Items.MainCamera := FCamera;
1704 end;
1705 end;
1706
1707 procedure TCastleViewport.CameraFreeNotification(const Sender: TFreeNotificationObserver);
1708 begin
1709 Camera := nil;
1710 end;
1711
1712 procedure TCastleViewport.Loaded;
1713
1714 {
1715 function ComponentDebugStr(const C: TComponent): String;
1716 begin
1717 if C = nil then
1718 Result := 'nil'
1719 else
1720 Result := C.Name + ' (' + C.ClassName + ')';
1721 end;
1722 }
1723
1724 var
1725 InitialPos, InitialDir, InitialUp: TVector3;
1726 begin
1727 inherited;
1728
1729 { To read old designs (before Camera was assignable, before Camera was a TCastleTransform):
1730 - add Camera to Items (so that it doesn't disappear when saving the design)
1731 - invent name for Camera (default 'Camera' could conflict e.g. in case of multiple viewports)
1732 }
1733 if (Camera <> nil) and
1734 (Camera.World = nil) and
1735 { We used to make exception when "Camera.Owner <> Owner", like this:
1736
1737 if Camera.Owner <> Owner then
1738 begin
1739 raise EInternalError.CreateFmt('After loading design, Camera and Viewport must have equal owner. But Camera = %s, Viewport = %s, Camera.Owner = %s, Viewport.Owner = %s', [
1740 ComponentDebugStr(Camera),
1741 ComponentDebugStr(Self),
1742 ComponentDebugStr(Camera.Owner),
1743 ComponentDebugStr(Owner)
1744 ]);
1745 end;
1746
1747 But now, this situation is valid in new designs (after we made TCastleCamera
1748 a normal component, assignable to Viewport.Items, settable in Viewport.Camera).
1749 Viewport.Camera may be just not resolved yet, if it is in another Viewport.Items
1750 (see examples/viewport_and_scenes/multiple_viewports/ for valid example).
1751
1752 Ignore this case -- this is not an "old design", nothing to fix. }
1753 (Camera.Owner = Owner) then
1754 begin
1755 Items.Add(Camera);
1756 WritelnLog('Camera in viewport "%s" was not part of Viewport.Items, adding it to Viewport.Items', [
1757 Name
1758 ]);
1759
1760 if InternalDesignManipulation then
1761 begin
1762 { If Camera was orthographic,
1763 then design-time camera should also be orthographic.
1764 This makes better experience when opening old designs. }
1765 InternalDesignCamera.ProjectionType := Camera.ProjectionType;
1766
1767 { Copy all camera projection (field of view) parameters, just like
1768 TDesignFrame.CameraSynchronize does.
1769 This makes the design-time view behave just as run-time,
1770 when opening old designs, which is best for backward compatibility.
1771 }
1772 InternalDesignCamera.Perspective.FieldOfView := Camera.Perspective.FieldOfView;
1773 InternalDesignCamera.Perspective.FieldOfViewAxis := Camera.Perspective.FieldOfViewAxis;
1774 InternalDesignCamera.Orthographic.Origin := Camera.Orthographic.Origin;
1775 InternalDesignCamera.Orthographic.Width := Camera.Orthographic.Width;
1776 InternalDesignCamera.Orthographic.Height := Camera.Orthographic.Height;
1777
1778 { Assign useful InternalDesignCamera vectors, because in case of reading old designs --
1779 TCastleViewport.CustomSerialization could not read any useful InternalDesignCamera
1780 from design file.
1781
1782 Note known limitation: This will not adjust InternalCamera to final Camera view
1783 if AutoCamera is used. AutoCamera is applied later.
1784 This will only adjust InternalCamera to Camera view that is serialized. }
1785 Camera.GetWorldView(InitialPos, InitialDir, InitialUp);
1786 if Camera.ProjectionType = ptOrthographic then
1787 begin
1788 InternalDesignCamera.SetWorldView(
1789 { We move Z back, to be able to see from design-time camera the runtime camera gizmo.
1790 Note that 2D Camera.EffectiveProjectionNear is negative by default (after Setup2D),
1791 so "- Camera.EffectiveProjectionNear" actually does "+ 1000". }
1792 InitialPos + Vector3(0, 0, - Camera.EffectiveProjectionNear + 100),
1793 InitialDir,
1794 InitialUp);
1795
1796 // best navigation for 2D
1797 InternalDesignNavigationType := dn2D;
1798 end else
1799 begin
1800 InternalDesignCamera.SetWorldView(InitialPos, InitialDir, InitialUp);
1801
1802 // best navigation for 3D
1803 InternalDesignNavigationType := dnFly;
1804 end;
1805 end;
1806
1807 if InternalDesignManipulation and (Camera.Name = 'Camera') and (Owner <> nil) then
1808 begin
1809 Camera.Name := ProposeComponentName(TCastleCamera, Owner);
1810 WritelnLog('Camera in viewport "%s" renamed to "%s" to not conflict with other components', [
1811 Name,
1812 Camera.Name
1813 ]);
1814 end;
1815 end;
1816
1817 if InternalDesignManipulation then
1818 begin
1819 { Make sure InternalDesignCamera, InternalDesignNavigation are on children.
1820 As TCastleUserInterface.SerializeChildrenClear, TCastleTransform.SerializeChildrenClear
1821 do not touch csTransient children, they should be OK always. }
1822 Assert(Items.List.IndexOf(InternalDesignCamera) <> -1);
1823 Assert(IndexOfControl(InternalDesignNavigation) <> -1);
1824 end;
1825
1826 {$warnings off} // using deprecated to warn about it
1827 if AutoCamera then
1828 WritelnWarning('AutoCamera is deprecated (on TCastleViewport named "%s"). Instead: It is simpler to set camera at design-time explicitly, or use CameraViewpointForWholeScene from code to auto-adjust camera.' + ' If you want to animate the camera, attach TCastleCamera to a bone transformation exposed by Scene.ExposeTransforms', [
1829 Name
1830 ]);
1831 if UseGlobalFog <> DefaultUseGlobalFog then
1832 WritelnWarning('UseGlobalFog is deprecated (on TCastleViewport named "%s"). Instead: Assign TCastleViewport.Fog to use fog, and leave deprecated TCastleViewport.MainScene = nil', [
1833 Name
1834 ]);
1835 if UseGlobalLights <> DefaultUseGlobalLights then
1836 WritelnWarning('UseGlobalLights is deprecated (on TCastleViewport named "%s"). Instead: If you need to tweak lighting, then use regular TCastleScene and set CastGlobalLights as needed; leave deprecated TCastleViewport.MainScene = nil', [
1837 Name
1838 ]);
1839 {$warnings on}
1840 end;
1841
1842 procedure TCastleViewport.SetCapturePointingDevice(const Value: TCastleTransform);
1843 begin
1844 if FCapturePointingDevice <> Value then
1845 begin
1846 FCapturePointingDevice := Value;
1847 FCapturePointingDeviceObserver.Observed := Value;
1848 end;
1849 end;
1850
1851 procedure TCastleViewport.CapturePointingDeviceFreeNotification(
1852 const Sender: TFreeNotificationObserver);
1853 begin
1854 CapturePointingDevice := nil;
1855 end;
1856
1857 procedure TCastleViewport.SetBackground(const Value: TCastleBackground);
1858 begin
1859 if FBackground <> Value then
1860 begin
1861 FBackground := Value;
1862 FBackgroundObserver.Observed := Value;
1863 end;
1864 end;
1865
1866 procedure TCastleViewport.BackgroundFreeNotification(
1867 const Sender: TFreeNotificationObserver);
1868 begin
1869 Background := nil;
1870 end;
1871
1872 procedure TCastleViewport.SetFog(const Value: TCastleFog);
1873 begin
1874 if FFog <> Value then
1875 begin
1876 FFog := Value;
1877 FFogObserver.Observed := Value;
1878 end;
1879 end;
1880
1881 procedure TCastleViewport.FogFreeNotification(
1882 const Sender: TFreeNotificationObserver);
1883 begin
1884 Fog := nil;
1885 end;
1886
1887 function TCastleViewport.FillsWholeContainer: boolean;
1888 begin
1889 if Container = nil then
1890 Result := FullSize
1891 else
1892 Result := RenderRect.Round.Equals(Container.PixelsRect);
1893 end;
1894
1895 function TCastleViewport.GetNavigation: TCastleNavigation;
1896 var
1897 I: Integer;
1898 begin
1899 for I := ControlsCount - 1 downto 0 do
1900 if Controls[I] is TCastleNavigation then
1901 Exit(TCastleNavigation(Controls[I]));
1902 Result := nil;
1903 end;
1904
1905 procedure TCastleViewport.SetNavigation(const Value: TCastleNavigation);
1906 var
1907 I: Integer;
1908 begin
1909 for I := ControlsCount - 1 downto 0 do
1910 if Controls[I] is TCastleNavigation then
1911 RemoveControl(Controls[I]);
1912 if Value <> nil then
1913 InsertBack(Value);
1914 end;
1915
1916 procedure TCastleViewport.Notification(AComponent: TComponent; Operation: TOperation);
1917 begin
1918 inherited;
1919
1920 if Operation = opRemove then
1921 begin
1922 if (AComponent is TCastleTransform) and
1923 MouseRayHitContains(TCastleTransform(AComponent)) then
1924 ClearMouseRayHit;
1925
1926 if AComponent = FAvoidNavigationCollisions then
1927 AvoidNavigationCollisions := nil;
1928 end;
1929 end;
1930
1931 function TCastleViewport.Press(const Event: TInputPressRelease): boolean;
1932 var
1933 I: Integer;
1934 begin
1935 Result := inherited;
1936 if Result or Items.Paused then Exit;
1937
1938 { Call UpdateMouseRayHit at nearest moment.
1939 As our PointingDevicePress (called below) uses it.
1940 Also this makes MouseRayHit valid during TCastleTransform.PointingDevicePress calls.
1941 Although implementors should rather use information passed
1942 as TCastleTransform.PointingDevicePress argument, not look at Viewport.MouseRayHit. }
1943 ClearMouseRayHit;
1944
1945 LastPressEvent := Event;
1946
1947 if Items.InternalPressReleaseListeners <> nil then
1948 // use downto, to work in case some Press will remove transform from list
1949 for I := Items.InternalPressReleaseListeners.Count - 1 downto 0 do
1950 if Items.InternalPressReleaseListeners[I].Press(Event) then
1951 Exit(true);
1952
1953 if Input_Interact.IsEvent(Event) and
1954 PointingDevicePress then
1955 begin
1956 InternalPointingDeviceDragging := true;
1957 Exit(true);
1958 end;
1959 end;
1960
1961 function TCastleViewport.Release(const Event: TInputPressRelease): boolean;
1962 var
1963 I: Integer;
1964 begin
1965 Result := inherited;
1966 if Result or Items.Paused then Exit;
1967
1968 { Call UpdateMouseRayHit at nearest moment.
1969 As our PointingDeviceRelease (called below) uses it. }
1970 ClearMouseRayHit;
1971
1972 if Items.InternalPressReleaseListeners <> nil then
1973 // use downto, to work in case some Release will remove transform from list
1974 for I := Items.InternalPressReleaseListeners.Count - 1 downto 0 do
1975 if Items.InternalPressReleaseListeners[I].Release(Event) then
1976 Exit(true);
1977
1978 if Input_Interact.IsEvent(Event) then
1979 begin
1980 InternalPointingDeviceDragging := false;
1981 if PointingDeviceRelease then
1982 Exit(true);
1983 end;
1984 end;
1985
1986 function TCastleViewport.Motion(const Event: TInputMotion): boolean;
1987
1988 { Call Transform.PointingDeviceRelease with CancelAction = true. }
1989 procedure PointingDeviceCancel(const Transform: TCastleTransform);
1990 var
1991 RayOrigin, RayDirection: TVector3;
1992 MousePosition: TVector2;
1993 begin
1994 if GetMousePosition(MousePosition) then
1995 begin
1996 PositionToRay(MousePosition, true, RayOrigin, RayDirection);
1997 Transform.PointingDeviceRelease(FakeRayCollisionNode(RayOrigin, RayDirection, Transform), MaxSingle, true { CancelAction });
1998 end;
1999 end;
2000
2001 function IsTouchSensorActiveInScene(const Scene: TCastleTransform): boolean;
2002 var
2003 ActiveSensorsList: TX3DNodeList;
2004 I: Integer;
2005 begin
2006 Result := false;
2007 if not (Scene is TCastleSceneCore) then
2008 Exit;
2009 ActiveSensorsList := (Scene as TCastleSceneCore).PointingDeviceActiveSensors;
2010 for I := 0 to ActiveSensorsList.Count -1 do
2011 begin
2012 if ActiveSensorsList.Items[I] is TTouchSensorNode then
2013 Exit(true);
2014 end;
2015 end;
2016
2017 const
2018 DistanceToHijackDragging = 5 * 96;
2019 var
2020 TopMostTransform: TCastleTransform;
2021 begin
2022 Result := inherited;
2023 if (not Result) and (not Items.Paused) then
2024 begin
2025 {$warnings off} // TODO: using deprecated Navigation for now
2026 if Navigation <> nil then
2027 begin
2028 TopMostTransform := TransformUnderMouse;
2029
2030 { Test if dragging TTouchSensorNode. In that case cancel its dragging
2031 and let navigation move instead. }
2032 if (TopMostTransform <> nil) and
2033 IsTouchSensorActiveInScene(TopMostTransform) and
2034 (PointsDistance(LastPressEvent.Position, Event.Position) >
2035 DistanceToHijackDragging / Container.Dpi) then
2036 begin
2037 PointingDeviceCancel(TopMostTransform);
2038
2039 if EnableParentDragging then
2040 begin
2041 { Without ReleaseCapture, the parent (like TCastleScrollView) would still
2042 not receive the following motion events. }
2043 Container.ReleaseCapture(Navigation);
2044 end;
2045
2046 Navigation.Press(LastPressEvent);
2047 end;
2048 end;
2049 {$warnings on}
2050
2051 { Note: we ignore PointingDeviceMove result.
2052 Maybe we should use PointingDeviceMove result as our Motion result?
2053 Answer unknown. Historically we do not do this, and I found no practical
2054 use-case when it would be useful to do this. }
2055 PointingDeviceMove;
2056 end;
2057 end;
2058
2059 function TCastleViewport.GetMouseRayHit: TRayCollision;
2060
2061 procedure UpdateMouseRayHit;
2062 var
2063 MousePosition: TVector2;
2064 begin
2065 if { This may be called from destruction, testcase
2066 TTestCastleWindow.TestViewportWithoutCamera with Delphi 12.
2067 It shouldn't access then EffectiveWidth which runs some
2068 TCastleUserInteface code that assumes that things are ready
2069 (e.g. TBorder instance in TCastleUserInteface.Border is not nil). }
2070 (not (csDestroying in ComponentState)) and
2071 { Check conditions required by PositionToPrerequisites and PositionToRay to work.
2072 This must be robust, as
2073 (outdated reason:) it WAS called also from RecalculateCursor,
2074 which is from TCastleTransformList.Notify. (when some transform gets removed). }
2075 (EffectiveWidth <> 0) and
2076 (EffectiveHeight <> 0) and
2077 // calculate MousePosition
2078 GetMousePosition(MousePosition) and
2079 // PositionToRay assumes InternalCamera <> nil
2080 (InternalCamera <> nil) and
2081 // do not update MouseRayHit if camera doesn't exist
2082 InternalCamera.ExistsInRoot then
2083 begin
2084 PositionToRay(MousePosition, true, MouseRayOrigin, MouseRayDirection);
2085
2086 { Update MouseRayHit.
2087 We know that MouseRayDirection is normalized now, which is important
2088 to get correct MouseRayHit.Distance. }
2089 SetMouseRayHit(CameraRayCollision(MouseRayOrigin, MouseRayDirection));
2090 end;
2091 end;
2092
2093 begin
2094 if not FMouseRayHitValid then
2095 begin
2096 UpdateMouseRayHit;
2097 FMouseRayHitValid := true;
2098 end;
2099 Assert(FMouseRayHitValid);
2100
2101 Result := FMouseRayHit;
2102 end;
2103
2104 function TCastleViewport.TransformUnderMouse: TCastleTransform;
2105 var
2106 R: TRayCollision;
2107 begin
2108 R := MouseRayHit;
2109 if R <> nil then
2110 Result := R.Transform
2111 else
2112 Result := nil;
2113 end;
2114
2115 procedure TCastleViewport.ItemsNodesFree(Sender: TObject);
2116 begin
2117 { Reloading nodes by TCastleSceneCore.Load invalidates information
2118 on FMouseRayHit, the TShape references are no longer valid.
2119
2120 Testcase:
2121 - (only reproducible on Windows for some reason, but in theory problem is cross-platform)
2122 - open in castle-model-viewer anchor_test.x3dv
2123 - click on something, like "Key Sensor"
2124 - without this fix, the next EventMotion causes crash as
2125 TCastleSceneCore.PointingDeviceMove is run with TRayCollisionNode
2126 containing invalid references.
2127
2128 TODO: This is not a complete solution.
2129 - What if Items are shared across few TCastleViewport?
2130 Our Items.OnXxx do not link to viewport then, and should not be relied upon.
2131 }
2132 ClearMouseRayHit;
2133
2134 { Signal to PointingDevicePressCore to not process further collision list.
2135 TODO: why is this necessary? But anchor_test on castle-model-viewer otherwise crashes. }
2136 ItemsNodesFreeOccurred := true;
2137 end;
2138
2139 function TCastleViewport.TriangleHit: PTriangle;
2140 begin
2141 if (MouseRayHit <> nil) and
2142 (MouseRayHit.Count <> 0) then
2143 Result := MouseRayHit.First.Triangle
2144 else
2145 Result := nil;
2146 end;
2147
2148 procedure TCastleViewport.Update(const SecondsPassed: Single;
2149 var HandleInput: boolean);
2150 var
2151 SecondsPassedScaled: Single;
2152
2153 procedure ItemsUpdate;
2154 var
2155 RemoveItem: TRemoveType;
2156 begin
2157 if Items.Exists then
2158 begin
2159 RemoveItem := rtNone;
2160
2161 { Note that Items.Update do not take HandleInput
2162 parameter, as it would not be controllable for them: TCastleTransform objects do not
2163 have strict front-to-back order, so we would not know in what order
2164 call their Update methods, so we have to let many Items handle keys anyway.
2165 So, it's consistent to just treat TCastleTransform objects as "cannot definitely
2166 mark keys/mouse as handled". }
2167
2168 Items.Update(SecondsPassedScaled, RemoveItem);
2169 { we ignore RemoveItem --- main Items list cannot be removed }
2170 end;
2171 end;
2172
2173 procedure UpdateVisibleChange;
2174 begin
2175 { when some TCastleTransform calls TCastleTransform.VisibleChangeHere,
2176 in effect TCastleViewport will call VisibleChange. }
2177 if LastVisibleStateIdForVisibleChange < Items.InternalVisibleStateId then
2178 begin
2179 LastVisibleStateIdForVisibleChange := Items.InternalVisibleStateId;
2180 VisibleChange([chRender]);
2181 end;
2182 end;
2183
2184 procedure WatchMainSceneChange;
2185 begin
2186 if InternalDesignManipulation then
2187 begin
2188 {$warnings off} // using deprecated to keep it working
2189 if FLastSeenMainScene <> Items.MainScene then
2190 begin
2191 FLastSeenMainScene := Items.MainScene;
2192 AssignDefaultCameraDone := false;
2193 end;
2194 {$warnings on}
2195 end;
2196 end;
2197
2198 { Prepare information used by TCastleScene.UpdateGeneratedTextures, called from TCastleScene.Update }
2199 procedure PrepareUpdateGeneratedTexturesParameters;
2200 begin
2201 if (FProjection.ProjectionNear = 0) or
2202 (FProjection.ProjectionFar = 0) then // in case ApplyProjection was not called yet
2203 FProjection := CalculateProjection;
2204 Items.InternalRenderEverythingEvent := {$ifdef FPC}@{$endif}RenderFromViewEverything;
2205 Items.InternalProjectionNear := FProjection.ProjectionNear;
2206 Items.InternalProjectionFar := FProjection.ProjectionFar;
2207 end;
2208
2209 begin
2210 inherited;
2211
2212 { We invalidate FMouseRayHit in every Update.
2213 This way
2214 - we will recalculate it also when mouse didn't move,
2215 but something else moved "in front of the mouse cursor",
2216 e.g. creature walked in front of us.
2217 - we will recalculate it also when mouse moved but we didn't get
2218 Motion event, because navigation class marked Motion as handled.
2219 Fixes https://forum.castle-engine.io/t/mouserayhit-not-updating-while-dragging/844/4
2220 }
2221 ClearMouseRayHit;
2222
2223 if Items.Paused then
2224 Exit;
2225
2226 SecondsPassedScaled := SecondsPassed * Items.TimeScale;
2227
2228 PrepareUpdateGeneratedTexturesParameters;
2229 ItemsUpdate;
2230 UpdateVisibleChange;
2231 WatchMainSceneChange;
2232 end;
2233
2234 function TCastleViewport.AllowSuspendForInput: boolean;
2235 begin
2236 Result := Items.Paused;
2237 end;
2238
2239 procedure TCastleViewport.EnsureCameraDetected;
2240 begin
2241 if Camera <> nil then
2242 begin
2243 {$warnings off} // using deprecated to warn about it
2244 if AutoCamera and not AssignDefaultCameraDone then
2245 AssignDefaultCamera;
2246 {$warnings on}
2247 { Set AssignDefaultCameraDone to done,
2248 regardless if AssignDefaultCameraDone was done or not.
2249 Otherwise later setting AutoCamera to true would suddenly
2250 reinitialize camera (initial and current vectors) in the middle of game. }
2251 AssignDefaultCameraDone := true;
2252 end;
2253 end;
2254
2255 procedure TCastleViewport.ApplyProjection;
2256 var
2257 Viewport: TRectangle;
2258 AspectRatio: Single;
2259 M: TMatrix4;
2260 begin
2261 EnsureCameraDetected;
2262
2263 Viewport := RenderRect.Round;
2264 RenderContext.Viewport := Viewport;
2265
2266 FProjection := CalculateProjection;
2267 {$ifdef FPC}
2268 {$warnings off} // using deprecated to keep it working
2269 if Assigned(OnProjection) then
2270 OnProjection(FProjection);
2271 {$warnings on}
2272 {$endif}
2273
2274 { take into account InternalDistort* properties }
2275 AspectRatio := InternalDistortViewAspect * Viewport.Width / Viewport.Height;
2276 FProjection.PerspectiveAnglesRad.Y := InternalDistortFieldOfViewY * FProjection.PerspectiveAnglesRad.Y;
2277
2278 { Apply new FProjection values }
2279 M := FProjection.Matrix(AspectRatio);
2280 if InternalCamera <> nil then // as InternalCamera is assignable, tolerate InternalCamera = nil
2281 InternalCamera.ProjectionMatrix := M;
2282 RenderContext.ProjectionMatrix := M;
2283 end;
2284
2285 function TCastleViewport.ItemsBoundingBox: TBox3D;
2286 begin
2287 if Items <> nil then
2288 begin
2289 Inc(TInternalCastleEditorGizmo.EmptyBoundingBox);
2290 try
2291 Result := Items.BoundingBox;
2292 finally Dec(TInternalCastleEditorGizmo.EmptyBoundingBox) end;
2293 end else
2294 Result := TBox3D.Empty;
2295 end;
2296
2297 function TCastleViewport.ItemsWithGizmosBoundingBox: TBox3D;
2298 begin
2299 if Items <> nil then
2300 begin
2301 Inc(InternalGizmoBoundingBox);
2302 try
2303 Result := Items.BoundingBox;
2304 finally Dec(InternalGizmoBoundingBox) end;
2305 end else
2306 Result := TBox3D.Empty;
2307 end;
2308
2309 procedure TCastleViewport.SetAutoCamera(const Value: Boolean);
2310 begin
2311 if FAutoCamera <> Value then
2312 begin
2313 FAutoCamera := Value;
2314
2315 (*
2316 At one point I had an idea to do this:
2317
2318 { When setting AutoCamera to false, then back to true,
2319 call AssignDefaultCamera again (thus resetting camera initial and current
2320 vectors).
2321 This provides a way to cause AssignDefaultCamera initialization again. }
2322 if Value then
2323 AssignDefaultCameraDone := false;
2324
2325 Docs in interface:
2326 Setting it back to @true will make the initialization again at nearest
2327 render.
2328
2329 Later:
2330 This does not seem useful, and makes more confusion,
2331 because it overrides both initial and current camera vectors.
2332 You would not expect that
2333
2334 if AutoCamera then
2335 begin
2336 AutoCamera := false;
2337 AutoCamera := true;
2338 end;
2339
2340 does something, but here it would do something.
2341 Doing the same thing with AutoNavigation doesn't
2342 recreate navigation (if Navigation <> nil, it will stay as it was).
2343
2344 Later yet: This seems very useful in editor though, to see the effect
2345 in editor immediately, without reloading file.
2346 *)
2347
2348 if InternalDesignManipulation and Value then
2349 AssignDefaultCameraDone := false;
2350 end;
2351 end;
2352
2353 function TCastleViewport.InternalOverride2DProjectionSizing: TCastleUserInterface;
2354 begin
2355 Result := nil;
2356 end;
2357
2358 function TCastleViewport.CalculateProjection: TProjection;
2359 var
2360 ViewportWidth, ViewportHeight: Single;
2361 begin
2362 if (InternalOverride2DProjectionSizing <> nil)
2363 { We could use InternalOverride2DProjectionSizing only when really necessary,
2364 but it more consistent and easier to test to use it always when available.
2365 TODO test }
2366 { and
2367 (InternalCamera <> nil) and
2368 (InternalCamera.ProjectionType = ptOrthographic) and
2369 (InternalCamera.Orthographic.Width = 0) and
2370 (InternalCamera.Orthographic.Height = 0) } then
2371 begin
2372 { Bugfix for camera preview in CGE editor, when the selected viewport has
2373 Orthographic.Width = 0 and Orthographic.Height = 0.
2374 The camera preview uses the same camera (and items) as selected viewport,
2375 but the orthographic size should be then derived from selected viewport size,
2376 not size of camera preview. }
2377 ViewportWidth := InternalOverride2DProjectionSizing.EffectiveWidthForChildren;
2378 ViewportHeight := InternalOverride2DProjectionSizing.EffectiveHeightForChildren;
2379 end else
2380 begin
2381 ViewportWidth := EffectiveWidthForChildren;
2382 ViewportHeight := EffectiveHeightForChildren;
2383 end;
2384
2385 if (InternalCamera = nil) or (not InternalCamera.ExistsInRoot) then
2386 begin
2387 { As InternalCamera is assignable, and may be nil, be tolerant and handle it.
2388 Just use default perspective settings. }
2389 Result.ProjectionType := ptPerspective;
2390 Result.PerspectiveAnglesRad := TViewpointNode.InternalFieldOfView(
2391 TCastlePerspective.DefaultFieldOfView,
2392 TCastlePerspective.DefaultFieldOfViewAxis,
2393 ViewportWidth,
2394 ViewportHeight);
2395 Result.ProjectionNear := 1;
2396 Result.ProjectionFar := 1000;
2397 Exit;
2398 end;
2399
2400 Result := InternalCamera.InternalProjection(
2401 {$ifdef FPC}@{$endif} ItemsBoundingBox,
2402 {$ifdef FPC}@{$endif} ItemsWithGizmosBoundingBox,
2403 ViewportWidth, ViewportHeight,
2404 InternalCamera = InternalDesignCamera);
2405 end;
2406
2407 function TCastleViewport.MainLightForShadowVolumes(out AMainLightPosition: TVector4): boolean;
2408
2409 { Check does scene define light for shadow volumes,
2410 if yes - calculate the position/direction of it in world space to AMainLightPosition
2411 and return @true.
2412
2413 May modify AMainLightPosition even when returns @false, the value AMainLightPosition
2414 is undefined after returning @false. }
2415 function LightForShadowVolumesFromScene(const Scene: TCastleScene;
2416 out AMainLightPosition: TVector4): Boolean;
2417 begin
2418 Result :=
2419 Scene.InternalMainLightForShadowVolumes(AMainLightPosition) and
2420 { We need WorldTransform for below conversion local<->world space.
2421 It may not be available, if
2422 - Scene is present multiple times in Items
2423 - Scene is not present in Items at all, temporarily, but is still a MainScene.
2424 Testcase: castle-game, change from level to level using debug menu.
2425 }
2426 Scene.HasWorldTransform;
2427 { Transform AMainLightPosition to world space. }
2428 if Result then
2429 begin
2430 if AMainLightPosition.W = 0 then
2431 AMainLightPosition.XYZ := Scene.LocalToWorldDirection(AMainLightPosition.XYZ)
2432 else
2433 AMainLightPosition := Vector4(
2434 Scene.LocalToWorld(AMainLightPosition.XYZ / AMainLightPosition.W), 1.0);
2435 end;
2436 end;
2437
2438 var
2439 SceneCastingLights: TCastleScene;
2440 begin
2441 Result := false;
2442
2443 {$warnings off} // using deprecated MainScene to keep it working
2444 if Items.MainScene <> nil then
2445 begin
2446 Result := LightForShadowVolumesFromScene(Items.MainScene, AMainLightPosition);
2447 if Result then
2448 Exit;
2449 end;
2450
2451 { scan InternalScenesCastGlobalLights }
2452 if Items.InternalScenesCastGlobalLights <> nil then
2453 for SceneCastingLights in Items.InternalScenesCastGlobalLights do
2454 if Items.MainScene <> SceneCastingLights then // MainScene is already accounted for above
2455 begin
2456 Result := LightForShadowVolumesFromScene(SceneCastingLights, AMainLightPosition);
2457 if Result then
2458 Exit;
2459 end;
2460 {$warnings on}
2461 end;
2462
2463 procedure TCastleViewport.Render3D(const Params: TRenderParams);
2464 begin
2465 end;
2466
2467 procedure TCastleViewport.RenderOnePass(const Params: TRenderParams);
2468
2469 { Based on BlendingSort, determine
2470 ShapesRenderer.BlendingSort, making sure that sortAuto is handled correctly.
2471
2472 Note: This is copy-pasted now to TestCastleViewport for testing. }
2473 function EffectiveBlendingSort: TShapeSortNoAuto;
2474 begin
2475 if BlendingSort = sortAuto then
2476 begin
2477 if (Camera <> nil) and
2478 (Camera.ProjectionType = ptOrthographic) and
2479 (TVector3.Equals(Camera.Direction, DefaultCameraDirection)) then
2480 Result := sort2D
2481 else
2482 Result := sort3D;
2483 end else
2484 Result := BlendingSort;
2485 end;
2486
2487 { Based on OcclusionSort, determine
2488 ShapesRenderer.OcclusionSort, making sure that sortAuto is handled correctly. }
2489 function EffectiveOcclusionSort: TShapeSortNoAuto;
2490 begin
2491 if OcclusionSort = sortAuto then
2492 begin
2493 Result := sortNone;
2494 end else
2495 Result := OcclusionSort;
2496 end;
2497
2498 begin
2499 ShapesCollector.Clear;
2500 Assert(Params.Collector = ShapesCollector);
2501
2502 {$warnings off} // keep deprecated working
2503 Render3D(Params);
2504 {$warnings on}
2505
2506 Params.Frustum := @Params.RenderingCamera.Frustum;
2507 Items.Render(Params);
2508
2509 ShapesRenderer.OcclusionSort := EffectiveOcclusionSort;
2510 ShapesRenderer.BlendingSort := EffectiveBlendingSort;
2511 ShapesRenderer.OnCustomShapeSort := OnCustomShapeSort;
2512 ShapesRenderer.Render(ShapesCollector, Params);
2513 end;
2514
2515 procedure TCastleViewport.RenderShadowVolume(const Params: TRenderParams);
2516 begin
2517 Params.Frustum := @Params.RenderingCamera.Frustum;
2518 Items.RenderShadowVolume(Params, FShadowVolumeRenderer);
2519 end;
2520
2521 procedure TCastleViewport.InitializeGlobalLights(const GlobalLights: TLightInstancesList);
2522 var
2523 HI: TLightInstance;
2524 begin
2525 {$warnings off}
2526 if HeadlightInstance(HI) then
2527 GlobalLights.Add(HI);
2528 {$warnings on}
2529 end;
2530
2531 procedure TCastleViewport.InitializeLights(const GlobalLights: TLightInstancesList);
2532 begin
2533 InitializeGlobalLights(GlobalLights);
2534 end;
2535
2536 function TCastleViewport.InternalHeadlightCamera: TCastleCamera;
2537 begin
2538 { At design-time: As an exception, this *does not* use design-time camera for headlight
2539 pos/dir/up, as this would prevent observing headlight from various other points of view.
2540 So below condition actually *avoids* using InternalDesignCamera when InternalDesignManipulation. }
2541 if InternalDesignManipulation then
2542 Result := Camera
2543 else
2544 Result := Items.MainCamera;
2545
2546 // do not cast headlight from camera that does not exist
2547 if (Result <> nil) and (not Result.ExistsInRoot) then
2548 Result := nil;
2549 end;
2550
2551 function TCastleViewport.HeadlightInstance(out Instance: TLightInstance): boolean;
2552 var
2553 Node: TAbstractLightNode;
2554
2555 procedure PrepareInstance(const HC: TCastleCamera);
2556 var
2557 Position, Direction, Up: TVector3;
2558 begin
2559 Assert(Node <> nil);
2560 Node.InternalHeadlight := true;
2561
2562 HC.GetWorldView(Position, Direction, Up);
2563
2564 { set location/direction of Node }
2565 if Node is TAbstractPositionalLightNode then
2566 begin
2567 TAbstractPositionalLightNode(Node).FdLocation.Send(Position);
2568 if Node is TSpotLightNode then
2569 TSpotLightNode(Node).FdDirection.Send(Direction) else
2570 if Node is TSpotLightNode_1 then
2571 TSpotLightNode_1(Node).FdDirection.Send(Direction);
2572 end else
2573 if Node is TAbstractDirectionalLightNode then
2574 TAbstractDirectionalLightNode(Node).FdDirection.Send(Direction);
2575
2576 Instance.Node := Node;
2577 Instance.Location := Position;
2578 Instance.Direction := Direction;
2579 Instance.Transform := TMatrix4.Identity;
2580 Instance.TransformScale := 1;
2581 Instance.Radius := MaxSingle;
2582 Instance.WorldCoordinates := true;
2583 end;
2584
2585 var
2586 HC: TCastleCamera;
2587 begin
2588 Result := false;
2589 Node := Items.InternalHeadlight;
2590 if Node <> nil then
2591 begin
2592 HC := InternalHeadlightCamera;
2593 if HC <> nil then
2594 begin
2595 PrepareInstance(HC);
2596 Result := true;
2597 end;
2598 end;
2599 end;
2600
2601 function TCastleViewport.PrepareParams: TPrepareParams;
2602 { Note: you cannot refer to PrepareParams inside
2603 the TCastleTransform.PrepareResources or TCastleTransform.Render implementation,
2604 as they may change the referenced PrepareParams.GlobalLights value.
2605 }
2606 begin
2607 { We just reuse FRenderParams.FGlobalLights below as a temporary
2608 TLightInstancesList that we already have created. }
2609
2610 { initialize FPrepareParams.GlobalLights }
2611 FRenderParams.FGlobalLights.Clear;
2612 InitializeGlobalLights(FRenderParams.FGlobalLights);
2613 FPrepareParams.GlobalLights := FRenderParams.FGlobalLights;
2614
2615 { initialize FPrepareParams.GlobalFog }
2616 if Fog <> nil then
2617 FPrepareParams.GlobalFog := Fog.InternalFogNode
2618 else
2619 {$warnings off} // using deprecated MainScene to keep it working
2620 if UseGlobalFog and
2621 (Items.MainScene <> nil) then
2622 FPrepareParams.GlobalFog := Items.MainScene.FogStack.Top
2623 {$warnings on}
2624 else
2625 FPrepareParams.GlobalFog := nil;
2626
2627 FPrepareParams.RendererToPrepareShapes := ShapesRenderer.Renderer;
2628
2629 Result := FPrepareParams;
2630 end;
2631
2632 function TCastleViewport.BaseLights: TLightInstancesList;
2633 begin
2634 {$warnings off} // using deprecated in deprecated, to keep it working
2635 Result := PrepareParams.GlobalLights as TLightInstancesList;
2636 {$warnings on}
2637 end;
2638
2639 procedure TCastleViewport.RenderFromView3D(const Params: TRenderParams);
2640
2641 procedure RenderNoShadowVolumes;
2642 begin
2643 { We must first render all non-transparent objects,
2644 then all transparent objects. Otherwise transparent objects
2645 (that must be rendered without updating depth buffer) could get brutally
2646 covered by non-transparent objects (that are in fact further away from
2647 the camera). }
2648
2649 Params.InShadow := false;
2650
2651 Params.Transparent := false; Params.ShadowVolumesReceivers := [false, true]; RenderOnePass(Params);
2652 Params.Transparent := true ; Params.ShadowVolumesReceivers := [false, true]; RenderOnePass(Params);
2653 end;
2654
2655 procedure RenderWithShadowVolumes(const MainLightPosition: TVector4);
2656 begin
2657 if (FProjection.ProjectionFar <> ZFarInfinity) and (not FWarningZFarInfinityDone) then
2658 begin
2659 FWarningZFarInfinityDone := true;
2660 WritelnWarning('Rendering with Shadow Volumes, but ProjectionFar is not ZFarInfinity. Shadow volumes require ProjectionFar = ZFarInfinity. Leave TCastleCamera.ProjectionFar = 0.');
2661 end;
2662
2663 { Initialize FShadowVolumeRenderer if needed, along with its OpenGL resources.
2664 This way we never even create FShadowVolumeRenderer if we will never render with shadow volumes. }
2665 if FShadowVolumeRenderer = nil then
2666 begin
2667 FShadowVolumeRenderer := TGLShadowVolumeRenderer.Create;
2668 FShadowVolumeRenderer.PrepareRenderingResources;
2669 end;
2670 FShadowVolumeRenderer.DebugRender := ShadowVolumesRender;
2671 FShadowVolumeRenderer.InitFrustumAndLight(Params.RenderingCamera.Frustum, MainLightPosition);
2672 FShadowVolumeRenderer.Render(Params,
2673 {$ifdef FPC}@{$endif}RenderOnePass,
2674 {$ifdef FPC}@{$endif}RenderShadowVolume);
2675 end;
2676
2677 var
2678 MainLightPosition: TVector4;
2679 begin
2680 if GLFeatures.ShadowVolumesPossible and
2681 ShadowVolumes and
2682 MainLightForShadowVolumes(MainLightPosition) then
2683 RenderWithShadowVolumes(MainLightPosition)
2684 else
2685 RenderNoShadowVolumes;
2686 end;
2687
2688 procedure TCastleViewport.RenderFromViewEverything(const RenderingCamera: TRenderingCamera);
2689
2690 { Call RenderContext.Clear with proper options. }
2691 procedure RenderClear;
2692 var
2693 ClearBuffers: TClearBuffers;
2694 ClearColor: TCastleColor;
2695 MainLightPosition: TVector4; { ignored }
2696 begin
2697 { Make ClearColor anything defined.
2698 If we will include cbColor in ClearBuffers, it will actually always
2699 be adjusted to something appropriate. }
2700 ClearColor := Black;
2701 ClearBuffers := [];
2702
2703 if ClearDepth then
2704 Include(ClearBuffers, cbDepth);
2705
2706 if RenderingCamera.Target = rtVarianceShadowMap then
2707 begin
2708 { When rendering to VSM, we want to clear the screen to max depths (1, 1^2). }
2709 Include(ClearBuffers, cbColor);
2710 ClearColor := Vector4(1, 1, 0, 1);
2711 end else
2712 if not Transparent then
2713 begin
2714 { Note that we clear cbColor regardless whether some BackgroundRenderer
2715 is used in RenderBackground.
2716 This is more reliable, in case BackgroundRenderer rendering is transparent,
2717
2718 - e.g. TImageBackgroundNode can be completely transparent or partially-transparent
2719 in a couple of ways. When ImageBackground.color has alpha < 1,
2720 when ImageBackground.texture is transparent,
2721 when ImageBackground.texture is NULL...
2722
2723 - likewise, TBackgroundNode rendering can be transparent.
2724 E.g. if one of the textures on 6 cube sides didn't load.
2725 Or when BackgroundWireframe.
2726 }
2727 Include(ClearBuffers, cbColor);
2728 ClearColor := BackgroundColor;
2729 end;
2730
2731 if GLFeatures.ShadowVolumesPossible and
2732 ShadowVolumes and
2733 MainLightForShadowVolumes(MainLightPosition) then
2734 Include(ClearBuffers, cbStencil);
2735
2736 RenderContext.Clear(ClearBuffers, ClearColor);
2737 end;
2738
2739 procedure RenderBackground;
2740 var
2741 BackgroundRenderer: TBackgroundRenderer;
2742 begin
2743 if Transparent then
2744 Exit;
2745
2746 if Background <> nil then
2747 BackgroundRenderer := Background.InternalBackgroundRenderer
2748 else
2749 {$warnings off} // using deprecated MainScene to keep it working
2750 if Items.MainScene <> nil then
2751 BackgroundRenderer := Items.MainScene.InternalBackgroundRenderer
2752 else
2753 {$warnings on}
2754 BackgroundRenderer := nil;
2755
2756 if BackgroundRenderer <> nil then
2757 begin
2758 if GLFeatures.EnableFixedFunction then
2759 begin
2760 {$ifndef OpenGLES}
2761 glLoadMatrix(RenderingCamera.RotationMatrix);
2762 {$endif}
2763 end;
2764 RenderingCamera.RotationOnly := true;
2765 { TODO: BackgroundRenderer should have its own ShapesRenderer,
2766 ShapesCollector. }
2767 BackgroundRenderer.Render(RenderingCamera, BackgroundWireframe,
2768 RenderRect, FProjection, ShapesCollector, ShapesRenderer);
2769 RenderingCamera.RotationOnly := false;
2770 end;
2771 end;
2772
2773 procedure AddGlobalLightsFromScene(const SceneCastingLights: TCastleScene);
2774 var
2775 J: Integer;
2776 NewGlobalLight: PLightInstance;
2777 begin
2778 if not SceneCastingLights.ExistsInRoot then
2779 Exit;
2780
2781 for J := 0 to SceneCastingLights.InternalGlobalLights.Count - 1 do
2782 begin
2783 NewGlobalLight := PLightInstance(FRenderParams.FGlobalLights.Add);
2784 NewGlobalLight^ := SceneCastingLights.InternalGlobalLights.L[J];
2785 { make NewGlobalLight^ in world coordinates }
2786 NewGlobalLight^.Transform := SceneCastingLights.WorldTransform * NewGlobalLight^.Transform;
2787 NewGlobalLight^.TransformScale := Approximate3DScale(SceneCastingLights.WorldTransform) * NewGlobalLight^.TransformScale;
2788 NewGlobalLight^.WorldCoordinates := true;
2789 NewGlobalLight^.Node.UpdateLightInstance(NewGlobalLight^);
2790 end;
2791 end;
2792
2793 var
2794 SceneCastingLights: TCastleScene;
2795 begin
2796 RenderClear;
2797 RenderBackground;
2798
2799 if GLFeatures.EnableFixedFunction then
2800 begin
2801 {$ifndef OpenGLES}
2802 glLoadMatrix(RenderingCamera.Matrix);
2803 {$endif}
2804 end;
2805
2806 { clear FRenderParams instance }
2807 FRenderParams.InternalPass := 0;
2808 FillChar(FRenderParams.Statistics, SizeOf(FRenderParams.Statistics), #0);
2809
2810 { various FRenderParams initialization }
2811 FRenderParams.UserPass := CustomRenderingPass;
2812 FRenderParams.RenderingCamera := RenderingCamera;
2813 FRenderParams.Collector := ShapesCollector;
2814 FRenderParams.RendererToPrepareShapes := ShapesRenderer.Renderer;
2815
2816 { calculate FRenderParams.Projection*, simplified from just like CalculateProjection does }
2817 FRenderParams.ProjectionBoxWithoutGizmos := {$ifdef FPC}@{$endif} ItemsBoundingBox;
2818 FRenderParams.ProjectionBoxWithGizmos := {$ifdef FPC}@{$endif} ItemsWithGizmosBoundingBox;
2819 FRenderParams.ProjectionViewportWidth := EffectiveWidthForChildren;
2820 FRenderParams.ProjectionViewportHeight := EffectiveHeightForChildren;
2821
2822 { calculate FRenderParams.FGlobalLights }
2823 FRenderParams.FGlobalLights.Clear;
2824 { Add headlight }
2825 InitializeGlobalLights(FRenderParams.FGlobalLights);
2826 { Add lights from MainScene }
2827 {$warnings off} // using deprecated MainScene to keep it working
2828 if Items.MainScene <> nil then
2829 AddGlobalLightsFromScene(Items.MainScene);
2830 { Add lights from all scenes with CastGlobalLights }
2831 if Items.InternalScenesCastGlobalLights <> nil then
2832 for SceneCastingLights in Items.InternalScenesCastGlobalLights do
2833 if Items.MainScene <> SceneCastingLights then // MainScene is already accounted for above
2834 AddGlobalLightsFromScene(SceneCastingLights);
2835 {$warnings on}
2836
2837 { calculate FRenderParams.GlobalFog }
2838 if Fog <> nil then
2839 FRenderParams.GlobalFog := Fog.InternalFogNode
2840 else
2841 {$warnings off} // using deprecated MainScene to keep it working
2842 if UseGlobalFog and
2843 (Items.MainScene <> nil) then
2844 FRenderParams.GlobalFog := Items.MainScene.FogStack.Top
2845 else
2846 {$warnings on}
2847 FRenderParams.GlobalFog := nil;
2848
2849 { Start with DefaultDepthRange,
2850 as this is the meaning of rlParent on Viewport.Items. }
2851 FRenderParams.DepthRange := DefaultDepthRange;
2852
2853 RenderFromView3D(FRenderParams);
2854 end;
2855
2856 procedure TCastleViewport.RenderWithoutScreenEffects;
2857
2858 { Render everything (by RenderFromViewEverything) on the screen.
2859 Takes care to set RenderingCamera (Target = rtScreen and camera as given),
2860 and takes care to apply Scissor if not FillsWholeContainer,
2861 and calls RenderFromViewEverything.
2862
2863 Always call ApplyProjection before this, to set correct
2864 projection matrix. }
2865 procedure RenderOnScreen(ACamera: TCastleCamera);
2866 var
2867 RenderingCamera: TRenderingCamera;
2868 begin
2869 { We reuse FRenderWithoutScreenEffectsRenderingCamera,
2870 but to be clean (to not use it when it's not really initialized)
2871 this is the only place where we refer to FRenderWithoutScreenEffectsRenderingCamera field.
2872 Rest of code should get RenderingCamera by parameters. }
2873 RenderingCamera := FRenderWithoutScreenEffectsRenderingCamera;
2874
2875 RenderingCamera.Target := rtScreen;
2876 RenderingCamera.FromCameraObject(ACamera);
2877
2878 if (not FillsWholeContainer) and (not RenderScreenEffects) then
2879 { Use Scissor to limit what RenderContext.Clear clears. }
2880 RenderContext.ScissorEnable(
2881 RenderRect.Translate(Vector2(RenderContext.ViewportDelta)).Round);
2882
2883 RenderFromViewEverything(RenderingCamera);
2884
2885 if (not FillsWholeContainer) and (not RenderScreenEffects) then
2886 RenderContext.ScissorDisable;
2887 end;
2888
2889 begin
2890 inherited;
2891
2892 // as Camera is assignable, gracefully handle the case of Camera = nil
2893 FMissingCameraRect.Exists := (InternalCamera = nil) or (not InternalCamera.ExistsInRoot);
2894 if FMissingCameraRect.Exists then
2895 begin
2896 { We show the "No camera selected" using UI controls, as this is most flexible.
2897
2898 Note: in particular, we do not clear viewport using RenderContext.Clear here,
2899 as RenderContext.Clear requires logic of RenderContext.ScissorEnable/Disable
2900 around it to be properly limited.
2901 The FMissingCameraRect clears the viewport with BackgroundColor already. }
2902
2903 FMissingCameraRect.Color := BackgroundColor;
2904 FMissingCameraLabel.Color := Vector4(WhiteRGB - BackgroundColor.XYZ, 1);
2905 FMissingCameraLabel.MaxWidth := FMissingCameraRect.EffectiveWidthForChildren;
2906 Exit;
2907 end;
2908
2909 { What happens if Camera is not part of our Items?
2910
2911 In principle we could tolerate this right now and
2912 even render from camera from unrelated viewport.
2913 But this is not something we want to support in the long run -- it's hard to define
2914 what should be the behavior (maybe camera from another viewport should show
2915 another viewport?). As there doesn't seem to be a useful usecase to allow this,
2916 better to prohibit it now. }
2917 (*
2918 if (InternalCamera.World <> Items) and not WarningCameraInvalidItemsDone then
2919 begin
2920 WritelnWarning('Camera "%s" of viewport "%s" is not part of this viewport Items hierarchy. You should add it to %s.Items.', [
2921 InternalCamera.Name,
2922 Name,
2923 Name
2924 ]);
2925 WarningCameraInvalidItemsDone := true; // avoid flooding log with warnings about it
2926 end;
2927 *)
2928 if InternalCamera.World <> Items then
2929 raise Exception.CreateFmt('Camera "%s" of viewport "%s" is not part of this viewport''s Items. You must add the camera to %s.Items.', [
2930 InternalCamera.Name,
2931 Name,
2932 Name
2933 ]);
2934
2935 ApplyProjection;
2936 RenderOnScreen(InternalCamera);
2937 end;
2938
2939 function TCastleViewport.InternalExtraGetScreenEffects(const Index: Integer): TGLSLProgram;
2940 begin
2941 if ScreenSpaceAmbientOcclusion then
2942 SSAOShaderInitialize;
2943 if ScreenSpaceReflections then
2944 SSRShaderInitialize;
2945
2946 {$warnings off} // using deprecated MainScene to keep it working
2947 if ScreenSpaceAmbientOcclusion and (SSAOShader <> nil) and ScreenSpaceReflections and (SSRShader <> nil) then
2948 begin
2949 if Index = 0 then
2950 Result := SSAOShader
2951 else
2952 if Index = 1 then
2953 Result := SSRShader
2954 else
2955 Result := Items.MainScene.InternalScreenEffects(Index - 2);
2956 end else
2957 if ScreenSpaceAmbientOcclusion and (SSAOShader <> nil) then
2958 begin
2959 if Index = 0 then
2960 Result := SSAOShader
2961 else
2962 Result := Items.MainScene.InternalScreenEffects(Index - 1);
2963 end else
2964 if ScreenSpaceReflections and (SSRShader <> nil) then
2965 begin
2966 if Index = 0 then
2967 Result := SSRShader
2968 else
2969 Result := Items.MainScene.InternalScreenEffects(Index - 1);
2970 end else
2971 if Items.MainScene <> nil then
2972 Result := Items.MainScene.InternalScreenEffects(Index)
2973 else
2974 { no Index is valid, since ScreenEffectsCount = 0 in this class }
2975 Result := nil;
2976 {$warnings on}
2977 end;
2978
2979 function TCastleViewport.InternalExtraScreenEffectsCount: Integer;
2980 begin
2981 if ScreenSpaceAmbientOcclusion then
2982 SSAOShaderInitialize;
2983 if ScreenSpaceReflections then
2984 SSRShaderInitialize;
2985
2986 {$warnings off} // using deprecated MainScene to keep it working
2987 if Items.MainScene <> nil then
2988 Result := Items.MainScene.InternalScreenEffectsCount
2989 else
2990 Result := 0;
2991 {$warnings off}
2992
2993 if ScreenSpaceAmbientOcclusion and (SSAOShader <> nil) then
2994 Inc(Result);
2995 if ScreenSpaceReflections and (SSRShader <> nil) then
2996 Inc(Result);
2997 end;
2998
2999 function TCastleViewport.InternalExtraScreenEffectsNeedDepth: Boolean;
3000 begin
3001 if ScreenSpaceAmbientOcclusion then
3002 SSAOShaderInitialize;
3003 if ScreenSpaceReflections then
3004 SSRShaderInitialize;
3005
3006 if ScreenSpaceAmbientOcclusion and (SSAOShader <> nil) then
3007 Exit(true);
3008 if ScreenSpaceReflections and (SSRShader <> nil) then
3009 Exit(true);
3010 {$warnings off} // using deprecated MainScene to keep it working
3011 if Items.MainScene <> nil then
3012 Result := Items.MainScene.InternalScreenEffectsNeedDepth
3013 else
3014 {$warnings on}
3015 Result := false;
3016 end;
3017
3018 procedure TCastleViewport.SSAOShaderInitialize;
3019 begin
3020 { Do not retry creating SSAOShader if SSAOShaderInitialize was already called.
3021 Even if SSAOShader is nil (when SSAOShaderInitialize = true but
3022 SSAOShader = nil it means that compiling SSAO shader fails on this GPU). }
3023 if SSAOShaderInitialized then Exit;
3024
3025 // SSAOShaderInitialized = false implies SSAOShader = nil
3026 Assert(SSAOShader = nil);
3027
3028 if GLFeatures.Shaders then
3029 begin
3030 try
3031 SSAOShader := TSSAOScreenEffect.Create;
3032 SSAOShader.Viewport := Self;
3033 SSAOShader.NeedsDepth := true;
3034 SSAOShader.ScreenEffectShader := {$I ssao.glsl.inc};
3035 SSAOShader.Link;
3036 except
3037 on E: EGLSLError do
3038 begin
3039 WritelnLog('GLSL', 'Error when initializing GLSL shader for ScreenSpaceAmbientOcclusionShader: ' + E.Message);
3040 FreeAndNil(SSAOShader);
3041 ScreenSpaceAmbientOcclusion := false;
3042 end;
3043 end;
3044 end;
3045 SSAOShaderInitialized := true;
3046 end;
3047
3048 procedure TCastleViewport.SSRShaderInitialize;
3049 begin
3050 { Do not retry creating SSRShader if SSRShaderInitialize was already called.
3051 Even if SSRShader is nil (when SSRShaderInitialize = true but
3052 SSRShader = nil it means that compiling SSR shader fails on this GPU). }
3053 if SSRShaderInitialized then Exit;
3054
3055 // SSAOShaderInitialized = false implies SSRShader = nil
3056 Assert(SSRShader = nil);
3057 if GLFeatures.Shaders then
3058 begin
3059 try
3060 SSRShader := TSSRScreenEffect.Create;
3061 SSRShader.Viewport := Self;
3062 SSRShader.NeedsDepth := True;
3063 SSRShader.ScreenEffectShader := {$I ssr.glsl.inc};
3064 SSRShader.Link;
3065 except
3066 on E: EGLSLError do
3067 begin
3068 WritelnLog('GLSL', 'Error when initializing GLSL shader for ScreenSpaceReflectionsShader: ' + E.Message);
3069 FreeAndNil(SSRShader);
3070 ScreenSpaceReflections := False;
3071 end;
3072 end;
3073 end;
3074 SSRShaderInitialized := True;
3075 end;
3076
3077 procedure TCastleViewport.GLContextOpen;
3078 begin
3079 inherited;
3080 end;
3081
3082 procedure TCastleViewport.GLContextClose;
3083 begin
3084 FreeAndNil(FShadowVolumeRenderer);
3085
3086 FreeAndNil(SSAOShader);
3087 SSAOShaderInitialized := false;
3088
3089 if ShapesRenderer <> nil then
3090 ShapesRenderer.GLContextClose;
3091
3092 inherited;
3093 end;
3094
3095 function TCastleViewport.ScreenSpaceAmbientOcclusionAvailable: boolean;
3096 begin
3097 SSAOShaderInitialize;
3098 Result := (SSAOShader <> nil);
3099 end;
3100
3101 function TCastleViewport.ScreenSpaceReflectionsAvailable: Boolean;
3102 begin
3103 SSRShaderInitialize;
3104 Result := (SSRShader <> nil);
3105 end;
3106
3107 procedure TCastleViewport.SetScreenSpaceAmbientOcclusion(const Value: boolean);
3108 begin
3109 if FScreenSpaceAmbientOcclusion <> Value then
3110 begin
3111 FScreenSpaceAmbientOcclusion := Value;
3112 VisibleChange([chRender]);
3113 end;
3114 end;
3115
3116 procedure TCastleViewport.SetScreenSpaceReflections(const Value: Boolean);
3117 begin
3118 if FScreenSpaceReflections <> Value then
3119 begin
3120 FScreenSpaceReflections := Value;
3121 VisibleChange([chRender]);
3122 end;
3123 end;
3124
3125 procedure TCastleViewport.SetScreenSpaceReflectionsSurfaceGlossiness(const Value: Single);
3126 begin
3127 if FScreenSpaceReflectionsSurfaceGlossiness <> Value then
3128 begin
3129 FScreenSpaceReflectionsSurfaceGlossiness := Value;
3130 VisibleChange([chRender]);
3131 end;
3132 end;
3133
3134 procedure TCastleViewport.AssignDefaultCamera;
3135 var
3136 Box: TBox3D;
3137 Scene: TCastleScene;
3138 APos, ADir, AUp, NewGravityUp: TVector3;
3139 begin
3140 if Camera = nil then
3141 Exit; // abort, until you assign Camera
3142
3143 Box := ItemsBoundingBox;
3144 {$warnings off} // using deprecated MainScene to keep it working
3145 Scene := Items.MainScene;
3146 {$warnings on}
3147 if Scene <> nil then
3148 begin
3149 Scene.InternalUpdateCamera(Camera, Box, false, false);
3150 end else
3151 begin
3152 CameraViewpointForWholeScene(Box, 2, 1, false, true,
3153 APos, ADir, AUp, NewGravityUp);
3154 Camera.SetWorldView(APos, ADir, AUp);
3155 Camera.GravityUp := NewGravityUp;
3156 end;
3157
3158 { Mark it as done, so that next EnsureCameraDetected does nothing
3159 if you manually called this earlier.
3160 This is consistent with AssignDefaultNavigation,
3161 that always sets Navigation <> nil thus it is no longer auto-detected
3162 if you call AssignDefaultNavigation again. }
3163 AssignDefaultCameraDone := true;
3164 end;
3165
3166 function TCastleViewport.Statistics: TRenderStatistics;
3167 begin
3168 Result := FRenderParams.Statistics;
3169 end;
3170
3171 procedure TCastleViewport.Setup2D;
3172 begin
3173 Camera.SetWorldView(
3174 { pos } Vector3(0, 0, Default2DCameraZ),
3175 { dir } Vector3(0, 0, -1),
3176 { up } Vector3(0, 1, 0));
3177 Camera.GravityUp := Vector3(0, 1, 0);
3178 Camera.ProjectionType := ptOrthographic;
3179 {$warnings off} // using deprecated AutoCamera for backward compat, so that TCastleSceneManager.Setup2D does what it did
3180 AutoCamera := false;
3181 {$warnings on}
3182 end;
3183
3184 procedure TCastleViewport.PositionToPrerequisites;
3185 begin
3186 { Note that we need to call this every time before PositionToXxx,
3187 not just only once (in case ApplyProjection did not yet happen).
3188 That's because Camera settings, that determine how CalculateProjection calculates
3189 FProjection, may change at any moment, e.g. when doing a sequence
3190
3191 Viewport.PositionToCameraPlane(...);
3192 Camera.Orthographic.Scale := Camera.Orthographic.Scale * ...;
3193 Viewport.PositionToCameraPlane(...);
3194 }
3195 if (EffectiveWidth = 0) or
3196 (EffectiveHeight = 0) then
3197 raise Exception.Create('Cannot use TCastleViewport.PositionToXxx when viewport has effectively empty size. ' + 'The typical solution is to add TCastleViewport to some UI hierarchy, like "Window.Container.InsertFront(MyViewport)", although you could also set TCastleViewport.Width/Height explicitly.');
3198
3199 EnsureCameraDetected;
3200
3201 FProjection := CalculateProjection;
3202 {$ifdef FPC}
3203 {$warnings off} // using deprecated to keep it working
3204 if Assigned(OnProjection) then
3205 OnProjection(FProjection);
3206 {$warnings on}
3207 {$endif}
3208 end;
3209
3210 procedure TCastleViewport.PositionToRay(const Position: TVector2;
3211 const ContainerCoordinates: Boolean;
3212 out RayOrigin, RayDirection: TVector3);
3213 var
3214 R: TFloatRectangle;
3215 ContainerPosition: TVector2;
3216 begin
3217 PositionToPrerequisites;
3218
3219 R := RenderRect;
3220
3221 if ContainerCoordinates then
3222 ContainerPosition := Position
3223 else
3224 ContainerPosition := LocalToContainerPosition(Position);
3225
3226 Assert(InternalCamera <> nil);
3227 InternalCamera.CustomRay(R, ContainerPosition, FProjection, RayOrigin, RayDirection);
3228 end;
3229
3230 function TCastleViewport.PositionToCameraPlane(const Position: TVector2;
3231 const ContainerCoordinates: Boolean;
3232 const Depth: Single; out PlanePosition: TVector3): Boolean;
3233 var
3234 RayOrigin, RayDirection: TVector3;
3235 Plane: TVector4;
3236 begin
3237 PositionToRay(Position, ContainerCoordinates, RayOrigin, RayDirection);
3238
3239 Plane := Vector4(InternalCamera.Direction,
3240 { We know that InternalCamera.Direction, which is used as Plane.XYZ, is normalized.
3241 Calculate Plane[3] such that point RayOrigin + InternalCamera.Direction * Depth
3242 satisfies the plane equation. }
3243 - TVector3.DotProduct(RayOrigin + InternalCamera.Direction * Depth, InternalCamera.Direction));
3244
3245 Result := TryPlaneRayIntersection(PlanePosition, Plane, RayOrigin, RayDirection);
3246 end;
3247
3248 function TCastleViewport.PositionToWorldPlane(const Position: TVector2;
3249 const ContainerCoordinates: Boolean;
3250 const PlaneConstValue: Single;
3251 out PlanePosition: TVector3): Boolean;
3252 begin
3253 Result := PositionToWorldPlane(Position, ContainerCoordinates,
3254 2, PlaneConstValue, PlanePosition);
3255 end;
3256
3257 function TCastleViewport.PositionToWorldPlane(const Position: TVector2;
3258 const ContainerCoordinates: Boolean;
3259 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
3260 out PlanePosition: TVector3): Boolean;
3261 var
3262 RayOrigin, RayDirection: TVector3;
3263 begin
3264 PositionToRay(Position, ContainerCoordinates, RayOrigin, RayDirection);
3265 Result := TrySimplePlaneRayIntersection(PlanePosition, PlaneConstCoord, PlaneConstValue,
3266 RayOrigin, RayDirection);
3267 end;
3268
3269 function TCastleViewport.PositionTo2DWorld(const Position: TVector2;
3270 const ContainerCoordinates: Boolean): TVector2;
3271
3272 { Version 1:
3273 This makes sense, but ignores TCastleExamineNavigation.ScaleFactor (assumes unscaled camera).
3274
3275 var
3276 P: TVector2;
3277 Proj: TProjection;
3278 ProjRect: TFloatRectangle;
3279 begin
3280 if ContainerCoordinates then
3281 P := (Position - RenderRect.LeftBottom) / UIScale
3282 else
3283 P := Position;
3284
3285 Proj := Projection;
3286 if Proj.ProjectionType <> ptOrthographic then
3287 raise Exception.Create('TCastleViewport.PositionTo2DWorld assumes an orthographic projection, like the one set by TCastle2DSceneManager.CalculateProjection');
3288 ProjRect := Proj.Dimensions;
3289
3290 if Navigation <> nil then
3291 ProjRect := ProjRect.Translate(Navigation.Position.XY);
3292
3293 Result := Vector2(
3294 MapRange(P.X, 0, EffectiveWidth , ProjRect.Left , ProjRect.Right),
3295 MapRange(P.Y, 0, EffectiveHeight, ProjRect.Bottom, ProjRect.Top)
3296 );
3297 end; }
3298
3299 { Version 2:
3300 This also makes sense, but also
3301 ignores TCastleExamineNavigation.ScaleFactor (assumes unscaled camera).
3302 PositionToRay looks only at camera pos/dir/up and ignores scaling.
3303
3304 var
3305 RayOrigin, RayDirection: TVector3;
3306 begin
3307 PositionToRay(MousePosition, true, RayOrigin, RayDirection);
3308 Result := RayOrigin.XY;
3309 end; }
3310
3311 { Version 3:
3312 Should work, but
3313 1. Cannot invert projection matrix,
3314 2. Also it's not efficient, since camera has ready InverseMatrix calculated
3315 more efficiently.
3316
3317 var
3318 WorldToScreenMatrix: TMatrix4;
3319 ScreenToWorldMatrix: TMatrix4;
3320 P: TVector2;
3321 begin
3322 WorldToScreenMatrix := RequiredNavigation.ProjectionMatrix * RequiredNavigation.Matrix;
3323 if not WorldToScreenMatrix.TryInverse(ScreenToWorldMatrix) then
3324 raise Exception.Create('Cannot invert projection * camera matrix. Possibly one of them was not initialized, or camera contains scale to zero.');
3325
3326 if ContainerCoordinates then
3327 P := (Position - RenderRect.LeftBottom) / UIScale
3328 else
3329 P := Position;
3330 P := Vector2(
3331 MapRange(P.X, 0, EffectiveWidth , -1, 1),
3332 MapRange(P.Y, 0, EffectiveHeight, -1, 1)
3333 );
3334
3335 Result := ScreenToWorldMatrix.MultPoint(Vector3(P, 0)).XY;
3336 end; }
3337
3338 var
3339 CameraToWorldMatrix: TMatrix4;
3340 P: TVector2;
3341 begin
3342 PositionToPrerequisites;
3343
3344 CameraToWorldMatrix := InternalCamera.MatrixInverse;
3345
3346 if ContainerCoordinates then
3347 P := ContainerToLocalPosition(Position)
3348 else
3349 P := Position;
3350 P := Vector2(
3351 MapRange(P.X, 0, EffectiveWidth , FProjection.Dimensions.Left , FProjection.Dimensions.Right),
3352 MapRange(P.Y, 0, EffectiveHeight, FProjection.Dimensions.Bottom, FProjection.Dimensions.Top)
3353 );
3354
3355 Result := CameraToWorldMatrix.MultPoint(Vector3(P, 0)).XY;
3356 end;
3357
3358 function TCastleViewport.PositionFrom2DWorld(const WorldPosition: TVector2;
3359 const ContainerCoordinates: Boolean): TVector2;
3360 var
3361 CameraFromWorldMatrix: TMatrix4;
3362 P: TVector2;
3363 begin
3364 PositionToPrerequisites;
3365
3366 CameraFromWorldMatrix := InternalCamera.Matrix;
3367 P := CameraFromWorldMatrix.MultPoint(Vector3(WorldPosition, 0)).XY;
3368 P := Vector2(
3369 MapRange(P.X, FProjection.Dimensions.Left , FProjection.Dimensions.Right, 0, EffectiveWidth ),
3370 MapRange(P.Y, FProjection.Dimensions.Bottom, FProjection.Dimensions.Top , 0, EffectiveHeight)
3371 );
3372 if ContainerCoordinates then
3373 Result := LocalToContainerPosition(P)
3374 else
3375 Result := P;
3376 end;
3377
3378 function TCastleViewport.PositionFromWorld(const WorldPosition: TVector3): TVector2;
3379 var
3380 Matrix: TMatrix4;
3381 P: TVector3;
3382 begin
3383 PositionToPrerequisites;
3384
3385 Matrix := InternalCamera.ProjectionMatrix * InternalCamera.Matrix;
3386 P := Matrix.MultPoint(WorldPosition);
3387 Result := Vector2(
3388 MapRange(P.X, -1, 1, 0, EffectiveWidth ),
3389 MapRange(P.Y, -1, 1, 0, EffectiveHeight)
3390 );
3391 end;
3392
3393 procedure TCastleViewport.SetItems(Value: TCastleRootTransform);
3394 begin
3395 if FItems <> Value then
3396 begin
3397 { Do not allow to set this to nil, for now, unless csDestroying. }
3398 if (Value = nil) and not (csDestroying in ComponentState) then
3399 begin
3400 Value := TCastleRootTransform.Create(Self);
3401 end;
3402
3403 if InternalDesignManipulation then
3404 if FItems <> nil then
3405 FItems.Remove(InternalDesignCamera);
3406
3407 FItems := Value;
3408 FItemsObserver.Observed := Value;
3409
3410 { Keep InternalDesignCamera part of current Items.
3411 Note: This is actually never executed in reality, for now.
3412 Because we don't allow to do SetItems on viewports in designs in CGE editor.
3413 And only they have InternalDesignManipulation = true.
3414 Maybe it will become useful in the future, once we allow to set Items in editor. }
3415 if InternalDesignManipulation then
3416 if FItems <> nil then
3417 FItems.Add(InternalDesignCamera);
3418
3419 LastVisibleStateIdForVisibleChange := 0;
3420
3421 {
3422 // No need to change this, it's documented that MainCamera has to be manually managed if you reuse items
3423 // FItems.MainCamera := Camera;
3424 }
3425 end;
3426 end;
3427
3428 procedure TCastleViewport.ItemsFreeNotification(const Sender: TFreeNotificationObserver);
3429 begin
3430 Items := nil;
3431 end;
3432
3433 function TCastleViewport.GetPaused: Boolean;
3434 begin
3435 Result := Items.Paused;
3436 end;
3437
3438 procedure TCastleViewport.SetPaused(const Value: Boolean);
3439 begin
3440 Items.Paused := Value;
3441 end;
3442
3443 function TCastleViewport.GetMainScene: TCastleScene;
3444 begin
3445 {$warnings off} // using deprecated MainScene to keep it working
3446 Result := Items.MainScene;
3447 {$warnings on}
3448 end;
3449
3450 function TCastleViewport.MouseRayHitContains(const Item: TCastleTransform): boolean;
3451 begin
3452 { Do not validate FMouseRayHit using UpdateMouseRayHit.
3453 Fixes TTestCastleWindow.TestViewportWithoutCamera with Delphi 12.
3454 Also this is more sensible and safer: this method is used
3455 to check whether FMouseRayHit contains something,
3456 it isn't expected it will actually query using raycast. }
3457
3458 { When FMouseRayHitValid=false then always FMouseRayHit=nil. }
3459 Assert(FMouseRayHitValid or (FMouseRayHit = nil));
3460
3461 Result :=
3462 (FMouseRayHit <> nil) and
3463 (FMouseRayHit.IndexOfItem(Item) <> -1);
3464 end;
3465
3466 procedure TCastleViewport.ClearMouseRayHit;
3467 begin
3468 SetMouseRayHit(nil);
3469 FMouseRayHitValid := false;
3470 end;
3471
3472 procedure TCastleViewport.SetMouseRayHit(const Value: TRayCollision);
3473 var
3474 I: Integer;
3475 begin
3476 if FMouseRayHit <> Value then
3477 begin
3478 { Always keep FreeNotification on every 3D item inside MouseRayHit.
3479 When it's destroyed, our MouseRayHit must be freed too. }
3480
3481 if FMouseRayHit <> nil then
3482 begin
3483 for I := 0 to FMouseRayHit.Count - 1 do
3484 begin
3485 { leave free notification for 3D item if it's also present somewhere else }
3486 if (FMouseRayHit[I].Item <> FAvoidNavigationCollisions) then
3487 FMouseRayHit[I].Item.RemoveFreeNotification(Self);
3488 end;
3489 FreeAndNil(FMouseRayHit);
3490 end;
3491
3492 FMouseRayHit := Value;
3493
3494 if FMouseRayHit <> nil then
3495 begin
3496 for I := 0 to FMouseRayHit.Count - 1 do
3497 FMouseRayHit[I].Item.FreeNotification(Self);
3498 end;
3499 end;
3500 end;
3501
3502 procedure TCastleViewport.SetAvoidNavigationCollisions(const Value: TCastleTransform);
3503 begin
3504 if FAvoidNavigationCollisions <> Value then
3505 begin
3506 if FAvoidNavigationCollisions <> nil then
3507 begin
3508 { leave free notification for FAvoidNavigationCollisions if it's also present somewhere else }
3509 if (not MouseRayHitContains(FAvoidNavigationCollisions)) then
3510 FAvoidNavigationCollisions.RemoveFreeNotification(Self);
3511 end;
3512
3513 FAvoidNavigationCollisions := Value;
3514
3515 if FAvoidNavigationCollisions <> nil then
3516 FAvoidNavigationCollisions.FreeNotification(Self);
3517 end;
3518 end;
3519
3520 procedure TCastleViewport.PrepareResources(const DisplayProgressTitle: string;
3521 const Options: TPrepareResourcesOptions);
3522 begin
3523 PrepareResources(Options);
3524 end;
3525
3526 procedure TCastleViewport.PrepareResources(const Item: TCastleTransform;
3527 const DisplayProgressTitle: string;
3528 Options: TPrepareResourcesOptions);
3529 begin
3530 PrepareResources(Item, Options);
3531 end;
3532
3533 procedure TCastleViewport.PrepareResources(const Item: TCastleTransform;
3534 Options: TPrepareResourcesOptions);
3535 var
3536 MainLightPosition: TVector4; // value of this is ignored
3537 begin
3538 if not ApplicationProperties.IsGLContextOpen then
3539 begin
3540 WritelnWarning('It is best to call PrepareResources only once rendering context is initialized, to allow preparing all rendering resources.' + NL +
3541 'Various events and virtual methods can be used to wait for the context:' + NL +
3542 '- (if you use CastleWindow) Application.OnInitialize' + NL +
3543 '- TCastleUserInterface.GLContextOpen' + NL +
3544 'We will continue, but some rendering resources may need to be prepared on-demand later.'
3545 );
3546 // despite the warning, allow PrepareResources to run, to make it easy for users
3547 end;
3548
3549 if (GLFeatures <> nil) and
3550 GLFeatures.ShadowVolumesPossible and
3551 ShadowVolumes and
3552 MainLightForShadowVolumes(MainLightPosition) then
3553 Include(Options, prShadowVolume);
3554
3555 { call TCastleScreenEffects.PrepareResources. }
3556 inherited PrepareResources;
3557
3558 {$warnings off} // using deprecated, this should be internal
3559 Item.PrepareResources(Options, PrepareParams);
3560 {$warnings on}
3561
3562 ShapesRenderer.PrepareResources;
3563 end;
3564
3565 procedure TCastleViewport.PrepareResources(
3566 const Options: TPrepareResourcesOptions);
3567 begin
3568 PrepareResources(Items, Options);
3569 end;
3570
3571 procedure TCastleViewport.BeforeRender;
3572 begin
3573 inherited;
3574
3575 { Do it only once, otherwise BeforeRender eats time each frame
3576 (traversing TCastleTransform tree one more time, usually doing nothing if
3577 the TCastleScene are already prepared). }
3578 if not PrepareResourcesDone then
3579 begin
3580 PrepareResources;
3581 PrepareResourcesDone := true;
3582 end;
3583 end;
3584
3585 function TCastleViewport.GetMousePosition(out MousePosition: TVector2): Boolean;
3586 var
3587 C: TCastleContainer;
3588 begin
3589 C := Container;
3590 Result := C <> nil;
3591 if Result then
3592 begin
3593 {$warnings off} // TODO: using deprecated Navigation for now
3594 if (Navigation is TCastleMouseLookNavigation) and
3595 { Note: We need to check InternalUsingMouseLook, not just MouseLook,
3596 to prevent from honoring MouseLook on user-designed TCastleWalkNavigation component
3597 at design-time. At design-time, only MouseLook on TCastleWalkNavigationDesign
3598 should have any effect.
3599 See https://forum.castle-engine.io/t/gizmos-for-transforming-objects-stopped-working/643/5 . }
3600 TCastleMouseLookNavigation(Navigation).InternalUsingMouseLook then
3601 {$warnings on}
3602 MousePosition := RenderRect.Center
3603 else
3604 MousePosition := C.MousePosition;
3605 end;
3606 end;
3607
3608 function TCastleViewport.FakeRayCollisionNode(const RayOriginWorld, RayDirectionWorld: TVector3;
3609 const Item: TCastleTransform): TRayCollisionNode;
3610 var
3611 RayOrigin, RayDirection: TVector3;
3612 begin
3613 if Item.HasWorldTransform and
3614 (Item.Parent <> nil) and
3615 Item.Parent.HasWorldTransform then
3616 begin
3617 RayOrigin := Item.Parent.WorldToLocal(RayOriginWorld);
3618 RayDirection := Item.Parent.WorldToLocalDirection(RayDirectionWorld);
3619 end else
3620 begin
3621 WritelnWarning('TODO: Item %s(%s) is not part of World, or is present in the World multiple times. PointingDeviceXxx events will receive ray in world coordinates, while they should be in local.', [
3622 Item.Name,
3623 Item.ClassName
3624 ]);
3625 RayOrigin := RayOriginWorld;
3626 RayDirection := RayDirectionWorld;
3627 end;
3628
3629 { sets Triangle and Point (and any potential future fields) to zero }
3630 FillChar(Result, SizeOf(Result), #0);
3631 Result.Item := Item;
3632 Result.RayOrigin := RayOrigin;
3633 Result.RayDirection := RayDirection;
3634 end;
3635
3636 function TCastleViewport.PointingDevicePress: Boolean;
3637
3638 { Pass pointing device (mouse or touch) press event
3639 to TCastleTransform instances in @link(Items) hit by RayHit. }
3640 function PointingDevicePressCore(const RayHit: TRayCollision; const RayOrigin, RayDirection: TVector3): boolean;
3641
3642 function CallPress(const Pick: TRayCollisionNode; const Distance: Single): Boolean;
3643 begin
3644 if not Pick.Item.Exists then // prevent calling Pick.Item.PointingDeviceXxx when item Exists=false
3645 Result := false
3646 else
3647 Result := Pick.Item.PointingDevicePress(Pick, Distance);
3648 end;
3649
3650 var
3651 Distance: Single;
3652 I: Integer;
3653 begin
3654 Result := false;
3655
3656 if RayHit <> nil then
3657 Distance := RayHit.Distance
3658 else
3659 Distance := MaxSingle;
3660
3661 // call TCastleTransform.PointingDevicePress on all items on RayHit
3662 if RayHit <> nil then
3663 for I := 0 to RayHit.Count - 1 do
3664 begin
3665 ItemsNodesFreeOccurred := false;
3666 Result := CallPress(RayHit[I], Distance);
3667 if ItemsNodesFreeOccurred then
3668 Break;
3669 if Result then
3670 begin
3671 { This check avoids assigning to CapturePointingDevice something
3672 that is no longer part of our Items after it handled PointingDevicePress. }
3673 if RayHit[I].Item.World = Items then
3674 CapturePointingDevice := RayHit[I].Item;
3675 Exit;
3676 end;
3677 end;
3678 end;
3679
3680 var
3681 MousePosition: TVector2;
3682
3683 { Try PointingDevicePressCore on stuff hit by ray,
3684 with ray moved by given number of screen pixels from current mouse position.
3685 Call only if MousePosition is already assigned. }
3686 function TryActivateAround(const Change: TVector2): boolean;
3687 var
3688 RayOrigin, RayDirection: TVector3;
3689 RayHit: TRayCollision;
3690 begin
3691 PositionToRay(MousePosition + Change, true, RayOrigin, RayDirection);
3692 RayHit := CameraRayCollision(RayOrigin, RayDirection);
3693 try
3694 Result := PointingDevicePressCore(RayHit, RayOrigin, RayDirection);
3695 finally FreeAndNil(RayHit) end;
3696 end;
3697
3698 function TryActivateAroundSquare(const Change: Single): boolean;
3699 begin
3700 Result := TryActivateAround(Vector2(-Change, -Change)) or
3701 TryActivateAround(Vector2(-Change, +Change)) or
3702 TryActivateAround(Vector2(+Change, +Change)) or
3703 TryActivateAround(Vector2(+Change, -Change)) or
3704 TryActivateAround(Vector2( 0, -Change)) or
3705 TryActivateAround(Vector2( 0, +Change)) or
3706 TryActivateAround(Vector2(-Change, 0)) or
3707 TryActivateAround(Vector2(+Change, 0));
3708 end;
3709
3710 begin
3711 Result := PointingDevicePressCore(MouseRayHit, MouseRayOrigin, MouseRayDirection);
3712
3713 if not Result then
3714 begin
3715 if ApproximateActivation and GetMousePosition(MousePosition) then
3716 Result := TryActivateAroundSquare(25) or
3717 TryActivateAroundSquare(50) or
3718 TryActivateAroundSquare(100) or
3719 TryActivateAroundSquare(200);
3720 end;
3721
3722 if not Result then
3723 PointingDevicePressFailed;
3724 end;
3725
3726 procedure TCastleViewport.PointingDevicePressFailed;
3727 begin
3728 {$warnings off} // just to keep deprecated working
3729 SoundEngine.Play(stPlayerInteractFailed);
3730 {$warnings on}
3731 end;
3732
3733 function TCastleViewport.PointingDeviceRelease: Boolean;
3734
3735 { Pass pointing device (mouse or touch) release event
3736 to TCastleTransform instances in @link(Items) hit by RayHit. }
3737 function PointingDeviceReleaseCore(const RayHit: TRayCollision; const RayOrigin, RayDirection: TVector3): boolean;
3738
3739 function CallRelease(const Pick: TRayCollisionNode; const Distance: Single): Boolean;
3740 begin
3741 if not Pick.Item.Exists then // prevent calling Pick.Item.PointingDeviceXxx when item Exists=false
3742 Result := false
3743 else
3744 Result := Pick.Item.PointingDeviceRelease(Pick, Distance, false);
3745 end;
3746
3747 var
3748 Distance: Single;
3749 NodeIndex, I: Integer;
3750 begin
3751 Result := false;
3752
3753 if RayHit <> nil then
3754 Distance := RayHit.Distance
3755 else
3756 Distance := MaxSingle;
3757
3758 if CapturePointingDevice <> nil then
3759 begin
3760 // call CapturePointingDevice.PointingDeviceRelease
3761 if RayHit <> nil then
3762 NodeIndex := RayHit.IndexOfItem(CapturePointingDevice)
3763 else
3764 NodeIndex := -1;
3765 if NodeIndex <> -1 then
3766 Result := CallRelease(RayHit[NodeIndex], Distance)
3767 else
3768 Result := CallRelease(FakeRayCollisionNode(RayOrigin, RayDirection, CapturePointingDevice), Distance);
3769 CapturePointingDevice := nil; // no longer capturing, after release
3770 if Result then Exit;
3771 end;
3772
3773 // call TCastleTransform.PointingDeviceRelease on remaining items on RayHit
3774 if RayHit <> nil then
3775 for I := 0 to RayHit.Count - 1 do
3776 if (CapturePointingDevice = nil) or
3777 (CapturePointingDevice <> RayHit[I].Item) then
3778 begin
3779 Result := CallRelease(RayHit[I], Distance);
3780 if Result then Exit;
3781 end;
3782 end;
3783
3784 begin
3785 Result := PointingDeviceReleaseCore(MouseRayHit, MouseRayOrigin, MouseRayDirection);
3786 end;
3787
3788 function TCastleViewport.PointingDeviceMove: boolean;
3789
3790 { Pass pointing device (mouse or touch) move event
3791 to TCastleTransform instances in @link(Items) hit by RayHit. }
3792 function PointingDeviceMoveCore(const RayHit: TRayCollision; const RayOrigin, RayDirection: TVector3): boolean;
3793
3794 function CallMove(const Pick: TRayCollisionNode; const Distance: Single): Boolean;
3795 begin
3796 if not Pick.Item.Exists then // prevent calling Pick.Item.PointingDeviceXxx when item Exists=false
3797 Result := false
3798 else
3799 Result := Pick.Item.PointingDeviceMove(Pick, Distance);
3800 end;
3801
3802 var
3803 Distance: Single;
3804 I, NodeIndex: Integer;
3805 begin
3806 Result := false;
3807
3808 if RayHit <> nil then
3809 Distance := RayHit.Distance
3810 else
3811 Distance := MaxSingle;
3812
3813 if CapturePointingDevice <> nil then
3814 begin
3815 // call CapturePointingDevice.PointingDeviceMove
3816 if RayHit <> nil then
3817 NodeIndex := RayHit.IndexOfItem(CapturePointingDevice)
3818 else
3819 NodeIndex := -1;
3820 if NodeIndex <> -1 then
3821 Result := CallMove(RayHit[NodeIndex], Distance)
3822 else
3823 Result := CallMove(FakeRayCollisionNode(RayOrigin, RayDirection, CapturePointingDevice), Distance);
3824 if Result then Exit;
3825 end;
3826
3827 // call TCastleTransform.PointingDeviceMove on remaining items on RayHit
3828 if RayHit <> nil then
3829 for I := 0 to RayHit.Count - 1 do
3830 if (CapturePointingDevice = nil) or
3831 (CapturePointingDevice <> RayHit[I].Item) then
3832 begin
3833 Result := CallMove(RayHit[I], Distance);
3834 if Result then Exit;
3835 end;
3836
3837 // call MainScene.PointingDeviceMove, to allow to update X3D sensors "isOver"
3838 {$warnings off} // using deprecated MainScene to keep it working
3839 if (Items.MainScene <> nil) and
3840 (CapturePointingDevice <> Items.MainScene) and
3841 ((RayHit = nil) or (RayHit.IndexOfItem(Items.MainScene) = -1)) then
3842 CallMove(FakeRayCollisionNode(RayOrigin, RayDirection, Items.MainScene), Distance);
3843 {$warnings on}
3844 end;
3845
3846 begin
3847 Result := PointingDeviceMoveCore(MouseRayHit, MouseRayOrigin, MouseRayDirection);
3848 end;
3849
3850 procedure TCastleViewport.InternalCameraChanged(Sender: TObject);
3851 var
3852 Pos, Dir, Up: TVector3;
3853 SenderCamera: TCastleCamera;
3854 MainCamera: TCastleCamera;
3855 begin
3856 SenderCamera := Sender as TCastleCamera; // may be Camera or InternalDesignCamera
3857 MainCamera := Items.MainCamera;
3858 if SenderCamera = MainCamera then
3859 begin
3860 Inc(Items.InternalMainCameraStateId);
3861
3862 // we should redraw soon, this will cause VisibleChange() call
3863 Inc(Items.InternalVisibleStateId);
3864
3865 // we changed MainCamera which makes headlight -> so lighting changed
3866 if Items.InternalHeadlight <> nil then
3867 Inc(Items.InternalVisibleNonGeometryStateId);
3868
3869 SenderCamera.GetView(Pos, Dir, Up);
3870 if UpdateSoundListener then
3871 SoundEngine.InternalUpdateListener(Pos, Dir, Up);
3872 end;
3873
3874 if Assigned(OnCameraChanged) then
3875 OnCameraChanged(Self);
3876 end;
3877
3878 function TCastleViewport.UseAvoidNavigationCollisions: Boolean;
3879 begin
3880 { Only use AvoidNavigationCollisions when it is part of current world.
3881 Otherwise using methods like TCastleTransform.Ray (by AvoidNavigationCollisions.Ray)
3882 would try to access AvoidNavigationCollisions's World,
3883 which is not correct now (nil, or points to something else).
3884 See https://github.com/castle-engine/castle-engine/pull/220 ,
3885 https://trello.com/c/iz7uvjKN/79-frogger3d-crash-when-pressing-enter-on-game-over-message-box . }
3886 Result := (AvoidNavigationCollisions <> nil) and (AvoidNavigationCollisions.World = Items);
3887 end;
3888
3889 function TCastleViewport.InternalNavigationMoveAllowed(const Sender: TCastleNavigation;
3890 const OldPos, ProposedNewPos: TVector3; out NewPos: TVector3;
3891 const Radius: Single; const BecauseOfGravity: Boolean): Boolean;
3892
3893 function PositionOutsideBoundingBox: Boolean;
3894 var
3895 Box: TBox3D;
3896 GravityCoordinate, Coord1, Coord2: T3DAxis;
3897 begin
3898 Box := ItemsBoundingBox;
3899 if Box.IsEmpty then Exit(false);
3900 GravityCoordinate := MaxAbsVectorCoord(NewPos - OldPos);
3901 RestOf3DCoords(GravityCoordinate, Coord1, Coord2);
3902 { Do not fall down if OldPos is outside of Box.
3903 But in case OldPos is *above* Box, consider it *inside* the box
3904 (gravity will work there).
3905 This is useful to allow jumping on top of the scene work naturally. }
3906 Result :=
3907 (OldPos[Coord1] < Box.Data[0][Coord1]) or
3908 (OldPos[Coord1] > Box.Data[1][Coord1]) or
3909 (OldPos[Coord2] < Box.Data[0][Coord2]) or
3910 (OldPos[Coord2] > Box.Data[1][Coord2]) or
3911 (OldPos[GravityCoordinate] < Box.Data[0][GravityCoordinate]);
3912 end;
3913
3914 var
3915 SavedExists: Boolean;
3916 begin
3917 // take into account PreventInfiniteFallingDown
3918 if BecauseOfGravity and
3919 PreventInfiniteFallingDown and
3920 PositionOutsideBoundingBox then
3921 Exit(false);
3922
3923 if UseAvoidNavigationCollisions then
3924 begin
3925 SavedExists := AvoidNavigationCollisions.Exists;
3926 AvoidNavigationCollisions.Exists := false;
3927 end else
3928 SavedExists := false; // avoid Delphi warnings about SavedDepthRange uninitialized
3929
3930 Result := Items.WorldMoveAllowed(OldPos, ProposedNewPos, NewPos, true, Radius,
3931 { We prefer to resolve collisions with navigation using sphere.
3932 But for TCastleTransform implementations that can't use sphere, we can construct box. }
3933 Box3DAroundPoint(OldPos, Radius * 2),
3934 Box3DAroundPoint(ProposedNewPos, Radius * 2), BecauseOfGravity);
3935
3936 if UseAvoidNavigationCollisions then
3937 AvoidNavigationCollisions.Exists := SavedExists;
3938 end;
3939
3940 function TCastleViewport.InternalNavigationHeight(const Sender: TCastleNavigation;
3941 const Position: TVector3;
3942 out AboveHeight: Single; out AboveGround: PTriangle): boolean;
3943 var
3944 SavedExists: Boolean;
3945 begin
3946 if UseAvoidNavigationCollisions then
3947 begin
3948 SavedExists := AvoidNavigationCollisions.Exists;
3949 AvoidNavigationCollisions.Exists := false;
3950 end else
3951 SavedExists := false; // avoid Delphi warnings about SavedDepthRange uninitialized
3952
3953 Result := Items.WorldHeight(Position, AboveHeight, AboveGround);
3954
3955 if UseAvoidNavigationCollisions then
3956 AvoidNavigationCollisions.Exists := SavedExists;
3957 end;
3958
3959 function TCastleViewport.CameraRayCollision(const RayOrigin, RayDirection: TVector3): TRayCollision;
3960 var
3961 SavedExists: Boolean;
3962 begin
3963 if UseAvoidNavigationCollisions then
3964 begin
3965 SavedExists := AvoidNavigationCollisions.Exists;
3966 AvoidNavigationCollisions.Exists := false;
3967 end else
3968 SavedExists := false; // avoid Delphi warnings about SavedDepthRange uninitialized
3969
3970 Result := Items.WorldRay(RayOrigin, RayDirection);
3971
3972 if UseAvoidNavigationCollisions then
3973 AvoidNavigationCollisions.Exists := SavedExists;
3974 end;
3975
3976 procedure TCastleViewport.BoundViewpointChanged;
3977 begin
3978 if Assigned(OnBoundViewpointChanged) then
3979 OnBoundViewpointChanged(Self);
3980 end;
3981
3982 procedure TCastleViewport.BoundNavigationInfoChanged;
3983 begin
3984 if Assigned(OnBoundNavigationInfoChanged) then
3985 OnBoundNavigationInfoChanged(Self);
3986 end;
3987
3988 procedure TCastleViewport.MainSceneAndCamera_BoundViewpointChanged(Sender: TObject);
3989 begin
3990 {$warnings off} // using deprecated AutoCamera and MainScene to keep it working
3991 if AutoCamera then
3992 begin
3993 Items.MainScene.InternalUpdateCamera(Camera, ItemsBoundingBox, false, true);
3994 BoundViewpointChanged;
3995 end;
3996 {$warnings on}
3997 end;
3998
3999 procedure TCastleViewport.MainSceneAndCamera_BoundNavigationInfoChanged(Sender: TObject);
4000 begin
4001 BoundNavigationInfoChanged;
4002 end;
4003
4004 procedure TCastleViewport.MainSceneAndCamera_BoundViewpointVectorsChanged(Sender: TObject);
4005 begin
4006 {$warnings off} // using deprecated AutoCamera and MainScene to keep it working
4007 if AutoCamera { or AnimateCameraByViewpoint } then
4008 Items.MainScene.InternalUpdateCamera(Camera, ItemsBoundingBox, true,
4009 { AllowTransitionAnimate - this would break Viewpoint animation from X3D if true } false);
4010 {$warnings on}
4011 end;
4012
4013 class procedure TCastleViewport.CreateComponentWithChildren3D(Sender: TObject);
4014 begin
4015 (Sender as TCastleViewport).SetupChildren3D;
4016 end;
4017
4018 class procedure TCastleViewport.CreateComponentWithChildren2D(Sender: TObject);
4019 begin
4020 (Sender as TCastleViewport).SetupChildren2D;
4021 end;
4022
4023 procedure TCastleViewport.SetupChildren2D;
4024 var
4025 Plane: TCastlePlane;
4026 begin
4027 FullSize := true;
4028 SetupDesignTimeCamera;
4029 { Better Origin default, makes things in center }
4030 Camera.Orthographic.Origin := Vector2(0.5, 0.5);
4031 { Set Orthographic.Height,
4032 as we advise users to set Camera.Orthographic.Width/Height to non-zero.
4033
4034 This way the displayed items don't depend on your viewport size.
4035 So you can change viewport size (even to something very small,
4036 e.g. to squeeze it into some TCastleButton) and keep the same fov.
4037 You can also change UI scaling and keep the same fov. }
4038 Camera.Orthographic.Height := 1000;
4039 Setup2D;
4040
4041 { purpose: initial 2D object,
4042 that you can see as a whole in initial view,
4043 allows to see screen corner - also has distance from edge. }
4044 Plane := TCastlePlane.Create(Owner);
4045 Plane.Name := ProposeComponentName(TCastlePlane, Owner);
4046 Plane.Axis := 2;
4047 Plane.Size := Vector2(200, 200);
4048 Plane.Material := pmUnlit;
4049 Items.Add(Plane);
4050
4051 if InternalDesignManipulation then
4052 begin
4053 { Similar to Setup2D, but here done on design-time camera. }
4054 InternalDesignCamera.ProjectionType := ptOrthographic;
4055 InternalDesignCamera.SetWorldView(
4056 { We move Z back, to be able to see from design-time camera the runtime camera gizmo.
4057 Note that 2D Camera.EffectiveProjectionNear is negative by default (after Setup2D),
4058 so "- Camera.EffectiveProjectionNear" actually does "+ 1000". }
4059 { pos } Vector3(0, 0, Camera.Translation.Z - Camera.EffectiveProjectionNear + 100),
4060 { dir } Vector3(0, 0, -1),
4061 { up } Vector3(0, 1, 0));
4062 { Better Origin default, makes things in center.
4063 Makes ViewSelected, ViewAll sensible in 2D }
4064 InternalDesignCamera.Orthographic.Origin := Vector2(0.5, 0.5);
4065 { Just like for run-time camera,
4066 we set non-zero Orthographic.Height for design-time camera.
4067 This is a bit larger, this way it is clear what happens when creating new 2D viewport. }
4068 InternalDesignCamera.Orthographic.Height := Camera.Orthographic.Height + 200;
4069
4070 InternalDesignNavigationType := dn2D;
4071 end;
4072
4073 { Darker than 0.5, which is default in CGE editor background.
4074 But not so dark as to look like black. }
4075 BackgroundColor := Vector4(0.25, 0.25, 0.25, 1);
4076 end;
4077
4078 procedure TCastleViewport.SetupChildren3D;
4079 var
4080 Light: TCastlePointLight;
4081 Plane: TCastlePlane;
4082 NewBackground: TCastleBackground;
4083 begin
4084 FullSize := true;
4085 SetupDesignTimeCamera;
4086 Camera.Translation := Vector3(0.00, 2.00, 4.00);
4087
4088 { purpose: initial light,
4089 bright to make PBR colors visible (e.g. yellow sphere should visibly be really yellow),
4090 low above ground to see the attenuation on floor. }
4091 Light := TCastlePointLight.Create(Owner);
4092 Light.Name := ProposeComponentName(TCastlePointLight, Owner);
4093 Light.Translation := Vector3(4.00, 3.00, 1.00);
4094 // Light.Intensity := 100; // default for TCastlePointLight now
4095 Items.Add(Light);
4096
4097 { purpose: initial 3D object,
4098 that you can see as a whole in initial view,
4099 serves as floor to place new 3D stuff }
4100 Plane := TCastlePlane.Create(Owner);
4101 Plane.Name := ProposeComponentName(TCastlePlane, Owner);
4102 Plane.Size := Vector2(10, 10);
4103 Items.Add(Plane);
4104
4105 if InternalDesignManipulation then
4106 begin
4107 InternalDesignCamera.Translation := Vector3(
4108 7.7023463249206543E+000,
4109 3.3161113262176514E+000,
4110 8.0032939910888672E+000);
4111 InternalDesignCamera.Rotation := Vector4(
4112 -2.9199448227882385E-001,
4113 9.4821619987487793E-001,
4114 1.2500144541263580E-001,
4115 8.6496734619140625E-001);
4116 end;
4117
4118 NewBackground := TCastleBackground.Create(Owner);
4119 NewBackground.Name := ProposeComponentName(TCastleBackground, Owner);
4120 AddNonVisualComponent(NewBackground);
4121 Background := NewBackground;
4122 end;
4123
4124 procedure TCastleViewport.SetSceneManager(const Value: TCastleSceneManager);
4125 begin
4126 {$ifdef FPC}
4127 {$warnings off} // only to keep deprecated feature working
4128 if Value <> FSceneManager then
4129 begin
4130 if SceneManager <> nil then
4131 SceneManager.Viewports.Remove(Self);
4132 FSceneManager := Value;
4133 if SceneManager <> nil then
4134 SceneManager.Viewports.Add(Self);
4135 end;
4136 {$warnings on}
4137 {$endif}
4138 end;
4139
4140 function TCastleViewport.PropertySections(const PropertyName: String): TPropertySections;
4141 begin
4142 if ArrayContainsString(PropertyName, [
4143 'Transparent', 'Camera', 'Navigation', 'Background',
4144 'Fog', 'BackgroundColorPersistent', 'DynamicBatching', 'Items',
4145 'OcclusionSort', 'OcclusionCulling', 'BlendingSort'
4146 ]) then
4147 Result := [psBasic]
4148 else
4149 Result := inherited PropertySections(PropertyName);
4150 end;
4151
4152 procedure TCastleViewport.CustomSerialization(const SerializationProcess: TSerializationProcess);
4153
4154 { If PreserveDataAcrossUndo contains a viewport from which we should copy design data
4155 (camera, navigation at design-time), return @true and set CopyFromViewport. }
4156 function CopyDesignDataFromViewport(const PreserveDataAcrossUndo: TComponent;
4157 out CopyFromViewport: TCastleViewport): Boolean;
4158 var
4159 CopyFrom: TComponent;
4160 begin
4161 Result := false;
4162 CopyFromViewport := nil;
4163 if (PreserveDataAcrossUndo <> nil) and
4164 (Name <> '') then
4165 begin
4166 CopyFrom := PreserveDataAcrossUndo.FindComponent(Name);
4167 if CopyFrom is TCastleViewport then // also checks CopyFrom <> nil
4168 begin
4169 CopyFromViewport := TCastleViewport(CopyFrom);
4170 Result := true;
4171 end;
4172 end;
4173 end;
4174
4175 var
4176 Nav: TInternalDesignNavigationType;
4177 InternalDesignNavigationTypeInt: Integer;
4178 CopyFromViewport: TCastleViewport;
4179 AutoNavigation, InternalGridAxisVar: Boolean;
4180 begin
4181 inherited;
4182
4183 { Note: We are not loading/saving design-time params when InternalDesignManipulation=false.
4184
4185 Reason: the instances of design-time cameras/navigation are not even available.
4186
4187 Consequence: This means that loading+saving a design at runtime may result in losing
4188 design-time information. There's no easy way around it. If we would create dummy
4189 instances of InternalDesignCamera just to carry this info, we would waste time/memory
4190 only to support a special case without a certain use-case. }
4191
4192 if InternalDesignManipulation then
4193 begin
4194 if CopyDesignDataFromViewport(SerializationProcess.InternalPreserveDataAcrossUndo, CopyFromViewport) then
4195 begin
4196 { This copies the same things that are (de)serialized below when
4197 CopyDesignDataFromViewport returns false. }
4198 InternalAssignUsingSerialization(InternalDesignCamera, CopyFromViewport.InternalDesignCamera);
4199 InternalDesignNavigationType := CopyFromViewport.InternalDesignNavigationType;
4200 for Nav := Low(Nav) to High(Nav) do
4201 InternalAssignUsingSerialization(FInternalDesignNavigations[Nav],
4202 CopyFromViewport.FInternalDesignNavigations[Nav]);
4203 InternalGridAxis := CopyFromViewport.InternalGridAxis;
4204 end else
4205 begin
4206 { We want to serialize
4207 - camera pos,dir,up
4208 - projection properties, changed by TDesignFrame.CameraSynchronize
4209 }
4210 SerializationProcess.ReadWriteSubComponent('InternalDesignCamera', InternalDesignCamera, true);
4211 InternalGridAxisVar := InternalGridAxis;
4212 SerializationProcess.ReadWriteBoolean('InternalGridAxis', InternalGridAxisVar,
4213 InternalGridAxis <> DefaultInternalGridAxis);
4214 InternalGridAxis := InternalGridAxisVar;
4215
4216 InternalDesignNavigationTypeInt := Ord(InternalDesignNavigationType);
4217 SerializationProcess.ReadWriteInteger('InternalDesignNavigationType',
4218 InternalDesignNavigationTypeInt,
4219 InternalDesignNavigationType <> DefaultInternalDesignNavigationType);
4220 InternalDesignNavigationType := TInternalDesignNavigationType(InternalDesignNavigationTypeInt);
4221
4222 for Nav := Low(Nav) to High(Nav) do
4223 SerializationProcess.ReadWriteSubComponent('InternalDesignNavigations[' +
4224 GetEnumName(TypeInfo(TInternalDesignNavigationType), Ord(Nav)) + ']',
4225 FInternalDesignNavigations[Nav], true);
4226 end;
4227 end;
4228
4229 AutoNavigation := false;
4230 SerializationProcess.ReadWriteBoolean('AutoNavigation', AutoNavigation, false);
4231 if AutoNavigation then
4232 begin
4233 WritelnWarning('Viewport named "%s" uses AutoNavigation, this is no longer supported. Instead: 1. (Advised) Add explicit navigation instance to viewport. 2. (Eventually, a temporary solution) Use TCastleAutoNavigationViewport.', [
4234 Name
4235 ]);
4236 end;
4237 end;
4238
4239 procedure TCastleViewport.SetDynamicBatching(const Value: Boolean);
4240 begin
4241 if FDynamicBatching <> Value then
4242 begin
4243 FDynamicBatching := Value;
4244 if ShapesRenderer <> nil then
4245 ShapesRenderer.DynamicBatching := Value;
4246 end;
4247 end;
4248
4249 procedure TCastleViewport.SetOcclusionCulling(const Value: Boolean);
4250 begin
4251 if FOcclusionCulling <> Value then
4252 begin
4253 FOcclusionCulling := Value;
4254 if ShapesRenderer <> nil then
4255 ShapesRenderer.OcclusionCulling := Value;
4256 end;
4257 end;
4258
4259 {$define read_implementation_methods}
4260 {$I auto_generated_persistent_vectors/tcastleviewport_persistent_vectors.inc}
4261 {$undef read_implementation_methods}
4262
4263 { TCastleViewportList -------------------------------------------------- }
4264
4265 procedure TCastleViewportList.Notify({$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Value: TCastleViewport;
4266 Action: TCollectionNotification);
4267 begin
4268 inherited;
4269
4270 { Note that SceneManager itself is also on SceneManager.Viewports list,
4271 depending on SceneManager.DefaultViewport value.
4272 Ignore it below, since we don't want to change SceneManager.Items value. }
4273 if Value <> SceneManager then
4274 begin
4275 if Action = cnAdded then
4276 Value.Items := SceneManager.Items
4277 else
4278 // Action in [cnRemoved, cnExtracted]
4279 Value.Items := TCastleRootTransform.Create(Value);
4280 end;
4281 end;
4282
4283 var
4284 R: TRegisteredComponent;
4285 initialization
4286 Input_Interact := TInputShortcut.Create(nil, 'Interact (press, open door)', 'interact', igOther);
4287 Input_Interact.Assign(keyNone, keyNone, '', true, buttonLeft);
4288
4289 R := TRegisteredComponent.Create;
4290 {$warnings off} // using deprecated, to keep reading it from castle-user-interface working
4291 R.ComponentClass := TCastleSceneManager;
4292 {$warnings on}
4293 R.Caption := ['Scene Manager'];
4294 R.IsDeprecated := true;
4295 RegisterSerializableComponent(R);
4296
4297 RegisterSerializableComponent(TCastleTouchNavigation, 'Touch Navigation');
4298
4299 R := TRegisteredComponent.Create;
4300 R.ComponentClass := TCastleViewport;
4301 R.Caption := ['Viewport (3D)'];
4302 R.OnCreate := {$ifdef FPC}@{$endif}TCastleViewport.CreateComponentWithChildren3D;
4303 RegisterSerializableComponent(R);
4304
4305 R := TRegisteredComponent.Create;
4306 R.ComponentClass := TCastleViewport;
4307 R.Caption := ['Viewport (2D)'];
4308 R.OnCreate := {$ifdef FPC}@{$endif}TCastleViewport.CreateComponentWithChildren2D;
4309 RegisterSerializableComponent(R);
4310
4311 InitializeWarmupCache;
4312 end.