Debian Codegraph @

src/transform/castletransform_camera.inc

raw
1 {%MainUnit castletransform.pas}
2 {
3 Copyright 2003-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16 { TCastleCamera and friends. }
17
18 {$ifdef read_interface}
19 { Value of @link(TCastlePerspective.FieldOfViewAxis). }
20 TFieldOfViewAxis = (
21 { @link(TCastlePerspective.FieldOfView)
22 specifies the angle along the smaller viewport axis.
23
24 E.g. on a full-screen viewport, on a typical desktop screen,
25 with a typical panoramic window (wide, not tall),
26 this will determine the vertical axis angle.
27 The horizontal axis will be adjusted following the aspect ratio. }
28 faSmallest,
29 { @link(TCastlePerspective.FieldOfView)
30 specifies the angle along the larger viewport axis.
31 The other axis will be adjusted, following the aspect ratio. }
32 faLargest,
33 { @link(TCastlePerspective.FieldOfView)
34 specifies the angle along the horizontal axis.
35 The vertical axis will be adjusted, following the aspect ratio. }
36 faHorizontal,
37 { @link(TCastlePerspective.FieldOfView)
38 specifies the angle along the vertical axis.
39 The horizontal axis will be adjusted, following the aspect ratio. }
40 faVertical
41 );
42
43 { Subcomponent used in @link(TCastleCamera.Perspective) to set perspective
44 projection parameters.
45
46 Do not create instances of this class yourself,
47 these are automatically created by TCastleCamera. }
48 TCastlePerspective = class(TCastleComponent)
49 strict private
50 FFieldOfView: Single;
51 FFieldOfViewAxis: TFieldOfViewAxis;
52 FEffectiveFieldOfView: TVector2;
53 procedure SetFieldOfView(const Value: Single);
54 procedure SetFieldOfViewAxis(const Value: TFieldOfViewAxis);
55 function IsStoredFieldOfView: Boolean;
56 private
57 Camera: TCastleCamera;
58 // @exclude
59 procedure InternalSetEffectiveFieldOfView(const AEffectiveFieldOfView: TVector2);
60 public
61 const
62 DefaultFieldOfView = Pi / 4;
63 DefaultFieldOfViewAxis = faSmallest;
64
65 constructor Create(AOwner: TComponent); override;
66 function PropertySections(const PropertyName: String): TPropertySections; override;
67
68 { Effective field of view, horizontal and vertical, in radians.
69 Calculated looking at @link(FieldOfView) and @link(FieldOfViewAxis),
70 taking into account sizes of the viewport using this camera. }
71 property EffectiveFieldOfView: TVector2 read FEffectiveFieldOfView;
72 published
73 { Perspective field of view angle, in radians.
74 The @link(FieldOfViewAxis) determines whether this is horizontal
75 or vertical angle. }
76 property FieldOfView: Single read FFieldOfView write SetFieldOfView
77 stored IsStoredFieldOfView {$ifdef FPC}default DefaultFieldOfView{$endif};
78
79 { Which axis is determined explicitly by @link(FieldOfView).
80 @seealso TFieldOfViewAxis }
81 property FieldOfViewAxis: TFieldOfViewAxis
82 read FFieldOfViewAxis write SetFieldOfViewAxis default DefaultFieldOfViewAxis;
83 end;
84
85 { Subcomponent used in @link(TCastleCamera.Orthographic) to set orthographic
86 projection parameters.
87
88 Do not create instances of this class yourself,
89 these are automatically created by TCastleCamera. }
90 TCastleOrthographic = class(TCastleComponent)
91 strict private
92 FOrigin: TVector2;
93 FWidth, FHeight, FScale: Single;
94 FEffectiveRect: TFloatRectangle;
95 FStretch, WarningEffectiveSizeZeroDone: Boolean;
96 procedure SetOrigin(const Value: TVector2);
97 procedure SetWidth(const Value: Single);
98 procedure SetHeight(const Value: Single);
99 procedure SetScale(const Value: Single);
100 procedure SetStretch(const Value: Boolean);
101 private
102 Camera: TCastleCamera;
103 // @exclude
104 procedure InternalSetEffectiveRect(const AEffectiveRect: TFloatRectangle);
105 public
106 constructor Create(AOwner: TComponent); override;
107 destructor Destroy; override;
108 function PropertySections(const PropertyName: String): TPropertySections; override;
109 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
110
111 { Additional translation of the camera.
112 The camera movement applied here is always scaled by
113 the calculated orthographic projection width and height.
114
115 By default this equals (0,0) which means that @link(TCastleTransform.Translation Camera.Translation)
116 determines what is visible in the left-bottom corner of the viewport.
117 This matches the typical 2D drawing coordinates used throughout our engine.
118 In other words, if the camera is at position (0,0,whatever),
119 then the (0,0) position in 2D is in the left-bottom corner of the TCastleViewport.
120
121 You can change it e.g. to (0.5,0.5) to move the camera to
122 the middle of the viewport.
123 In effect, if the camera is at position (0,0,whatever),
124 then the (0,0) position is in the center of the TCastleViewport.
125
126 Both values of @name make sense,
127 it depends on the game type and how you prefer to think in 2D coordinates.
128 And how do you want the result to behave when aspect ratio changes:
129
130 @unorderedList(
131 @item(With (0.5,0.5), things will stay "glued"
132 to the center.)
133 @item(With (0,0), things will stay "glued"
134 to the left-bottom corner.)
135 )
136 }
137 property Origin: TVector2 read FOrigin write SetOrigin;
138
139 { Currently used projection dimensions,
140 calculated following the algorithm described at @link(Width) and @link(Height),
141 taking into account sizes of the viewport using this camera. }
142 property EffectiveRect: TFloatRectangle read FEffectiveRect;
143 function EffectiveWidth: Single; deprecated 'use EffectiveRect.Width';
144 function EffectiveHeight: Single; deprecated 'use EffectiveRect.Height';
145
146 { Scales the projection size derived from @link(Width) and @link(Height).
147
148 The effect of this scale is also affected by the @link(Origin).
149 When @link(Origin) is zero, this behaves like scaling around left-bottom corner
150 of the viewport.
151 When @link(Origin) is (0.5,0.5), this behaves like scaling around
152 the middle of the viewport. }
153 property Scale: Single read FScale write SetScale {$ifdef FPC}default 1{$endif};
154 {$ifdef FPC} deprecated 'just multiply Width or Height instead of using this'; {$endif}
155
156 { Allow non-proportional stretch of projection.
157 In effect the @link(Width) and @link(Height)
158 (if both non-zero) are applied directly, without correcting them to follow
159 aspect ratio of the viewport. }
160 property Stretch: Boolean read FStretch write SetStretch default false;
161 {$ifdef FPC} experimental; {$endif}
162 published
163 { Orthographic projection width and height.
164
165 You can leave one or both of them as zero (default) to automatically
166 calculate effective projection width and height
167 (in @link(EffectiveWidth) and @link(EffectiveHeight)):
168
169 @unorderedList(
170 @item(When both @link(Width) and @link(Height) are zero,
171 then the effective projection width and height
172 are based on the viewport width and height.
173 That is, they will follow
174 @link(TCastleUserInterface.EffectiveWidth TCastleViewport.EffectiveWidth)
175 and
176 @link(TCastleUserInterface.EffectiveHeight TCastleViewport.EffectiveHeight).
177 )
178
179 @item(When exactly one of @link(Width) and @link(Height) is non-zero,
180 then it explicitly determines the projection width or height accordingly.
181 This allows to easily display the same piece of the game world,
182 regardless of the viewport size.
183
184 The other size is then calculated to follow the aspect ratio
185 of the viewport control.
186 )
187
188 @item(When both @link(Width) and @link(Height) are non-zero,
189 they determine the projection width and height following the algorithm outlined below.
190 This also allows to easily display the same piece of the game world,
191 regardless of the viewport size.
192
193 @unorderedList(
194 @item(When @link(Stretch) = @false (default), they determine the @italic(minimum)
195 projection width and height along the given axis.
196
197 If the displayed viewport aspect ratio will be different than given
198 @link(Width) and @link(Height) ratio, then these values will be
199 treated as minimum values, and they will be adjusted (one of them will be increased)
200 for the purposes of rendering.
201 You can read the @link(EffectiveWidth), @link(EffectiveHeight) to know
202 the adjusted values.
203
204 Note that the @link(TCastleTransform.Translation Camera.Translation) is considered to be relative
205 to unadjusted @link(Width) and @link(Height), not to the adjusted
206 @link(EffectiveWidth), @link(EffectiveHeight).
207 In effect, when @link(Origin) is zero, the @link(TCastleTransform.Translation Camera.Translation) does not point
208 to the left-bottom of the whole viewport.
209 It points to the left-bottom of the rectangle of aspect ratio
210 @link(Width) / @link(Height) within the viewport.
211 This way the enlarged viewport shows equal amount of additional space on the left and
212 the right (or bottom and top) of the @link(Width) / @link(Height) rectangle within.
213 )
214
215 @item(When @link(Stretch) = @true, these values are used directly,
216 even if it means that aspect ratio of the projection
217 will not reflect the aspect ratio of the viewport on screen.
218
219 This allows to implement some tricks, like @italic(Military Projection),
220 https://github.com/castle-engine/castle-engine/issues/290 .)
221 )
222 )
223 )
224
225 In all the cases, the resulting size is also multiplied by @link(Scale),
226 by default 1.0.
227
228 You can read @link(EffectiveWidth) and @link(EffectiveHeight)
229 to learn the actual projection width and height, calculated using
230 the above algorithm.
231
232 @groupBegin }
233 property Width: Single read FWidth write SetWidth {$ifdef FPC}default 0{$endif};
234 property Height: Single read FHeight write SetHeight {$ifdef FPC}default 0{$endif};
235 { @groupEnd }
236
237 {$define read_interface_class}
238 {$I auto_generated_persistent_vectors/tcastleorthographic_persistent_vectors.inc}
239 {$undef read_interface_class}
240 end;
241
242 { Camera determines viewer position and orientation in the viewport.
243
244 You can create instances of this class yourself,
245 and add them to @link(TCastleViewport.Items),
246 and set them as @link(TCastleViewport.Camera).
247
248 Note that this class does not handle any user input to modify the camera.
249 For this, see TCastleNavigation descendants. }
250 TCastleCamera = class(TCastleTransform)
251 strict private
252 FGravityUp: TVector3;
253 FProjectionMatrix: TMatrix4;
254 FProjectionNear, FProjectionFar: Single;
255 FEffectiveProjectionNear, FEffectiveProjectionFar: Single;
256 FProjectionType: TProjectionType;
257
258 FAnimation: boolean;
259 AnimationEndTime: TFloatTime;
260 AnimationCurrentTime: TFloatTime;
261
262 AnimationBeginPosition: TVector3;
263 AnimationBeginDirection: TVector3;
264 AnimationBeginUp: TVector3;
265 AnimationEndPosition: TVector3;
266 AnimationEndDirection: TVector3;
267 AnimationEndUp: TVector3;
268
269 FFrustum: TFrustum;
270 FPerspective: TCastlePerspective;
271 FOrthographic: TCastleOrthographic;
272
273 FGizmoCoord: TObject; //< This is TCoordinateNode but we cannot declare it as such
274 LastGizmoEffectiveProjectionNear: Single;
275 LastGizmoEffectiveProjectionFar: Single;
276 LastGizmoEffectiveRect: TFloatRectangle;
277 LastGizmoEffectiveFov: TVector2;
278
279 procedure CommonCreate(const AOwner: TComponent; const AShowGizmo: Boolean);
280 procedure RecalculateFrustum;
281 procedure SetGravityUp(const Value: TVector3);
282 procedure UpdateGizmoCoord;
283
284 { Setter of the @link(ProjectionMatrix) property. }
285 procedure SetProjectionMatrix(const Value: TMatrix4);
286
287 procedure SetProjectionNear(const Value: Single);
288 procedure SetProjectionFar(const Value: Single);
289 procedure SetProjectionType(const Value: TProjectionType);
290 private
291 procedure VisibleParameterChange;
292 // @exclude
293 procedure InternalSetEffectiveProjection(
294 const AEffectiveProjectionNear, AEffectiveProjectionFar: Single);
295 public
296 InternalOnSceneBoundViewpointChanged,
297 InternalOnSceneBoundViewpointVectorsChanged,
298 InternalOnSceneBoundNavigationInfoChanged,
299 InternalOnCameraChanged: TNotifyEvent;
300
301 constructor Create(AOwner: TComponent); override;
302 { @exclude Create camera that doesn't show any gizmo in CGE editor. }
303 constructor InternalCreateNonDesign(const AOwner: TComponent; const Ignored: Integer);
304 destructor Destroy; override;
305 procedure Assign(Source: TPersistent); override;
306 function PropertySections(const PropertyName: String): TPropertySections; override;
307 procedure DesignerInfo(const SList: TStrings); override;
308 procedure LocalRender(const Params: TRenderParams); override;
309 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
310
311 { "Up" direction of the world in which player moves.
312 Always normalized (when setting this property, we take
313 care to normalize the provided vector).
314
315 This determines in which direction @link(TCastleWalkNavigation.Gravity) works.
316
317 This is also the "normal" value for "up" vector in world coordinates.
318 Navigation uses it, e.g. features like PreferGravityUpForRotations
319 and/or PreferGravityUpForMoving.
320
321 The default value of this vector is (0, 1, 0) (same as the default
322 @link(Up) vector). }
323 property GravityUp: TVector3 read FGravityUp write SetGravityUp;
324
325 { Camera matrix, transforming from world space into camera space. }
326 function Matrix: TMatrix4;
327
328 { Inverse of @link(Matrix), transforming from camera space into world space. }
329 function MatrixInverse: TMatrix4;
330
331 { Extract only rotation from your current camera @link(Matrix).
332 This is useful for rendering skybox in 3D programs
333 (e.g. for VRML/X3D Background node) and generally to transform
334 directions between world and camera space.
335
336 It's guaranteed that this is actually only 3x3 matrix,
337 the 4th row and 4th column are all zero except the lowest right item
338 which is 1.0. }
339 function RotationMatrix: TMatrix4;
340
341 { The current camera (viewing frustum, based on
342 @link(ProjectionMatrix) (set by you) and @link(Matrix) (calculated here).
343 This is recalculated whenever one of these two properties change.
344 Be sure to set @link(ProjectionMatrix) before using this. }
345 property Frustum: TFrustum read FFrustum;
346
347 { Projection matrix of the camera.
348 Camera needs to know this to calculate @link(Frustum),
349 which in turn allows rendering code to use frustum culling.
350
351 In normal circumstances, if you use @link(TCastleViewport) for rendering,
352 this is automatically correctly set for you. }
353 property ProjectionMatrix: TMatrix4
354 read FProjectionMatrix write SetProjectionMatrix;
355
356 { Calculate a ray picked by WindowPosition position on the viewport,
357 assuming current viewport dimensions are as given.
358 This doesn't look at our container sizes at all.
359
360 Projection (read-only here) describe projection,
361 required for calculating the ray properly.
362
363 Resulting RayDirection is always normalized.
364
365 WindowPosition is given in the same style as TCastleContainer.MousePosition:
366 (0, 0) is bottom-left. }
367 procedure CustomRay(
368 const ViewportRect: TFloatRectangle;
369 const WindowPosition: TVector2;
370 const Projection: TProjection;
371 out RayOrigin, RayDirection: TVector3);
372
373 { Animate a camera smoothly into another camera settings.
374 This will gradually change our settings (position, direction, up)
375 to match the target vectors (in world coordinate space).
376
377 If you use overload with OtherCamera:
378 Current OtherCamera settings will be internally copied during this call.
379 So you can even free OtherCamera instance immediately after calling this.
380
381 Calling AnimateTo while the previous animation didn't finish yet
382 is OK. This simply cancels the previous animation,
383 and starts the new animation from the current position.
384
385 Check @link(Animation) to see if we're currently during the camera
386 animation.
387
388 @groupBegin }
389 procedure AnimateTo(const OtherCamera: TCastleCamera;
390 const Time: TFloatTime); overload;
391 procedure AnimateTo(const APos, ADir, AUp: TVector3;
392 const Time: TFloatTime); overload;
393 { @groupEnd }
394
395 { Are we currently during animation (caused by @link(AnimateTo)). }
396 function Animation: boolean;
397
398 procedure Init(const AInitialPosition, AInitialDirection, AInitialUp,
399 AGravityUp: TVector3); deprecated 'use SetWorldView, set GravityUp directly';
400
401 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
402
403 { Currently used projection near.
404 Derived from @link(ProjectionNear) and possibly scene sizes. }
405 function EffectiveProjectionNear: Single;
406
407 { Currently used projection far.
408 Derived from @link(ProjectionFar) and possibly scene sizes.
409 May be equal ZFarInfinity. }
410 function EffectiveProjectionFar: Single;
411
412 procedure VisibleChangeHere(const Changes: TVisibleChanges); override;
413
414 property Orientation default TCastleTransform.DefaultCameraOrientation;
415
416 { Calculate current projection based on this camera parameters and viewport
417 sizes and update EffectiveXxx properties like EffectiveProjectionNear,
418 EffectiveProjectionFar.
419
420 Note that we get TBox3D as an event, we only use it if necessary (usually
421 not necessary).
422
423 @exclude }
424 function InternalProjection(
425 const BoxWithoutGizmosEvent, BoxWithGizmosEvent: TBox3DEvent;
426 const ViewportWidth, ViewportHeight: Single;
427 const DesignCamera: Boolean): TProjection; virtual;
428 published
429 { Projection near plane distance.
430
431 0 (default) means to automatically calculate a correct value.
432 Note that automatic calculation differs between
433 perspective projection (uses DefaultCameraRadius, RadiusToProjectionNear for near,
434 and infinity for far)
435 and orthographic projection (adjusts to scene sizes and distance from camera).
436
437 For perspective projection, values <= 0 are invalid.
438 So both value = 0 and value < 0 behave the same:
439 they indicate we should automatically calculate the effective ProjectionNear.
440
441 For orthographic projection, all values are valid and reasonable.
442 So value < 0 is just used literally,
443 it doesn't cause the effective value to be autocalculated. }
444 property ProjectionNear: Single read FProjectionNear write SetProjectionNear {$ifdef FPC}default 0{$endif};
445
446 { Projection far plane distance.
447
448 0 (default) means to automatically calculate a correct value.
449 Note that automatic calculation differs between
450 perspective projection (uses DefaultCameraRadius, RadiusToProjectionNear for near,
451 and infinity for far)
452 and orthographic projection (adjusts to scene sizes and distance from camera). }
453 property ProjectionFar: Single read FProjectionFar write SetProjectionFar {$ifdef FPC}default 0{$endif};
454
455 { Perspective or orthographic projection.
456 Depending on it, we either use @link(Perspective) or @link(Orthographic) settings. }
457 property ProjectionType: TProjectionType
458 read FProjectionType write SetProjectionType default ptPerspective;
459
460 { Perspective projection properties, used only if @link(ProjectionType) is ptPerspective. }
461 property Perspective: TCastlePerspective read FPerspective;
462
463 { Orthographic projection properties, used only if @link(ProjectionType) is ptOrthographic. }
464 property Orthographic: TCastleOrthographic read FOrthographic;
465
466 {$define read_interface_class}
467 {$I auto_generated_persistent_vectors/tcastlecamera_persistent_vectors.inc}
468 {$undef read_interface_class}
469 end;
470
471 {$endif read_interface}
472
473 {$ifdef read_implementation}
474
475 { TCastlePerspective --------------------------------------------------------- }
476
477 constructor TCastlePerspective.Create(AOwner: TComponent);
478 begin
479 inherited;
480 FFieldOfView := DefaultFieldOfView;
481 FFieldOfViewAxis := DefaultFieldOfViewAxis;
482 end;
483
484 procedure TCastlePerspective.SetFieldOfView(const Value: Single);
485 begin
486 if FFieldOfView <> Value then
487 begin
488 FFieldOfView := Value;
489 Camera.VisibleParameterChange;
490 end;
491 end;
492
493 procedure TCastlePerspective.SetFieldOfViewAxis(const Value: TFieldOfViewAxis);
494 begin
495 if FFieldOfViewAxis <> Value then
496 begin
497 FFieldOfViewAxis := Value;
498 Camera.VisibleParameterChange;
499 end;
500 end;
501
502 procedure TCastlePerspective.InternalSetEffectiveFieldOfView(const AEffectiveFieldOfView: TVector2);
503 begin
504 FEffectiveFieldOfView := AEffectiveFieldOfView;
505 end;
506
507 function TCastlePerspective.IsStoredFieldOfView: Boolean;
508 begin
509 { Seems like this is the only way to avoid always serializing FieldOfView.
510 Possibly displaying it in object inspector always modifies it a bit,
511 due to rounding when displaying?
512 TODO: Is this really necessary still? }
513 Result := not SameValue(FFieldOfView, DefaultFieldOfView);
514 end;
515
516 function TCastlePerspective.PropertySections(const PropertyName: String): TPropertySections;
517 begin
518 if (PropertyName = 'FieldOfView') or
519 (PropertyName = 'FieldOfViewAxis') then
520 Result := [psBasic]
521 else
522 Result := inherited PropertySections(PropertyName);
523 end;
524
525 { TCastleOrthographic --------------------------------------------------------- }
526
527 constructor TCastleOrthographic.Create(AOwner: TComponent);
528 begin
529 inherited;
530 FScale := 1;
531 {$define read_implementation_constructor}
532 {$I auto_generated_persistent_vectors/tcastleorthographic_persistent_vectors.inc}
533 {$undef read_implementation_constructor}
534 end;
535
536 destructor TCastleOrthographic.Destroy;
537 begin
538 {$define read_implementation_destructor}
539 {$I auto_generated_persistent_vectors/tcastleorthographic_persistent_vectors.inc}
540 {$undef read_implementation_destructor}
541 inherited;
542 end;
543
544 procedure TCastleOrthographic.SetOrigin(const Value: TVector2);
545 begin
546 if not TVector2.PerfectlyEquals(FOrigin, Value) then
547 begin
548 FOrigin := Value;
549 Camera.VisibleParameterChange;
550 end;
551 end;
552
553 procedure TCastleOrthographic.SetWidth(const Value: Single);
554 begin
555 if FWidth <> Value then
556 begin
557 FWidth := Value;
558 Camera.VisibleParameterChange;
559 end;
560 end;
561
562 procedure TCastleOrthographic.SetHeight(const Value: Single);
563 begin
564 if FHeight <> Value then
565 begin
566 FHeight := Value;
567 Camera.VisibleParameterChange;
568 end;
569 end;
570
571 procedure TCastleOrthographic.SetScale(const Value: Single);
572 begin
573 if FScale <> Value then
574 begin
575 if Value <= 0 then
576 WritelnWarning('Orthographic projection scale (Camera.Orthographic.Scale) should be > 0, but is being set to %f', [
577 Value
578 ]);
579 FScale := Value;
580 Camera.VisibleParameterChange;
581 end;
582 end;
583
584 procedure TCastleOrthographic.SetStretch(const Value: Boolean);
585 begin
586 if FStretch <> Value then
587 begin
588 FStretch := Value;
589 Camera.VisibleParameterChange;
590 end;
591 end;
592
593 procedure TCastleOrthographic.InternalSetEffectiveRect(const AEffectiveRect: TFloatRectangle);
594 begin
595 if ((AEffectiveRect.Width <= 0) or (AEffectiveRect.Height <= 0)) and (not WarningEffectiveSizeZeroDone) then
596 begin
597 WritelnWarning('Orthographic projection effective width and height (calculated based on Camera.Orthographic.Width,Height,Scale and viewport size) should be > 0, but are %f x %f (further warnings about it will be supressed, to not spam log)', [
598 AEffectiveRect.Width,
599 AEffectiveRect.Height
600 ]);
601 WarningEffectiveSizeZeroDone := true;
602 end;
603 FEffectiveRect := AEffectiveRect;
604 end;
605
606 function TCastleOrthographic.EffectiveWidth: Single;
607 begin
608 Result := FEffectiveRect.Width;
609 end;
610
611 function TCastleOrthographic.EffectiveHeight: Single;
612 begin
613 Result := FEffectiveRect.Height;
614 end;
615
616 function TCastleOrthographic.PropertySections(const PropertyName: String): TPropertySections;
617 begin
618 if (PropertyName = 'Width') or
619 (PropertyName = 'Height') or
620 (PropertyName = 'OriginPersistent') then
621 Result := [psBasic]
622 else
623 Result := inherited PropertySections(PropertyName);
624 end;
625
626 procedure TCastleOrthographic.CustomSerialization(const SerializationProcess: TSerializationProcess);
627 var
628 ScaleValue: Single;
629 begin
630 inherited;
631 ScaleValue := 1;
632 SerializationProcess.ReadWriteSingle('Scale', ScaleValue, false);
633
634 { Scale property is not published anymore, we read it in CustomSerialization
635 and apply by multiplying Width / Height.
636
637 Note that we rely on the fact that CustomSerialization is done
638 after reading all published properties, so Width and Height are already surely read from design file. }
639
640 if not SameValue(ScaleValue, 1.0) then
641 begin
642 if (Width = 0) and (Height = 0) then
643 begin
644 WritelnWarning('Deprecated TCastleOrthographic.Scale value %f will be lost. Set to non-zero TCastleOrthographic.Width or TCastleOrthographic.Height to control the viewport field of view', [
645 ScaleValue
646 ]);
647 end else
648 begin
649 WritelnWarning('Upgrading deprecated TCastleOrthographic.Scale %f to just multiply TCastleOrthographic.Width and TCastleOrthographic.Height. Width x Height: old %f x %f -> new %f x %f.', [
650 ScaleValue,
651 Width,
652 Height,
653 Width * ScaleValue,
654 Height * ScaleValue
655 ]);
656 Width := Width * ScaleValue;
657 Height := Height * ScaleValue;
658 end;
659 end;
660 end;
661
662 {$define read_implementation_methods}
663 {$I auto_generated_persistent_vectors/tcastleorthographic_persistent_vectors.inc}
664 {$undef read_implementation_methods}
665
666 { TCastleCamera -------------------------------------------------------------- }
667
668 constructor TCastleCamera.Create(AOwner: TComponent);
669 begin
670 CommonCreate(AOwner, CastleDesignMode);
671 end;
672
673 constructor TCastleCamera.InternalCreateNonDesign(const AOwner: TComponent; const Ignored: Integer);
674 begin
675 CommonCreate(AOwner, false);
676 end;
677
678 procedure TCastleCamera.CommonCreate(const AOwner: TComponent; const AShowGizmo: Boolean);
679 var
680 Gizmo: TInternalCastleEditorGizmo;
681
682 function BuildGizmo: TX3DRootNode;
683 begin
684 Result := TX3DRootNode.Create;
685 Result.AddChildren(Gizmo.LinesShape(TCoordinateNode(FGizmoCoord)));
686 UpdateGizmoCoord;
687 end;
688
689 begin
690 inherited Create(AOwner);
691
692 { Override orientation, this is more intuitive for cameras. }
693 Orientation := DefaultCameraOrientation;
694
695 FProjectionType := ptPerspective;
696
697 { This is not necessary,
698 as this is actually the effect of default state of TCastleTransform.
699
700 Moreover, this would set Rotation to (0,0,1,0)
701 (because OrientationQuaternionFromDirectionUp uses DefaultUp for axis
702 when there's no need rotation), causing bugs when reading back
703 for serialized JSON. As RotationPersistent.InternalDefaultValue
704 would remain at (0,0,0,0). Thus Z=0 is not saved to JSON (as it's default)
705 but after creation+deserialization Z=1.
706
707 We could workaround it by changing RotationPersistent.InternalDefaultValue,
708 but actually it's easiest to not modify it at all.
709 SetView(
710 TVector3.Zero,
711 DefaultCameraDirection,
712 DefaultCameraUp); }
713
714 FGravityUp := DefaultCameraUp;
715 FProjectionMatrix := TMatrix4.Identity; // any sensible initial value
716 FFrustum.Init(TMatrix4.Identity); // any sensible initial value
717
718 FPerspective := TCastlePerspective.Create(Self);
719 FPerspective.Camera := Self;
720 FPerspective.Name := 'Perspective';
721 FPerspective.SetSubComponent(true);
722
723 FOrthographic := TCastleOrthographic.Create(Self);
724 FOrthographic.Camera := Self;
725 FOrthographic.Name := 'Orthographic';
726 FOrthographic.SetSubComponent(true);
727
728 if AShowGizmo then
729 begin
730 Gizmo := TInternalCastleEditorGizmo.Create(Self);
731 Gizmo.InternalIgnoreParentScale := true;
732 Gizmo.LoadVisualization(BuildGizmo);
733 Gizmo.SelectBoxTranslation := CastleVectors.Vector3(0, 0, -0.5); // matches nicely our visualization set by UpdateGizmoCoord
734 { No need for icon anymore, gizmo is recognizeable enough.
735 And it removes worry about icon size in 2D games, where it would be too small. }
736 // Gizmo.SetIconUrl(InternalCastleDesignData + 'gizmos/camera/camera.png');
737 Add(Gizmo);
738 end;
739
740 {$define read_implementation_constructor}
741 {$I auto_generated_persistent_vectors/tcastlecamera_persistent_vectors.inc}
742 {$undef read_implementation_constructor}
743 end;
744
745 destructor TCastleCamera.Destroy;
746 begin
747 {$define read_implementation_destructor}
748 {$I auto_generated_persistent_vectors/tcastlecamera_persistent_vectors.inc}
749 {$undef read_implementation_destructor}
750 inherited;
751 end;
752
753 procedure TCastleCamera.Assign(Source: TPersistent);
754 var
755 SourceCamera: TCastleCamera;
756 begin
757 if Source is TCastleCamera then
758 begin
759 SourceCamera := TCastleCamera(Source);
760
761 { Copies non-temporary properties (in particular, the published properties). }
762 Translation := SourceCamera.Translation;
763 Rotation := SourceCamera.Rotation;
764 GravityUp := SourceCamera.GravityUp;
765 ProjectionNear := SourceCamera.ProjectionNear;
766 ProjectionFar := SourceCamera.ProjectionFar;
767 ProjectionType := SourceCamera.ProjectionType;
768 Perspective.FieldOfView := SourceCamera.Perspective.FieldOfView;
769 Perspective.FieldOfViewAxis := SourceCamera.Perspective.FieldOfViewAxis;
770 Orthographic.Origin := SourceCamera.Orthographic.Origin;
771 Orthographic.Width := SourceCamera.Orthographic.Width;
772 Orthographic.Height := SourceCamera.Orthographic.Height;
773 end else
774 { Call inherited ONLY when you cannot handle Source class,
775 to raise EConvertError from TPersistent.Assign. }
776 inherited Assign(Source);
777 end;
778
779 procedure TCastleCamera.SetGravityUp(const Value: TVector3);
780 begin
781 FGravityUp := Value.Normalize;
782 end;
783
784 function TCastleCamera.Matrix: TMatrix4;
785 var
786 P, D, U: TVector3;
787 begin
788 GetWorldView(P, D, U);
789 Result := LookDirMatrix(P, D, U);
790 end;
791
792 function TCastleCamera.RotationMatrix: TMatrix4;
793 var
794 P, D, U: TVector3;
795 begin
796 GetWorldView(P, D, U);
797 Result := FastLookDirMatrix(D, U);
798 end;
799
800 function TCastleCamera.MatrixInverse: TMatrix4;
801 begin
802 if not Matrix.TryInverse(Result) then
803 raise Exception.Create('Cannot invert camera matrix, possibly it contains scaling to zero');
804 end;
805
806 procedure TCastleCamera.RecalculateFrustum;
807 begin
808 FFrustum.Init(ProjectionMatrix, Matrix);
809 end;
810
811 procedure TCastleCamera.SetProjectionMatrix(const Value: TMatrix4);
812 begin
813 FProjectionMatrix := Value;
814 RecalculateFrustum;
815 end;
816
817 procedure TCastleCamera.CustomRay(
818 const ViewportRect: TFloatRectangle;
819 const WindowPosition: TVector2;
820 const Projection: TProjection;
821 out RayOrigin, RayDirection: TVector3);
822 var
823 APos, ADir, AUp: TVector3;
824 begin
825 GetWorldView(APos, ADir, AUp);
826
827 PrimaryRay(
828 WindowPosition[0] - ViewportRect.Left,
829 WindowPosition[1] - ViewportRect.Bottom,
830 ViewportRect.Width, ViewportRect.Height,
831 APos, ADir, AUp,
832 Projection,
833 RayOrigin, RayDirection);
834 end;
835
836 procedure TCastleCamera.Init(
837 const AInitialPosition, AInitialDirection, AInitialUp, AGravityUp: TVector3);
838 begin
839 SetWorldView(AInitialPosition, AInitialDirection, AInitialUp);
840 GravityUp := AGravityUp;
841 end;
842
843 procedure TCastleCamera.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
844 begin
845 inherited;
846 if FAnimation then
847 begin
848 AnimationCurrentTime := AnimationCurrentTime + SecondsPassed;
849 if AnimationCurrentTime > AnimationEndTime then
850 begin
851 FAnimation := false;
852 { When animation ended, make sure you're exactly at the final view. }
853 SetWorldView(AnimationEndPosition, AnimationEndDirection, AnimationEndUp);
854 end else
855 begin
856 SetWorldView(
857 Lerp(AnimationCurrentTime / AnimationEndTime, AnimationBeginPosition , AnimationEndPosition),
858 Lerp(AnimationCurrentTime / AnimationEndTime, AnimationBeginDirection, AnimationEndDirection),
859 Lerp(AnimationCurrentTime / AnimationEndTime, AnimationBeginUp , AnimationEndUp));
860 end;
861 end;
862 end;
863
864 procedure TCastleCamera.AnimateTo(const APos, ADir, AUp: TVector3; const Time: TFloatTime);
865 begin
866 GetWorldView(
867 AnimationBeginPosition,
868 AnimationBeginDirection,
869 AnimationBeginUp);
870
871 AnimationEndPosition := APos;
872 AnimationEndDirection := ADir;
873 AnimationEndUp := AUp;
874
875 AnimationEndTime := Time;
876 AnimationCurrentTime := 0;
877 { No point in doing animation (especially since it blocks camera movement
878 for Time seconds) if we're already there. }
879 FAnimation := not (
880 TVector3.Equals(AnimationBeginPosition , AnimationEndPosition) and
881 TVector3.Equals(AnimationBeginDirection, AnimationEndDirection) and
882 TVector3.Equals(AnimationBeginUp , AnimationEndUp));
883 end;
884
885 procedure TCastleCamera.AnimateTo(const OtherCamera: TCastleCamera; const Time: TFloatTime);
886 var
887 APos, ADir, AUp: TVector3;
888 begin
889 OtherCamera.GetWorldView(APos, ADir, AUp);
890 AnimateTo(APos, ADir, AUp, Time);
891 end;
892
893 function TCastleCamera.Animation: boolean;
894 begin
895 Result := FAnimation;
896 end;
897
898 procedure TCastleCamera.SetProjectionNear(const Value: Single);
899 begin
900 if FProjectionNear <> Value then
901 begin
902 FProjectionNear := Value;
903 VisibleParameterChange;
904 end;
905 end;
906
907 procedure TCastleCamera.SetProjectionFar(const Value: Single);
908 begin
909 if FProjectionFar <> Value then
910 begin
911 FProjectionFar := Value;
912 VisibleParameterChange;
913 end;
914 end;
915
916 procedure TCastleCamera.SetProjectionType(const Value: TProjectionType);
917 begin
918 if FProjectionType <> Value then
919 begin
920 FProjectionType := Value;
921 VisibleParameterChange;
922 end;
923 end;
924
925 function TCastleCamera.EffectiveProjectionNear: Single;
926 begin
927 if FEffectiveProjectionNear <> 0 then
928 Exit(FEffectiveProjectionNear);
929
930 { In this case, we can return something valid even before the 1st InternalSetEffectiveProjection call. }
931 if FProjectionNear <> 0 then
932 Result := FProjectionNear
933 else
934 Result := FEffectiveProjectionNear;
935 end;
936
937 function TCastleCamera.EffectiveProjectionFar: Single;
938 begin
939 if FEffectiveProjectionFar <> 0 then
940 Exit(FEffectiveProjectionFar);
941
942 { In this case, we can return something valid even before the 1st InternalSetEffectiveProjection call. }
943 if FProjectionFar <> 0 then
944 Result := FProjectionFar
945 else
946 Result := FEffectiveProjectionFar;
947 end;
948
949 procedure TCastleCamera.InternalSetEffectiveProjection(
950 const AEffectiveProjectionNear, AEffectiveProjectionFar: Single);
951 begin
952 FEffectiveProjectionNear := AEffectiveProjectionNear;
953 FEffectiveProjectionFar := AEffectiveProjectionFar;
954 end;
955
956 function TCastleCamera.PropertySections(const PropertyName: String): TPropertySections;
957 begin
958 if ArrayContainsString(PropertyName, [
959 'GravityUpPersistent',
960 'ProjectionFar', 'ProjectionNear', 'ProjectionType',
961 'Orthographic', 'Perspective'
962 ]) then
963 Result := [psBasic]
964 else
965
966 { Bad idea to move it to "Layout" only for camera -
967 as Direction, Up are on all TCastleTransform,
968 including on camera's parent transformations,
969 and then make sense there.
970
971 if ArrayContainsString(PropertyName, [
972 'DirectionPersistent', 'UpPersistent'
973 ]) then
974 Result := [psLayout]
975 else
976 }
977
978 Result := inherited PropertySections(PropertyName);
979 end;
980
981 procedure TCastleCamera.CustomSerialization(const SerializationProcess: TSerializationProcess);
982 const
983 DefaultCameraPosition: TVector3 = (X: 0; Y: 0; Z: 0);
984 var
985 InitialPosition, InitialDirection, InitialUp: TVector3;
986 begin
987 inherited;
988
989 { Support old designs, before new-cameras branch, with old camera properties. }
990
991 InitialPosition := DefaultCameraPosition;
992 InitialDirection := DefaultCameraDirection;
993 InitialUp := DefaultCameraUp;
994
995 SerializationProcess.ReadWriteVector('InitialPositionPersistent', InitialPosition, DefaultCameraPosition, false);
996 SerializationProcess.ReadWriteVector('InitialDirectionPersistent', InitialDirection, DefaultCameraDirection, false);
997 SerializationProcess.ReadWriteVector('InitialUpPersistent', InitialUp, DefaultCameraUp, false);
998
999 { Apply deprecated InitialXxx props only if they have been modified by the design.
1000 Otherwise, they would override the values read
1001 from non-deprecated Translation and Rotation. }
1002 if (not TVector3.PerfectlyEquals(InitialPosition, DefaultCameraPosition)) or
1003 (not TVector3.PerfectlyEquals(InitialDirection, DefaultCameraDirection)) or
1004 (not TVector3.PerfectlyEquals(InitialUp, DefaultCameraUp)) then
1005 begin
1006 { Old cameras with InitialPosition/Direction/Up could not be a child
1007 of some TCastleTransform.
1008 Does it matter if we use SetView or SetWorldView here?
1009 Only when Viewport.Items had some transformation. }
1010 SetWorldView(InitialPosition, InitialDirection, InitialUp);
1011 end;
1012 end;
1013
1014 procedure TCastleCamera.VisibleParameterChange;
1015 begin
1016 { What to do when camera parameter, like projection fov, changes?
1017 For now we just cause vcVisibleGeometry because we just want to cause
1018 InternalOnCameraChanged. }
1019 VisibleChangeHere([vcVisibleGeometry]);
1020 end;
1021
1022 procedure TCastleCamera.VisibleChangeHere(const Changes: TVisibleChanges);
1023 begin
1024 inherited;
1025
1026 { When e.g. Translation of camera changes, make sure to call InternalOnCameraChanged.
1027 This way e.g. CGE editor gizmo is updated when we get closer/further to it. }
1028 if vcVisibleGeometry in Changes then
1029 if Assigned(InternalOnCameraChanged) then
1030 InternalOnCameraChanged(Self);
1031 end;
1032
1033 procedure TCastleCamera.UpdateGizmoCoord;
1034 const
1035 { Camera plane is shown at EffectiveProjectionNear,
1036 unless it is smaller than this. }
1037 PerspectiveMinDistanceToPlane = 1;
1038 UpArrowSize = 0.1; // fraction of upper plane line to take for arrow
1039 var
1040 PlaneMinPoints, PlaneMaxPoints: array [0..3] of TVector3;
1041 UpArrowPoints: array [0..2] of TVector3;
1042 PerspX, PerspY, PlaneMinZ, PlaneMaxZ: Single;
1043 I: Integer;
1044 begin
1045 { We use LastXxx to avoid repeating this calculation, and updating gizmo points,
1046 every frame. In practice gizmo changes seldom -- e.g. if camera params change
1047 or viewport sizes change. }
1048 if (LastGizmoEffectiveProjectionNear <> EffectiveProjectionNear) or
1049 (LastGizmoEffectiveProjectionFar <> EffectiveProjectionFar) or
1050 (not LastGizmoEffectiveRect.PerfectlyEquals(Orthographic.EffectiveRect)) or
1051 (not TVector2.PerfectlyEquals(LastGizmoEffectiveFov, Perspective.EffectiveFieldOfView)) then
1052 begin
1053 LastGizmoEffectiveProjectionNear := EffectiveProjectionNear;
1054 LastGizmoEffectiveProjectionFar := EffectiveProjectionFar;
1055 LastGizmoEffectiveRect := Orthographic.EffectiveRect;
1056 LastGizmoEffectiveFov := Perspective.EffectiveFieldOfView;
1057
1058 { calculate 4 PlaneMinPoints }
1059 case ProjectionType of
1060 ptOrthographic:
1061 begin
1062 PlaneMinZ := -EffectiveProjectionNear;
1063 PlaneMaxZ := -EffectiveProjectionFar;
1064
1065 PlaneMinPoints[0] := CastleVectors.Vector3(Orthographic.EffectiveRect.Left , Orthographic.EffectiveRect.Bottom, PlaneMinZ);
1066 PlaneMinPoints[1] := CastleVectors.Vector3(Orthographic.EffectiveRect.Right, Orthographic.EffectiveRect.Bottom, PlaneMinZ);
1067 PlaneMinPoints[2] := CastleVectors.Vector3(Orthographic.EffectiveRect.Right, Orthographic.EffectiveRect.Top , PlaneMinZ);
1068 PlaneMinPoints[3] := CastleVectors.Vector3(Orthographic.EffectiveRect.Left , Orthographic.EffectiveRect.Top , PlaneMinZ);
1069 end;
1070 ptPerspective:
1071 begin
1072 PlaneMinZ := -Max(EffectiveProjectionNear, PerspectiveMinDistanceToPlane);
1073 // PlaneMaxZ is unused with ptPerspective for now
1074 PlaneMaxZ := -EffectiveProjectionFar;
1075
1076 PerspX := Tan(Perspective.EffectiveFieldOfView.X / 2) * Abs(PlaneMinZ);
1077 PerspY := Tan(Perspective.EffectiveFieldOfView.Y / 2) * Abs(PlaneMinZ);
1078 PlaneMinPoints[0] := CastleVectors.Vector3(-PerspX, -PerspY, PlaneMinZ);
1079 PlaneMinPoints[1] := CastleVectors.Vector3( PerspX, -PerspY, PlaneMinZ);
1080 PlaneMinPoints[2] := CastleVectors.Vector3( PerspX, PerspY, PlaneMinZ);
1081 PlaneMinPoints[3] := CastleVectors.Vector3(-PerspX, PerspY, PlaneMinZ);
1082 end;
1083 {$ifndef COMPILER_CASE_ANALYSIS}
1084 else raise EInternalError.Create('TCastleCamera.UpdateGizmoCoord:ProjectionType?');
1085 {$endif}
1086 end;
1087
1088 { calculate PlaneMaxPoints }
1089 for I := 0 to High(PlaneMaxPoints) do
1090 begin
1091 PlaneMaxPoints[I] := PlaneMinPoints[I];
1092 PlaneMaxPoints[I].Z := PlaneMaxZ;
1093 end;
1094
1095 { calculate 3 UpArrowPoints }
1096 UpArrowPoints[0] := CastleVectors.Vector3(Lerp(0.5 - UpArrowSize, PlaneMinPoints[3].X, PlaneMinPoints[2].X), PlaneMinPoints[3].Y, PlaneMinZ);
1097 UpArrowPoints[2] := CastleVectors.Vector3(Lerp(0.5 + UpArrowSize, PlaneMinPoints[3].X, PlaneMinPoints[2].X), PlaneMinPoints[3].Y, PlaneMinZ);
1098 UpArrowPoints[1] := CastleVectors.Vector3(Lerp(0.5 , PlaneMinPoints[3].X, PlaneMinPoints[2].X),
1099 PlaneMinPoints[3].Y + PointsDistance(UpArrowPoints[0], UpArrowPoints[2]) / 2,
1100 PlaneMinZ);
1101
1102 { call FGizmoCoord.SetPoint }
1103 case ProjectionType of
1104 ptOrthographic:
1105 begin
1106 TCoordinateNode(FGizmoCoord).SetPoint([
1107 // rect at PlaneMinZ
1108 PlaneMinPoints[0], PlaneMinPoints[1],
1109 PlaneMinPoints[1], PlaneMinPoints[2],
1110 PlaneMinPoints[2], PlaneMinPoints[3],
1111 PlaneMinPoints[3], PlaneMinPoints[0],
1112
1113 // rect at PlaneMaxZ
1114 PlaneMaxPoints[0], PlaneMaxPoints[1],
1115 PlaneMaxPoints[1], PlaneMaxPoints[2],
1116 PlaneMaxPoints[2], PlaneMaxPoints[3],
1117 PlaneMaxPoints[3], PlaneMaxPoints[0],
1118
1119 // connect rects from PlaneMinZ to PlaneMaxZ
1120 PlaneMinPoints[0], PlaneMaxPoints[0],
1121 PlaneMinPoints[1], PlaneMaxPoints[1],
1122 PlaneMinPoints[2], PlaneMaxPoints[2],
1123 PlaneMinPoints[3], PlaneMaxPoints[3],
1124
1125 // arrow at PlaneMinZ
1126 UpArrowPoints[0], UpArrowPoints[1],
1127 UpArrowPoints[1], UpArrowPoints[2]
1128 ]);
1129 end;
1130 ptPerspective:
1131 begin
1132 TCoordinateNode(FGizmoCoord).SetPoint([
1133 // 4 lines connecting camera position -> rect at PlaneMinZ
1134 TVector3.Zero, PlaneMinPoints[0],
1135 TVector3.Zero, PlaneMinPoints[1],
1136 TVector3.Zero, PlaneMinPoints[2],
1137 TVector3.Zero, PlaneMinPoints[3],
1138
1139 // rect at PlaneMinZ
1140 PlaneMinPoints[0], PlaneMinPoints[1],
1141 PlaneMinPoints[1], PlaneMinPoints[2],
1142 PlaneMinPoints[2], PlaneMinPoints[3],
1143 PlaneMinPoints[3], PlaneMinPoints[0],
1144
1145 // arrow at PlaneMinZ
1146 UpArrowPoints[0], UpArrowPoints[1],
1147 UpArrowPoints[1], UpArrowPoints[2]
1148 ]);
1149 end;
1150 {$ifndef COMPILER_CASE_ANALYSIS}
1151 else raise EInternalError.Create('TCastleCamera.UpdateGizmoCoord:ProjectionType 2?');
1152 {$endif}
1153 end;
1154 end;
1155 end;
1156
1157 function TCastleCamera.InternalProjection(
1158 const BoxWithoutGizmosEvent, BoxWithGizmosEvent: TBox3DEvent;
1159 const ViewportWidth, ViewportHeight: Single;
1160 const DesignCamera: Boolean): TProjection;
1161
1162 { Update Result.Dimensions and Orthographic.EffectiveXxx
1163 based on Orthographic.Width, Height and viewport size. }
1164 procedure UpdateOrthographicDimensions;
1165 var
1166 EffectiveProjectionWidth, EffectiveProjectionHeight: Single;
1167
1168 procedure CalculateDimensions;
1169 begin
1170 { Apply Orthographic.Scale here,
1171 this way it scales around Origin (e.g. around middle, when Origin is 0.5,0.5) }
1172 {$warnings off} // using deprecated to keep it working
1173 EffectiveProjectionWidth := EffectiveProjectionWidth * Orthographic.Scale;
1174 EffectiveProjectionHeight := EffectiveProjectionHeight * Orthographic.Scale;
1175 {$warnings on}
1176
1177 Result.Dimensions.Width := EffectiveProjectionWidth;
1178 Result.Dimensions.Height := EffectiveProjectionHeight;
1179 Result.Dimensions.Left := - Orthographic.Origin.X * EffectiveProjectionWidth;
1180 Result.Dimensions.Bottom := - Orthographic.Origin.Y * EffectiveProjectionHeight;
1181 end;
1182
1183 begin
1184 if (Orthographic.Width = 0) and
1185 (Orthographic.Height = 0) then
1186 begin
1187 EffectiveProjectionWidth := ViewportWidth;
1188 EffectiveProjectionHeight := ViewportHeight;
1189 CalculateDimensions;
1190 end else
1191 if Orthographic.Width = 0 then
1192 begin
1193 EffectiveProjectionWidth := Orthographic.Height * ViewportWidth / ViewportHeight;
1194 EffectiveProjectionHeight := Orthographic.Height;
1195 CalculateDimensions;
1196 end else
1197 if Orthographic.Height = 0 then
1198 begin
1199 EffectiveProjectionWidth := Orthographic.Width;
1200 EffectiveProjectionHeight := Orthographic.Width * ViewportHeight / ViewportWidth;
1201 CalculateDimensions;
1202 end else
1203 begin
1204 EffectiveProjectionWidth := Orthographic.Width;
1205 EffectiveProjectionHeight := Orthographic.Height;
1206
1207 CalculateDimensions;
1208
1209 {$warnings off} // using experimental to make it working
1210 if not Orthographic.Stretch then
1211 Result.Dimensions := TOrthoViewpointNode.InternalFieldOfView(
1212 Result.Dimensions,
1213 ViewportWidth,
1214 ViewportHeight);
1215 {$warnings on}
1216
1217 EffectiveProjectionWidth := Result.Dimensions.Width;
1218 EffectiveProjectionHeight := Result.Dimensions.Height;
1219 end;
1220
1221 Assert(Result.Dimensions.Width = EffectiveProjectionWidth);
1222 Assert(Result.Dimensions.Height = EffectiveProjectionHeight);
1223
1224 Orthographic.InternalSetEffectiveRect(Result.Dimensions);
1225 end;
1226
1227 procedure GetBoxDistances(out MinBoxDistance, MaxBoxDistance: Single);
1228 var
1229 Box: TBox3D;
1230 Pos, Dir, Up: TVector3;
1231 begin
1232 { Which callback to use to calculate bbox of whole world?
1233
1234 - If this camera has a gizmo (which can happen at design-time
1235 for non-internal cameras) then we have to use BoxWithoutGizmosEvent.
1236 Otherwise camera would account for its own gizmo when trying to
1237 auto-calculate projection near/far, but the gizmo reflects
1238 the new projection near/far, thus the projection near/far would grow
1239 to infinity.
1240
1241 - If this camera does not have gizmo, it may be an internal camera
1242 used for viewing TCastleViewport at design-time.
1243 (It may also be any camera at run-time.)
1244 We should then use BoxWithGizmosEvent, because at design-time
1245 we have to show gizmo of other cameras. }
1246 if FGizmoCoord <> nil then
1247 Box := BoxWithoutGizmosEvent()
1248 else
1249 Box := BoxWithGizmosEvent();
1250
1251 if Box.IsEmpty then
1252 begin
1253 // any values are OK, as we'll not render anyhitng
1254 MinBoxDistance := -10;
1255 MaxBoxDistance := 10;
1256 Exit;
1257 end;
1258 GetWorldView(Pos, Dir, Up);
1259 Box.DirectionDistances(Pos, Dir, MinBoxDistance, MaxBoxDistance);
1260 { Make the range MinBoxDistance...MaxBoxDistance slightly larger,
1261 to avoid cutting things due to imprecision when they lie exactly on the min/max distance.
1262 Testcase: trees in isometric_game when observer sprite has Exists=false. }
1263 MinBoxDistance := MinBoxDistance - 1;
1264 MaxBoxDistance := (MaxBoxDistance + 1) * 1.1;
1265 end;
1266
1267 var
1268 MinBoxDistanceForOrtho, MaxBoxDistanceForOrtho: Single;
1269
1270 { Calculate reasonable perspective projection near. }
1271 function GetDefaultProjectionNear(const CurrentProjectionType: TProjectionType): Single;
1272 var
1273 Radius: Single;
1274 begin
1275 if CurrentProjectionType = ptOrthographic then
1276 begin
1277 Result := MinBoxDistanceForOrtho;
1278 end else
1279 begin
1280 Radius := DefaultCameraRadius;
1281 Result := Radius * RadiusToProjectionNear;
1282 end;
1283 end;
1284
1285 { Calculate reasonable perspective projection far.
1286 May return ZFarInfinity (0). }
1287 function GetDefaultProjectionFar(const CurrentProjectionType: TProjectionType): Single;
1288 //var
1289 //MinBoxDistance, MaxBoxDistance: Single;
1290 begin
1291 if CurrentProjectionType = ptOrthographic then
1292 begin
1293 Result := MaxBoxDistanceForOrtho;
1294
1295 { Note that the design-time camera in 2D should have larger ProjectionFar than
1296 at run-time, to really see everything that runtime sees,
1297 because design-time camera Z is larger than runtime.
1298
1299 But it doesn't require any special code anymore, as we adjust to Box. }
1300 end else
1301 begin
1302 { We used to have a smart calculation of it here, based on Box.
1303 And override with ZFarInfinity if ShadowVolumesPossible (usually true).
1304
1305 But it is simpler to just use ZFarInfinity always:
1306
1307 - It means that ShadowVolumesPossible don't matter,
1308 in particular it doesn't matter whether context has stencil buffer.
1309 This removes often "weird" differences due to subtle differences how
1310 TCastleControl and TCastleWindow initialize OpenGL context, we usually had
1311 ShadowVolumesPossible = false in editor and ShadowVolumesPossible = true
1312 in TCastleWindow. So ProjectionFarFinite was only observed in editor.
1313
1314 - Minor reason: It avoids the need to calculate Viewport.ItemsBoundingBox
1315 at each frame, at least for the purpose of automatic projection
1316 for ProjectionFar for perspective.
1317 It was never observed in profiler,
1318 but in theory Viewport.ItemsBoundingBox may be costly when you have a lot of scenes.
1319
1320 - Super-Minor reason: It's much easier, for implementation and from the user point of view,
1321 to just use ZFarInfinity.
1322
1323 - Super-Minor reason: It also means user has a way to choose ZFarInfinity,
1324 despite our unfortunate choice of Camera.ProjectionFar = 0 meaning "autocalculate"
1325 and ZFarInfinity = 0. So user has no way to explictly request ZFarInfinity...
1326 except right now, "autocalculate" actually just implies ZFarInfinity.
1327
1328 We could have solved it better though, using e.g. ZFarInfinity = -1.
1329 But no need anymore.
1330
1331 Note: Only perspective projection supports ZFarInfinity, there's just no equivalent
1332 equation for orthographic projection to implement infinite z far.
1333
1334 Old Note (when we had calculation based on Box): when box is empty (or has 0 sizes),
1335 ProjectionFar cannot be simply "any dummy value".
1336 It must be appropriately larger than GetDefaultProjectionNear
1337 to provide sufficient space for rendering Background node.
1338 }
1339
1340 { Just for test, this is a proper code to calculate projection far based on world Box.
1341 Test this if you worry that ZFarInfinity causes visible imprecision in depth buffer
1342 (results of my tests: it does not). }
1343 {
1344 Box := BoxEvent();
1345 if Box.IsEmpty then
1346 begin
1347 // any values are OK, as we'll not render anyhitng
1348 Result := 10;
1349 Exit;
1350 end;
1351 Box.PointDistances(WorldTranslation, MinBoxDistance, MaxBoxDistance);
1352 Result := MaxBoxDistance * 2;
1353 WritelnLog('Autocalculated ProjectionFar %f', [Result]);
1354 }
1355
1356 Result := ZFarInfinity;
1357 end;
1358 end;
1359
1360 begin
1361 Result.ProjectionType := ProjectionType;
1362
1363 Result.PerspectiveAnglesRad := TViewpointNode.InternalFieldOfView(
1364 Perspective.FieldOfView,
1365 Perspective.FieldOfViewAxis,
1366 ViewportWidth,
1367 ViewportHeight);
1368 Perspective.InternalSetEffectiveFieldOfView(
1369 Result.PerspectiveAnglesRad);
1370
1371 if (ProjectionType = ptOrthographic) and
1372 ( (ProjectionNear <= 0) or
1373 (ProjectionFar <= 0) ) then
1374 GetBoxDistances(MinBoxDistanceForOrtho, MaxBoxDistanceForOrtho);
1375
1376 { calculate Result.ProjectionNear }
1377 Result.ProjectionNear := ProjectionNear;
1378 if (Result.ProjectionNear = 0) or
1379 ((Result.ProjectionType = ptPerspective) and
1380 (Result.ProjectionNear <= 0) ) then
1381 begin
1382 Result.ProjectionNear := GetDefaultProjectionNear(Result.ProjectionType);
1383 // in perspective, effective ProjectionNear must be > 0
1384 Assert((Result.ProjectionNear > 0) or (Result.ProjectionType <> ptPerspective));
1385 end;
1386
1387 { calculate Result.ProjectionFar }
1388 if ProjectionFar > 0 then
1389 begin
1390 { When ProjectionFar is non-zero on camera, use it unconditionally
1391 (do not override e.g. with ZFarInfinity, even if shadow volumes are possible).
1392 Reasons:
1393
1394 - This is more intuitive for developer. We do what was requested.
1395 Maybe developer wants ProjectionFar to really limit player's view,
1396 for gameplay purposes.
1397
1398 - Overriding with ZFarInfinity when shadow volumes are possible
1399 was also bad, because "shadow volumes are possible" may differ between
1400 CGE editor and runtime.
1401
1402 TCastleControl is initialized without stencil, TCastleWindow with stencil.
1403 So CGE editor preview was honoring ProjectionFar,
1404 while runtime TCastleWindow was ignoring it, overriding with ZFarInfinity.
1405 Testcase: physics-joints in physics_j branch.
1406 }
1407 Result.ProjectionFar := ProjectionFar;
1408 end else
1409 begin
1410 Result.ProjectionFar := GetDefaultProjectionFar(Result.ProjectionType);
1411 end;
1412
1413 InternalSetEffectiveProjection(
1414 Result.ProjectionNear,
1415 Result.ProjectionFar);
1416
1417 { Calculate Result.Dimensions regardless of Result.ProjectionType,
1418 this way OnProjection can easily change projection type to orthographic. }
1419 UpdateOrthographicDimensions;
1420
1421 {
1422 WritelnLogMultiline('Projection', Format(
1423 'ProjectionType: %s' + NL +
1424 'Perspective Field of View (Angles in degrees): %f x %f' + NL +
1425 'Orthographic Dimensions: %s' + NL +
1426 'Near: %f' + NL +
1427 'Far: %f', [
1428 ProjectionTypeToStr(Result.ProjectionType),
1429 RadToDeg(Result.PerspectiveAnglesRad.X),
1430 RadToDeg(Result.PerspectiveAnglesRad.Y),
1431 Result.Dimensions.ToString,
1432 Result.ProjectionNear,
1433 Result.ProjectionFar
1434 ]));
1435 }
1436 end;
1437
1438 procedure TCastleCamera.LocalRender(const Params: TRenderParams);
1439 begin
1440 if FGizmoCoord <> nil then
1441 begin
1442 { Update EffectiveProjection to show latest projection values. }
1443 InternalProjection(
1444 Params.ProjectionBoxWithoutGizmos,
1445 Params.ProjectionBoxWithGizmos,
1446 Params.ProjectionViewportWidth,
1447 Params.ProjectionViewportHeight,
1448 false);
1449 UpdateGizmoCoord;
1450 end;
1451
1452 inherited;
1453 end;
1454
1455 procedure TCastleCamera.DesignerInfo(const SList: TStrings);
1456 begin
1457 inherited;
1458 SList.Add(Format('EffectiveProjectionNear: %f', [EffectiveProjectionNear]));
1459 SList.Add(Format('EffectiveProjectionFar: %f%s', [
1460 EffectiveProjectionFar,
1461 Iff(EffectiveProjectionFar = ZFarInfinity, ' (infinity: no far clipping plane)', '')
1462 ]));
1463 end;
1464
1465 {$define read_implementation_methods}
1466 {$I auto_generated_persistent_vectors/tcastlecamera_persistent_vectors.inc}
1467 {$undef read_implementation_methods}
1468
1469 {$endif read_implementation}