Debian Codegraph @

src/transform/castletransform_camera_utils.inc

raw
1 {
2 Copyright 2003-2022 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 { Camera-related global routines. }
16
17 {$ifdef read_interface}
18
19 const
20 { Default camera direction and up vectors, used to define the meaning
21 of "camera orientation" for @link(OrientationFromDirectionUp),
22 @link(OrientationToDirection), @link(OrientationToUp).
23 These match X3D default camera values.
24 @groupBegin }
25 DefaultCameraDirection: TVector3 = (X: 0; Y: 0; Z: -1);
26 DefaultCameraUp : TVector3 = (X: 0; Y: 1; Z: 0);
27 { @groupEnd }
28
29 Default2DProjectionFar = 1000.0 deprecated 'this default is not used; ProjectionFar in orthographic projection is now automatically adjusted to what you display';
30 Default2DProjectionNear = - {Default2DProjectionFar}1000.0 deprecated 'this default is not used; ProjectionNear in orthographic projection is now automatically adjusted to what you display';
31 Default2DCameraZ = {Default2DProjectionFar}1000.0 / 2;
32
33 { Convert camera direction and up vectors into a rotation (X3D "orientation" vector).
34
35 Orientation vector expresses Direction and Up as a rotation.
36 First three components of the resulting vector are the Axis (normalized) and the
37 4th component is the Angle (in radians). If you would rotate the standard
38 direction and up (see DefaultCameraDirection, DefaultCameraUp) around Axis
39 by the Angle, then you would get Direction and Up back.
40
41 There is an overloaded version where you can pass your custom
42 DefaultDirection, DefaultUp to be used instead of
43 default DefaultCameraDirection, DefaultCameraUp.
44
45 Given here Direction and Up must be orthogonal and non-zero.
46 Their lengths are not relevant (that is, you don't need to normalize them
47 before passing here).
48
49 @groupBegin }
50 function OrientationFromDirectionUp(const Direction, Up: TVector3): TVector4; overload;
51 procedure OrientationFromDirectionUp(const Direction, Up: TVector3;
52 out Axis: TVector3; out Angle: Single); overload;
53 function OrientationFromDirectionUp(const Direction, Up: TVector3;
54 const DefaultDirection, DefaultUp: TVector3): TVector4; overload;
55 { @groupEnd }
56
57 { Convert rotation (X3D orientation) to a direction vector,
58 reversing the @link(OrientationFromDirectionUp). }
59 function OrientationToDirection(const OrientationRotation: TVector4): TVector3;
60
61 { Convert rotation (X3D orientation) to an up vector,
62 reversing the @link(OrientationFromDirectionUp). }
63 function OrientationToUp(const OrientationRotation: TVector4): TVector3;
64
65 function CamDirUp2Orient(const Direction, Up: TVector3): TVector4; overload;
66 deprecated 'use OrientationFromDirectionUp';
67 procedure CamDirUp2Orient(const Direction, Up: TVector3;
68 out Axis: TVector3; out Angle: Single); overload;
69 deprecated 'use OrientationFromDirectionUp';
70
71 { Convert camera direction and up vectors into a "rotation quaternion".
72 Just like OrientationFromDirectionUp, but the result is a quaternion,
73 not an axis-angle vector.
74 @groupBegin }
75 function OrientationQuaternionFromDirectionUp(Direction, Up: TVector3;
76 const DefaultDirection, DefaultUp: TVector3): TQuaternion; overload;
77 function OrientationQuaternionFromDirectionUp(const Direction,
78 Up: TVector3): TQuaternion; overload;
79 { @groupEnd }
80
81 function CamDirUp2OrientQuat(const Direction, Up: TVector3): TQuaternion;
82 deprecated 'OrientationQuaternionFromDirectionUp';
83
84 { Calculate sensible camera configuration to see the whole Box.
85
86 WantedDirection and WantedUp indicate desired look direction/up axis
87 (0, 1 or 2 for X, Y or Z). WantedDirectionPositive and WantedUpPositive
88 indicate if we want the positive axis. Obviously look direction and up
89 cannot be parallel, so WantedDirection must be different than WantedUp.
90
91 Returned Direction, Up, GravityUp are normalized. }
92 procedure CameraViewpointForWholeScene(const Box: TBox3D;
93 const WantedDirection, WantedUp: Integer;
94 const WantedDirectionPositive, WantedUpPositive: boolean;
95 out Position, Direction, Up, GravityUp: TVector3);
96
97 { Calculate suitable camera to see everything using an orthographic projection.
98
99 Assumes that the camera direction is -Z, and camera up is +Y.
100 So the horizontal axis of the world is X,
101 vertical axis is Y.
102 These are default values of camera set by @link(TCastleViewport.Setup2D).
103
104 The meaning of Origin is the same as @link(TCastleOrthographic.Origin).
105
106 Returns new correct values of
107 @link(TCastleOrthographic.Width),
108 @link(TCastleOrthographic.Height),
109 @link(TCastleCamera.ProjectionFar) and camera position
110 (set it like @code(Viewport.Camera.Translation := NewPosition;)).
111 }
112 procedure CameraOrthoViewpointForWholeScene(const Box: TBox3D;
113 const ViewportWidth, ViewportHeight: Single;
114 const Origin: TVector2;
115 out Position: TVector3;
116 out AProjectionWidth, AProjectionHeight, AProjectionFar: Single);
117
118 { TODO: move these consts somewhere more private? }
119
120 const
121 { Following X3D spec of NavigationType:
122 "It is recommended that the near clipping plane be set to one-half
123 of the collision radius as specified in the avatarSize field." }
124 RadiusToProjectionNear = 0.6;
125
126 { Default Radius, determining also (with RadiusToProjectionNear)
127 default TCastleCamera.EffectiveProjectionNear.
128
129 Note: *Do not* base automatic Radius (and, consistently,
130 automatic ProjectionNear) on Box size.
131
132 - Major reason: It makes things go bad, as automatic ProjectionNear increases
133 and clipping at near plane becomes visible,
134 when you have some TCastleTransform in your world that travels forever
135 (and thus increases the Viewport.ItemsBoundingBox into infinity).
136
137 E.g. a missile that flies into infinity.
138 Or a box that falls down due to gravity into infinity.
139 While such things in general should not happen (you should prevent things
140 from traveling to infinity), but they may happen esp. in development,
141 and it's bad when one problem (flying to infinity) causes another (sudden
142 clipping at near plane).
143
144 - Minor reason: It avoids the need to calculate Viewport.ItemsBoundingBox
145 at each frame, at least for the purpose of automatic projection
146 for ProjectionNear.
147 It was never observed in profiler,
148 but in theory Viewport.ItemsBoundingBox may be costly when you have a lot of scenes.
149
150 Note: This is smaller, so even safer, than X3D default Navigation.avatarSize[0] (0.25).
151 }
152 DefaultCameraRadius = 0.1;
153
154 { Multiply radius by this to get sensible "preferred height".
155
156 We need to make "preferred height" much larger than Radius * 2, to allow some
157 space to decrease (e.g. by Input_DecreasePreferredHeight).
158 Remember that CorrectPreferredHeight
159 adds a limit to PreferredHeight, around Radius * 2.
160
161 This determines minimal PreferredHeight, it should be used always like
162 Max(DefaultPreferredHeight, Radius * RadiusToPreferredHeightMin)
163 This way, in case of models that are small, but still follow the standard "1 unit = 1 meter",
164 the PreferredHeight will not get weirdly small, it will be DefaultPreferredHeight.
165 Testcase: examples/third_person_navigation/data/level/level-dungeon.gltf open with castle-model-viewer.
166 }
167 RadiusToPreferredHeightMin = 4.0;
168
169 {$endif read_interface}
170
171 {$ifdef read_implementation}
172
173 function OrientationQuaternionFromDirectionUp(const Direction, Up: TVector3): TQuaternion;
174 begin
175 Result := OrientationQuaternionFromDirectionUp(Direction, Up,
176 DefaultCameraDirection, DefaultCameraUp);
177 end;
178
179 function OrientationQuaternionFromDirectionUp(Direction, Up: TVector3;
180 const DefaultDirection, DefaultUp: TVector3): TQuaternion;
181
182 { This was initially based on Stephen Chenney's ANSI C code orient.c,
183 available still from here: http://vrmlworks.crispen.org/tools.html
184 I rewrote it a couple of times, possibly removing and possibly adding
185 some bugs :)
186
187 Idea: we want to convert Direction and Up into VRML orientation,
188 which is a rotation from DefaultDirection/DefaultUp into Direction/Up.
189
190 1) Take vector orthogonal to standard DefaultDirection and Direction.
191 Rotate around it, to match DefaultDirection with Direction.
192
193 2) Now rotate around Direction such that standard up (already rotated
194 by 1st transform) matches with Up. We know it's possible,
195 since Direction and Up are orthogonal and normalized,
196 just like standard DefaultDirection/DefaultUp.
197
198 Combine these two rotations and you have the result.
199
200 How to combine two rotations, such that in the end you get nice
201 single rotation? That's where quaternions rule.
202 }
203
204 function QuatFromAxisAngleCos(const Axis: TVector3;
205 const AngleRadCos: Single): TQuaternion;
206 begin
207 Result := QuatFromAxisAngle(Axis, ArcCos(Clamped(AngleRadCos, -1.0, 1.0)));
208 end;
209
210 var
211 Rot1Axis, Rot2Axis, DefaultUpAfterRot1: TVector3;
212 Rot1Quat, Rot2Quat: TQuaternion;
213 Rot1CosAngle, Rot2CosAngle: Single;
214 begin
215 Direction := Direction.Normalize;
216 Up := Up.Normalize;
217
218 { calculate Rot1Quat }
219 Rot1Axis := TVector3.CrossProduct(DefaultDirection, Direction);
220 { Rot1Axis may be zero if DefaultDirection and Direction are parallel.
221 When they point in the same direction, then it doesn't matter
222 (rotation will be by 0 angle anyway), but when they are in opposite
223 direction we want to do some rotation, so we need some non-zero
224 sensible Rot1Axis. }
225 if Rot1Axis.IsZero then
226 Rot1Axis := DefaultUp
227 else
228 { Normalize *after* checking ZeroVector, otherwise normalization
229 could change some almost-zero vector into a (practically random)
230 vector of length 1. }
231 Rot1Axis := Rot1Axis.Normalize;
232 Rot1CosAngle := TVector3.DotProduct(DefaultDirection, Direction);
233 Rot1Quat := QuatFromAxisAngleCos(Rot1Axis, Rot1CosAngle);
234
235 { calculate Rot2Quat }
236 DefaultUpAfterRot1 := Rot1Quat.Rotate(DefaultUp);
237 { We know Rot2Axis should be either Direction or -Direction. But how do we know
238 which one? (To make the rotation around it in correct direction.)
239 Calculating Rot2Axis below is a solution. }
240 Rot2Axis := TVector3.CrossProduct(DefaultUpAfterRot1, Up);
241
242 (*We could now do Rot2Axis := Rot2Axis.Normalize,
243 after making sure it's not zero. Like
244
245 { we need larger epsilon for ZeroVector below, in case
246 DefaultUpAfterRot1 is = -Up.
247 testcameras.pas contains testcases that require it. }
248 if Rot2Axis.IsZero(0.001) then
249 Rot2Axis := Direction else
250 { Normalize *after* checking ZeroVector, otherwise normalization
251 could change some almost-zero vector into a (practically random)
252 vector of length 1. }
253 Rot2Axis := Rot2Axis.Normalize;
254
255 And later do
256
257 { epsilon for TVector3.Equals 0.001 is too small }
258 Assert( TVector3.Equals(Rot2Axis, Direction, 0.01) or
259 TVector3.Equals(Rot2Axis, -Direction, 0.01),
260 Format('OrientationQuaternionFromDirectionUp failed for Direction, Up: (%s), (%s)',
261 [ Direction.ToRawString, Up.ToRawString ]));
262
263 However, as can be seen in above comments, this requires some careful
264 adjustments of epsilons, so it's somewhat numerically unstable.
265 It's better to just use now the knowledge that Rot2Axis
266 is either Direction or -Direction, and choose one of them. *)
267 if AreParallelVectorsSameDirection(Rot2Axis, Direction) then
268 Rot2Axis := Direction else
269 Rot2Axis := -Direction;
270
271 Rot2CosAngle := TVector3.DotProduct(DefaultUpAfterRot1, Up);
272 Rot2Quat := QuatFromAxisAngleCos(Rot2Axis, Rot2CosAngle);
273
274 { calculate Result = combine Rot1 and Rot2 (yes, the order
275 for QuatMultiply is reversed) }
276 Result := Rot2Quat * Rot1Quat;
277 end;
278
279 procedure OrientationFromDirectionUp(const Direction, Up: TVector3;
280 out Axis: TVector3; out Angle: Single);
281 begin
282 { Call OrientationQuaternionFromDirectionUp,
283 and extract the axis and angle from the quaternion. }
284 OrientationQuaternionFromDirectionUp(Direction, Up).ToAxisAngle(Axis, Angle);
285 end;
286
287 function OrientationFromDirectionUp(const Direction, Up: TVector3): TVector4;
288 var
289 Axis: TVector3;
290 Angle: Single;
291 begin
292 OrientationFromDirectionUp(Direction, Up, Axis, Angle);
293 Result := Vector4(Axis, Angle);
294 end;
295
296 function OrientationFromDirectionUp(const Direction, Up,
297 DefaultDirection, DefaultUp: TVector3): TVector4;
298 var
299 Axis: TVector3;
300 Angle: Single;
301 begin
302 OrientationQuaternionFromDirectionUp(Direction, Up, DefaultDirection, DefaultUp).
303 ToAxisAngle(Axis, Angle);
304 Result := Vector4(Axis, Angle);
305 end;
306
307 function OrientationToDirection(const OrientationRotation: TVector4): TVector3;
308 begin
309 Result := RotatePointAroundAxis(OrientationRotation, DefaultCameraDirection);
310 end;
311
312 function OrientationToUp(const OrientationRotation: TVector4): TVector3;
313 begin
314 Result := RotatePointAroundAxis(OrientationRotation, DefaultCameraUp);
315 end;
316
317 function CamDirUp2Orient(const Direction, Up: TVector3): TVector4;
318 begin
319 Result := OrientationFromDirectionUp(Direction, Up);
320 end;
321
322 procedure CamDirUp2Orient(const Direction, Up: TVector3;
323 out Axis: TVector3; out Angle: Single);
324 begin
325 OrientationFromDirectionUp(Direction, Up, Axis, Angle);
326 end;
327
328 function CamDirUp2OrientQuat(const Direction, Up: TVector3): TQuaternion;
329 begin
330 Result := OrientationQuaternionFromDirectionUp(Direction, Up);
331 end;
332
333 procedure CameraViewpointForWholeScene(const Box: TBox3D;
334 const WantedDirection, WantedUp: Integer;
335 const WantedDirectionPositive, WantedUpPositive: boolean;
336 out Position, Direction, Up, GravityUp: TVector3);
337 var
338 Offset: Single;
339 begin
340 Direction := TVector3.One[WantedDirection];
341 if not WantedDirectionPositive then Direction := -Direction;
342
343 Up := TVector3.One[WantedUp];
344 if not WantedUpPositive then Up := -Up;
345
346 if Box.IsEmpty then
347 begin
348 { If box is empty, choose the default X3D viewpoint.
349 This is least surprising, see https://github.com/castle-engine/castle-model-viewer/issues/3 }
350 Position := CastleVectors.Vector3(0, 0, 10); // DefaultX3DCameraPosition[cvVrml2_X3d];
351 end else
352 begin
353 Position := Box.Center;
354 Offset := 2 * Box.AverageSize;
355
356 if WantedDirectionPositive then
357 Position.Data[WantedDirection] := Box.Data[0].Data[WantedDirection] - Offset
358 else
359 Position.Data[WantedDirection] := Box.Data[1].Data[WantedDirection] + Offset;
360 end;
361
362 { GravityUp is just always equal Up here. }
363 GravityUp := Up;
364 end;
365
366 procedure CameraOrthoViewpointForWholeScene(const Box: TBox3D;
367 const ViewportWidth, ViewportHeight: Single;
368 const Origin: TVector2;
369 out Position: TVector3;
370 out AProjectionWidth, AProjectionHeight, AProjectionFar: Single);
371
372 { Calculate Position.XY and AProjectionWidth, AProjectionHeight. }
373 function PositionXY: TVector2;
374 var
375 Rect: TFloatRectangle;
376 EffectiveProjectionWidth, EffectiveProjectionHeight: Single;
377 begin
378 if Box.IsEmpty then
379 begin
380 Result := Vector2(0, 0);
381 AProjectionWidth := 0;
382 AProjectionHeight := 0;
383 end else
384 begin
385 Rect := Box.RectangleXY;
386
387 if ViewportWidth / ViewportHeight >
388 Rect.Width / Rect.Height then
389 begin
390 AProjectionWidth := 0;
391 AProjectionHeight := Rect.Height;
392 { Calculate EffectiveProjectionXxx
393 the same way that TCastleOrthographic.EffectiveWidth/Height would be calculated. }
394 EffectiveProjectionWidth := Rect.Height * ViewportWidth / ViewportHeight;
395 EffectiveProjectionHeight := AProjectionHeight;
396 end else
397 begin
398 AProjectionWidth := Rect.Width;
399 AProjectionHeight := 0;
400 { Calculate EffectiveProjectionXxx
401 the same way that TCastleOrthographic.EffectiveWidth/Height would be calculated. }
402 EffectiveProjectionWidth := AProjectionWidth;
403 EffectiveProjectionHeight := Rect.Width * ViewportHeight / ViewportWidth;
404 end;
405
406 // calculate PositionXY
407 Result := Rect.Center +
408 (Origin - Vector2(0.5, 0.5)) *
409 Vector2(EffectiveProjectionWidth, EffectiveProjectionHeight);
410 end;
411 end;
412
413 { Calculate Position.Z and AProjectionFar. }
414 function PositionZ: Single;
415 const
416 Default2DProjectionFar = 1000.0;
417 var
418 MinZ, MaxZ: Single;
419 begin
420 if Box.IsEmpty then
421 begin
422 Result := Default2DCameraZ;
423 AProjectionFar := Default2DProjectionFar;
424 end else
425 begin
426 MinZ := Box.Min.Z;
427 MaxZ := Box.Max.Z;
428 if (MinZ > - Default2DProjectionFar / 2) and
429 (MaxZ < Default2DProjectionFar / 2) then
430 begin
431 // prefer to use Default2DProjectionFar and Default2DCameraZ, if the scene fits inside
432 Result := Default2DCameraZ;
433 AProjectionFar := Default2DProjectionFar;
434 end else
435 begin
436 Result := MaxZ + 1;
437 AProjectionFar := MaxZ - MinZ;
438 end;
439 end;
440 end;
441
442 begin
443 Position := Vector3(PositionXY, PositionZ);
444 end;
445
446 {$endif read_implementation}